gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/** * 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.deephacks.confit.test; import com.google.common.base.Optional; import junit.framework.AssertionFailedError; import org.deephacks.confit.model.AbortRuntimeException; import org.deephacks.confit.model.Bean; import org.deephacks.confit.model.BeanId; import org.deephacks.confit.test.ConfigTestData.Grandfather; import org.deephacks.confit.test.ConfigTestData.Person; import org.deephacks.confit.test.ConfigTestData.Singleton; import org.deephacks.confit.test.ConfigTestData.SingletonParent; import org.deephacks.confit.test.validation.BinaryTree; import org.deephacks.confit.test.validation.BinaryTreeUtils; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.deephacks.confit.model.Events.*; import static org.deephacks.confit.test.ConversionUtils.toBean; import static org.deephacks.confit.test.ConversionUtils.toBeans; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals; import static org.unitils.reflectionassert.ReflectionComparatorMode.LENIENT_ORDER; /** * A funcational set of end-to-end tests for running compatibility tests. * * Theses tests are intended to be easily reused as a test suite for simplifying * testing compatibility of many different combinations of service providers * and configurations. * * It is the responsibility of subclasses to initalize the lookup of * service providers and their behaviour. * */ public abstract class ConfigTckTests extends ConfigDefaultSetup { /** * This method can be used to do initalize tests in the subclass * before the superclass. */ public abstract void before(); @Before public final void beforeMethod() { before(); setupDefaultConfigData(); } @Test public void test_create_set_merge_non_existing_property() { createDefault(); Bean bean = Bean.create(c1.getBeanId()); bean.addProperty("non_existing", "bogus"); try { admin.create(bean); fail("Not possible to set property names that does not exist in schema"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG110)); } try { admin.set(bean); fail("Not possible to set property names that does not exist in schema"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG110)); } try { admin.merge(bean); fail("Not possible to set property names that does not exist in schema"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG110)); } try { bean = Bean.create(BeanId.create("c5", ConfigTestData.CHILD_SCHEMA_NAME)); bean.setReference("non_existing", c1.getBeanId()); admin.create(bean); fail("Not possible to set property names that does not exist in schema"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG111)); } bean = Bean.create(c1.getBeanId()); bean.addProperty("non_existing", "bogus"); try { admin.set(bean); fail("Not possible to set property names that does not exist in schema"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG110)); } try { admin.merge(bean); fail("Not possible to set property names that does not exist in schema"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG110)); } } /** * Test the possibility for: * * 1) Creating individual beans that have references to eachother. * 2) Created beans can be fetched individually. * 3) That the config view sees the same result. */ @Test public void test_create_single_then_get_list() { createThenGet(c1); createThenGet(c2); listAndAssert(c1.getBeanId().getSchemaName(), c1, c2); createThenGet(p1); createThenGet(p2); listAndAssert(p1.getBeanId().getSchemaName(), p1, p2); createThenGet(g1); createThenGet(g2); listAndAssert(g1.getBeanId().getSchemaName(), g1, g2); } /** * Test the possibility for: * * 1) Creating a collection of beans that have references to eachother. * 2) Created beans can be fetched individually afterwards. * 3) Created beans can be listed afterwards. * 4) That the config view sees the same result as admin view. */ @Test public void test_create_multiple_then_get_list() { createDefault(); getAndAssert(c1); getAndAssert(c2); listAndAssert(c1.getBeanId().getSchemaName(), c1, c2); getAndAssert(p1); getAndAssert(p2); listAndAssert(p1.getBeanId().getSchemaName(), p1, p2); getAndAssert(g1); getAndAssert(g2); listAndAssert(g1.getBeanId().getSchemaName(), g1, g2); } /** * Test that lookup beans have their default instance created after registration. */ @Test public void test_register_singleton() { Singleton singleton = config.get(Singleton.class); assertNotNull(singleton); } /** * Test that lookup references are automatically assigned without needing to provision them * from admin context. */ @Test public void test_singleton_references() { // provision a bean without the lookup reference. Bean singletonParent = toBean(sp1); admin.create(singletonParent); // asert that the lookup reference is set for config SingletonParent parent = config.get(singletonParent.getId().getInstanceId(), SingletonParent.class).get(); assertNotNull(parent.getSingleton()); // assert that the lookup reference is set for admin Bean result = admin.get(singletonParent.getId()).get(); BeanId singletonId = result.getFirstReference("lookup"); assertThat(singletonId, is(s1.getBeanId())); assertThat(singletonId.getBean(), is(toBean(s1))); } /** * Test the possibility for: * * 1) Setting an empty bean that will erase properties and references. * 3) Bean that was set empty can be fetched individually. * 4) That the config view sees the same result as admin view. */ @Test public void test_set_get_single() { createDefault(); Grandfather empty = new Grandfather("g1"); Bean empty_expect = toBean(empty); admin.set(empty_expect); Bean empty_result = admin.get(empty.getBeanId()).get(); assertReflectionEquals(empty_expect, empty_result, LENIENT_ORDER); } @Test public void test_set_get_list() { createDefault(); Grandfather empty_g1 = new Grandfather("g1"); Grandfather empty_g2 = new Grandfather("g2"); Collection<Bean> empty_expect = toBeans(empty_g1, empty_g2); admin.set(empty_expect); Collection<Bean> empty_result = admin.list(empty_g1.getBeanId().getSchemaName()); assertReflectionEquals(empty_expect, empty_result, LENIENT_ORDER); runtimeAllAndAssert(empty_g1.getClass(), empty_g1, empty_g2); } @Test public void test_merge_get_single() { createDefault(); Grandfather merged = new Grandfather("g1"); merged.setProp14(TimeUnit.NANOSECONDS); merged.setProp19(Arrays.asList(TimeUnit.DAYS, TimeUnit.HOURS)); merged.setProp1("newName"); Bean mergeBean = toBean(merged); admin.merge(mergeBean); // modify the original to fit the expected merge g1.setProp1(merged.getProp1()); g1.setProp19(merged.getProp19()); g1.setProp14(merged.getProp14()); getAndAssert(g1); } @Test public void test_merge_get_list() { createDefault(); Grandfather g1_merged = new Grandfather("g1"); g1_merged.setProp14(TimeUnit.NANOSECONDS); g1_merged.setProp19(Arrays.asList(TimeUnit.DAYS, TimeUnit.HOURS)); g1_merged.setProp1("newName"); Grandfather g2_merged = new Grandfather("g2"); g2_merged.setProp14(TimeUnit.NANOSECONDS); g2_merged.setProp19(Arrays.asList(TimeUnit.DAYS, TimeUnit.HOURS)); g2_merged.setProp1("newName"); Collection<Bean> mergeBeans = toBeans(g1_merged, g2_merged); admin.merge(mergeBeans); // modify the original to fit the expected merge g1.setProp1(g1_merged.getProp1()); g1.setProp19(g1_merged.getProp19()); g1.setProp14(g1_merged.getProp14()); g2.setProp1(g2_merged.getProp1()); g2.setProp19(g2_merged.getProp19()); g2.setProp14(g2_merged.getProp14()); listAndAssert(g1.getBeanId().getSchemaName(), g1, g2); } @Test public void test_merge_and_set_broken_references() { createDefault(); // try merge a invalid single reference Bean b = Bean.create(BeanId.create("p1", ConfigTestData.PARENT_SCHEMA_NAME)); b.addReference("prop6", BeanId.create("non_existing_child_ref", "")); try { admin.merge(b); fail("Should not be possible to merge invalid reference"); } catch (AbortRuntimeException e) { if (e.getEvent().getCode() != CFG301) { fail("Should not be possible to merge invalid reference"); } } // try merge a invalid reference on collection b = Bean.create(BeanId.create("p2", ConfigTestData.PARENT_SCHEMA_NAME)); b.addReference("prop7", BeanId.create("non_existing_child_ref", "")); try { admin.merge(b); fail("Should not be possible to merge invalid reference"); } catch (AbortRuntimeException e) { if (e.getEvent().getCode() != CFG301) { fail("Should not be possible to merge invalid reference"); } } // try set a invalid single reference b = Bean.create(BeanId.create("parent4", ConfigTestData.PARENT_SCHEMA_NAME)); b.addReference("prop6", BeanId.create("non_existing_child_ref", "")); try { admin.set(b); fail("Should not be possible to merge beans that does not exist"); } catch (AbortRuntimeException e) { if (e.getEvent().getCode() != CFG301) { fail("Should not be possible to merge invalid reference"); } } // try merge a invalid single reference b = Bean.create(BeanId.create("p1", ConfigTestData.PARENT_SCHEMA_NAME)); b.addReference("prop6", BeanId.create("non_existing_child_ref", "")); try { admin.set(b); fail("Should not be possible to merge invalid reference"); } catch (AbortRuntimeException e) { if (e.getEvent().getCode() != CFG301) { fail("Should not be possible to merge invalid reference"); } } } @Test public void test_delete_bean() { createDefault(); admin.delete(g1.getBeanId()); Optional<Bean> bean = admin.get(g1.getBeanId()); assertFalse(bean.isPresent()); } @Test public void test_delete_beans() { createDefault(); admin.delete(g1.getBeanId().getSchemaName(), Arrays.asList("g1", "g2")); List<Bean> result = admin.list(g1.getBeanId().getSchemaName()); assertThat(result.size(), is(0)); } @Test public void test_delete_reference_violation() { admin.createObjects(Arrays.asList(g1, g2, p1, p2, c1, c2)); // test single try { admin.delete(BeanId.create("c1", ConfigTestData.CHILD_SCHEMA_NAME)); fail("Should not be possible to delete a bean with references"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG302)); } // test multiple try { admin.delete(ConfigTestData.CHILD_SCHEMA_NAME, Arrays.asList("c1", "c2")); fail("Should not be possible to delete a bean with references"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG302)); } } @Test public void test_set_merge_without_schema() { Bean b = Bean.create(BeanId.create("1", "missing_schema_name")); try { admin.create(b); fail("Cant add beans without a schema."); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG101)); } try { admin.merge(b); fail("Cant add beans without a schema."); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG101)); } } @Test public void test_set_merge_violating_types() { admin.create(toBeans(g1, g2, p1, p2, c1, c2)); Bean child = Bean.create(BeanId.create("c1", ConfigTestData.CHILD_SCHEMA_NAME)); // child merge invalid byte try { child.setProperty("prop8", "100000"); admin.set(child); fail("10000 does not fit java.lang.Byte"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG105)); } // child merge invalid integer try { child.addProperty("prop3", "2.2"); admin.merge(child); fail("2.2 does not fit a collection of java.lang.Integer"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG105)); } // parent set invalid enum value Bean parent = Bean.create(BeanId.create("g1", ConfigTestData.GRANDFATHER_SCHEMA_NAME)); try { parent.setProperty("prop14", "not_a_enum"); admin.set(parent); fail("not_a_enum is not a value of TimeUnit"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG105)); } // parent merge invalid value to enum list parent = Bean.create(BeanId.create("p1", ConfigTestData.PARENT_SCHEMA_NAME)); try { parent.addProperty("prop19", "not_a_enum"); admin.merge(parent); fail("not_a_enum is not a value of TimeUnit"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG105)); } // grandfather merge invalid multiplicity type, i.e. single on multi value. Bean grandfather = Bean.create(BeanId.create("g1", ConfigTestData.GRANDFATHER_SCHEMA_NAME)); try { grandfather.addProperty("prop1", Arrays.asList("1", "2")); admin.merge(grandfather); fail("Cannot add mutiple values to a single valued property."); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG106)); } // grandfather set invalid multiplicity type, multi value on single. grandfather = Bean.create(BeanId.create("p1", ConfigTestData.PARENT_SCHEMA_NAME)); try { grandfather.addProperty("prop11", "2.0"); admin.set(parent); fail("Cannot add a value to a single typed value."); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG105)); } } @Test public void test_circular_references() { String personSchema = "person"; config.register(Person.class); BeanId aId = BeanId.create("a", personSchema); BeanId bId = BeanId.create("b", personSchema); BeanId cId = BeanId.create("c", personSchema); BeanId dId = BeanId.create("d", personSchema); Bean a = Bean.create(aId); Bean b = Bean.create(bId); Bean c = Bean.create(cId); Bean d = Bean.create(dId); admin.create(Arrays.asList(a, b, c, d)); a.setReference("bestFriend", bId); b.setReference("bestFriend", aId); c.setReference("bestFriend", dId); d.setReference("bestFriend", cId); a.addReference("closeFriends", Arrays.asList(bId, cId, dId)); b.addReference("closeFriends", Arrays.asList(aId, cId, dId)); c.addReference("closeFriends", Arrays.asList(aId, bId, dId)); d.addReference("closeFriends", Arrays.asList(aId, bId, cId)); a.addReference("colleauges", Arrays.asList(bId, cId, dId)); b.addReference("colleauges", Arrays.asList(aId, cId, dId)); c.addReference("colleauges", Arrays.asList(aId, bId, dId)); d.addReference("colleauges", Arrays.asList(aId, bId, cId)); /** * Now test list operations from admin and config to make * sure that none of them lookup stuck in infinite recrusion. */ admin.merge(Arrays.asList(a, b, c, d)); admin.set(Arrays.asList(a, b, c, d)); admin.list("person"); admin.get(BeanId.create("b", "person")); config.list(Person.class); config.get("c", Person.class); } @Test public void test_JSR303_validation_success() { jsr303.setProp("Valid upper value for @FirstUpperValidator"); jsr303.setWidth(2); jsr303.setHeight(2); Bean jsr303Bean = toBean(jsr303); admin.create(jsr303Bean); } @Test public void test_JSR303_validation_failures() { jsr303.setProp("Valid upper value for @FirstUpperValidator"); jsr303.setWidth(20); jsr303.setHeight(20); Bean jsr303Bean = toBean(jsr303); try { admin.create(jsr303Bean); fail("Area exceeds constraint"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG309)); } jsr303.setProp("test"); jsr303.setWidth(1); jsr303.setHeight(1); jsr303Bean = toBean(jsr303); try { admin.create(jsr303Bean); fail("Prop does not have first upper case."); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG309)); } jsr303.setProp("T"); jsr303.setWidth(1); jsr303.setHeight(1); jsr303Bean = toBean(jsr303); try { admin.create(jsr303Bean); fail("Prop must be longer than one char"); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG309)); } jsr303.setProp("Valid upper value for @FirstUpperValidator"); jsr303.setWidth(null); jsr303.setHeight(null); jsr303Bean = toBean(jsr303); try { admin.create(jsr303Bean); fail("Width and height may not be null."); } catch (AbortRuntimeException e) { assertThat(e.getEvent().getCode(), is(CFG309)); } } /** * Test that JSR303 validation can operate on references in order * to validate that a binary tree is correct after modification. * * This is what the test-tree looks like. * * _______5______ * / \ * ___4 ___8__ * / / \ * _2 6 10 * / \ \ / * 1 3 7 9 */ @Test public void test_JSR303_reference_validation() { config.register(BinaryTree.class); // generate the tree seen in the javadoc Set<Bean> beans = BinaryTreeUtils.getTree(5, Arrays.asList(8, 4, 10, 2, 5, 1, 9, 6, 3, 7)); admin.create(beans); BinaryTree root = config.get("5", BinaryTree.class).get(); BinaryTreeUtils.printPretty(root); /** * TEST1: a correct delete of 8 where 9 takes its place */ Bean eight = BinaryTreeUtils.getBean(8, beans); Bean ten = BinaryTreeUtils.getBean(10, beans); // 8: set value 9 eight.setProperty("value", "9"); // 10: remove reference to 9 ten.remove("left"); admin.set(Arrays.asList(eight, ten)); root = config.get("5", BinaryTree.class).get(); // take a look at the tree after delete BinaryTreeUtils.printPretty(root); /** * TEST2: set 4 to 7 should fail */ try { Bean four = BinaryTreeUtils.getBean(4, beans); four.setProperty("value", "7"); admin.merge(four); fail("setting 4 to 7 should not be possible."); } catch (AbortRuntimeException e) { // BinaryTreeValidator should notice that 7 satisfies left 2 // but not parent 5 (7 should be to right of 5) assertThat(e.getEvent().getCode(), is(CFG309)); // display error message to prove that validator found the error. System.out.println(e.getEvent().getMessage()); } } private void createThenGet(Object object) throws AssertionFailedError { admin.createObject(object); getAndAssert(object); } private void getAndAssert(Object object) throws AssertionFailedError { Bean bean = toBean(object); Bean result = admin.get(bean.getId()).get(); assertReflectionEquals(bean, result, LENIENT_ORDER); runtimeGetAndAssert(object, bean); } /** * Create the default testdata structure. */ private void createDefault() { admin.create(defaultBeans); } private void listAndAssert(String schemaName, Object... objects) { Collection<Bean> beans = admin.list(schemaName); assertReflectionEquals(toBeans(objects), beans, LENIENT_ORDER); runtimeAllAndAssert(objects[0].getClass(), objects); } private void runtimeGetAndAssert(Object object, Bean bean) throws AssertionFailedError { Object o = config.get(bean.getId().getInstanceId(), object.getClass()); assertReflectionEquals(object, o, LENIENT_ORDER); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void runtimeAllAndAssert(Class clazz, Object... objects) throws AssertionFailedError { List<Object> reslut = config.list(clazz); assertReflectionEquals(objects, reslut, LENIENT_ORDER); } }
/** * 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. See accompanying LICENSE file. */ package org.apache.hadoop.security.authentication.server; import org.apache.hadoop.security.authentication.client.AuthenticatedURL; import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.hadoop.security.authentication.util.Signer; import org.apache.hadoop.security.authentication.util.SignerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.Principal; import java.util.Enumeration; import java.util.Properties; import java.util.Random; /** * The {@link AuthenticationFilter} enables protecting web application resources with different (pluggable) * authentication mechanisms. * <p/> * Out of the box it provides 2 authentication mechanisms: Pseudo and Kerberos SPNEGO. * <p/> * Additional authentication mechanisms are supported via the {@link AuthenticationHandler} interface. * <p/> * This filter delegates to the configured authentication handler for authentication and once it obtains an * {@link AuthenticationToken} from it, sets a signed HTTP cookie with the token. For client requests * that provide the signed HTTP cookie, it verifies the validity of the cookie, extracts the user information * and lets the request proceed to the target resource. * <p/> * The supported configuration properties are: * <ul> * <li>config.prefix: indicates the prefix to be used by all other configuration properties, the default value * is no prefix. See below for details on how/why this prefix is used.</li> * <li>[#PREFIX#.]type: simple|kerberos|#CLASS#, 'simple' is short for the * {@link PseudoAuthenticationHandler}, 'kerberos' is short for {@link KerberosAuthenticationHandler}, otherwise * the full class name of the {@link AuthenticationHandler} must be specified.</li> * <li>[#PREFIX#.]signature.secret: the secret used to sign the HTTP cookie value. The default value is a random * value. Unless multiple webapp instances need to share the secret the random value is adequate.</li> * <li>[#PREFIX#.]token.validity: time -in seconds- that the generated token is valid before a * new authentication is triggered, default value is <code>3600</code> seconds.</li> * <li>[#PREFIX#.]cookie.domain: domain to use for the HTTP cookie that stores the authentication token.</li> * <li>[#PREFIX#.]cookie.path: path to use for the HTTP cookie that stores the authentication token.</li> * </ul> * <p/> * The rest of the configuration properties are specific to the {@link AuthenticationHandler} implementation and the * {@link AuthenticationFilter} will take all the properties that start with the prefix #PREFIX#, it will remove * the prefix from it and it will pass them to the the authentication handler for initialization. Properties that do * not start with the prefix will not be passed to the authentication handler initialization. */ public class AuthenticationFilter implements Filter { private static Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class); /** * Constant for the property that specifies the configuration prefix. */ public static final String CONFIG_PREFIX = "config.prefix"; /** * Constant for the property that specifies the authentication handler to use. */ public static final String AUTH_TYPE = "type"; /** * Constant for the property that specifies the secret to use for signing the HTTP Cookies. */ public static final String SIGNATURE_SECRET = "signature.secret"; /** * Constant for the configuration property that indicates the validity of the generated token. */ public static final String AUTH_TOKEN_VALIDITY = "token.validity"; /** * Constant for the configuration property that indicates the domain to use in the HTTP cookie. */ public static final String COOKIE_DOMAIN = "cookie.domain"; /** * Constant for the configuration property that indicates the path to use in the HTTP cookie. */ public static final String COOKIE_PATH = "cookie.path"; private static final Random RAN = new Random(); private Signer signer; private AuthenticationHandler authHandler; private boolean randomSecret; private long validity; private String cookieDomain; private String cookiePath; /** * Initializes the authentication filter. * <p/> * It instantiates and initializes the specified {@link AuthenticationHandler}. * <p/> * * @param filterConfig filter configuration. * * @throws ServletException thrown if the filter or the authentication handler could not be initialized properly. */ @Override public void init(FilterConfig filterConfig) throws ServletException { String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; Properties config = getConfiguration(configPrefix, filterConfig); String authHandlerName = config.getProperty(AUTH_TYPE, null); String authHandlerClassName; if (authHandlerName == null) { throw new ServletException("Authentication type must be specified: simple|kerberos|<class>"); } if (authHandlerName.equals("simple")) { authHandlerClassName = PseudoAuthenticationHandler.class.getName(); } else if (authHandlerName.equals("kerberos")) { authHandlerClassName = KerberosAuthenticationHandler.class.getName(); } else { authHandlerClassName = authHandlerName; } try { Class<?> klass = Thread.currentThread().getContextClassLoader().loadClass(authHandlerClassName); authHandler = (AuthenticationHandler) klass.newInstance(); authHandler.init(config); } catch (ClassNotFoundException ex) { throw new ServletException(ex); } catch (InstantiationException ex) { throw new ServletException(ex); } catch (IllegalAccessException ex) { throw new ServletException(ex); } String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET); if (signatureSecret == null) { signatureSecret = Long.toString(RAN.nextLong()); randomSecret = true; LOG.warn("'signature.secret' configuration not set, using a random value as secret"); } signer = new Signer(signatureSecret.getBytes()); validity = Long.parseLong(config.getProperty(AUTH_TOKEN_VALIDITY, "36000")) * 1000; //10 hours cookieDomain = config.getProperty(COOKIE_DOMAIN, null); cookiePath = config.getProperty(COOKIE_PATH, null); } /** * Returns the authentication handler being used. * * @return the authentication handler being used. */ protected AuthenticationHandler getAuthenticationHandler() { return authHandler; } /** * Returns if a random secret is being used. * * @return if a random secret is being used. */ protected boolean isRandomSecret() { return randomSecret; } /** * Returns the validity time of the generated tokens. * * @return the validity time of the generated tokens, in seconds. */ protected long getValidity() { return validity / 1000; } /** * Returns the cookie domain to use for the HTTP cookie. * * @return the cookie domain to use for the HTTP cookie. */ protected String getCookieDomain() { return cookieDomain; } /** * Returns the cookie path to use for the HTTP cookie. * * @return the cookie path to use for the HTTP cookie. */ protected String getCookiePath() { return cookiePath; } /** * Destroys the filter. * <p/> * It invokes the {@link AuthenticationHandler#destroy()} method to release any resources it may hold. */ @Override public void destroy() { if (authHandler != null) { authHandler.destroy(); authHandler = null; } } /** * Returns the filtered configuration (only properties starting with the specified prefix). The property keys * are also trimmed from the prefix. The returned {@link Properties} object is used to initialized the * {@link AuthenticationHandler}. * <p/> * This method can be overriden by subclasses to obtain the configuration from other configuration source than * the web.xml file. * * @param configPrefix configuration prefix to use for extracting configuration properties. * @param filterConfig filter configuration object * * @return the configuration to be used with the {@link AuthenticationHandler} instance. * * @throws ServletException thrown if the configuration could not be created. */ protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException { Properties props = new Properties(); Enumeration<?> names = filterConfig.getInitParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); if (name.startsWith(configPrefix)) { String value = filterConfig.getInitParameter(name); props.put(name.substring(configPrefix.length()), value); } } return props; } /** * Returns the full URL of the request including the query string. * <p/> * Used as a convenience method for logging purposes. * * @param request the request object. * * @return the full URL of the request including the query string. */ protected String getRequestURL(HttpServletRequest request) { StringBuffer sb = request.getRequestURL(); if (request.getQueryString() != null) { sb.append("?").append(request.getQueryString()); } return sb.toString(); } /** * Returns the {@link AuthenticationToken} for the request. * <p/> * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE} * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns * it. * <p/> * If this method returns <code>null</code> the filter will invoke the configured {@link AuthenticationHandler} * to perform user authentication. * * @param request request object. * * @return the Authentication token if the request is authenticated, <code>null</code> otherwise. * * @throws IOException thrown if an IO error occurred. * @throws AuthenticationException thrown if the token is invalid or if it has expired. */ protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException { AuthenticationToken token = null; String tokenStr = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) { tokenStr = cookie.getValue(); try { tokenStr = signer.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } break; } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (!token.getType().equals(authHandler.getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (LOG.isDebugEnabled() && token.isExpired ()) { LOG.debug("Authentication Token expired"); } } return token; } /** * If the request has a valid authentication token it allows the request to continue to the target resource, * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}. * * @param request the request object. * @param response the response object. * @param filterChain the filter chain object. * * @throws IOException thrown if an IO error occurred. * @throws ServletException thrown if a processing error occurred. */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { boolean unauthorizedResponse = true; String unauthorizedMsg = ""; HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try { boolean newToken = false; AuthenticationToken token; try { token = getToken(httpRequest); } catch (AuthenticationException ex) { LOG.warn("AuthenticationToken ignored: " + ex.getMessage()); token = null; } if (token == null || token.isExpired ()) { if (LOG.isDebugEnabled()) { LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest)); } token = authHandler.authenticate(httpRequest, httpResponse); if (token != null && token != AuthenticationToken.ANONYMOUS) { token.setExpires(System.currentTimeMillis() + getValidity() * 1000); } newToken = true; } if (token != null) { unauthorizedResponse = false; if (LOG.isDebugEnabled()) { LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName()); } final AuthenticationToken authToken = token; httpRequest = new HttpServletRequestWrapper(httpRequest) { @Override public String getAuthType() { return authToken.getType(); } @Override public String getRemoteUser() { return authToken.getUserName(); } @Override public Principal getUserPrincipal() { return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; } }; if (newToken && token != AuthenticationToken.ANONYMOUS) { String signedToken = signer.sign(token.toString()); Cookie cookie = createCookie(signedToken); httpResponse.addCookie(cookie); } filterChain.doFilter(httpRequest, httpResponse); } } catch (AuthenticationException ex) { unauthorizedMsg = ex.toString(); LOG.warn("Authentication exception: " + ex.getMessage(), ex); } if (unauthorizedResponse) { if (!httpResponse.isCommitted()) { Cookie cookie = createCookie(""); cookie.setMaxAge(0); httpResponse.addCookie(cookie); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, unauthorizedMsg); } } } /** * Creates the Hadoop authentiation HTTP cookie. * <p/> * It sets the domain and path specified in the configuration. * * @param token authentication token for the cookie. * * @return the HTTP cookie. */ protected Cookie createCookie(String token) { Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, token); if (getCookieDomain() != null) { cookie.setDomain(getCookieDomain()); } if (getCookiePath() != null) { cookie.setPath(getCookiePath()); } return cookie; } }
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.tasks.generic; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.tasks.Task; import com.intellij.tasks.impl.TaskUtil; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.XCollection; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; /** * @author Mikhail Golubev */ public abstract class SelectorBasedResponseHandler extends ResponseHandler { private static final Logger LOG = Logger.getInstance(SelectorBasedResponseHandler.class); // Supported selector names @NonNls protected static final String TASKS = "tasks"; @NonNls protected static final String SUMMARY = "summary"; @NonNls protected static final String DESCRIPTION = "description"; @NonNls protected static final String ISSUE_URL = "issueUrl"; @NonNls protected static final String CLOSED = "closed"; @NonNls protected static final String UPDATED = "updated"; @NonNls protected static final String CREATED = "created"; @NonNls protected static final String SINGLE_TASK_ID = "singleTask-id"; @NonNls protected static final String SINGLE_TASK_SUMMARY = "singleTask-summary"; @NonNls protected static final String SINGLE_TASK_DESCRIPTION = "singleTask-description"; @NonNls protected static final String SINGLE_TASK_ISSUE_URL = "singleTask-issueUrl"; @NonNls protected static final String SINGLE_TASK_CLOSED = "singleTask-closed"; @NonNls protected static final String SINGLE_TASK_UPDATED = "singleTask-updated"; @NonNls protected static final String SINGLE_TASK_CREATED = "singleTask-created"; @NonNls protected static final String ID = "id"; protected LinkedHashMap<String, Selector> mySelectors = new LinkedHashMap<>(); /** * Serialization constructor */ @SuppressWarnings("UnusedDeclaration") protected SelectorBasedResponseHandler() { // empty } protected SelectorBasedResponseHandler(GenericRepository repository) { super(repository); // standard selectors setSelectors(ContainerUtil.newArrayList( // matched against list of tasks at whole downloaded from "taskListUrl" new Selector(TASKS), // matched against single tasks extracted from the list downloaded from "taskListUrl" new Selector(ID), new Selector(SUMMARY), new Selector(DESCRIPTION), new Selector(UPDATED), new Selector(CREATED), new Selector(CLOSED), new Selector(ISSUE_URL), // matched against single task downloaded from "singleTaskUrl" new Selector(SINGLE_TASK_ID), new Selector(SINGLE_TASK_SUMMARY), new Selector(SINGLE_TASK_DESCRIPTION), new Selector(SINGLE_TASK_UPDATED), new Selector(SINGLE_TASK_CREATED), new Selector(SINGLE_TASK_CLOSED), new Selector(SINGLE_TASK_ISSUE_URL) )); } @XCollection(propertyElementName = "selectors") @NotNull public List<Selector> getSelectors() { return new ArrayList<>(mySelectors.values()); } public void setSelectors(@NotNull List<Selector> selectors) { mySelectors.clear(); for (Selector selector : selectors) { mySelectors.put(selector.getName(), selector); } } /** * Only predefined selectors should be accessed. */ @NotNull protected Selector getSelector(@NotNull String name) { return mySelectors.get(name); } @NotNull protected String getSelectorPath(@NotNull String name) { Selector s = getSelector(name); return s.getPath(); } @NotNull @Override public JComponent getConfigurationComponent(@NotNull Project project) { FileType fileType = getResponseType().getSelectorFileType(); HighlightedSelectorsTable table = new HighlightedSelectorsTable(fileType, project, getSelectors()); return new JBScrollPane(table); } @Override public SelectorBasedResponseHandler clone() { SelectorBasedResponseHandler clone = (SelectorBasedResponseHandler)super.clone(); clone.mySelectors = new LinkedHashMap<>(mySelectors.size()); for (Selector selector : mySelectors.values()) { clone.mySelectors.put(selector.getName(), selector.clone()); } return clone; } @Override public boolean isConfigured() { Selector idSelector = getSelector(ID); if (StringUtil.isEmpty(idSelector.getPath())) return false; Selector summarySelector = getSelector(SUMMARY); if (StringUtil.isEmpty(summarySelector.getPath()) && !myRepository.getDownloadTasksInSeparateRequests()) return false; return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SelectorBasedResponseHandler)) return false; SelectorBasedResponseHandler handler = (SelectorBasedResponseHandler)o; if (!mySelectors.equals(handler.mySelectors)) return false; return true; } @Override public int hashCode() { return mySelectors.hashCode(); } @Override public final Task @NotNull [] parseIssues(@NotNull String response, int max) throws Exception { if (StringUtil.isEmpty(getSelectorPath(TASKS)) || StringUtil.isEmpty(getSelectorPath(ID)) || (StringUtil.isEmpty(getSelectorPath(SUMMARY)) && !myRepository.getDownloadTasksInSeparateRequests())) { throw new Exception("Selectors 'tasks', 'id' and 'summary' are mandatory"); } List<Object> tasks = selectTasksList(response, max); LOG.debug(String.format("Total %d tasks extracted from response", tasks.size())); List<Task> result = new ArrayList<>(tasks.size()); for (Object context : tasks) { String id = selectString(getSelector(ID), context); GenericTask task; if (myRepository.getDownloadTasksInSeparateRequests()) { task = new GenericTask(id, "", myRepository); } else { String summary = selectString(getSelector(SUMMARY), context); assert id != null && summary != null; task = new GenericTask(id, summary, myRepository); String description = selectString(getSelector(DESCRIPTION), context); if (description != null) { task.setDescription(description); } String issueUrl = selectString(getSelector(ISSUE_URL), context); if (issueUrl != null) { task.setIssueUrl(issueUrl); } Boolean closed = selectBoolean(getSelector(CLOSED), context); if (closed != null) { task.setClosed(closed); } Date updated = selectDate(getSelector(UPDATED), context); if (updated != null) { task.setUpdated(updated); } Date created = selectDate(getSelector(CREATED), context); if (created != null) { task.setCreated(created); } } result.add(task); } return result.toArray(Task.EMPTY_ARRAY); } @Nullable private Date selectDate(@NotNull Selector selector, @NotNull Object context) throws Exception { String s = selectString(selector, context); if (s == null) { return null; } return TaskUtil.parseDate(s); } @Nullable protected Boolean selectBoolean(@NotNull Selector selector, @NotNull Object context) throws Exception { String s = selectString(selector, context); if (s == null) { return null; } s = StringUtil.toLowerCase(s.trim()); if (s.equals("true")) { return true; } else if (s.equals("false")) { return false; } throw new Exception( String.format("Expression '%s' should match boolean value. Got '%s' instead", selector.getName(), s)); } @NotNull protected abstract List<Object> selectTasksList(@NotNull String response, int max) throws Exception; @Nullable protected abstract @Nls String selectString(@NotNull Selector selector, @NotNull Object context) throws Exception; @Nullable @Override public final Task parseIssue(@NotNull String response) throws Exception { if (StringUtil.isEmpty(getSelectorPath(SINGLE_TASK_ID)) || StringUtil.isEmpty(getSelectorPath(SINGLE_TASK_SUMMARY))) { throw new Exception("Selectors 'singleTask-id' and 'singleTask-summary' are mandatory"); } String id = selectString(getSelector(SINGLE_TASK_ID), response); String summary = selectString(getSelector(SINGLE_TASK_SUMMARY), response); assert id != null && summary != null; GenericTask task = new GenericTask(id, summary, myRepository); String description = selectString(getSelector(SINGLE_TASK_DESCRIPTION), response); if (description != null) { task.setDescription(description); } String issueUrl = selectString(getSelector(SINGLE_TASK_ISSUE_URL), response); if (issueUrl != null) { task.setIssueUrl(issueUrl); } Boolean closed = selectBoolean(getSelector(SINGLE_TASK_CLOSED), response); if (closed != null) { task.setClosed(closed); } Date updated = selectDate(getSelector(SINGLE_TASK_UPDATED), response); if (updated != null) { task.setUpdated(updated); } Date created = selectDate(getSelector(SINGLE_TASK_CREATED), response); if (created != null) { task.setCreated(created); } return task; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.tomcat.util.net.jsse; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CRL; import java.security.cert.CRLException; import java.security.cert.CertPathParameters; import java.security.cert.CertStore; import java.security.cert.CertStoreParameters; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CollectionCertStoreParameters; import java.security.cert.PKIXBuilderParameters; import java.security.cert.X509CertSelector; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Locale; import javax.net.ssl.CertPathTrustManagerParameters; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509KeyManager; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.Constants; import org.apache.tomcat.util.net.SSLUtil; import org.apache.tomcat.util.net.ServerSocketFactory; import org.apache.tomcat.util.res.StringManager; /** * SSL server socket factory. It <b>requires</b> a valid RSA key and * JSSE.<br/> * keytool -genkey -alias tomcat -keyalg RSA</br> * Use "changeit" as password (this is the default we use). * * @author Harish Prabandham * @author Costin Manolache * @author Stefan Freyr Stefansson * @author EKR -- renamed to JSSESocketFactory * @author Jan Luehe */ public class JSSESocketFactory implements ServerSocketFactory, SSLUtil { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(JSSESocketFactory.class); private static final StringManager sm = StringManager.getManager("org.apache.tomcat.util.net.jsse.res"); private static final boolean RFC_5746_SUPPORTED; private static final String[] DEFAULT_SERVER_PROTOCOLS; private static final String[] DEFAULT_SERVER_CIPHER_SUITES; // Defaults - made public where re-used private static final String defaultProtocol = "TLS"; private static final String defaultKeystoreType = "JKS"; private static final String defaultKeystoreFile = System.getProperty("user.home") + "/.keystore"; private static final int defaultSessionCacheSize = 0; private static final int defaultSessionTimeout = 86400; private static final String ALLOW_ALL_SUPPORTED_CIPHERS = "ALL"; public static final String DEFAULT_KEY_PASS = "changeit"; static { boolean result = false; SSLContext context; String[] ciphers = null; String[] protocols = null; try { context = SSLContext.getInstance("TLS"); context.init(null, null, null); SSLServerSocketFactory ssf = context.getServerSocketFactory(); String supportedCiphers[] = ssf.getSupportedCipherSuites(); for (String cipher : supportedCiphers) { if ("TLS_EMPTY_RENEGOTIATION_INFO_SCSV".equals(cipher)) { result = true; break; } } // There is no API to obtain the default server protocols and cipher // suites. Having inspected the OpenJDK code there the same results // can be achieved via the standard API but there is no guarantee // that every JVM implementation determines the defaults the same // way. Therefore the defaults are determined by creating a server // socket and requested the configured values. SSLServerSocket socket = (SSLServerSocket) ssf.createServerSocket(); ciphers = socket.getEnabledCipherSuites(); protocols = socket.getEnabledProtocols(); } catch (NoSuchAlgorithmException e) { // Assume no RFC 5746 support } catch (KeyManagementException e) { // Assume no RFC 5746 support } catch (IOException e) { // Unable to determine default ciphers/protocols so use none } RFC_5746_SUPPORTED = result; DEFAULT_SERVER_CIPHER_SUITES = ciphers; DEFAULT_SERVER_PROTOCOLS = protocols; } private AbstractEndpoint<?> endpoint; protected SSLServerSocketFactory sslProxy = null; protected String[] enabledCiphers; protected String[] enabledProtocols; protected boolean allowUnsafeLegacyRenegotiation = false; /** * Flag to state that we require client authentication. */ protected boolean requireClientAuth = false; /** * Flag to state that we would like client authentication. */ protected boolean wantClientAuth = false; public JSSESocketFactory (AbstractEndpoint<?> endpoint) { this.endpoint = endpoint; } @Override public ServerSocket createSocket (int port) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port); initServerSocket(socket); return socket; } @Override public ServerSocket createSocket (int port, int backlog) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog); initServerSocket(socket); return socket; } @Override public ServerSocket createSocket (int port, int backlog, InetAddress ifAddress) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog, ifAddress); initServerSocket(socket); return socket; } @Override public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try { asock = (SSLSocket)socket.accept(); } catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); } return asock; } @Override public void handshake(Socket sock) throws IOException { // We do getSession instead of startHandshake() so we can call this multiple times SSLSession session = ((SSLSocket)sock).getSession(); if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL"); if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) { // Prevent further handshakes by removing all cipher suites ((SSLSocket) sock).setEnabledCipherSuites(new String[0]); } } @Override public String[] getEnableableCiphers(SSLContext context) { String requestedCiphersStr = endpoint.getCiphers(); if (ALLOW_ALL_SUPPORTED_CIPHERS.equals(requestedCiphersStr)) { return context.getSupportedSSLParameters().getCipherSuites(); } if ((requestedCiphersStr == null) || (requestedCiphersStr.trim().length() == 0)) { return DEFAULT_SERVER_CIPHER_SUITES; } List<String> requestedCiphers = new ArrayList<>(); for (String rc : requestedCiphersStr.split(",")) { final String cipher = rc.trim(); if (cipher.length() > 0) { requestedCiphers.add(cipher); } } if (requestedCiphers.isEmpty()) { return DEFAULT_SERVER_CIPHER_SUITES; } List<String> ciphers = new ArrayList<>(requestedCiphers); ciphers.retainAll(Arrays.asList(context.getSupportedSSLParameters() .getCipherSuites())); if (ciphers.isEmpty()) { log.warn(sm.getString("jsse.requested_ciphers_not_supported", requestedCiphersStr)); } if (log.isDebugEnabled()) { log.debug(sm.getString("jsse.enableable_ciphers", ciphers)); if (ciphers.size() != requestedCiphers.size()) { List<String> skipped = new ArrayList<>(requestedCiphers); skipped.removeAll(ciphers); log.debug(sm.getString("jsse.unsupported_ciphers", skipped)); } } return ciphers.toArray(new String[ciphers.size()]); } public String[] getEnabledCiphers() { return enabledCiphers; } /* * Gets the SSL server's keystore password. */ protected String getKeystorePassword() { String keystorePass = endpoint.getKeystorePass(); if (keystorePass == null) { keystorePass = endpoint.getKeyPass(); } if (keystorePass == null) { keystorePass = DEFAULT_KEY_PASS; } return keystorePass; } /* * Gets the SSL server's keystore. */ protected KeyStore getKeystore(String type, String provider, String pass) throws IOException { String keystoreFile = endpoint.getKeystoreFile(); if (keystoreFile == null) keystoreFile = defaultKeystoreFile; return getStore(type, provider, keystoreFile, pass); } /* * Gets the SSL server's truststore. */ protected KeyStore getTrustStore(String keystoreType, String keystoreProvider) throws IOException { KeyStore trustStore = null; String truststoreFile = endpoint.getTruststoreFile(); if(truststoreFile == null) { truststoreFile = System.getProperty("javax.net.ssl.trustStore"); } if(log.isDebugEnabled()) { log.debug("Truststore = " + truststoreFile); } String truststorePassword = endpoint.getTruststorePass(); if( truststorePassword == null) { truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); } if(log.isDebugEnabled()) { log.debug("TrustPass = " + truststorePassword); } String truststoreType = endpoint.getTruststoreType(); if( truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if(truststoreType == null) { truststoreType = keystoreType; } if(log.isDebugEnabled()) { log.debug("trustType = " + truststoreType); } String truststoreProvider = endpoint.getTruststoreProvider(); if( truststoreProvider == null) { truststoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider"); } if (truststoreProvider == null) { truststoreProvider = keystoreProvider; } if(log.isDebugEnabled()) { log.debug("trustProvider = " + truststoreProvider); } if (truststoreFile != null){ try { trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, truststorePassword); } catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } } } return trustStore; } /* * Gets the key- or truststore with the specified type, path, and password. */ private KeyStore getStore(String type, String provider, String path, String pass) throws IOException { KeyStore ks = null; InputStream istream = null; try { if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) { File keyStoreFile = new File(path); if (!keyStoreFile.isAbsolute()) { keyStoreFile = new File(System.getProperty( Constants.CATALINA_BASE_PROP), path); } istream = new FileInputStream(keyStoreFile); } char[] storePass = null; if (pass != null && !"".equals(pass)) { storePass = pass.toCharArray(); } ks.load(istream, storePass); } catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; } catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; } catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); } finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } } return ks; } /** * Reads the keystore and initializes the SSL socket factory. */ void init() throws IOException { try { String clientAuthStr = endpoint.getClientAuth(); if("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } SSLContext context = createSSLContext(); context.init(getKeyManagers(), getTrustManagers(), null); // Configure SSL session cache SSLSessionContext sessionContext = context.getServerSessionContext(); if (sessionContext != null) { configureSessionContext(sessionContext); } // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable enabledCiphers = getEnableableCiphers(context); enabledProtocols = getEnableableProtocols(context); allowUnsafeLegacyRenegotiation = "true".equals( endpoint.getAllowUnsafeLegacyRenegotiation()); // Check the SSL config is OK checkConfig(); } catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); } } @Override public SSLContext createSSLContext() throws Exception { // SSL protocol variant (e.g., TLS, SSL v3, etc.) String protocol = endpoint.getSslProtocol(); if (protocol == null) { protocol = defaultProtocol; } SSLContext context = SSLContext.getInstance(protocol); return context; } @Override public KeyManager[] getKeyManagers() throws Exception { String keystoreType = endpoint.getKeystoreType(); if (keystoreType == null) { keystoreType = defaultKeystoreType; } String algorithm = endpoint.getAlgorithm(); if (algorithm == null) { algorithm = KeyManagerFactory.getDefaultAlgorithm(); } return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(), algorithm, endpoint.getKeyAlias()); } @Override public TrustManager[] getTrustManagers() throws Exception { String truststoreType = endpoint.getTruststoreType(); if (truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if (truststoreType == null) { truststoreType = endpoint.getKeystoreType(); } if (truststoreType == null) { truststoreType = defaultKeystoreType; } String algorithm = endpoint.getTruststoreAlgorithm(); if (algorithm == null) { algorithm = TrustManagerFactory.getDefaultAlgorithm(); } return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(), algorithm); } @Override public void configureSessionContext(SSLSessionContext sslSessionContext) { int sessionCacheSize; if (endpoint.getSessionCacheSize() != null) { sessionCacheSize = Integer.parseInt( endpoint.getSessionCacheSize()); } else { sessionCacheSize = defaultSessionCacheSize; } int sessionTimeout; if (endpoint.getSessionTimeout() != null) { sessionTimeout = Integer.parseInt(endpoint.getSessionTimeout()); } else { sessionTimeout = defaultSessionTimeout; } sslSessionContext.setSessionCacheSize(sessionCacheSize); sslSessionContext.setSessionTimeout(sessionTimeout); } /** * Gets the initialized key managers. */ protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if ("JKS".equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; } /** * Gets the initialized trust managers. */ protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { String crlf = endpoint.getCrlFile(); String className = endpoint.getTrustManagerClassName(); if(className != null && className.length() > 0) { ClassLoader classLoader = getClass().getClassLoader(); Class<?> clazz = classLoader.loadClass(className); if(!(TrustManager.class.isAssignableFrom(clazz))){ throw new InstantiationException(sm.getString( "jsse.invalidTrustManagerClassName", className)); } Object trustManagerObject = clazz.newInstance(); TrustManager trustManager = (TrustManager) trustManagerObject; return new TrustManager[]{ trustManager }; } TrustManager[] tms = null; KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); if (trustStore != null || endpoint.getTrustManagerClassName() != null) { if (crlf == null) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(trustStore); tms = tmf.getTrustManagers(); } else { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); CertPathParameters params = getParameters(algorithm, crlf, trustStore); ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params); tmf.init(mfp); tms = tmf.getTrustManagers(); } } return tms; } /** * Return the initialization parameters for the TrustManager. * Currently, only the default <code>PKIX</code> is supported. * * @param algorithm The algorithm to get parameters for. * @param crlf The path to the CRL file. * @param trustStore The configured TrustStore. * @return The parameters including the CRLs and TrustStore. */ protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); } } params = xparams; } else { throw new CRLException("CRLs not supported for type: "+algorithm); } return params; } /** * Load the collection of CRLs. * */ protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); try (InputStream is = new FileInputStream(crlFile)) { crls = cf.generateCRLs(is); } } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } return crls; } @Override public String[] getEnableableProtocols(SSLContext context) { String[] requestedProtocols = endpoint.getSslEnabledProtocolsArray(); if ((requestedProtocols == null) || (requestedProtocols.length == 0)) { return DEFAULT_SERVER_PROTOCOLS; } List<String> protocols = new ArrayList<>( Arrays.asList(requestedProtocols)); protocols.retainAll(Arrays.asList(context.getSupportedSSLParameters() .getProtocols())); if (protocols.isEmpty()) { log.warn(sm.getString("jsse.requested_protocols_not_supported", Arrays.asList(requestedProtocols))); } if (log.isDebugEnabled()) { log.debug(sm.getString("jsse.enableable_protocols", protocols)); if (protocols.size() != requestedProtocols.length) { List<String> skipped = new ArrayList<>( Arrays.asList(requestedProtocols)); skipped.removeAll(protocols); log.debug(sm.getString("jsse.unsupported_protocols", skipped)); } } return protocols.toArray(new String[protocols.size()]); } /** * Configure Client authentication for this version of JSSE. The * JSSE included in Java 1.4 supports the 'want' value. Prior * versions of JSSE will treat 'want' as 'false'. * @param socket the SSLServerSocket */ protected void configureClientAuth(SSLServerSocket socket){ if (wantClientAuth){ socket.setWantClientAuth(wantClientAuth); } else { socket.setNeedClientAuth(requireClientAuth); } } /** * Configures the given SSL server socket with the requested cipher suites, * protocol versions, and need for client authentication */ private void initServerSocket(ServerSocket ssocket) { SSLServerSocket socket = (SSLServerSocket) ssocket; socket.setEnabledCipherSuites(enabledCiphers); socket.setEnabledProtocols(enabledProtocols); // we don't know if client auth is needed - // after parsing the request we may re-handshake configureClientAuth(socket); } /** * Checks that the certificate is compatible with the enabled cipher suites. * If we don't check now, the JIoEndpoint can enter a nasty logging loop. * See bug 45528. */ private void checkConfig() throws IOException { // Create an unbound server socket ServerSocket socket = sslProxy.createServerSocket(); initServerSocket(socket); try { // Set the timeout to 1ms as all we care about is if it throws an // SSLException on accept. socket.setSoTimeout(1); socket.accept(); // Will never get here - no client can connect to an unbound port } catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; } catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ } finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.gobblin.source.extractor.extract; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.State; import org.apache.gobblin.configuration.WorkUnitState; import org.apache.gobblin.source.extractor.DataRecordException; import org.apache.gobblin.source.extractor.exception.HighWatermarkException; import org.apache.gobblin.source.extractor.exception.RecordCountException; import org.apache.gobblin.source.extractor.exception.SchemaException; import org.apache.gobblin.source.extractor.partition.Partition; import org.apache.gobblin.source.extractor.partition.Partitioner; import org.apache.gobblin.source.extractor.watermark.Predicate; import org.apache.gobblin.source.extractor.watermark.WatermarkPredicate; import org.apache.gobblin.source.extractor.watermark.WatermarkType; import org.apache.gobblin.source.workunit.WorkUnit; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.hadoop.yarn.webapp.hamlet.HamletSpec; import org.testng.Assert; import org.testng.annotations.Test; /** * Unit tests for {@link QueryBasedExtractor} */ public class QueryBasedExtractorTest { @Test public void testDataPullUpperBoundsRemovedInLastWorkUnit() { int totalCount = 5; ArrayList<DataRecord> records = this.generateRecords(totalCount); WorkUnit workUnit = WorkUnit.createEmpty(); workUnit.setProp(Partition.IS_LAST_PARTIITON, true); workUnit.setProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE, "SNAPSHOT"); WorkUnitState workUnitState = new WorkUnitState(workUnit, new State()); workUnitState.setId("testDataPullUpperBoundsRemovedInLastWorkUnit"); TestQueryBasedExtractor testExtractor = new TestQueryBasedExtractor(workUnitState, records); testExtractor.setRangePredicates(1, 3); this.verify(testExtractor, totalCount); } @Test public void testDataPullUpperBoundsNotRemovedInLastWorkUnit() { int totalCount = 5; ArrayList<DataRecord> records = this.generateRecords(totalCount); WorkUnit workUnit = WorkUnit.createEmpty(); WorkUnitState workUnitState = new WorkUnitState(workUnit, new State()); workUnitState.setId("testDataPullUpperBoundsNotRemovedInLastWorkUnit"); // It's not a last work unit TestQueryBasedExtractor testExtractor = new TestQueryBasedExtractor(workUnitState, records); testExtractor.setRangePredicates(1, 3); this.verify(testExtractor, 3); // It's a last work unit but user specifies high watermark workUnit.setProp(Partition.IS_LAST_PARTIITON, true); workUnit.setProp(Partition.HAS_USER_SPECIFIED_HIGH_WATERMARK, true); testExtractor.reset(); testExtractor.setRangePredicates(1, 3); this.verify(testExtractor, 3); // It's a last work unit but it has WORK_UNIT_STATE_ACTUAL_HIGH_WATER_MARK_KEY on record workUnit.removeProp(Partition.HAS_USER_SPECIFIED_HIGH_WATERMARK); workUnit.setProp(ConfigurationKeys.WORK_UNIT_STATE_ACTUAL_HIGH_WATER_MARK_KEY, "3"); testExtractor.reset(); testExtractor.setRangePredicates(1, 3); this.verify(testExtractor, 3); } private ArrayList<DataRecord> generateRecords(int count) { ArrayList<DataRecord> records = new ArrayList<>(); while (count > 0) { records.add(new DataRecord(count, count)); count--; } return records; } private void verify(TestQueryBasedExtractor testExtractor, int expectedCount) { int actualCount = 0; try { while (testExtractor.readRecord(null) != null) { actualCount++; } } catch (Exception e) { Assert.fail("There should not incur any exception"); } Assert.assertEquals(actualCount, expectedCount, "Expect " + expectedCount + " records!"); } private class TestQueryBasedExtractor extends QueryBasedExtractor<ArrayList, DataRecord> { private final ArrayList<DataRecord> records; private long previousActualHwmValue; TestQueryBasedExtractor(WorkUnitState workUnitState, ArrayList<DataRecord> records) { super(workUnitState); this.records = records; previousActualHwmValue = -1; } void setRangePredicates(long lwmValue, long hwmValue) { WatermarkPredicate watermark = new WatermarkPredicate("timeStamp", WatermarkType.SIMPLE); predicateList.add(watermark.getPredicate(this, lwmValue, ">=", Predicate.PredicateType.LWM)); predicateList.add(watermark.getPredicate(this, hwmValue, "<=", Predicate.PredicateType.HWM)); } void reset() { previousActualHwmValue = -1; predicateList.clear(); setFetchStatus(true); } @Override public void extractMetadata(String schema, String entity, WorkUnit workUnit) throws SchemaException, IOException { } @Override public long getMaxWatermark(String schema, String entity, String watermarkColumn, List<Predicate> snapshotPredicateList, String watermarkSourceFormat) throws HighWatermarkException { return 0; } @Override public long getSourceCount(String schema, String entity, WorkUnit workUnit, List<Predicate> predicateList) throws RecordCountException { return records.size(); } @Override public Iterator<DataRecord> getRecordSet(String schema, String entity, WorkUnit workUnit, List<Predicate> predicateList) throws DataRecordException, IOException { if (records == null || predicateList == null) { // No new data to pull return null; } long lwmValue = -1; long hwmValue = Long.MAX_VALUE; long actualHwmValue = -1; // Adjust watermarks from predicate list for (Predicate predicate: predicateList) { if (predicate.getType() == Predicate.PredicateType.HWM) { hwmValue = predicate.value; } if (predicate.getType() == Predicate.PredicateType.LWM) { lwmValue = predicate.value; } } ArrayList<DataRecord> filteredRecords = new ArrayList<>(); for (DataRecord record : records) { if (record.timeStamp <= previousActualHwmValue) { // The record has been pulled previously continue; } if (record.timeStamp >= lwmValue && record.timeStamp <= hwmValue) { // Make a copy filteredRecords.add(new DataRecord(record.value, record.timeStamp)); // Mark actual high watermark if (record.timeStamp > actualHwmValue) { actualHwmValue = record.timeStamp; } } } if (filteredRecords.isEmpty()) { return null; } previousActualHwmValue = actualHwmValue; return filteredRecords.iterator(); } @Override public String getWatermarkSourceFormat(WatermarkType watermarkType) { return null; } @Override public String getHourPredicateCondition(String column, long value, String valueFormat, String operator) { return null; } @Override public String getDatePredicateCondition(String column, long value, String valueFormat, String operator) { return null; } @Override public String getTimestampPredicateCondition(String column, long value, String valueFormat, String operator) { return null; } @Override public void setTimeOut(int timeOut) { } @Override public Map<String, String> getDataTypeMap() { return null; } @Override public void closeConnection() throws Exception { } @Override public Iterator<DataRecord> getRecordSetFromSourceApi(String schema, String entity, WorkUnit workUnit, List<Predicate> predicateList) throws IOException { try { return getRecordSet(schema, entity, workUnit, predicateList); } catch (DataRecordException e) { e.printStackTrace(); return null; } } } private class DataRecord { int value; long timeStamp; DataRecord(int value, long timeStamp) { this.value = value; this.timeStamp = timeStamp; } } }
/** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com * */ package org.hoteia.qalingo.core.web.mvc.factory; import java.util.Iterator; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.hoteia.qalingo.core.domain.Customer; import org.hoteia.qalingo.core.domain.CustomerAddress; import org.hoteia.qalingo.core.domain.CustomerMarketArea; import org.hoteia.qalingo.core.domain.CustomerOptin; import org.hoteia.qalingo.core.domain.MarketArea; import org.hoteia.qalingo.core.i18n.message.CoreMessageSource; import org.hoteia.qalingo.core.service.UrlService; import org.hoteia.qalingo.core.web.mvc.form.CartForm; import org.hoteia.qalingo.core.web.mvc.form.ContactForm; import org.hoteia.qalingo.core.web.mvc.form.CreateAccountForm; import org.hoteia.qalingo.core.web.mvc.form.CustomerAddressForm; import org.hoteia.qalingo.core.web.mvc.form.CustomerCommentForm; import org.hoteia.qalingo.core.web.mvc.form.CustomerContactForm; import org.hoteia.qalingo.core.web.mvc.form.CustomerEditForm; import org.hoteia.qalingo.core.web.mvc.form.FollowUsForm; import org.hoteia.qalingo.core.web.mvc.form.PaymentForm; import org.hoteia.qalingo.core.web.mvc.form.QuickSearchForm; import org.hoteia.qalingo.core.web.mvc.form.SearchForm; import org.hoteia.qalingo.core.web.resolver.RequestData; import org.hoteia.qalingo.core.web.util.RequestUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * */ @Service("formFactory") public class FormFactory { @Autowired protected CoreMessageSource coreMessageSource; @Autowired protected RequestUtil requestUtil; @Autowired protected UrlService urlService; public ContactForm buildContactForm(final RequestData requestData) throws Exception { final ContactForm contactUsForm = new ContactForm(); String languageCode = requestData.getMarketAreaLocalization().getCode(); if(languageCode.equals("en")) { contactUsForm.setCountry("US"); } else if(languageCode.equals("fr")) { contactUsForm.setCountry("FR"); } else if(languageCode.equals("de")) { contactUsForm.setCountry("DE"); } else if(languageCode.equals("es")) { contactUsForm.setCountry("ES"); } else if(languageCode.equals("it")) { contactUsForm.setCountry("IT"); } else if(languageCode.equals("nl")) { contactUsForm.setCountry("NL"); } else if(languageCode.equals("pt")) { contactUsForm.setCountry("PT"); } return contactUsForm; } public SearchForm buildSearchForm(final RequestData requestData) throws Exception { final SearchForm searchForm = new SearchForm(); return searchForm; } public QuickSearchForm buildQuickSearchForm(final RequestData requestData) throws Exception { final QuickSearchForm quickSearchForm = new QuickSearchForm(); return quickSearchForm; } public FollowUsForm buildFollowUsForm(final RequestData requestData) throws Exception { final FollowUsForm followUsForm = new FollowUsForm(); return followUsForm; } public CreateAccountForm buildCreateAccountForm(final RequestData requestData) throws Exception { final CreateAccountForm createAccountForm = new CreateAccountForm(); String languageCode = requestData.getMarketAreaLocalization().getCode(); if(languageCode.equals("en")) { createAccountForm.setCountryCode("US"); } else if(languageCode.equals("fr")) { createAccountForm.setCountryCode("FR"); } else if(languageCode.equals("de")) { createAccountForm.setCountryCode("DE"); } else if(languageCode.equals("es")) { createAccountForm.setCountryCode("ES"); } else if(languageCode.equals("it")) { createAccountForm.setCountryCode("IT"); } else if(languageCode.equals("nl")) { createAccountForm.setCountryCode("NL"); } else if(languageCode.equals("pt")) { createAccountForm.setCountryCode("PT"); } return createAccountForm; } public CustomerEditForm buildCustomerEditForm(final RequestData requestData, final Customer customer) throws Exception { final MarketArea marketArea = requestData.getMarketArea(); CustomerEditForm customerEditForm = new CustomerEditForm(); if(customer != null){ customerEditForm.setTitle(customer.getTitle()); customerEditForm.setLastname(customer.getLastname()); customerEditForm.setFirstname(customer.getFirstname()); customerEditForm.setEmail(customer.getEmail()); final CustomerMarketArea customerMarketContext = customer.getCurrentCustomerMarketArea(marketArea.getId()); if(customerMarketContext != null){ customerEditForm.setMobile(customerMarketContext.getMobile()); customerEditForm.setPhone(customerMarketContext.getPhone()); customerEditForm.setFax(customerMarketContext.getFax()); CustomerOptin optinNewsletter = customerMarketContext.getOptins(CustomerOptin.OPTIN_TYPE_WWW_NEWSLETTER); if(optinNewsletter != null){ customerEditForm.setOptin(optinNewsletter.isActive()); } } } return customerEditForm; } public CustomerAddressForm buildCustomerAddressForm(final RequestData requestData, final CustomerAddress customerAddress) throws Exception { final CustomerAddressForm customerAddressForm = new CustomerAddressForm(); String languageCode = requestData.getMarketAreaLocalization().getCode(); if(languageCode.equals("en")) { customerAddressForm.setCountryCode("US"); } else if(languageCode.equals("fr")) { customerAddressForm.setCountryCode("FR"); } else if(languageCode.equals("de")) { customerAddressForm.setCountryCode("DE"); } else if(languageCode.equals("es")) { customerAddressForm.setCountryCode("ES"); } else if(languageCode.equals("it")) { customerAddressForm.setCountryCode("IT"); } else if(languageCode.equals("nl")) { customerAddressForm.setCountryCode("NL"); } else if(languageCode.equals("pt")) { customerAddressForm.setCountryCode("PT"); } else if(languageCode.equals("ru")) { customerAddressForm.setCountryCode("RU"); } if(customerAddress != null){ customerAddressForm.setId(customerAddress.getId().toString()); customerAddressForm.setAddressName(customerAddress.getAddressName()); customerAddressForm.setTitle(customerAddress.getTitle()); customerAddressForm.setLastname(customerAddress.getLastname()); customerAddressForm.setFirstname(customerAddress.getFirstname()); customerAddressForm.setAddress1(customerAddress.getAddress1()); customerAddressForm.setAddress2(customerAddress.getAddress2()); customerAddressForm.setAddressAdditionalInformation(customerAddress.getAddressAdditionalInformation()); customerAddressForm.setPostalCode(customerAddress.getPostalCode()); customerAddressForm.setCity(customerAddress.getCity()); customerAddressForm.setStateCode(customerAddress.getStateCode()); customerAddressForm.setAreaCode(customerAddress.getAreaCode()); customerAddressForm.setCountryCode(customerAddress.getCountryCode()); } return customerAddressForm; } public CartForm buildCartForm(final RequestData requestData) throws Exception { final CartForm cartForm = new CartForm(); Customer customer = requestData.getCustomer(); if(customer != null) { Set<CustomerAddress> addresses = customer.getAddresses(); for (Iterator<CustomerAddress> iterator = addresses.iterator(); iterator.hasNext();) { CustomerAddress customerAddress = (CustomerAddress) iterator.next(); if(customerAddress.isDefaultBilling()) { cartForm.setBillingAddressId(customerAddress.getId().toString()); } if(customerAddress.isDefaultShipping()) { cartForm.setShippingAddressId(customerAddress.getId().toString()); } } } return cartForm; } public PaymentForm buildPaymentForm(final RequestData requestData) throws Exception { final PaymentForm paymentForm = new PaymentForm(); return paymentForm; } public CustomerCommentForm buildCustomerCommentForm(final RequestData requestData, final String objectCode) throws Exception { final CustomerCommentForm customerCommentForm = new CustomerCommentForm(); customerCommentForm.setObjectCode(objectCode); final Customer customer = requestData.getCustomer(); if(customer != null){ if(StringUtils.isNotEmpty(customer.getScreenName())){ customerCommentForm.setName(customer.getScreenName()); } else { customerCommentForm.setName(customer.getLastname() + " " + customer.getFirstname()); } customerCommentForm.setEmail(customer.getEmail()); } return customerCommentForm; } public CustomerContactForm buildCustomerContactForm(final RequestData requestData, final String objectCode) throws Exception { final CustomerContactForm retailerContactForm = new CustomerContactForm(); retailerContactForm.setObjectCode(objectCode); String languageCode = requestData.getMarketAreaLocalization().getCode(); if(languageCode.equals("en")) { retailerContactForm.setCountry("US"); } else if(languageCode.equals("fr")) { retailerContactForm.setCountry("FR"); } else if(languageCode.equals("de")) { retailerContactForm.setCountry("DE"); } else if(languageCode.equals("es")) { retailerContactForm.setCountry("ES"); } else if(languageCode.equals("it")) { retailerContactForm.setCountry("IT"); } else if(languageCode.equals("nl")) { retailerContactForm.setCountry("NL"); } else if(languageCode.equals("pt")) { retailerContactForm.setCountry("PT"); } return retailerContactForm; } }
package com.roche.sequencing.bioinformatics.common.directorymonitor; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DirectoryMonitor implements IDirectoryMonitor { private WatchService watchService; private Map<File, Set<Pattern>> directoryToPatternMap; private Set<IFileEventListener> fileEventListeners; private Set<File> scannedDirectories; private boolean monitorDirectoryRunnableIsOnEventQueue; private boolean isMonitoring; public DirectoryMonitor() throws IOException { watchService = FileSystems.getDefault().newWatchService(); directoryToPatternMap = new ConcurrentHashMap<File, Set<Pattern>>(); scannedDirectories = Collections.newSetFromMap(new ConcurrentHashMap<File, Boolean>()); fileEventListeners = new LinkedHashSet<IFileEventListener>(); isMonitoring = false; } @Override public File[] getDirectories() { return directoryToPatternMap.keySet().toArray(new File[0]); } @Override public void addDirectoryToMonitor(File directory) { addDirectoryToMonitor(directory, new Pattern[0]); } @Override public void addDirectoryToMonitor(File directory, Pattern pattern) { addDirectoryToMonitor(directory, new Pattern[] { pattern }); } @Override public void addDirectoryToMonitor(File directory, Pattern[] patterns) { addFilePatterns(directory, patterns); if (isMonitoring) { scanDirectory(directory); } } @Override public void removeDirectoryFromMonitor(File directory) { directoryToPatternMap.remove(directory); Path path = directory.toPath(); try { // Since the entry cannot be removed reduce the kinds of events that we listen for to // just deletions. Since there is no longer a directory entry in the directoryToPatternMap // this directory monitor will ignore the event anyway but this will reduce how many events are // triggered fro the underlying WatchService. path.register(watchService, StandardWatchEventKinds.ENTRY_DELETE); } catch (IOException e) { throw new IllegalStateException("Could not monitor directory[" + directory.getAbsolutePath() + "]." + e.getMessage(), e); } } private void addFilePatterns(File directory, Pattern[] patterns) { if (!directory.isDirectory()) { throw new IllegalStateException("The provided directory[" + directory.getAbsolutePath() + "] is not a directory."); } if (directoryToPatternMap.containsKey(directory)) { for (Pattern pattern : patterns) { directoryToPatternMap.get(directory).add(pattern); } } else { Set<Pattern> patternSet = Collections.newSetFromMap(new ConcurrentHashMap<Pattern, Boolean>()); for (Pattern pattern : patterns) { patternSet.add(pattern); } directoryToPatternMap.put(directory, patternSet); Path path = directory.toPath(); try { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException e) { throw new IllegalStateException("Could not monitor directory[" + directory.getAbsolutePath() + "]." + e.getMessage(), e); } } } @Override public Pattern[] getFilePatterns(File directory) { return directoryToPatternMap.get(directory).toArray(new Pattern[0]); } @Override public void start() { if (!monitorDirectoryRunnableIsOnEventQueue) { DirectoryMonitorThreadEventQueue.runInBackground(new MonitorDirectory()); } if (DirectoryMonitorThreadEventQueue.isPaused()) { DirectoryMonitorThreadEventQueue.resume(); } for (File directory : directoryToPatternMap.keySet()) { scanDirectory(directory); } isMonitoring = true; } private void scanDirectory(final File directoryBeingMonitored) { DirectoryMonitorThreadEventQueue.runInBackground(new Runnable() { @Override public void run() { internalScanDirectory(directoryBeingMonitored); } }); } private void internalScanDirectory(File directoryBeingMonitored) { synchronized (scannedDirectories) { if (scannedDirectories.add(directoryBeingMonitored)) { System.out.println("SCANNING" + directoryBeingMonitored.getAbsolutePath()); for (File file : directoryBeingMonitored.listFiles()) { if (!file.isDirectory()) { notifyListenersOfEventsIfNecessary(directoryBeingMonitored, file, FileEventEnum.INITIALLY_DETECTED); } } } } } private class MonitorDirectory implements Runnable { @Override public void run() { boolean valid = true; do { WatchKey watchKey; try { watchKey = watchService.take(); for (WatchEvent<?> event : watchKey.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); String fileName = event.context().toString(); FileEventEnum fileEvent = FileEventEnum.CREATED; if (kind == StandardWatchEventKinds.ENTRY_CREATE) { fileEvent = FileEventEnum.CREATED; } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { fileEvent = FileEventEnum.REMOVED; } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { fileEvent = FileEventEnum.MODIFIED; } Path directory = (Path) watchKey.watchable(); File directoryAsFile = directory.toFile(); final File file = new File(directoryAsFile, fileName); DirectoryMonitor.this.notifyListenersOfEventsIfNecessary(directoryAsFile, file, fileEvent); } valid = watchKey.reset(); } catch (InterruptedException e) { throw new IllegalStateException(e.getMessage(), e); } } while (valid); System.out.println("No longer valid so monitoring is down."); } } private void notifyListenersOfEventsIfNecessary(final File directoryBeingMonitored, final File file, FileEventEnum event) { if (directoryToPatternMap.containsKey(directoryBeingMonitored)) { Set<Pattern> patterns = directoryToPatternMap.get(directoryBeingMonitored); boolean matchesPattern = false; if (patterns.size() == 0) { // no patterns exist so all entries are accepted matchesPattern = true; } else { patternLoop: for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(file.getAbsolutePath()); if (matcher.find()) { matchesPattern = true; break patternLoop; } } } if (matchesPattern) { if (event == FileEventEnum.CREATED) { DirectoryMonitorThreadEventQueue.runInBackground(new Runnable() { @Override public void run() { for (IFileEventListener fileEventListener : fileEventListeners) { fileEventListener.fileCreated(directoryBeingMonitored, file); } } }); } else if (event == FileEventEnum.REMOVED) { DirectoryMonitorThreadEventQueue.runInBackground(new Runnable() { @Override public void run() { for (IFileEventListener fileEventListener : fileEventListeners) { fileEventListener.fileRemoved(directoryBeingMonitored, file); } } }); } else if (event == FileEventEnum.MODIFIED) { DirectoryMonitorThreadEventQueue.runInBackground(new Runnable() { @Override public void run() { for (IFileEventListener fileEventListener : fileEventListeners) { fileEventListener.fileModified(directoryBeingMonitored, file); } } }); } else if (event == FileEventEnum.INITIALLY_DETECTED) { DirectoryMonitorThreadEventQueue.runInBackground(new Runnable() { @Override public void run() { for (IFileEventListener fileEventListener : fileEventListeners) { fileEventListener.fileInitiallyDetected(directoryBeingMonitored, file); } } }); } else { throw new AssertionError(); } } } } @Override public void stop() { DirectoryMonitorThreadEventQueue.pause(); } public void shutdown() { DirectoryMonitorThreadEventQueue.shutdownNow(); isMonitoring = false; } @Override public IFileEventListener[] getFileEventListeners() { return fileEventListeners.toArray(new IFileEventListener[0]); } @Override public void clearFileEventListeners() { fileEventListeners.clear(); } @Override public void addFileEventListener(IFileEventListener fileEventListener) { fileEventListeners.add(fileEventListener); } @Override public void removeFileEventListener(IFileEventListener fileEventListener) { fileEventListeners.remove(fileEventListener); } @Override public boolean isMonitoring() { return isMonitoring; } }
// // ======================================================================== // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.continuation; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; public abstract class ContinuationBase extends TestCase { protected SuspendServlet _servlet=new SuspendServlet(); protected int _port; protected void doit(String type) throws Exception { String response; response=process(null,null); assertContains(type,response); assertContains("NORMAL",response); assertNotContains("history: onTimeout",response); assertNotContains("history: onComplete",response); response=process("sleep=200",null); assertContains("SLEPT",response); assertNotContains("history: onTimeout",response); assertNotContains("history: onComplete",response); response=process("suspend=200",null); assertContains("TIMEOUT",response); assertContains("history: onTimeout",response); assertContains("history: onComplete",response); response=process("suspend=200&resume=10",null); assertContains("RESUMED",response); assertNotContains("history: onTimeout",response); assertContains("history: onComplete",response); response=process("suspend=200&resume=0",null); assertContains("RESUMED",response); assertNotContains("history: onTimeout",response); assertContains("history: onComplete",response); response=process("suspend=200&complete=10",null); assertContains("COMPLETED",response); assertNotContains("history: onTimeout",response); assertContains("history: onComplete",response); response=process("suspend=200&complete=0",null); assertContains("COMPLETED",response); assertNotContains("history: onTimeout",response); assertContains("history: onComplete",response); response=process("suspend=1000&resume=10&suspend2=1000&resume2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(2,count(response,"history: resume")); assertEquals(0,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("RESUMED",response); response=process("suspend=1000&resume=10&suspend2=1000&resume2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(2,count(response,"history: resume")); assertEquals(0,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("RESUMED",response); response=process("suspend=1000&resume=10&suspend2=1000&complete2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(1,count(response,"history: resume")); assertEquals(0,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("COMPLETED",response); response=process("suspend=1000&resume=10&suspend2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(1,count(response,"history: resume")); assertEquals(1,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("TIMEOUT",response); response=process("suspend=10&suspend2=1000&resume2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(1,count(response,"history: resume")); assertEquals(1,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("RESUMED",response); response=process("suspend=10&suspend2=1000&resume2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(1,count(response,"history: resume")); assertEquals(1,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("RESUMED",response); response=process("suspend=10&suspend2=1000&complete2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(0,count(response,"history: resume")); assertEquals(1,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("COMPLETED",response); response=process("suspend=10&suspend2=10",null); assertEquals(2,count(response,"history: suspend")); assertEquals(0,count(response,"history: resume")); assertEquals(2,count(response,"history: onTimeout")); assertEquals(1,count(response,"history: onComplete")); assertContains("TIMEOUT",response); } private int count(String responses,String substring) { int count=0; int i=responses.indexOf(substring); while (i>=0) { count++; i=responses.indexOf(substring,i+substring.length()); } return count; } protected void assertContains(String content,String response) { assertEquals("HTTP/1.1 200 OK",response.substring(0,15)); if (response.indexOf(content,15)<0) { System.err.println(content+" NOT IN '"+response+"'"); assertTrue(false); } } protected void assertNotContains(String content,String response) { assertEquals("HTTP/1.1 200 OK",response.substring(0,15)); if (response.indexOf(content,15)>=0) { System.err.println(content+" IS IN '"+response+"'"); assertTrue(false); } } public synchronized String process(String query,String content) throws Exception { String request = "GET /"; if (query!=null) request+="?"+query; request+=" HTTP/1.1\r\n"+ "Host: localhost\r\n"+ "Connection: close\r\n"; if (content!=null) request+="Content-Length: "+content.length()+"\r\n"; request+="\r\n" + content; Socket socket = new Socket("localhost",_port); socket.getOutputStream().write(request.getBytes("UTF-8")); String response = toString(socket.getInputStream()); return response; } protected abstract String toString(InputStream in) throws IOException; private static class SuspendServlet extends HttpServlet { private Timer _timer=new Timer(); public SuspendServlet() {} /* ------------------------------------------------------------ */ protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final Continuation continuation = ContinuationSupport.getContinuation(request,response); response.addHeader("history",continuation.getClass().toString()); int read_before=0; long sleep_for=-1; long suspend_for=-1; long suspend2_for=-1; long resume_after=-1; long resume2_after=-1; long complete_after=-1; long complete2_after=-1; if (request.getParameter("read")!=null) read_before=Integer.parseInt(request.getParameter("read")); if (request.getParameter("sleep")!=null) sleep_for=Integer.parseInt(request.getParameter("sleep")); if (request.getParameter("suspend")!=null) suspend_for=Integer.parseInt(request.getParameter("suspend")); if (request.getParameter("suspend2")!=null) suspend2_for=Integer.parseInt(request.getParameter("suspend2")); if (request.getParameter("resume")!=null) resume_after=Integer.parseInt(request.getParameter("resume")); if (request.getParameter("resume2")!=null) resume2_after=Integer.parseInt(request.getParameter("resume2")); if (request.getParameter("complete")!=null) complete_after=Integer.parseInt(request.getParameter("complete")); if (request.getParameter("complete2")!=null) complete2_after=Integer.parseInt(request.getParameter("complete2")); if (continuation.isInitial()) { if (read_before>0) { byte[] buf=new byte[read_before]; request.getInputStream().read(buf); } else if (read_before<0) { InputStream in = request.getInputStream(); int b=in.read(); while(b!=-1) b=in.read(); } if (suspend_for>=0) { if (suspend_for>0) continuation.setTimeout(suspend_for); continuation.addContinuationListener(__listener); ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","suspend"); continuation.suspend(); if (complete_after>0) { TimerTask complete = new TimerTask() { public void run() { try { response.setStatus(200); response.getOutputStream().println("COMPLETED\n"); continuation.complete(); } catch(Exception e) { e.printStackTrace(); } } }; synchronized (_timer) { _timer.schedule(complete,complete_after); } } else if (complete_after==0) { response.setStatus(200); response.getOutputStream().println("COMPLETED\n"); continuation.complete(); } else if (resume_after>0) { TimerTask resume = new TimerTask() { public void run() { ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","resume"); continuation.resume(); } }; synchronized (_timer) { _timer.schedule(resume,resume_after); } } else if (resume_after==0) { ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","resume"); continuation.resume(); } } else if (sleep_for>=0) { try { Thread.sleep(sleep_for); } catch (InterruptedException e) { e.printStackTrace(); } response.setStatus(200); response.getOutputStream().println("SLEPT\n"); } else { response.setStatus(200); response.getOutputStream().println("NORMAL\n"); } } else if (suspend2_for>=0 && request.getAttribute("2nd")==null) { request.setAttribute("2nd","cycle"); if (suspend2_for>0) continuation.setTimeout(suspend2_for); // continuation.addContinuationListener(__listener); ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","suspend"); continuation.suspend(); if (complete2_after>0) { TimerTask complete = new TimerTask() { public void run() { try { response.setStatus(200); response.getOutputStream().println("COMPLETED\n"); continuation.complete(); } catch(Exception e) { e.printStackTrace(); } } }; synchronized (_timer) { _timer.schedule(complete,complete2_after); } } else if (complete2_after==0) { response.setStatus(200); response.getOutputStream().println("COMPLETED\n"); continuation.complete(); } else if (resume2_after>0) { TimerTask resume = new TimerTask() { public void run() { ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","resume"); continuation.resume(); } }; synchronized (_timer) { _timer.schedule(resume,resume2_after); } } else if (resume2_after==0) { ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","resume"); continuation.resume(); } return; } else if (continuation.isExpired()) { response.setStatus(200); response.getOutputStream().println("TIMEOUT\n"); } else if (continuation.isResumed()) { response.setStatus(200); response.getOutputStream().println("RESUMED\n"); } else { response.setStatus(200); response.getOutputStream().println("unknown???\n"); } } } private static ContinuationListener __listener = new ContinuationListener() { public void onComplete(Continuation continuation) { ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","onComplete"); } public void onTimeout(Continuation continuation) { ((HttpServletResponse)continuation.getServletResponse()).addHeader("history","onTimeout"); continuation.resume(); } }; }
/* * Copyright 2013 - 2020 Anton Tananaev (anton@traccar.org) * * 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.traccar.protocol; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; import org.traccar.helper.BitUtil; import org.traccar.helper.Checksum; import org.traccar.helper.DateBuilder; import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.helper.UnitsConverter; import org.traccar.model.CellTower; import org.traccar.model.Network; import org.traccar.model.Position; import java.net.SocketAddress; import java.util.regex.Pattern; public class TotemProtocolDecoder extends BaseProtocolDecoder { public TotemProtocolDecoder(Protocol protocol) { super(protocol); } private static final Pattern PATTERN1 = new PatternBuilder() .text("$$") // header .number("xx") // length .number("(d+)|") // imei .expression("(..)") // alarm .text("$GPRMC,") .number("(dd)(dd)(dd).d+,") // time (hhmmss) .expression("([AV]),") // validity .number("(d+)(dd.d+),([NS]),") // latitude .number("(d+)(dd.d+),([EW]),") // longitude .number("(d+.?d*)?,") // speed .number("(d+.?d*)?,") // course .number("(dd)(dd)(dd)") // date (ddmmyy) .expression("[^*]*").text("*") .number("xx|") // checksum .number("(d+.d+)|") // pdop .number("(d+.d+)|") // hdop .number("(d+.d+)|") // vdop .number("(d+)|") // io status .number("d+|") // battery time .number("d") // charged .number("(ddd)") // battery .number("(dddd)|") // power .number("(d+)|").optional() // adc .number("x*(xxxx)") // lac .number("(xxxx)|") // cid .number("(d+)|") // temperature .number("(d+.d+)|") // odometer .number("d+|") // serial number .any() .number("xxxx") // checksum .any() .compile(); private static final Pattern PATTERN2 = new PatternBuilder() .text("$$") // header .number("xx") // length .number("(d+)|") // imei .expression("(..)") // alarm type .number("(dd)(dd)(dd)") // date (ddmmyy) .number("(dd)(dd)(dd)|") // time (hhmmss) .expression("([AV])|") // validity .number("(d+)(dd.d+)|") // latitude .expression("([NS])|") .number("(d+)(dd.d+)|") // longitude .expression("([EW])|") .number("(d+.d+)?|") // speed .number("(d+)?|") // course .number("(d+.d+)|") // hdop .number("(d+)|") // io status .number("d") // charged .number("(dd)") // battery .number("(dd)|") // external power .number("(d+)|") // adc .number("(xxxx)") // lac .number("(xxxx)|") // cid .number("(d+)|") // temperature .number("(d+.d+)|") // odometer .number("d+|") // serial number .number("xxxx") // checksum .any() .compile(); private static final Pattern PATTERN3 = new PatternBuilder() .text("$$") // header .number("xx") // length .number("(d+)|") // imei .expression("(..)") // alarm type .number("(dd)(dd)(dd)") // date (ddmmyy) .number("(dd)(dd)(dd)") // time (hhmmss) .number("(xxxx)") // io status .expression("[01]") // charging .number("(dd)") // battery .number("(dd)") // external power .number("(dddd)") // adc 1 .number("(dddd)") // adc 2 .number("(ddd)") // temperature 1 .number("(ddd)") // temperature 2 .number("(xxxx)") // lac .number("(xxxx)") // cid .expression("([AV])") // validity .number("(dd)") // satellites .number("(ddd)") // course .number("(ddd)") // speed .number("(dd.d)") // pdop .number("(d{7})") // odometer .number("(dd)(dd.dddd)([NS])") // latitude .number("(ddd)(dd.dddd)([EW])") // longitude .number("dddd") // serial number .number("xxxx") // checksum .any() .compile(); private static final Pattern PATTERN4 = new PatternBuilder() .text("$$") // header .number("dddd") // length .number("(xx)") // type .number("(d+)|") // imei .number("(x{8})") // status .number("(dd)(dd)(dd)") // date (yymmdd) .number("(dd)(dd)(dd)") // time (hhmmss) .number("(dd)") // battery .number("(dd)") // external power .number("(dddd)") // adc 1 .groupBegin() .groupBegin() .number("(dddd)") // adc 2 .number("(dddd)") // adc 3 .number("(dddd)") // adc 4 .groupEnd("?") .number("(dddd)") // temperature 1 .number("(dddd)?") // temperature 2 .groupEnd("?") .number("(xxxx)") // lac .number("(xxxx)") // cid .groupBegin() .number("(dd)") // mcc .number("(ddd)") // mnc .groupEnd("?") .number("(dd)") // satellites .number("(dd)") // gsm (rssi) .number("(ddd)") // course .number("(ddd)") // speed .number("(dd.d)") // hdop .number("(d{7})") // odometer .number("(dd)(dd.dddd)([NS])") // latitude .number("(ddd)(dd.dddd)([EW])") // longitude .number("dddd") // serial number .number("xx") // checksum .any() .compile(); private static final Pattern PATTERN_OBD = new PatternBuilder() .text("$$") // header .number("dddd") // length .number("xx") // type .number("(d+)|") // imei .number("(dd)(dd)(dd)") // date (yymmdd) .number("(dd)(dd)(dd),") // time (hhmmss) .number("(-?d+.d+),") // longitude .number("(-?d+.d+),") // latitude .expression("[^,]*,") // obd version .number("(d+),") // odometer .number("(d+),") // fuel used .number("(d+),") // fuel consumption .number("(d+),") // power .number("(d+),") // rpm .number("(d+),") // speed .number("(d+),") // intake flow .number("(d+),") // intake pressure .number("(d+),") // coolant temperature .number("(d+),") // intake temperature .number("(d+),") // engine load .number("(d+),") // throttle .number("(d+),") // fuel .number("|xx") // checksum .any() .compile(); private String decodeAlarm123(int value) { switch (value) { case 0x01: return Position.ALARM_SOS; case 0x10: return Position.ALARM_LOW_BATTERY; case 0x11: return Position.ALARM_OVERSPEED; case 0x30: return Position.ALARM_PARKING; case 0x42: return Position.ALARM_GEOFENCE_EXIT; case 0x43: return Position.ALARM_GEOFENCE_ENTER; default: return null; } } private String decodeAlarm4(int value) { switch (value) { case 0x01: return Position.ALARM_SOS; case 0x02: return Position.ALARM_OVERSPEED; case 0x04: return Position.ALARM_GEOFENCE_EXIT; case 0x05: return Position.ALARM_GEOFENCE_ENTER; case 0x06: return Position.ALARM_TOW; case 0x07: return Position.ALARM_GPS_ANTENNA_CUT; case 0x10: return Position.ALARM_POWER_CUT; case 0x11: return Position.ALARM_POWER_RESTORED; case 0x12: return Position.ALARM_LOW_POWER; case 0x13: return Position.ALARM_LOW_BATTERY; case 0x40: return Position.ALARM_VIBRATION; case 0x41: return Position.ALARM_IDLE; case 0x42: return Position.ALARM_ACCELERATION; case 0x43: return Position.ALARM_BRAKING; default: return null; } } private boolean decode12(Position position, Parser parser, Pattern pattern) { if (parser.hasNext()) { position.set(Position.KEY_ALARM, decodeAlarm123(Short.parseShort(parser.next(), 16))); } DateBuilder dateBuilder = new DateBuilder(); int year = 0, month = 0, day = 0; if (pattern == PATTERN2) { day = parser.nextInt(0); month = parser.nextInt(0); year = parser.nextInt(0); } dateBuilder.setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0)); position.setValid(parser.next().equals("A")); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); position.setSpeed(parser.nextDouble(0)); position.setCourse(parser.nextDouble(0)); if (pattern == PATTERN1) { day = parser.nextInt(0); month = parser.nextInt(0); year = parser.nextInt(0); } if (year == 0) { return false; // ignore invalid data } dateBuilder.setDate(year, month, day); position.setTime(dateBuilder.getDate()); if (pattern == PATTERN1) { position.set(Position.KEY_PDOP, parser.nextDouble()); position.set(Position.KEY_HDOP, parser.nextDouble()); position.set(Position.KEY_VDOP, parser.nextDouble()); } else { position.set(Position.KEY_HDOP, parser.nextDouble()); } int io = parser.nextBinInt(); position.set(Position.KEY_STATUS, io); if (pattern == PATTERN1) { position.set(Position.KEY_ALARM, BitUtil.check(io, 0) ? Position.ALARM_SOS : null); position.set(Position.PREFIX_IN + 3, BitUtil.check(io, 4)); position.set(Position.PREFIX_IN + 4, BitUtil.check(io, 5)); position.set(Position.PREFIX_IN + 1, BitUtil.check(io, 6)); position.set(Position.PREFIX_IN + 2, BitUtil.check(io, 7)); position.set(Position.PREFIX_OUT + 1, BitUtil.check(io, 8)); position.set(Position.PREFIX_OUT + 2, BitUtil.check(io, 9)); position.set(Position.KEY_BATTERY, parser.nextDouble(0) * 0.01); } else { position.set(Position.KEY_ANTENNA, BitUtil.check(io, 0)); position.set(Position.KEY_CHARGE, BitUtil.check(io, 1)); for (int i = 1; i <= 6; i++) { position.set(Position.PREFIX_IN + i, BitUtil.check(io, 1 + i)); } for (int i = 1; i <= 4; i++) { position.set(Position.PREFIX_OUT + i, BitUtil.check(io, 7 + i)); } position.set(Position.KEY_BATTERY, parser.nextDouble(0) * 0.1); } position.set(Position.KEY_POWER, parser.nextDouble(0)); position.set(Position.PREFIX_ADC + 1, parser.next()); int lac = parser.nextHexInt(0); int cid = parser.nextHexInt(0); if (lac != 0 && cid != 0) { position.setNetwork(new Network(CellTower.fromLacCid(lac, cid))); } position.set(Position.PREFIX_TEMP + 1, parser.next()); position.set(Position.KEY_ODOMETER, parser.nextDouble(0) * 1000); return true; } private boolean decode3(Position position, Parser parser) { if (parser.hasNext()) { position.set(Position.KEY_ALARM, decodeAlarm123(Short.parseShort(parser.next(), 16))); } position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS)); position.set(Position.PREFIX_IO + 1, parser.next()); position.set(Position.KEY_BATTERY, parser.nextDouble(0) * 0.1); position.set(Position.KEY_POWER, parser.nextDouble(0)); position.set(Position.PREFIX_ADC + 1, parser.next()); position.set(Position.PREFIX_ADC + 2, parser.next()); position.set(Position.PREFIX_TEMP + 1, parser.next()); position.set(Position.PREFIX_TEMP + 2, parser.next()); position.setNetwork(new Network( CellTower.fromLacCid(parser.nextHexInt(0), parser.nextHexInt(0)))); position.setValid(parser.next().equals("A")); position.set(Position.KEY_SATELLITES, parser.nextInt()); position.setCourse(parser.nextDouble(0)); position.setSpeed(parser.nextDouble(0)); position.set(Position.KEY_PDOP, parser.nextDouble()); position.set(Position.KEY_ODOMETER, parser.nextInt(0) * 1000); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); return true; } private boolean decode4(Position position, Parser parser) { long status = parser.nextHexLong(); position.set(Position.KEY_ALARM, BitUtil.check(status, 32 - 1) ? Position.ALARM_SOS : null); position.set(Position.KEY_IGNITION, BitUtil.check(status, 32 - 2)); position.set(Position.KEY_ALARM, BitUtil.check(status, 32 - 3) ? Position.ALARM_OVERSPEED : null); position.set(Position.KEY_CHARGE, BitUtil.check(status, 32 - 4)); position.set(Position.KEY_ALARM, BitUtil.check(status, 32 - 5) ? Position.ALARM_GEOFENCE_EXIT : null); position.set(Position.KEY_ALARM, BitUtil.check(status, 32 - 6) ? Position.ALARM_GEOFENCE_ENTER : null); position.set(Position.KEY_ALARM, BitUtil.check(status, 32 - 7) ? Position.ALARM_GPS_ANTENNA_CUT : null); position.set(Position.PREFIX_OUT + 1, BitUtil.check(status, 32 - 9)); position.set(Position.PREFIX_OUT + 2, BitUtil.check(status, 32 - 10)); position.set(Position.PREFIX_OUT + 3, BitUtil.check(status, 32 - 11)); position.set(Position.KEY_STATUS, status); // see https://github.com/traccar/traccar/pull/4762 position.setTime(parser.nextDateTime()); position.set(Position.KEY_BATTERY, parser.nextDouble() * 0.1); position.set(Position.KEY_POWER, parser.nextDouble()); position.set(Position.PREFIX_ADC + 1, parser.next()); position.set(Position.PREFIX_ADC + 2, parser.next()); position.set(Position.PREFIX_ADC + 3, parser.next()); position.set(Position.PREFIX_ADC + 4, parser.next()); position.set(Position.PREFIX_TEMP + 1, parser.next()); if (parser.hasNext()) { position.set(Position.PREFIX_TEMP + 2, parser.next()); position.setValid(BitUtil.check(status, 32 - 20)); } else { position.setValid(BitUtil.check(status, 32 - 18)); } int lac = parser.nextHexInt(); int cid = parser.nextHexInt(); CellTower cellTower; if (parser.hasNext(2)) { int mnc = parser.nextInt(); int mcc = parser.nextInt(); cellTower = CellTower.from(mcc, mnc, lac, cid); } else { cellTower = CellTower.fromLacCid(lac, cid); } position.set(Position.KEY_SATELLITES, parser.nextInt()); cellTower.setSignalStrength(parser.nextInt()); position.setNetwork(new Network(cellTower)); position.setCourse(parser.nextDouble()); position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble())); position.set(Position.KEY_HDOP, parser.nextDouble()); position.set(Position.KEY_ODOMETER, parser.nextInt() * 1000); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); return true; } private boolean decodeObd(Position position, Parser parser) { position.setValid(true); position.setTime(parser.nextDateTime()); position.setLatitude(parser.nextDouble()); position.setLongitude(parser.nextDouble()); position.set(Position.KEY_ODOMETER, parser.nextLong()); position.set(Position.KEY_FUEL_USED, parser.nextInt()); position.set(Position.KEY_FUEL_CONSUMPTION, parser.nextInt()); position.set(Position.KEY_POWER, parser.nextInt() * 0.001); position.set(Position.KEY_RPM, parser.nextInt()); position.set(Position.KEY_OBD_SPEED, parser.nextInt()); parser.nextInt(); // intake flow parser.nextInt(); // intake pressure position.set(Position.KEY_COOLANT_TEMP, parser.nextInt()); position.set("intakeTemp", parser.nextInt()); position.set(Position.KEY_ENGINE_LOAD, parser.nextInt()); position.set(Position.KEY_THROTTLE, parser.nextInt()); position.set(Position.KEY_FUEL_LEVEL, parser.nextInt()); return true; } @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { String sentence = (String) msg; Pattern pattern = PATTERN3; if (sentence.contains("$Cloud")) { pattern = PATTERN_OBD; } else if (sentence.charAt(2) == '0') { pattern = PATTERN4; } else if (sentence.contains("$GPRMC")) { pattern = PATTERN1; } else { int index = sentence.indexOf('|'); if (index != -1 && sentence.indexOf('|', index + 1) != -1) { pattern = PATTERN2; } } Parser parser = new Parser(pattern, sentence); if (!parser.matches()) { return null; } Position position = new Position(getProtocolName()); if (pattern == PATTERN4) { position.set(Position.KEY_ALARM, decodeAlarm4(parser.nextHexInt())); } DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } position.setDeviceId(deviceSession.getDeviceId()); boolean result; if (pattern == PATTERN1 || pattern == PATTERN2) { result = decode12(position, parser, pattern); } else if (pattern == PATTERN3) { result = decode3(position, parser); } else if (pattern == PATTERN4) { result = decode4(position, parser); } else { result = decodeObd(position, parser); } if (channel != null) { if (pattern == PATTERN4) { String response = "$$0014AA" + sentence.substring(sentence.length() - 6, sentence.length() - 2); response += String.format("%02X", Checksum.xor(response)).toUpperCase(); channel.writeAndFlush(new NetworkMessage(response, remoteAddress)); } else { channel.writeAndFlush(new NetworkMessage("ACK OK\r\n", remoteAddress)); } } return result ? position : null; } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.test.cmmn.handler; import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_ACTIVITY_DESCRIPTION; import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_ACTIVITY_TYPE; import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_DISCRETIONARY; import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_REQUIRED_RULE; 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 org.camunda.bpm.engine.impl.cmmn.CaseControlRule; import org.camunda.bpm.engine.impl.cmmn.behavior.CmmnActivityBehavior; import org.camunda.bpm.engine.impl.cmmn.behavior.MilestoneActivityBehavior; import org.camunda.bpm.engine.impl.cmmn.handler.MilestoneItemHandler; import org.camunda.bpm.engine.impl.cmmn.model.CmmnActivity; import org.camunda.bpm.engine.impl.cmmn.model.CmmnCaseDefinition; import org.camunda.bpm.model.cmmn.Cmmn; import org.camunda.bpm.model.cmmn.impl.instance.Body; import org.camunda.bpm.model.cmmn.impl.instance.ConditionExpression; import org.camunda.bpm.model.cmmn.impl.instance.DefaultControl; import org.camunda.bpm.model.cmmn.impl.instance.ItemControl; import org.camunda.bpm.model.cmmn.instance.DiscretionaryItem; import org.camunda.bpm.model.cmmn.instance.Milestone; import org.camunda.bpm.model.cmmn.instance.PlanItemControl; import org.camunda.bpm.model.cmmn.instance.PlanningTable; import org.camunda.bpm.model.cmmn.instance.RequiredRule; import org.junit.Before; import org.junit.Test; /** * @author Roman Smirnov * */ public class MilestoneDiscretionaryItemHandlerTest extends CmmnElementHandlerTest { protected Milestone milestone; protected PlanningTable planningTable; protected DiscretionaryItem discretionaryItem; protected MilestoneItemHandler handler = new MilestoneItemHandler(); @Before public void setUp() { milestone = createElement(casePlanModel, "aMilestone", Milestone.class); planningTable = createElement(casePlanModel, "aPlanningTable", PlanningTable.class); discretionaryItem = createElement(planningTable, "DI_aMilestone", DiscretionaryItem.class); discretionaryItem.setDefinition(milestone); } @Test public void testMilestoneActivityName() { // given: // the Milestone has a name "A Milestone" String name = "A Milestone"; milestone.setName(name); // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then assertEquals(name, activity.getName()); } @Test public void testMilestoneActivityType() { // given // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then String activityType = (String) activity.getProperty(PROPERTY_ACTIVITY_TYPE); assertEquals("milestone", activityType); } @Test public void testMilestoneDescription() { // given String description = "This is a milestone"; milestone.setDescription(description); // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then assertEquals(description, activity.getProperty(PROPERTY_ACTIVITY_DESCRIPTION)); } @Test public void testDiscretionaryItemDescription() { // given String description = "This is a discretionaryItem"; discretionaryItem.setDescription(description); // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then assertEquals(description, activity.getProperty(PROPERTY_ACTIVITY_DESCRIPTION)); } @Test public void testActivityBehavior() { // given: a planItem // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then CmmnActivityBehavior behavior = activity.getActivityBehavior(); assertTrue(behavior instanceof MilestoneActivityBehavior); } @Test public void testIsDiscretionaryProperty() { // given: // a discretionary item to handle // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then Boolean discretionary = (Boolean) activity.getProperty(PROPERTY_DISCRETIONARY); assertTrue(discretionary); } @Test public void testWithoutParent() { // given: a planItem // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then assertNull(activity.getParent()); } @Test public void testWithParent() { // given: // a new activity as parent CmmnCaseDefinition parent = new CmmnCaseDefinition("aParentActivity"); context.setParent(parent); // when CmmnActivity activity = handler.handleElement(discretionaryItem, context); // then assertEquals(parent, activity.getParent()); assertTrue(parent.getActivities().contains(activity)); } @Test public void testRequiredRule() { // given ItemControl itemControl = createElement(discretionaryItem, "ItemControl_1", ItemControl.class); RequiredRule requiredRule = createElement(itemControl, "RequiredRule_1", RequiredRule.class); ConditionExpression expression = createElement(requiredRule, "Expression_1", ConditionExpression.class); Body body = createElement(expression, Body.class); body.setTextContent("${true}"); Cmmn.validateModel(modelInstance); // when CmmnActivity newActivity = handler.handleElement(discretionaryItem, context); // then Object rule = newActivity.getProperty(PROPERTY_REQUIRED_RULE); assertNotNull(rule); assertTrue(rule instanceof CaseControlRule); } @Test public void testRequiredRuleByDefaultPlanItemControl() { // given PlanItemControl defaultControl = createElement(milestone, "ItemControl_1", DefaultControl.class); RequiredRule requiredRule = createElement(defaultControl, "RequiredRule_1", RequiredRule.class); ConditionExpression expression = createElement(requiredRule, "Expression_1", ConditionExpression.class); Body body = createElement(expression, Body.class); body.setTextContent("${true}"); Cmmn.validateModel(modelInstance); // when CmmnActivity newActivity = handler.handleElement(discretionaryItem, context); // then Object rule = newActivity.getProperty(PROPERTY_REQUIRED_RULE); assertNotNull(rule); assertTrue(rule instanceof CaseControlRule); } }
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * Copyright 2017-2018 Ilya Malanin * Copyright 2017-2019 Eric Bishton * * 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.plugins.haxe.lang.psi; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.util.Key; import com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes; import com.intellij.plugins.haxe.model.*; import com.intellij.plugins.haxe.model.type.HaxeGenericResolver; import com.intellij.plugins.haxe.util.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNameHelper; import com.intellij.psi.ResolveState; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.plugins.haxe.util.HaxeStringUtil.elide; /** * @author: Fedor.Korotkov */ public class HaxeResolver implements ResolveCache.AbstractResolver<HaxeReference, List<? extends PsiElement>> { public static final int MAX_DEBUG_MESSAGE_LENGTH = 200; private static HaxeDebugLogger LOG = HaxeDebugLogger.getLogger(); //static { // Remove when finished debugging. // LOG.setLevel(Level.DEBUG); // LOG.debug(" ========= Starting up debug logger for HaxeResolver. =========="); //} public static final HaxeResolver INSTANCE = new HaxeResolver(); public static ThreadLocal<Boolean> isExtension = new ThreadLocal<>().withInitial(()->new Boolean(false)); private static boolean reportCacheMetrics = false; // Should always be false when checked in. private static AtomicInteger dumbRequests = new AtomicInteger(0); private static AtomicInteger requests = new AtomicInteger(0); private static AtomicInteger resolves = new AtomicInteger(0); private final static int REPORT_FREQUENCY = 100; @Override public List<? extends PsiElement> resolve(@NotNull HaxeReference reference, boolean incompleteCode) { // Set this true when debugging the resolver. boolean skipCachingForDebug = false; // Should always be false when checked in. // If we are in dumb mode (e.g. we are still indexing files and resolving may // fail until the indices are complete), we don't want to cache the (likely incorrect) // results. boolean isDumb = DumbService.isDumb(reference.getProject()); boolean skipCaching = skipCachingForDebug || isDumb; List<? extends PsiElement> elements = skipCaching ? doResolve(reference, incompleteCode) : ResolveCache.getInstance(reference.getProject()).resolveWithCaching( reference, this::doResolve,true, incompleteCode); if (reportCacheMetrics) { if (skipCachingForDebug) { LOG.debug("Resolve cache is disabled. No metrics computed."); reportCacheMetrics = false; } else { int dumb = isDumb ? dumbRequests.incrementAndGet() : dumbRequests.get(); int requestCount = isDumb ? requests.get() : requests.incrementAndGet(); if ((dumb + requestCount) % REPORT_FREQUENCY == 0) { int res = resolves.get(); Formatter formatter = new Formatter(); formatter.format("Resolve requests: %d; cache misses: %d; (%2.2f%% effective); Dumb requests: %d", requestCount, res, (1.0 - (Float.intBitsToFloat(res)/Float.intBitsToFloat(requestCount))) * 100, dumb); LOG.debug(formatter.toString()); } } } return elements; } private List<? extends PsiElement> doResolve(@NotNull HaxeReference reference, boolean incompleteCode) { if (LOG.isTraceEnabled()) LOG.trace(traceMsg("-----------------------------------------")); if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Resolving reference: " + reference.getText())); isExtension.set(false); if (reportCacheMetrics) { resolves.incrementAndGet(); } List<? extends PsiElement> result = checkIsType(reference); if (result == null) result = checkIsFullyQualifiedStatement(reference); if (result == null) result = checkIsSuperExpression(reference); if (result == null) result = checkIsClassName(reference); if (result == null) result = checkIsChain(reference); if (result == null) result = checkIsAccessor(reference); if (result == null) result = checkByTreeWalk(reference); if (result == null) { // try super field List<? extends PsiElement> superElements = resolveByClassAndSymbol(PsiTreeUtil.getParentOfType(reference, HaxeClass.class), reference); if (!superElements.isEmpty()) { LogResolution(reference, "via super field."); return superElements; } HaxeFileModel fileModel = HaxeFileModel.fromElement(reference); if (fileModel != null) { String className = reference.getText(); PsiElement target = HaxeResolveUtil.searchInSameFile(fileModel, className); if (target == null) target = HaxeResolveUtil.searchInImports(fileModel, className); if (target == null) target = HaxeResolveUtil.searchInSamePackage(fileModel, className); if (target != null) { return asList(target); } } if (PsiNameHelper.getInstance(reference.getProject()).isQualifiedName(reference.getText())) { List<HaxeModel> resolvedPackage = HaxeProjectModel.fromElement(reference).resolve(new FullyQualifiedInfo(reference.getText()), reference.getResolveScope()); if (resolvedPackage != null && !resolvedPackage.isEmpty() && resolvedPackage.get(0) instanceof HaxePackageModel) { LogResolution(reference, "via project qualified name."); return Collections.singletonList(resolvedPackage.get(0).getBasePsi()); } } } LogResolution(reference, "failed after exhausting all options."); return result == null ? ContainerUtil.emptyList() : result; } private List<? extends PsiElement> checkByTreeWalk(HaxeReference reference) { final List<PsiElement> result = new ArrayList<>(); PsiTreeUtil.treeWalkUp(new ResolveScopeProcessor(result, reference.getText()), reference, null, new ResolveState()); if (result.isEmpty()) return null; LogResolution(reference, "via tree walk."); return result; } private List<? extends PsiElement> checkIsAccessor(HaxeReference reference) { if (reference instanceof HaxePropertyAccessor) { final HaxeAccessorType accessorType = HaxeAccessorType.fromPsi(reference); if (accessorType != HaxeAccessorType.GET && accessorType != HaxeAccessorType.SET) return null; final HaxeFieldDeclaration varDeclaration = PsiTreeUtil.getParentOfType(reference, HaxeFieldDeclaration.class); if (varDeclaration == null) return null; final HaxeFieldModel fieldModel = new HaxeFieldModel(varDeclaration); final HaxeMethodModel method = accessorType == HaxeAccessorType.GET ? fieldModel.getGetterMethod() : fieldModel.getSetterMethod(); if (method != null) { return asList(method.getBasePsi()); } } return null; } @Nullable private List<? extends PsiElement> checkIsChain(@NotNull HaxeReference reference) { final HaxeReference leftReference = HaxeResolveUtil.getLeftReference(reference); if (leftReference != null) { List<? extends PsiElement> result = resolveChain(leftReference, reference); if (result != null && !result.isEmpty()) { LogResolution(reference, "via simple chain using leftReference."); return result; } LogResolution(reference, "via simple chain against package."); PsiElement item = resolveQualifiedReference(reference); if (item != null) { return asList(item); } } return null; } @Nullable private List<? extends PsiElement> checkIsClassName(@NotNull HaxeReference reference) { final HaxeClass resultClass = HaxeResolveUtil.tryResolveClassByQName(reference); if (resultClass != null) { LogResolution(reference, "via class qualified name."); return asList(resultClass.getComponentName()); } return null; } @Nullable private List<? extends PsiElement> checkIsSuperExpression(HaxeReference reference) { if (reference instanceof HaxeSuperExpression && reference.getParent() instanceof HaxeCallExpression) { final HaxeClass haxeClass = PsiTreeUtil.getParentOfType(reference, HaxeClass.class); assert haxeClass != null; if (!haxeClass.getHaxeExtendsList().isEmpty()) { final HaxeExpression superExpression = haxeClass.getHaxeExtendsList().get(0).getReferenceExpression(); final HaxeClass superClass = ((HaxeReference)superExpression).resolveHaxeClass().getHaxeClass(); final HaxeNamedComponent constructor = ((superClass == null) ? null : superClass.findHaxeMethodByName(HaxeTokenTypes.ONEW.toString())); LogResolution(reference, "because it's a super expression."); return asList(((constructor != null) ? constructor : superClass)); } } return null; } @Nullable private List<? extends PsiElement> checkIsType(HaxeReference reference) { final HaxeType type = PsiTreeUtil.getParentOfType(reference, HaxeType.class); final HaxeClass haxeClassInType = HaxeResolveUtil.tryResolveClassByQName(type); if (type != null && haxeClassInType != null) { LogResolution(reference, "via parent type name."); return asList(haxeClassInType.getComponentName()); } return null; } private List<? extends PsiElement> checkIsFullyQualifiedStatement(@NotNull HaxeReference reference) { if (PsiTreeUtil.getParentOfType(reference, HaxePackageStatement.class, HaxeImportStatement.class, HaxeUsingStatement.class) != null && reference instanceof HaxeReferenceExpression) { LogResolution(reference, "via parent/package import."); return asList(resolveQualifiedReference((HaxeReferenceExpression)reference)); } return null; } private static void LogResolution(HaxeReference ref, String tailmsg) { // Debug is always enabled if trace is enabled. if (LOG.isDebugEnabled()) { String message = "Resolved " + (ref == null ? "empty result" : ref.getText()) + " " + elide(tailmsg, MAX_DEBUG_MESSAGE_LENGTH); if (LOG.isTraceEnabled()) { LOG.traceAs(HaxeDebugUtil.getCallerStackFrame(), message); } else { LOG.debug(message); } } } /** * Resolve a chain reference, given two references: the qualifier, and the name. * * @param lefthandExpression - qualifying expression (e.g. "((ref = reference).getProject())") * @param reference - field/method name to resolve. * @return the resolved element, if found; null, otherwise. */ @Nullable private List<? extends PsiElement> resolveChain(HaxeReference lefthandExpression, HaxeReference reference) { String identifier = reference instanceof HaxeReferenceExpression ? ((HaxeReferenceExpression)reference).getIdentifier().getText() : reference.getText(); HaxeClassResolveResult leftExpression = lefthandExpression.resolveHaxeClass(); if (leftExpression.getHaxeClass() != null) { HaxeMemberModel member = leftExpression.getHaxeClass().getModel().getMember(identifier); if (member != null) { return Collections.singletonList(member.getBasePsi()); } } if (LOG.isTraceEnabled()) LOG.trace(traceMsg(null)); final HaxeComponentName componentName = tryResolveHelperClass(lefthandExpression, identifier); if (componentName != null) { if (LOG.isTraceEnabled()) LOG.trace("Found component " + componentName.getText()); return Collections.singletonList(componentName); } if (LOG.isTraceEnabled()) LOG.trace(traceMsg("trying keywords (super, new) arrays, literals, etc.")); // Try resolving keywords (super, new), arrays, literals, etc. return resolveByClassAndSymbol(lefthandExpression.resolveHaxeClass(), reference); } private PsiElement resolveQualifiedReference(HaxeReference reference) { String qualifiedName = reference.getText(); final FullyQualifiedInfo qualifiedInfo = new FullyQualifiedInfo(qualifiedName); List<HaxeModel> result = HaxeProjectModel.fromElement(reference).resolve(qualifiedInfo, reference.getResolveScope()); if (result != null && !result.isEmpty()) { HaxeModel item = result.get(0); if (item instanceof HaxeFileModel) { HaxeClassModel mainClass = ((HaxeFileModel)item).getMainClassModel(); if (mainClass != null) { return mainClass.getBasePsi(); } } return item.getBasePsi(); } return null; } /** * Test if the leftReference is a class name (either locally or in a super-class), * and if so, find the named field/method declared inside of it. * * If the leftReference is to a file, and helperName is a class, we return the name * of that class. * * @param leftReference - a potential class/file name. * @param helperName - the field/method/class to find. * @return the name of the found field/method/class. null if not found. */ @Nullable private HaxeComponentName tryResolveHelperClass(HaxeReference leftReference, String helperName) { if (LOG.isTraceEnabled()) LOG.trace(traceMsg("leftReference=" + leftReference + " helperName=" + helperName)); HaxeComponentName componentName = null; HaxeClass leftResultClass = HaxeResolveUtil.tryResolveClassByQName(leftReference); if (leftResultClass != null) { if (LOG.isTraceEnabled()) { LOG.trace(traceMsg("Found a left result via QName: " + (leftResultClass.getText() != null ? leftResultClass : "<no text>"))); } // helper reference via class com.bar.FooClass.HelperClass final HaxeClass componentDeclaration = HaxeResolveUtil.findComponentDeclaration(leftResultClass.getContainingFile(), helperName); componentName = componentDeclaration == null ? null : componentDeclaration.getComponentName(); } else { // try to find component at abstract forwarding underlying class HaxeClassResolveResult resolveResult = leftReference.resolveHaxeClass(); leftResultClass = resolveResult.getHaxeClass(); if (LOG.isTraceEnabled()) { String resultClassName = leftResultClass != null ? leftResultClass.getText() : null; LOG.trace(traceMsg("Found abstract left result:" + (resultClassName != null ? resultClassName : "<no text>"))); } if (leftResultClass != null) { HaxeClassModel model = leftResultClass.getModel(); if(model.isTypedef()) { // Resolve to the underlying type. HaxeClassResolveResult result = fullyResolveTypedef(leftResultClass, resolveResult.getSpecialization()); if (null != result.getHaxeClass()) { model = result.getHaxeClass().getModel(); } } HaxeMemberModel member = model.getMember(helperName); if (member != null) return member.getNamePsi(); if (model.isAbstract() && ((HaxeAbstractClassModel)model).hasForwards()) { HaxeGenericResolver resolver = resolveResult.getSpecialization().toGenericResolver(leftResultClass); final List<HaxeNamedComponent> forwardingHaxeNamedComponents = HaxeAbstractForwardUtil.findAbstractForwardingNamedSubComponents(leftResultClass, resolver); if (forwardingHaxeNamedComponents != null) { for (HaxeNamedComponent namedComponent : forwardingHaxeNamedComponents) { final HaxeComponentName forwardingComponentName = namedComponent.getComponentName(); if (forwardingComponentName != null && forwardingComponentName.getText().equals(helperName)) { componentName = forwardingComponentName; break; } } } } } } if (LOG.isTraceEnabled()) { String ctext = componentName != null ? componentName.getText() : null; if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Found component name " + (ctext != null ? ctext : "<no text>"))); } return componentName; } @NotNull private static HaxeClassResolveResult fullyResolveTypedef(@Nullable HaxeClass typedef, @Nullable HaxeGenericSpecialization specialization) { if (null == typedef) return HaxeClassResolveResult.EMPTY; HashSet<String> recursionGuard = new HashSet<>(); // Track which typedefs we've already resolved so we don't end up in an infinite loop. HaxeClassResolveResult result = HaxeClassResolveResult.EMPTY; HaxeClassModel model = typedef.getModel(); while (null != model && model.isTypedef() && !recursionGuard.contains(model.getName())) { recursionGuard.add(model.getName()); final HaxeTypeOrAnonymous toa = model.getUnderlyingType(); final HaxeType type = toa.getType(); if (null == type) { // Anonymous structure result = HaxeClassResolveResult.create(toa.getAnonymousType(), specialization); break; } // If the reference is to a type parameter, resolve that instead. HaxeClassResolveResult nakedResult = specialization.get(type, type.getReferenceExpression().getIdentifier().getText()); if (null == nakedResult) { nakedResult = type.getReferenceExpression().resolveHaxeClass(); } result = HaxeClassResolveResult.create(nakedResult.getHaxeClass(), specialization); model = null != result.getHaxeClass() ? result.getHaxeClass().getModel() : null; } return result; } private static List<? extends PsiElement> asList(@Nullable PsiElement element) { if (LOG.isDebugEnabled()) LOG.debug("Resolved as " + (element == null ? "empty result list." : elide(element.toString(), MAX_DEBUG_MESSAGE_LENGTH))); return element == null ? Collections.emptyList() : Collections.singletonList(element); } private static List<? extends PsiElement> resolveByClassAndSymbol(@Nullable HaxeClassResolveResult resolveResult, @NotNull HaxeReference reference) { if (resolveResult == null) { if (LOG.isDebugEnabled()) LogResolution(null, "(resolveByClassAndSymbol)"); } return resolveResult == null ? Collections.<PsiElement>emptyList() : resolveByClassAndSymbol(resolveResult.getHaxeClass(), reference); } private static List<? extends PsiElement> resolveByClassAndSymbol(@Nullable HaxeClass leftClass, @NotNull HaxeReference reference) { if (leftClass != null) { final HaxeClassModel classModel = leftClass.getModel(); HaxeMemberModel member = classModel.getMember(reference.getReferenceName()); if (member != null) return asList(member.getNamePsi()); // if class is abstract try find in forwards if (leftClass.isAbstract()) { HaxeAbstractClassModel model = (HaxeAbstractClassModel)leftClass.getModel(); if (model.isForwarded(reference.getReferenceName())) { final HaxeClass underlyingClass = model.getUnderlyingClass(reference.getSpecialization().toGenericResolver(leftClass)); if (underlyingClass != null) { member = underlyingClass.getModel().getMember(reference.getReferenceName()); if (member != null) { return asList(member.getNamePsi()); } } } } // try find using HaxeFileModel fileModel = HaxeFileModel.fromElement(reference); if (fileModel != null) { for (HaxeUsingModel model : fileModel.getUsingModels()) { HaxeMethodModel method = model.findExtensionMethod(reference.getReferenceName(), leftClass); if (method != null) { isExtension.set(true); return asList(method.getNamePsi()); } } } } return Collections.emptyList(); } private String traceMsg(String msg) { return HaxeDebugUtil.traceMessage(msg, 120); } private class ResolveScopeProcessor implements PsiScopeProcessor { private final List<PsiElement> result; final String name; private ResolveScopeProcessor(List<PsiElement> result, String name) { this.result = result; this.name = name; } @Override public boolean execute(@NotNull PsiElement element, ResolveState state) { HaxeComponentName componentName = null; if (element instanceof HaxeNamedComponent) { componentName = ((HaxeNamedComponent)element).getComponentName(); } else if (element instanceof HaxeOpenParameterList) { componentName = ((HaxeOpenParameterList)element).getComponentName(); } if (componentName != null && name.equals(componentName.getText())) { result.add(componentName); return false; } return true; } @Override public <T> T getHint(@NotNull Key<T> hintKey) { return null; } @Override public void handleEvent(Event event, @Nullable Object associated) { } } }
/* * 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 io.prestosql.benchmark; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import io.airlift.units.DataSize; import io.prestosql.benchmark.HandTpchQuery1.TpchQuery1Operator.TpchQuery1OperatorFactory; import io.prestosql.metadata.Metadata; import io.prestosql.operator.DriverContext; import io.prestosql.operator.HashAggregationOperator.HashAggregationOperatorFactory; import io.prestosql.operator.Operator; import io.prestosql.operator.OperatorContext; import io.prestosql.operator.OperatorFactory; import io.prestosql.operator.aggregation.InternalAggregationFunction; import io.prestosql.spi.Page; import io.prestosql.spi.PageBuilder; import io.prestosql.spi.block.Block; import io.prestosql.spi.type.Type; import io.prestosql.sql.gen.JoinCompiler; import io.prestosql.sql.planner.plan.AggregationNode.Step; import io.prestosql.sql.planner.plan.PlanNodeId; import io.prestosql.sql.tree.QualifiedName; import io.prestosql.testing.LocalQueryRunner; import io.prestosql.util.DateTimeUtils; import java.util.List; import java.util.Optional; import static com.google.common.base.Preconditions.checkState; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static io.prestosql.benchmark.BenchmarkQueryRunner.createLocalQueryRunner; import static io.prestosql.spi.type.BigintType.BIGINT; import static io.prestosql.spi.type.DateType.DATE; import static io.prestosql.spi.type.DoubleType.DOUBLE; import static io.prestosql.spi.type.VarcharType.VARCHAR; import static io.prestosql.sql.analyzer.TypeSignatureProvider.fromTypes; import static java.lang.Math.toIntExact; import static java.util.Objects.requireNonNull; public class HandTpchQuery1 extends AbstractSimpleOperatorBenchmark { private final InternalAggregationFunction longAverage; private final InternalAggregationFunction doubleAverage; private final InternalAggregationFunction doubleSum; private final InternalAggregationFunction countFunction; public HandTpchQuery1(LocalQueryRunner localQueryRunner) { super(localQueryRunner, "hand_tpch_query_1", 1, 5); Metadata metadata = localQueryRunner.getMetadata(); longAverage = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(QualifiedName.of("avg"), fromTypes(BIGINT))); doubleAverage = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(QualifiedName.of("avg"), fromTypes(DOUBLE))); doubleSum = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(QualifiedName.of("sum"), fromTypes(DOUBLE))); countFunction = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(QualifiedName.of("count"), ImmutableList.of())); } @Override protected List<? extends OperatorFactory> createOperatorFactories() { // select // returnflag, // linestatus, // sum(quantity) as sum_qty, // sum(extendedprice) as sum_base_price, // sum(extendedprice * (1 - discount)) as sum_disc_price, // sum(extendedprice * (1 - discount) * (1 + tax)) as sum_charge, // avg(quantity) as avg_qty, // avg(extendedprice) as avg_price, // avg(discount) as avg_disc, // count(*) as count_order // from // lineitem // where // shipdate <= '1998-09-02' // group by // returnflag, // linestatus // order by // returnflag, // linestatus OperatorFactory tableScanOperator = createTableScanOperator( 0, new PlanNodeId("test"), "lineitem", "returnflag", "linestatus", "quantity", "extendedprice", "discount", "tax", "shipdate"); TpchQuery1OperatorFactory tpchQuery1Operator = new TpchQuery1OperatorFactory(1); HashAggregationOperatorFactory aggregationOperator = new HashAggregationOperatorFactory( 2, new PlanNodeId("test"), getColumnTypes("lineitem", "returnflag", "linestatus"), Ints.asList(0, 1), ImmutableList.of(), Step.SINGLE, ImmutableList.of( doubleSum.bind(ImmutableList.of(2), Optional.empty()), doubleSum.bind(ImmutableList.of(3), Optional.empty()), doubleSum.bind(ImmutableList.of(4), Optional.empty()), longAverage.bind(ImmutableList.of(2), Optional.empty()), doubleAverage.bind(ImmutableList.of(5), Optional.empty()), doubleAverage.bind(ImmutableList.of(6), Optional.empty()), countFunction.bind(ImmutableList.of(2), Optional.empty())), Optional.empty(), Optional.empty(), 10_000, Optional.of(DataSize.of(16, MEGABYTE)), new JoinCompiler(localQueryRunner.getTypeOperators()), localQueryRunner.getBlockTypeOperators(), false); return ImmutableList.of(tableScanOperator, tpchQuery1Operator, aggregationOperator); } public static class TpchQuery1Operator implements io.prestosql.operator.Operator // TODO: use import when Java 7 compiler bug is fixed { private static final ImmutableList<Type> TYPES = ImmutableList.of( VARCHAR, VARCHAR, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE); public static class TpchQuery1OperatorFactory implements OperatorFactory { private final int operatorId; public TpchQuery1OperatorFactory(int operatorId) { this.operatorId = operatorId; } @Override public Operator createOperator(DriverContext driverContext) { OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, new PlanNodeId("test"), TpchQuery1Operator.class.getSimpleName()); return new TpchQuery1Operator(operatorContext); } @Override public void noMoreOperators() { } @Override public OperatorFactory duplicate() { throw new UnsupportedOperationException(); } } private final OperatorContext operatorContext; private final PageBuilder pageBuilder; private boolean finishing; public TpchQuery1Operator(OperatorContext operatorContext) { this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.pageBuilder = new PageBuilder(TYPES); } @Override public OperatorContext getOperatorContext() { return operatorContext; } @Override public void finish() { finishing = true; } @Override public boolean isFinished() { return finishing && pageBuilder.isEmpty(); } @Override public boolean needsInput() { return !pageBuilder.isFull(); } @Override public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!pageBuilder.isFull(), "Output buffer is full"); checkState(!finishing, "Operator is finished"); filterAndProjectRowOriented(pageBuilder, page.getBlock(0), page.getBlock(1), page.getBlock(2), page.getBlock(3), page.getBlock(4), page.getBlock(5), page.getBlock(6)); } @Override public Page getOutput() { // only return a page if the page buffer isFull or we are finishing and the page buffer has data if (pageBuilder.isFull() || (finishing && !pageBuilder.isEmpty())) { Page page = pageBuilder.build(); pageBuilder.reset(); return page; } return null; } private static final int MAX_SHIP_DATE = DateTimeUtils.parseDate("1998-09-02"); private static void filterAndProjectRowOriented( PageBuilder pageBuilder, Block returnFlagBlock, Block lineStatusBlock, Block quantityBlock, Block extendedPriceBlock, Block discountBlock, Block taxBlock, Block shipDateBlock) { int rows = returnFlagBlock.getPositionCount(); for (int position = 0; position < rows; position++) { if (shipDateBlock.isNull(position)) { continue; } int shipDate = toIntExact(DATE.getLong(shipDateBlock, position)); // where // shipdate <= '1998-09-02' if (shipDate <= MAX_SHIP_DATE) { // returnflag, // linestatus // quantity // extendedprice // extendedprice * (1 - discount) // extendedprice * (1 - discount) * (1 + tax) // discount pageBuilder.declarePosition(); if (returnFlagBlock.isNull(position)) { pageBuilder.getBlockBuilder(0).appendNull(); } else { VARCHAR.appendTo(returnFlagBlock, position, pageBuilder.getBlockBuilder(0)); } if (lineStatusBlock.isNull(position)) { pageBuilder.getBlockBuilder(1).appendNull(); } else { VARCHAR.appendTo(lineStatusBlock, position, pageBuilder.getBlockBuilder(1)); } double quantity = DOUBLE.getDouble(quantityBlock, position); double extendedPrice = DOUBLE.getDouble(extendedPriceBlock, position); double discount = DOUBLE.getDouble(discountBlock, position); double tax = DOUBLE.getDouble(taxBlock, position); boolean quantityIsNull = quantityBlock.isNull(position); boolean extendedPriceIsNull = extendedPriceBlock.isNull(position); boolean discountIsNull = discountBlock.isNull(position); boolean taxIsNull = taxBlock.isNull(position); if (quantityIsNull) { pageBuilder.getBlockBuilder(2).appendNull(); } else { DOUBLE.writeDouble(pageBuilder.getBlockBuilder(2), quantity); } if (extendedPriceIsNull) { pageBuilder.getBlockBuilder(3).appendNull(); } else { DOUBLE.writeDouble(pageBuilder.getBlockBuilder(3), extendedPrice); } if (extendedPriceIsNull || discountIsNull) { pageBuilder.getBlockBuilder(4).appendNull(); } else { DOUBLE.writeDouble(pageBuilder.getBlockBuilder(4), extendedPrice * (1 - discount)); } if (extendedPriceIsNull || discountIsNull || taxIsNull) { pageBuilder.getBlockBuilder(5).appendNull(); } else { DOUBLE.writeDouble(pageBuilder.getBlockBuilder(5), extendedPrice * (1 - discount) * (1 + tax)); } if (discountIsNull) { pageBuilder.getBlockBuilder(6).appendNull(); } else { DOUBLE.writeDouble(pageBuilder.getBlockBuilder(6), discount); } } } } } public static void main(String[] args) { new HandTpchQuery1(createLocalQueryRunner()).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out)); } }
package com.pg85.otg.interfaces; import java.util.List; import com.pg85.otg.constants.SettingsEnums.GrassColorModifier; import com.pg85.otg.constants.SettingsEnums.MineshaftType; import com.pg85.otg.constants.SettingsEnums.OceanRuinsType; import com.pg85.otg.constants.SettingsEnums.RareBuildingType; import com.pg85.otg.constants.SettingsEnums.RuinedPortalType; import com.pg85.otg.constants.SettingsEnums.VillageType; import com.pg85.otg.util.biome.ColorSet; import com.pg85.otg.util.biome.ReplaceBlockMatrix; import com.pg85.otg.util.biome.WeightedMobSpawnGroup; import com.pg85.otg.util.gen.ChunkBuffer; import com.pg85.otg.util.gen.GeneratingChunk; import com.pg85.otg.util.materials.LocalMaterialData; import com.pg85.otg.util.minecraft.SaplingType; /** * BiomeConfig (*.bc) classes * * IBiomeConfig defines anything that's used/exposed between projects. * BiomeConfigBase implements anything needed for IBiomeConfig. * BiomeConfig contains only fields/methods used for io/serialisation/instantiation. * * BiomeConfig should be used only in common-core and platform-specific layers, when reading/writing settings on app start. * IBiomeConfig should be used wherever settings are used in code. */ public interface IBiomeConfig { // Misc String getName(); IBiomeResourceLocation getRegistryKey(); void setOTGBiomeId(int id); int getOTGBiomeId(); void setRegistryKey(IBiomeResourceLocation registryKey); // WorldConfig getters // TODO: Ideally, don't contain worldConfig within biomeconfig, // use a parent object that holds both, like a worldgenregion. boolean biomeConfigsHaveReplacement(); double getFractureHorizontal(); double getFractureVertical(); boolean isFlatBedrock(); boolean isCeilingBedrock(); boolean isBedrockDisabled(); boolean isRemoveSurfaceStone(); // Inheritance List<String> getBiomeDictTags(); String getBiomeCategory(); boolean getIsTemplateForBiome(); // Placement int getBiomeSize(); int getBiomeRarity(); int getBiomeColor(); boolean isIsleBiome(); List<String> getIsleInBiomes(); int getBiomeSizeWhenIsle(); int getBiomeRarityWhenIsle(); boolean isBorderBiome(); List<String> getBorderInBiomes(); List<String> getOnlyBorderNearBiomes(); List<String> getNotBorderNearBiomes(); int getBiomeSizeWhenBorder(); // Height / volatility float getBiomeHeight(); float getBiomeVolatility(); int getSmoothRadius(); int getCHCSmoothRadius(); double getMaxAverageDepth(); double getMaxAverageHeight(); double getVolatility1(); double getVolatility2(); double getVolatilityWeight1(); double getVolatilityWeight2(); boolean disableBiomeHeight(); double getCHCData(int y); // Rivers String getRiverBiome(); // Blocks // Any blocks spawned/checked during base terrain gen that use the biomeconfig materials // call getXXXBlockReplaced to get the replaced blocks. // Any blocks spawned during decoration will have their materials parsed before spawning // them via world.setBlock(), so they use the default biomeconfig materials. // Note: getSurfaceBlockReplaced / getGroundBlockReplaced don't take into // account SAGC, so they should only be used by surfacegenerators. LocalMaterialData getSurfaceBlockAtHeight(ISurfaceGeneratorNoiseProvider noiseProvider, int x, int y, int z); LocalMaterialData getGroundBlockAtHeight(ISurfaceGeneratorNoiseProvider noiseProvider, int x, int y, int z); LocalMaterialData getSurfaceBlockReplaced(int y); LocalMaterialData getGroundBlockReplaced(int y); LocalMaterialData getStoneBlockReplaced(int y); LocalMaterialData getBedrockBlockReplaced(int y); LocalMaterialData getSandStoneBlockReplaced(int y); LocalMaterialData getDefaultGroundBlock(); LocalMaterialData getDefaultStoneBlock(); LocalMaterialData getDefaultWaterBlock(); void doSurfaceAndGroundControl(long worldSeed, GeneratingChunk generatingChunk, ChunkBuffer chunkBuffer, int x, int z, IBiome biome); boolean hasReplaceBlocksSettings(); ReplaceBlockMatrix getReplaceBlocks(); // Water / lava / freezing int getWaterLevelMax(); int getWaterLevelMin(); LocalMaterialData getWaterBlockReplaced(int y); LocalMaterialData getUnderWaterSurfaceBlockReplaced(int y); LocalMaterialData getIceBlockReplaced(int y); LocalMaterialData getPackedIceBlockReplaced(int y); LocalMaterialData getSnowBlockReplaced(int y); LocalMaterialData getCooledLavaBlockReplaced(int y); // Visuals / weather float getBiomeTemperature(); boolean useFrozenOceanTemperature(); float getBiomeWetness(); int getFogColor(); float getFogDensity(); int getWaterFogColor(); int getFoliageColor(); ColorSet getFoliageColorControl(); int getGrassColor(); ColorSet getGrassColorControl(); GrassColorModifier getGrassColorModifier(); int getSkyColor(); int getWaterColor(); ColorSet getWaterColorControl(); String getParticleType(); float getParticleProbability(); int getSnowHeight(float tempAtBlockToFreeze); String getMusic(); int getMusicMinDelay(); int getMusicMaxDelay(); boolean isReplaceCurrentMusic(); String getAmbientSound(); String getMoodSound(); int getMoodSoundDelay(); int getMoodSearchRange(); double getMoodOffset(); String getAdditionsSound(); double getAdditionsTickChance(); // OTG Custom structures (BO's) List<List<String>> getCustomStructureNames(); List<ICustomStructureGen> getCustomStructures(); ICustomStructureGen getStructureGen(); void setStructureGen(ICustomStructureGen customStructureGen); // Structures VillageType getVillageType(); int getVillageSize(); MineshaftType getMineShaftType(); float getMineShaftProbability(); OceanRuinsType getOceanRuinsType(); float getOceanRuinsLargeProbability(); float getOceanRuinsClusterProbability(); boolean getBuriedTreasureEnabled(); float getBuriedTreasureProbability(); boolean getPillagerOutpostEnabled(); int getPillagerOutPostSize(); boolean getBastionRemnantEnabled(); int getBastionRemnantSize(); RareBuildingType getRareBuildingType(); RuinedPortalType getRuinedPortalType(); boolean getWoodlandMansionsEnabled(); boolean getNetherFortressesEnabled(); boolean getShipWreckEnabled(); boolean getShipWreckBeachedEnabled(); boolean getNetherFossilEnabled(); boolean getEndCityEnabled(); boolean getStrongholdsEnabled(); boolean getOceanMonumentsEnabled(); // Mob spawning String getInheritMobsBiomeName(); List<WeightedMobSpawnGroup> getMonsters(); List<WeightedMobSpawnGroup> getCreatures(); List<WeightedMobSpawnGroup> getWaterCreatures(); List<WeightedMobSpawnGroup> getAmbientCreatures(); List<WeightedMobSpawnGroup> getWaterAmbientCreatures(); List<WeightedMobSpawnGroup> getMiscCreatures(); // Saplings ISaplingSpawner getSaplingGen(SaplingType type); ISaplingSpawner getCustomSaplingGen(LocalMaterialData materialData, boolean wideTrunk); // Misc public IBiomeConfig createTemplateBiome(); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.streams.processor.internals; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.AuthorizationException; import org.apache.kafka.common.errors.WakeupException; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.errors.LockException; import org.apache.kafka.streams.errors.ProcessorStateException; import org.apache.kafka.streams.errors.StreamsException; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.processor.TaskId; import org.slf4j.Logger; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; public abstract class AbstractTask implements Task { final TaskId id; final String applicationId; final ProcessorTopology topology; final ProcessorStateManager stateMgr; final Set<TopicPartition> partitions; final Consumer<byte[], byte[]> consumer; final String logPrefix; final boolean eosEnabled; final Logger log; final LogContext logContext; final StateDirectory stateDirectory; boolean taskInitialized; boolean taskClosed; boolean commitNeeded; InternalProcessorContext processorContext; /** * @throws ProcessorStateException if the state manager cannot be created */ AbstractTask(final TaskId id, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final Consumer<byte[], byte[]> consumer, final ChangelogReader changelogReader, final boolean isStandby, final StateDirectory stateDirectory, final StreamsConfig config) { this.id = id; this.applicationId = config.getString(StreamsConfig.APPLICATION_ID_CONFIG); this.partitions = new HashSet<>(partitions); this.topology = topology; this.consumer = consumer; this.eosEnabled = StreamsConfig.EXACTLY_ONCE.equals(config.getString(StreamsConfig.PROCESSING_GUARANTEE_CONFIG)); this.stateDirectory = stateDirectory; this.logPrefix = String.format("%s [%s] ", isStandby ? "standby-task" : "task", id); this.logContext = new LogContext(logPrefix); this.log = logContext.logger(getClass()); // create the processor state manager try { stateMgr = new ProcessorStateManager( id, partitions, isStandby, stateDirectory, topology.storeToChangelogTopic(), changelogReader, eosEnabled, logContext); } catch (final IOException e) { throw new ProcessorStateException(String.format("%sError while creating the state manager", logPrefix), e); } } @Override public TaskId id() { return id; } @Override public String applicationId() { return applicationId; } @Override public Set<TopicPartition> partitions() { return partitions; } @Override public ProcessorTopology topology() { return topology; } @Override public ProcessorContext context() { return processorContext; } @Override public StateStore getStore(final String name) { return stateMgr.getStore(name); } /** * Produces a string representation containing useful information about a Task. * This is useful in debugging scenarios. * * @return A string representation of the StreamTask instance. */ @Override public String toString() { return toString(""); } public boolean isEosEnabled() { return eosEnabled; } /** * Produces a string representation containing useful information about a Task starting with the given indent. * This is useful in debugging scenarios. * * @return A string representation of the Task instance. */ public String toString(final String indent) { final StringBuilder sb = new StringBuilder(); sb.append(indent); sb.append("TaskId: "); sb.append(id); sb.append("\n"); // print topology if (topology != null) { sb.append(indent).append(topology.toString(indent + "\t")); } // print assigned partitions if (partitions != null && !partitions.isEmpty()) { sb.append(indent).append("Partitions ["); for (final TopicPartition topicPartition : partitions) { sb.append(topicPartition.toString()).append(", "); } sb.setLength(sb.length() - 2); sb.append("]\n"); } return sb.toString(); } protected Map<TopicPartition, Long> activeTaskCheckpointableOffsets() { return Collections.emptyMap(); } protected void updateOffsetLimits() { for (final TopicPartition partition : partitions) { try { final OffsetAndMetadata metadata = consumer.committed(partition); // TODO: batch API? final long offset = metadata != null ? metadata.offset() : 0L; stateMgr.putOffsetLimit(partition, offset); if (log.isTraceEnabled()) { log.trace("Updating store offset limits {} for changelog {}", offset, partition); } } catch (final AuthorizationException e) { throw new ProcessorStateException(String.format("task [%s] AuthorizationException when initializing offsets for %s", id, partition), e); } catch (final WakeupException e) { throw e; } catch (final KafkaException e) { throw new ProcessorStateException(String.format("task [%s] Failed to initialize offsets for %s", id, partition), e); } } } /** * Flush all state stores owned by this task */ void flushState() { stateMgr.flush(); } /** * Package-private for testing only * * @throws StreamsException If the store's change log does not contain the partition */ void registerStateStores() { if (topology.stateStores().isEmpty()) { return; } try { if (!stateDirectory.lock(id)) { throw new LockException(String.format("%sFailed to lock the state directory for task %s", logPrefix, id)); } } catch (final IOException e) { throw new StreamsException( String.format("%sFatal error while trying to lock the state directory for task %s", logPrefix, id)); } log.trace("Initializing state stores"); // set initial offset limits updateOffsetLimits(); for (final StateStore store : topology.stateStores()) { log.trace("Initializing store {}", store.name()); processorContext.uninitialize(); store.init(processorContext, store); } } void reinitializeStateStoresForPartitions(final Collection<TopicPartition> partitions) { stateMgr.reinitializeStateStoresForPartitions(partitions, processorContext); } /** * @throws ProcessorStateException if there is an error while closing the state manager */ void closeStateManager(final boolean clean) throws ProcessorStateException { ProcessorStateException exception = null; log.trace("Closing state manager"); try { stateMgr.close(clean); } catch (final ProcessorStateException e) { exception = e; } finally { try { stateDirectory.unlock(id); } catch (final IOException e) { if (exception == null) { exception = new ProcessorStateException(String.format("%sFailed to release state dir lock", logPrefix), e); } } } if (exception != null) { throw exception; } } public boolean isClosed() { return taskClosed; } public boolean commitNeeded() { return commitNeeded; } public boolean hasStateStores() { return !topology.stateStores().isEmpty(); } public Collection<TopicPartition> changelogPartitions() { return stateMgr.changelogPartitions(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.tinkerpop.gremlin.hadoop.process.computer.spark; import org.apache.commons.configuration.ConfigurationUtils; import org.apache.commons.configuration.FileConfiguration; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.tinkerpop.gremlin.hadoop.Constants; import org.apache.tinkerpop.gremlin.hadoop.process.computer.AbstractHadoopGraphComputer; import org.apache.tinkerpop.gremlin.hadoop.process.computer.spark.io.InputFormatRDD; import org.apache.tinkerpop.gremlin.hadoop.process.computer.spark.io.InputRDD; import org.apache.tinkerpop.gremlin.hadoop.process.computer.spark.io.OutputFormatRDD; import org.apache.tinkerpop.gremlin.hadoop.process.computer.spark.io.OutputRDD; import org.apache.tinkerpop.gremlin.hadoop.process.computer.spark.payload.ViewIncomingPayload; import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopConfiguration; import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph; import org.apache.tinkerpop.gremlin.hadoop.structure.io.VertexWritable; import org.apache.tinkerpop.gremlin.hadoop.structure.util.ConfUtil; import org.apache.tinkerpop.gremlin.hadoop.structure.util.HadoopHelper; import org.apache.tinkerpop.gremlin.process.computer.ComputerResult; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.Memory; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.apache.tinkerpop.gremlin.process.computer.util.DefaultComputerResult; import org.apache.tinkerpop.gremlin.process.computer.util.MapMemory; import java.io.File; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.stream.Stream; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public final class SparkGraphComputer extends AbstractHadoopGraphComputer { public SparkGraphComputer(final HadoopGraph hadoopGraph) { super(hadoopGraph); } @Override public Future<ComputerResult> submit() { super.validateStatePriorToExecution(); // apache and hadoop configurations that are used throughout the graph computer computation final org.apache.commons.configuration.Configuration apacheConfiguration = new HadoopConfiguration(this.hadoopGraph.configuration()); apacheConfiguration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES, this.persist.equals(Persist.EDGES)); final Configuration hadoopConfiguration = ConfUtil.makeHadoopConfiguration(apacheConfiguration); if (FileInputFormat.class.isAssignableFrom(hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, InputFormat.class))) { try { final String inputLocation = FileSystem.get(hadoopConfiguration).getFileStatus(new Path(hadoopConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION))).getPath().toString(); apacheConfiguration.setProperty(Constants.MAPRED_INPUT_DIR, inputLocation); hadoopConfiguration.set(Constants.MAPRED_INPUT_DIR, inputLocation); } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } // create the completable future return CompletableFuture.<ComputerResult>supplyAsync(() -> { final long startTime = System.currentTimeMillis(); SparkMemory memory = null; // delete output location final String outputLocation = hadoopConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION, null); if (null != outputLocation) { try { FileSystem.get(hadoopConfiguration).delete(new Path(outputLocation), true); } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } // wire up a spark context final SparkConf sparkConfiguration = new SparkConf(); sparkConfiguration.setAppName(Constants.GREMLIN_HADOOP_SPARK_JOB_PREFIX + (null == this.vertexProgram ? "No VertexProgram" : this.vertexProgram) + "[" + this.mapReducers + "]"); /*final List<Class> classes = new ArrayList<>(); classes.addAll(IOClasses.getGryoClasses(GryoMapper.build().create())); classes.addAll(IOClasses.getSharedHadoopClasses()); classes.add(ViewPayload.class); classes.add(MessagePayload.class); classes.add(ViewIncomingPayload.class); classes.add(ViewOutgoingPayload.class); sparkConfiguration.registerKryoClasses(classes.toArray(new Class[classes.size()]));*/ // TODO: fix for user submitted jars in Spark 1.3.0 // create the spark configuration from the graph computer configuration hadoopConfiguration.forEach(entry -> sparkConfiguration.set(entry.getKey(), entry.getValue())); // execute the vertex program and map reducers and if there is a failure, auto-close the spark context try (final JavaSparkContext sparkContext = new JavaSparkContext(sparkConfiguration)) { // add the project jars to the cluster this.loadJars(sparkContext, hadoopConfiguration); // create a message-passing friendly rdd from the input rdd final JavaPairRDD<Object, VertexWritable> graphRDD; try { graphRDD = hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_RDD, InputFormatRDD.class, InputRDD.class) .newInstance() .readGraphRDD(apacheConfiguration, sparkContext) .setName("graphRDD") .cache(); } catch (final InstantiationException | IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } JavaPairRDD<Object, ViewIncomingPayload<Object>> viewIncomingRDD = null; //////////////////////////////// // process the vertex program // //////////////////////////////// if (null != this.vertexProgram) { // set up the vertex program and wire up configurations memory = new SparkMemory(this.vertexProgram, this.mapReducers, sparkContext); this.vertexProgram.setup(memory); memory.broadcastMemory(sparkContext); final HadoopConfiguration vertexProgramConfiguration = new HadoopConfiguration(); this.vertexProgram.storeState(vertexProgramConfiguration); ConfigurationUtils.copy(vertexProgramConfiguration, apacheConfiguration); ConfUtil.mergeApacheIntoHadoopConfiguration(vertexProgramConfiguration, hadoopConfiguration); // execute the vertex program while (true) { memory.setInTask(true); viewIncomingRDD = SparkExecutor.executeVertexProgramIteration(graphRDD, viewIncomingRDD, memory, vertexProgramConfiguration); memory.setInTask(false); if (this.vertexProgram.terminate(memory)) break; else { memory.incrIteration(); memory.broadcastMemory(sparkContext); } } // write the graph rdd using the output rdd if (!this.persist.equals(Persist.NOTHING)) { try { hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_RDD, OutputFormatRDD.class, OutputRDD.class) .newInstance() .writeGraphRDD(apacheConfiguration, graphRDD); } catch (final InstantiationException | IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } } } final Memory.Admin finalMemory = null == memory ? new MapMemory() : new MapMemory(memory); ////////////////////////////// // process the map reducers // ////////////////////////////// if (!this.mapReducers.isEmpty()) { final String[] elementComputeKeys = this.vertexProgram == null ? new String[0] : this.vertexProgram.getElementComputeKeys().toArray(new String[this.vertexProgram.getElementComputeKeys().size()]); final JavaPairRDD<Object, VertexWritable> mapReduceGraphRDD = SparkExecutor.prepareGraphRDDForMapReduce(graphRDD, viewIncomingRDD, elementComputeKeys).setName("mapReduceGraphRDD").cache(); for (final MapReduce mapReduce : this.mapReducers) { // execute the map reduce job final HadoopConfiguration newApacheConfiguration = new HadoopConfiguration(apacheConfiguration); mapReduce.storeState(newApacheConfiguration); // map final JavaPairRDD mapRDD = SparkExecutor.executeMap((JavaPairRDD) mapReduceGraphRDD, mapReduce, newApacheConfiguration).setName("mapRDD"); // combine TODO: is this really needed // reduce final JavaPairRDD reduceRDD = (mapReduce.doStage(MapReduce.Stage.REDUCE)) ? SparkExecutor.executeReduce(mapRDD, mapReduce, newApacheConfiguration).setName("reduceRDD") : null; // write the map reduce output back to disk (memory) SparkExecutor.saveMapReduceRDD(null == reduceRDD ? mapRDD : reduceRDD, mapReduce, finalMemory, hadoopConfiguration); } } // update runtime and return the newly computed graph finalMemory.setRuntime(System.currentTimeMillis() - startTime); return new DefaultComputerResult(HadoopHelper.getOutputGraph(this.hadoopGraph, this.resultGraph, this.persist), finalMemory.asImmutable()); } }); } ///////////////// private void loadJars(final JavaSparkContext sparkContext, final Configuration hadoopConfiguration) { if (hadoopConfiguration.getBoolean(Constants.GREMLIN_HADOOP_JARS_IN_DISTRIBUTED_CACHE, true)) { final String hadoopGremlinLocalLibs = System.getenv(Constants.HADOOP_GREMLIN_LIBS); if (null == hadoopGremlinLocalLibs) this.logger.warn(Constants.HADOOP_GREMLIN_LIBS + " is not set -- proceeding regardless"); else { final String[] paths = hadoopGremlinLocalLibs.split(":"); for (final String path : paths) { final File file = new File(path); if (file.exists()) Stream.of(file.listFiles()).filter(f -> f.getName().endsWith(Constants.DOT_JAR)).forEach(f -> sparkContext.addJar(f.getAbsolutePath())); else this.logger.warn(path + " does not reference a valid directory -- proceeding regardless"); } } } } public static void main(final String[] args) throws Exception { final FileConfiguration configuration = new PropertiesConfiguration(args[0]); new SparkGraphComputer(HadoopGraph.open(configuration)).program(VertexProgram.createVertexProgram(HadoopGraph.open(configuration), configuration)).submit().get(); } }
/* * ****************************************************************************** * Copyright 2014-2019 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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.spectralogic.ds3client.integration; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.spectralogic.ds3client.Ds3Client; import com.spectralogic.ds3client.commands.PutObjectRequest; import com.spectralogic.ds3client.commands.PutObjectResponse; import com.spectralogic.ds3client.commands.spectrads3.*; import com.spectralogic.ds3client.helpers.Ds3ClientHelpers; import com.spectralogic.ds3client.helpers.JobRecoveryException; import com.spectralogic.ds3client.integration.test.helpers.TempStorageIds; import com.spectralogic.ds3client.integration.test.helpers.TempStorageUtil; import com.spectralogic.ds3client.models.BulkObject; import com.spectralogic.ds3client.models.ChecksumType; import com.spectralogic.ds3client.models.Contents; import com.spectralogic.ds3client.models.Objects; import com.spectralogic.ds3client.models.bulk.Ds3Object; import com.spectralogic.ds3client.networking.FailedRequestException; import com.spectralogic.ds3client.utils.ResourceUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URISyntaxException; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Collections; import java.util.List; import java.util.UUID; import static com.spectralogic.ds3client.integration.Util.RESOURCE_BASE_NAME; import static com.spectralogic.ds3client.integration.Util.deleteAllContents; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class Regression_Test { private static final Logger LOG = LoggerFactory.getLogger(Regression_Test.class); private static final Ds3Client client = Util.fromEnv(); private static final Ds3ClientHelpers HELPERS = Ds3ClientHelpers.wrap(client); private static final String TEST_ENV_NAME = "regression_test"; private static TempStorageIds envStorageIds; private static UUID envDataPolicyId; @BeforeClass public static void startup() throws IOException { envDataPolicyId = TempStorageUtil.setupDataPolicy(TEST_ENV_NAME, false, ChecksumType.Type.MD5, client); envStorageIds = TempStorageUtil.setup(TEST_ENV_NAME, envDataPolicyId, client); } @AfterClass public static void teardown() throws IOException { TempStorageUtil.teardown(TEST_ENV_NAME, envStorageIds, client); client.close(); } @Test public void testMarkerWithSpaces() throws IOException { final String bucketName = "marker_with_spaces"; try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final List<Ds3Object> objects = Lists.newArrayList( new Ds3Object("obj1_no_spaces.txt", 1024), new Ds3Object("obj2_no_spaces.txt", 1024), new Ds3Object("obj3 has spaces.txt", 1024), new Ds3Object("obj4 also has spaces.txt", 1024)); final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, objects); putJob.transfer(new RandomDataChannelBuilder(objects)); final Iterable<Contents> objs = HELPERS.listObjects(bucketName, null, "obj3 has spaces.txt"); boolean foundObj4 = false; for (final Contents obj : objs) { LOG.info("marker with spaces name: " + obj.getKey()); if (obj.getKey().equals("obj4 also has spaces.txt")) foundObj4 = true; LOG.info("marker with spaces size: " + obj.getSize()); } assertThat(Iterables.size(objs), is(1)); assertTrue(foundObj4); final CancelJobSpectraS3Response cancelJobResponse = client .cancelJobSpectraS3(new CancelJobSpectraS3Request(putJob.getJobId().toString())); assertThat(cancelJobResponse, is(notNullValue())); } finally { deleteAllContents(client, bucketName); } } @Test public void testPrefixWithSpaces() throws IOException { final String bucketName = "prefix_with_spaces"; try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final List<Ds3Object> objects = Lists.newArrayList( new Ds3Object("obj1_no_spaces.txt", 1024), new Ds3Object("has spaces obj2.txt", 1024), new Ds3Object("obj3_no_spaces.txt", 1024), new Ds3Object("has spaces obj4.txt", 1024)); final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, objects); putJob.transfer(new RandomDataChannelBuilder(objects)); final Iterable<Contents> objs = HELPERS.listObjects(bucketName, "has spaces"); boolean foundObj2 = false; boolean foundObj4 = false; for (final Contents obj : objs) { LOG.info("prefix with spaces name: " + obj.getKey()); LOG.info("prefix with spaces size: " + obj.getSize()); if (obj.getKey().equals("has spaces obj2.txt")) foundObj2 = true; if (obj.getKey().equals("has spaces obj4.txt")) foundObj4 = true; } assertThat(Iterables.size(objs), is(2)); assertTrue(foundObj2); assertTrue(foundObj4); final CancelJobSpectraS3Response cancelJobResponse = client .cancelJobSpectraS3(new CancelJobSpectraS3Request(putJob.getJobId().toString())); assertThat(cancelJobResponse, is(notNullValue())); } finally { deleteAllContents(client, bucketName); } } @Test public void testPrefixForDirectoriesWithSpaces() throws IOException { final String bucketName = "prefix_directory_with_spaces"; try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final List<Ds3Object> objects = Lists.newArrayList( new Ds3Object("dir1/obj1_no_spaces.txt", 1024), new Ds3Object("dir1/has spaces obj2.txt", 1024), new Ds3Object("dir 2/obj3_no_spaces.txt", 1024), new Ds3Object("dir 2/has spaces obj4.txt", 1024)); final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, objects); putJob.transfer(new RandomDataChannelBuilder(objects)); final Iterable<Contents> dir1Objs = HELPERS.listObjects(bucketName, "dir1/"); boolean foundObj1 = false; boolean foundObj2 = false; for (final Contents obj : dir1Objs) { LOG.info("prefix with spaces name: " + obj.getKey()); LOG.info("prefix with spaces size: " + obj.getSize()); if (obj.getKey().equals("dir1/obj1_no_spaces.txt")) foundObj1 = true; if (obj.getKey().equals("dir1/has spaces obj2.txt")) foundObj2 = true; } assertThat(Iterables.size(dir1Objs), is(2)); assertTrue(foundObj1); assertTrue(foundObj2); final Iterable<Contents> objsDir2 = HELPERS.listObjects(bucketName, "dir 2/"); boolean foundObj3 = false; boolean foundObj4 = false; for (final Contents obj : objsDir2) { LOG.info("prefix with spaces name: " + obj.getKey()); LOG.info("prefix with spaces size: " + obj.getSize()); if (obj.getKey().equals("dir 2/obj3_no_spaces.txt")) foundObj3 = true; if (obj.getKey().equals("dir 2/has spaces obj4.txt")) foundObj4 = true; } assertThat(Iterables.size(objsDir2), is(2)); assertTrue(foundObj3); assertTrue(foundObj4); final CancelJobSpectraS3Response cancelJobResponse = client .cancelJobSpectraS3(new CancelJobSpectraS3Request(putJob.getJobId().toString())); assertThat(cancelJobResponse, is(notNullValue())); } finally { deleteAllContents(client, bucketName); } } @Test public void testPrefixForNestedDirectories() throws IOException { final String bucketName = "prefix__nested_directory"; try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final List<Ds3Object> objects = Lists.newArrayList( new Ds3Object("dir1/obj1_no_spaces.txt", 1024), new Ds3Object("dir1/has spaces obj2.txt", 1024), new Ds3Object("dir1/dir 2/obj3_no_spaces.txt", 1024), new Ds3Object("dir1/dir 2/has spaces obj4.txt", 1024)); final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, objects); putJob.transfer(new RandomDataChannelBuilder(objects)); final Iterable<Contents> dir1Objs = HELPERS.listObjects(bucketName, "dir1/"); boolean foundObj1 = false; boolean foundObj2 = false; for (final Contents obj : dir1Objs) { LOG.info("prefix with spaces name: " + obj.getKey()); LOG.info("prefix with spaces size: " + obj.getSize()); if (obj.getKey().equals("dir1/obj1_no_spaces.txt")) foundObj1 = true; if (obj.getKey().equals("dir1/has spaces obj2.txt")) foundObj2 = true; } assertThat(Iterables.size(dir1Objs), is(4)); assertTrue(foundObj1); assertTrue(foundObj2); final Iterable<Contents> objsDir2 = HELPERS.listObjects(bucketName, "dir1/dir 2/"); boolean foundObj3 = false; boolean foundObj4 = false; for (final Contents obj : objsDir2) { LOG.info("prefix with spaces name: " + obj.getKey()); LOG.info("prefix with spaces size: " + obj.getSize()); if (obj.getKey().equals("dir1/dir 2/obj3_no_spaces.txt")) foundObj3 = true; if (obj.getKey().equals("dir1/dir 2/has spaces obj4.txt")) foundObj4 = true; } assertThat(Iterables.size(objsDir2), is(2)); assertTrue(foundObj3); assertTrue(foundObj4); final CancelJobSpectraS3Response cancelJobResponse = client .cancelJobSpectraS3(new CancelJobSpectraS3Request(putJob.getJobId().toString())); assertThat(cancelJobResponse, is(notNullValue())); } finally { deleteAllContents(client, bucketName); } } @Test public void emptyObjectTest() throws IOException { Util.assumeVersionOneDotTwo(client); final String bucketName = "emptyObject"; final List<Ds3Object> objects = Collections.singletonList(new Ds3Object("obj1.txt", 0)); try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final Ds3ClientHelpers.Job job = HELPERS.startWriteJob(bucketName, objects); assertThat(job, is(notNullValue())); try { client.getJobChunksReadyForClientProcessingSpectraS3( new GetJobChunksReadyForClientProcessingSpectraS3Request(job.getJobId().toString())); fail(); } catch(final FailedRequestException e) { assertThat(e.getStatusCode(), is(404)); // this returns 410 in bp 3.0 } job.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { fail("This call should never be hit"); return new NullChannel(); } }); } finally { deleteAllContents(client, bucketName); } } @Test public void testRecoverWriteJobWithHelper() throws IOException, JobRecoveryException, URISyntaxException { final String bucketName = "test_recover_write_job_bucket"; final String book1 = "beowulf.txt"; final String book2 = "ulysses.txt"; try { HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1); final Path objPath2 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1)); final Ds3Object obj2 = new Ds3Object(book2, Files.size(objPath2)); final Ds3ClientHelpers.Job job = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); final PutObjectResponse putResponse1 = client.putObject(new PutObjectRequest( job.getBucketName(), book1, new ResourceObjectPutter(RESOURCE_BASE_NAME).buildChannel(book1), job.getJobId().toString(), 0, Files.size(objPath1))); assertThat(putResponse1, is(notNullValue())); // Interuption... final Ds3ClientHelpers.Job recoverJob = HELPERS.recoverWriteJob(job.getJobId()); recoverJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { return Files.newByteChannel(objPath2, StandardOpenOption.READ); } }); final GetJobSpectraS3Response finishedJob = client.getJobSpectraS3(new GetJobSpectraS3Request(job.getJobId())); for (final Objects objects : finishedJob.getMasterObjectListResult().getObjects()) { for (final BulkObject bulkObject : objects.getObjects()) { assertTrue(bulkObject.getInCache()); } } } finally { deleteAllContents(client, bucketName); } } }
/* * Copyright 2002-2004 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.richclient.core; import java.awt.Image; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.KeyStroke; import javax.swing.event.SwingPropertyChangeSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.style.ToStringCreator; import org.springframework.richclient.application.support.ApplicationServicesAccessor; import org.springframework.richclient.command.config.CommandButtonLabelInfo; import org.springframework.richclient.command.config.CommandLabelConfigurable; import org.springframework.richclient.image.config.ImageConfigurable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * A convenient super class for objects that can be labeled for display in a * GUI. * * @author Keith Donald */ public class LabeledObjectSupport extends ApplicationServicesAccessor implements DescribedElement, VisualizedElement, CommandLabelConfigurable, ImageConfigurable, DescriptionConfigurable, TitleConfigurable { protected final Log logger = LogFactory.getLog(getClass()); private CommandButtonLabelInfo label; private String title; private String caption; private String description; private Image image; private PropertyChangeSupport propertyChangeSupport; public void setLabelInfo(CommandButtonLabelInfo label) { String oldDisplayName = null; if (this.title != null || this.label != null) { oldDisplayName = getDisplayName(); } int oldMnemonic = getMnemonic(); int oldMnemonicIndex = getMnemonicIndex(); KeyStroke oldAccelerator = getAccelerator(); this.label = label; firePropertyChange(DISPLAY_NAME_PROPERTY, oldDisplayName, getDisplayName()); firePropertyChange("mnemonic", oldMnemonic, getMnemonic()); firePropertyChange("mnemonicIndex", oldMnemonicIndex, getMnemonicIndex()); firePropertyChange("accelerator", oldAccelerator, getAccelerator()); } public void setCaption(String caption) { String oldValue = caption; this.caption = caption; firePropertyChange(CAPTION_PROPERTY, oldValue, caption); } public void setDescription(String description) { String oldValue = this.description; this.description = description; firePropertyChange(DESCRIPTION_PROPERTY, oldValue, description); } public void setTitle(String title) { String oldValue = null; if (this.title != null || this.label != null) { oldValue = getDisplayName(); } this.title = title; firePropertyChange(DISPLAY_NAME_PROPERTY, oldValue, getDisplayName()); } public void setImage(Image image) { Image oldValue = image; this.image = image; firePropertyChange("image", oldValue, image); } public String getDisplayName() { if (title != null) { return title; } if (label == null) { if (logger.isInfoEnabled()) { logger.info("This labeled object's display name is not configured; returning 'displayName'"); } return "displayName"; } return label.getText(); } public String getCaption() { return caption; } public String getDescription() { return description; } public Image getImage() { return image; } public Icon getIcon() { if (image != null) return new ImageIcon(image); return null; } public int getMnemonic() { if (label != null) return label.getMnemonic(); return 0; } public int getMnemonicIndex() { if (label != null) return label.getMnemonicIndex(); return 0; } public KeyStroke getAccelerator() { if (label != null) return label.getAccelerator(); return null; } public CommandButtonLabelInfo getLabel() { return label; } public void addPropertyChangeListener(PropertyChangeListener l) { getOrCreatePropertyChangeSupport().addPropertyChangeListener(l); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) { getOrCreatePropertyChangeSupport().addPropertyChangeListener(propertyName, l); } public void removePropertyChangeListener(PropertyChangeListener l) { getPropertyChangeSupport().removePropertyChangeListener(l); } public void removePropertyChangeListener(String propertyName, PropertyChangeListener l) { getPropertyChangeSupport().removePropertyChangeListener(propertyName, l); } private PropertyChangeSupport getPropertyChangeSupport() { Assert.notNull(propertyChangeSupport, "Property change support has not yet been initialized; add a listener first!"); return propertyChangeSupport; } private PropertyChangeSupport getOrCreatePropertyChangeSupport() { if (propertyChangeSupport == null) { propertyChangeSupport = new SwingPropertyChangeSupport(this); } return propertyChangeSupport; } protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { if (propertyChangeSupport != null) { propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } } protected void firePropertyChange(String propertyName, int oldValue, int newValue) { if (propertyChangeSupport != null) { propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (propertyChangeSupport != null) { propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } } protected boolean hasChanged(Object currentValue, Object proposedValue) { return !ObjectUtils.nullSafeEquals(currentValue, proposedValue); } protected boolean hasChanged(boolean currentValue, boolean proposedValue) { return currentValue != proposedValue; } protected boolean hasChanged(int currentValue, int proposedValue) { return currentValue != proposedValue; } public String toString() { return new ToStringCreator(this).toString(); } }
/* * Copyright (C) 2011 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.android.gl2cameraeye; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.app.Activity; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.MotionEvent; import android.content.Context; import android.util.Log; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.opengl.Matrix; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.SensorManager; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.Sensor; public class GL2CameraEye extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGLView = new CamGLSurfaceView(this); setContentView(mGLView); setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLSurfaceView mGLView; } class CamGLSurfaceView extends GLSurfaceView implements SensorEventListener { public CamGLSurfaceView(Context context) { super(context); setEGLContextClientVersion(2); mRenderer = new CamRenderer(context); setRenderer(mRenderer); mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); mAcceleration = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); } public boolean onTouchEvent(final MotionEvent event) { queueEvent(new Runnable(){ public void run() { mRenderer.setPosition(event.getX() / getWidth(), event.getY() / getHeight()); }}); return true; } @Override public void onPause() { super.onPause(); mCamera.stopPreview(); mCamera.release(); mSensorManager.unregisterListener(this); } @Override public void onResume() { mCamera = Camera.open(); Camera.Parameters p = mCamera.getParameters(); // No changes to default camera parameters mCamera.setParameters(p); queueEvent(new Runnable(){ public void run() { mRenderer.setCamera(mCamera); }}); mSensorManager.registerListener(this, mAcceleration, SensorManager.SENSOR_DELAY_GAME); super.onResume(); } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { final float[] accelerationVector = event.values; queueEvent(new Runnable(){ public void run() { mRenderer.setAcceleration(accelerationVector); }}); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { // Ignoring sensor accuracy changes. } CamRenderer mRenderer; Camera mCamera; SensorManager mSensorManager; Sensor mAcceleration; } class CamRenderer implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener { public CamRenderer(Context context) { mContext = context; mTriangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer(); mTriangleVertices.put(mTriangleVerticesData).position(0); Matrix.setIdentityM(mSTMatrix, 0); Matrix.setIdentityM(mMMatrix, 0); float[] defaultAcceleration = {0.f,0.f,0.f}; setAcceleration(defaultAcceleration); mPos[0] = 0.f; mPos[1] = 0.f; mPos[2] = 0.f; mVel[0] = 0.f; mVel[1] = 0.f; mVel[2] = 0.f; } /* The following set methods are not synchronized, so should only * be called within the rendering thread context. Use GLSurfaceView.queueEvent for safe access. */ public void setPosition(float x, float y) { /* Map from screen (0,0)-(1,1) to scene coordinates */ mPos[0] = (x*2-1)*mRatio; mPos[1] = (-y)*2+1; mPos[2] = 0.f; mVel[0] = 0; mVel[1] = 0; mVel[2] = 0; } public void setCamera(Camera camera) { mCamera = camera; Camera.Size previewSize = camera.getParameters().getPreviewSize(); mCameraRatio = (float)previewSize.width/previewSize.height; } public void setAcceleration(float[] accelerationVector) { mGForce[0] = accelerationVector[0]; mGForce[1] = accelerationVector[1]; mGForce[2] = accelerationVector[2]; } public void onDrawFrame(GL10 glUnused) { synchronized(this) { if (updateSurface) { mSurface.updateTexImage(); mSurface.getTransformMatrix(mSTMatrix); long timestamp = mSurface.getTimestamp(); doPhysics(timestamp); updateSurface = false; } } // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); GLES20.glUseProgram(mProgram); checkGlError("glUseProgram"); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID); mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET); GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); checkGlError("glVertexAttribPointer maPosition"); GLES20.glEnableVertexAttribArray(maPositionHandle); checkGlError("glEnableVertexAttribArray maPositionHandle"); mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET); GLES20.glVertexAttribPointer(maTextureHandle, 3, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); checkGlError("glVertexAttribPointer maTextureHandle"); GLES20.glEnableVertexAttribArray(maTextureHandle); checkGlError("glEnableVertexAttribArray maTextureHandle"); Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0); Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0); GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0); GLES20.glUniform1f(muCRatioHandle, mCameraRatio); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); checkGlError("glDrawArrays"); } public void onSurfaceChanged(GL10 glUnused, int width, int height) { // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. GLES20.glViewport(0, 0, width, height); mRatio = (float) width / height; Matrix.frustumM(mProjMatrix, 0, -mRatio, mRatio, -1, 1, 3, 7); } public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. /* Set up alpha blending and an Android background color */ GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); GLES20.glClearColor(0.643f, 0.776f, 0.223f, 1.0f); /* Set up shaders and handles to their variables */ mProgram = createProgram(mVertexShader, mFragmentShader); if (mProgram == 0) { return; } maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition"); checkGlError("glGetAttribLocation aPosition"); if (maPositionHandle == -1) { throw new RuntimeException("Could not get attrib location for aPosition"); } maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord"); checkGlError("glGetAttribLocation aTextureCoord"); if (maTextureHandle == -1) { throw new RuntimeException("Could not get attrib location for aTextureCoord"); } muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); checkGlError("glGetUniformLocation uMVPMatrix"); if (muMVPMatrixHandle == -1) { throw new RuntimeException("Could not get attrib location for uMVPMatrix"); } muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix"); checkGlError("glGetUniformLocation uSTMatrix"); if (muMVPMatrixHandle == -1) { throw new RuntimeException("Could not get attrib location for uSTMatrix"); } muCRatioHandle = GLES20.glGetUniformLocation(mProgram, "uCRatio"); checkGlError("glGetUniformLocation uCRatio"); if (muMVPMatrixHandle == -1) { throw new RuntimeException("Could not get attrib location for uCRatio"); } /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTextureID = textures[0]; GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID); checkGlError("glBindTexture mTextureID"); // Can't do mipmapping with camera source GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); // Clamp to edge is the only option GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); checkGlError("glTexParameteri mTextureID"); /* * Create the SurfaceTexture that will feed this textureID, and pass it to the camera */ mSurface = new SurfaceTexture(mTextureID); mSurface.setOnFrameAvailableListener(this); try { mCamera.setPreviewTexture(mSurface); } catch (IOException t) { Log.e(TAG, "Cannot set preview texture target!"); } /* Start the camera */ mCamera.startPreview(); Matrix.setLookAtM(mVMatrix, 0, 0, 0, 5f, 0f, 0f, 0f, 0f, 1.0f, 0.0f); mLastTime = 0; synchronized(this) { updateSurface = false; } } synchronized public void onFrameAvailable(SurfaceTexture surface) { /* For simplicity, SurfaceTexture calls here when it has new * data available. Call may come in from some random thread, * so let's be safe and use synchronize. No OpenGL calls can be done here. */ updateSurface = true; } private void doPhysics(long timestamp) { /* * Move the camera surface around based on some simple spring physics with drag */ if (mLastTime == 0) mLastTime = timestamp; float deltaT = (timestamp - mLastTime)/1000000000.f; // To seconds float springStrength = 20.f; float frictionCoeff = 10.f; float mass = 10.f; float gMultiplier = 4.f; /* Only update physics every 30 ms */ if (deltaT > 0.030f) { mLastTime = timestamp; float[] totalForce = new float[3]; totalForce[0] = -mPos[0] * springStrength - mVel[0]*frictionCoeff + gMultiplier*mGForce[0]*mass; totalForce[1] = -mPos[1] * springStrength - mVel[1]*frictionCoeff + gMultiplier*mGForce[1]*mass; totalForce[2] = -mPos[2] * springStrength - mVel[2]*frictionCoeff + gMultiplier*mGForce[2]*mass; float[] accel = new float[3]; accel[0] = totalForce[0]/mass; accel[1] = totalForce[1]/mass; accel[2] = totalForce[2]/mass; /* Not a very accurate integrator */ mVel[0] = mVel[0] + accel[0]*deltaT; mVel[1] = mVel[1] + accel[1]*deltaT; mVel[2] = mVel[2] + accel[2]*deltaT; mPos[0] = mPos[0] + mVel[0]*deltaT; mPos[1] = mPos[1] + mVel[1]*deltaT; mPos[2] = mPos[2] + mVel[2]*deltaT; Matrix.setIdentityM(mMMatrix, 0); Matrix.translateM(mMMatrix, 0, mPos[0], mPos[1], mPos[2]); } } private int loadShader(int shaderType, String source) { int shader = GLES20.glCreateShader(shaderType); if (shader != 0) { GLES20.glShaderSource(shader, source); GLES20.glCompileShader(shader); int[] compiled = new int[1]; GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0); if (compiled[0] == 0) { Log.e(TAG, "Could not compile shader " + shaderType + ":"); Log.e(TAG, GLES20.glGetShaderInfoLog(shader)); GLES20.glDeleteShader(shader); shader = 0; } } return shader; } private int createProgram(String vertexSource, String fragmentSource) { int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); if (vertexShader == 0) { return 0; } int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); if (pixelShader == 0) { return 0; } int program = GLES20.glCreateProgram(); if (program != 0) { GLES20.glAttachShader(program, vertexShader); checkGlError("glAttachShader"); GLES20.glAttachShader(program, pixelShader); checkGlError("glAttachShader"); GLES20.glLinkProgram(program); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: "); Log.e(TAG, GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } } return program; } private void checkGlError(String op) { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { Log.e(TAG, op + ": glError " + error); throw new RuntimeException(op + ": glError " + error); } } private static final int FLOAT_SIZE_BYTES = 4; private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES; private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0; private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3; private final float[] mTriangleVerticesData = { // X, Y, Z, U, V -1.0f, -1.0f, 0, 0.f, 0.f, 1.0f, -1.0f, 0, 1.f, 0.f, -1.0f, 1.0f, 0, 0.f, 1.f, 1.0f, 1.0f, 0, 1.f, 1.f, }; private FloatBuffer mTriangleVertices; private final String mVertexShader = "uniform mat4 uMVPMatrix;\n" + "uniform mat4 uSTMatrix;\n" + "uniform float uCRatio;\n" + "attribute vec4 aPosition;\n" + "attribute vec4 aTextureCoord;\n" + "varying vec2 vTextureCoord;\n" + "varying vec2 vTextureNormCoord;\n" + "void main() {\n" + " vec4 scaledPos = aPosition;\n" + " scaledPos.x = scaledPos.x * uCRatio;\n" + " gl_Position = uMVPMatrix * scaledPos;\n" + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" + " vTextureNormCoord = aTextureCoord.xy;\n" + "}\n"; private final String mFragmentShader = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "varying vec2 vTextureNormCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + " gl_FragColor.a = 1.0-min(length(vTextureNormCoord-0.5)*2.0,1.0);\n" + "}\n"; private float[] mMVPMatrix = new float[16]; private float[] mProjMatrix = new float[16]; private float[] mMMatrix = new float[16]; private float[] mVMatrix = new float[16]; private float[] mSTMatrix = new float[16]; private int mProgram; private int mTextureID; private int muMVPMatrixHandle; private int muSTMatrixHandle; private int muCRatioHandle; private int maPositionHandle; private int maTextureHandle; private float mRatio = 1.0f; private float mCameraRatio = 1.0f; private float[] mVel = new float[3]; private float[] mPos = new float[3]; private float[] mGForce = new float[3]; private long mLastTime; private SurfaceTexture mSurface; private Camera mCamera; private boolean updateSurface = false; private Context mContext; private static String TAG = "CamRenderer"; // Magic key private static int GL_TEXTURE_EXTERNAL_OES = 0x8D65; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.reef.io.network.naming; import org.apache.reef.io.naming.NameAssignment; import org.apache.reef.io.network.naming.parameters.*; import org.apache.reef.io.network.util.StringIdentifierFactory; import org.apache.reef.tang.Configuration; import org.apache.reef.tang.Injector; import org.apache.reef.tang.Tang; import org.apache.reef.tang.exceptions.InjectionException; import org.apache.reef.util.Optional; import org.apache.reef.wake.Identifier; import org.apache.reef.wake.IdentifierFactory; import org.apache.reef.wake.remote.address.LocalAddressProvider; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Naming server and client test. */ public class NamingTest { private static final Logger LOG = Logger.getLogger(NamingTest.class.getName()); private static final int RETRY_COUNT; private static final int RETRY_TIMEOUT; static { try { final Injector injector = Tang.Factory.getTang().newInjector(); RETRY_COUNT = injector.getNamedInstance(NameResolverRetryCount.class); RETRY_TIMEOUT = injector.getNamedInstance(NameResolverRetryTimeout.class); } catch (final InjectionException ex) { final String msg = "Exception while trying to find default values for retryCount & Timeout"; LOG.log(Level.SEVERE, msg, ex); throw new RuntimeException(msg, ex); } } private final LocalAddressProvider localAddressProvider; @Rule public final TestName name = new TestName(); static final long TTL = 30000; private final IdentifierFactory factory = new StringIdentifierFactory(); private int port; public NamingTest() throws InjectionException { this.localAddressProvider = Tang.Factory.getTang().newInjector().getInstance(LocalAddressProvider.class); } /** * NameServer and NameLookupClient test. * * @throws Exception */ @Test public void testNamingLookup() throws Exception { final String localAddress = localAddressProvider.getLocalAddress(); LOG.log(Level.FINEST, this.name.getMethodName()); // names final Map<Identifier, InetSocketAddress> idToAddrMap = new HashMap<>(); idToAddrMap.put(this.factory.getNewInstance("task1"), new InetSocketAddress(localAddress, 7001)); idToAddrMap.put(this.factory.getNewInstance("task2"), new InetSocketAddress(localAddress, 7002)); // run a server final Injector injector = Tang.Factory.getTang().newInjector(); injector.bindVolatileParameter(NameServerParameters.NameServerIdentifierFactory.class, this.factory); injector.bindVolatileInstance(LocalAddressProvider.class, this.localAddressProvider); try (final NameServer server = injector.getInstance(NameServer.class)) { this.port = server.getPort(); for (final Identifier id : idToAddrMap.keySet()) { server.register(id, idToAddrMap.get(id)); } // run a client try (final NameLookupClient client = getNewNameLookupClient(localAddress, port, TTL, RETRY_COUNT, RETRY_TIMEOUT, Optional.of(this.localAddressProvider), Optional.of(this.factory))) { final Identifier id1 = this.factory.getNewInstance("task1"); final Identifier id2 = this.factory.getNewInstance("task2"); final Map<Identifier, InetSocketAddress> respMap = new HashMap<>(); final InetSocketAddress addr1 = client.lookup(id1); respMap.put(id1, addr1); final InetSocketAddress addr2 = client.lookup(id2); respMap.put(id2, addr2); for (final Identifier id : respMap.keySet()) { LOG.log(Level.FINEST, "Mapping: {0} -> {1}", new Object[]{id, respMap.get(id)}); } Assert.assertTrue(isEqual(idToAddrMap, respMap)); } } } private static NameLookupClient getNewNameLookupClient(final String serverAddr, final int serverPort, final long timeout, final int retryCount, final int retryTimeout, final Optional<LocalAddressProvider> localAddressProvider, final Optional<IdentifierFactory> factory) throws InjectionException { final Configuration injectorConf = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(NameResolverNameServerAddr.class, serverAddr) .bindNamedParameter(NameResolverNameServerPort.class, Integer.toString(serverPort)) .bindNamedParameter(NameResolverCacheTimeout.class, Long.toString(timeout)) .bindNamedParameter(NameResolverRetryCount.class, Integer.toString(retryCount)) .bindNamedParameter(NameResolverRetryTimeout.class, Integer.toString(retryTimeout)) .build(); final Injector injector = Tang.Factory.getTang().newInjector(injectorConf); if (localAddressProvider.isPresent()) { injector.bindVolatileInstance(LocalAddressProvider.class, localAddressProvider.get()); } if (factory.isPresent()) { injector.bindVolatileInstance(IdentifierFactory.class, factory.get()); } return injector.getInstance(NameLookupClient.class); } /** * Test concurrent lookups (threads share a client). * * @throws Exception */ @Test public void testConcurrentNamingLookup() throws Exception { LOG.log(Level.FINEST, this.name.getMethodName()); final String localAddress = localAddressProvider.getLocalAddress(); // test it 3 times to make failure likely for (int i = 0; i < 3; i++) { LOG.log(Level.FINEST, "test {0}", i); // names final Map<Identifier, InetSocketAddress> idToAddrMap = new HashMap<>(); idToAddrMap.put(this.factory.getNewInstance("task1"), new InetSocketAddress(localAddress, 7001)); idToAddrMap.put(this.factory.getNewInstance("task2"), new InetSocketAddress(localAddress, 7002)); idToAddrMap.put(this.factory.getNewInstance("task3"), new InetSocketAddress(localAddress, 7003)); // run a server final Injector injector = Tang.Factory.getTang().newInjector(); injector.bindVolatileParameter(NameServerParameters.NameServerIdentifierFactory.class, this.factory); injector.bindVolatileInstance(LocalAddressProvider.class, this.localAddressProvider); try (final NameServer server = injector.getInstance(NameServer.class)) { this.port = server.getPort(); for (final Identifier id : idToAddrMap.keySet()) { server.register(id, idToAddrMap.get(id)); } // run a client try (final NameLookupClient client = getNewNameLookupClient(localAddress, port, TTL, RETRY_COUNT, RETRY_TIMEOUT, Optional.of(this.localAddressProvider), Optional.of(this.factory))) { final Identifier id1 = this.factory.getNewInstance("task1"); final Identifier id2 = this.factory.getNewInstance("task2"); final Identifier id3 = this.factory.getNewInstance("task3"); final ExecutorService e = Executors.newCachedThreadPool(); final ConcurrentMap<Identifier, InetSocketAddress> respMap = new ConcurrentHashMap<>(); final Future<?> f1 = e.submit(new Runnable() { @Override public void run() { InetSocketAddress addr = null; try { addr = client.lookup(id1); } catch (final Exception e) { LOG.log(Level.SEVERE, "Lookup failed", e); Assert.fail(e.toString()); } respMap.put(id1, addr); } }); final Future<?> f2 = e.submit(new Runnable() { @Override public void run() { InetSocketAddress addr = null; try { addr = client.lookup(id2); } catch (final Exception e) { LOG.log(Level.SEVERE, "Lookup failed", e); Assert.fail(e.toString()); } respMap.put(id2, addr); } }); final Future<?> f3 = e.submit(new Runnable() { @Override public void run() { InetSocketAddress addr = null; try { addr = client.lookup(id3); } catch (final Exception e) { LOG.log(Level.SEVERE, "Lookup failed", e); Assert.fail(e.toString()); } respMap.put(id3, addr); } }); f1.get(); f2.get(); f3.get(); for (final Identifier id : respMap.keySet()) { LOG.log(Level.FINEST, "Mapping: {0} -> {1}", new Object[]{id, respMap.get(id)}); } Assert.assertTrue(isEqual(idToAddrMap, respMap)); } } } } /** * NameServer and NameRegistryClient test. * * @throws Exception */ @Test public void testNamingRegistry() throws Exception { LOG.log(Level.FINEST, this.name.getMethodName()); final Injector injector = Tang.Factory.getTang().newInjector(); injector.bindVolatileParameter(NameServerParameters.NameServerIdentifierFactory.class, this.factory); injector.bindVolatileInstance(LocalAddressProvider.class, this.localAddressProvider); try (final NameServer server = injector.getInstance(NameServer.class)) { this.port = server.getPort(); final String localAddress = localAddressProvider.getLocalAddress(); // names to start with final Map<Identifier, InetSocketAddress> idToAddrMap = new HashMap<>(); idToAddrMap.put(this.factory.getNewInstance("task1"), new InetSocketAddress(localAddress, 7001)); idToAddrMap.put(this.factory.getNewInstance("task2"), new InetSocketAddress(localAddress, 7002)); // registration // invoke registration from the client side try (final NameRegistryClient client = new NameRegistryClient(localAddress, this.port, this.factory, this.localAddressProvider)) { for (final Identifier id : idToAddrMap.keySet()) { client.register(id, idToAddrMap.get(id)); } // wait final Set<Identifier> ids = idToAddrMap.keySet(); busyWait(server, ids.size(), ids); // check the server side Map<Identifier, InetSocketAddress> serverMap = new HashMap<>(); Iterable<NameAssignment> nas = server.lookup(ids); for (final NameAssignment na : nas) { LOG.log(Level.FINEST, "Mapping: {0} -> {1}", new Object[]{na.getIdentifier(), na.getAddress()}); serverMap.put(na.getIdentifier(), na.getAddress()); } Assert.assertTrue(isEqual(idToAddrMap, serverMap)); // un-registration for (final Identifier id : idToAddrMap.keySet()) { client.unregister(id); } // wait busyWait(server, 0, ids); serverMap = new HashMap<>(); nas = server.lookup(ids); for (final NameAssignment na : nas) { serverMap.put(na.getIdentifier(), na.getAddress()); } Assert.assertEquals(0, serverMap.size()); } } } /** * NameServer and NameClient test. * * @throws Exception */ @Test public void testNameClient() throws Exception { LOG.log(Level.FINEST, this.name.getMethodName()); final String localAddress = localAddressProvider.getLocalAddress(); final Injector injector = Tang.Factory.getTang().newInjector(); injector.bindVolatileParameter(NameServerParameters.NameServerIdentifierFactory.class, this.factory); injector.bindVolatileInstance(LocalAddressProvider.class, this.localAddressProvider); try (final NameServer server = injector.getInstance(NameServer.class)) { this.port = server.getPort(); final Map<Identifier, InetSocketAddress> idToAddrMap = new HashMap<>(); idToAddrMap.put(this.factory.getNewInstance("task1"), new InetSocketAddress(localAddress, 7001)); idToAddrMap.put(this.factory.getNewInstance("task2"), new InetSocketAddress(localAddress, 7002)); // registration // invoke registration from the client side final Configuration nameResolverConf = NameResolverConfiguration.CONF .set(NameResolverConfiguration.NAME_SERVER_HOSTNAME, localAddress) .set(NameResolverConfiguration.NAME_SERVICE_PORT, this.port) .set(NameResolverConfiguration.CACHE_TIMEOUT, TTL) .set(NameResolverConfiguration.RETRY_TIMEOUT, RETRY_TIMEOUT) .set(NameResolverConfiguration.RETRY_COUNT, RETRY_COUNT) .build(); try (final NameResolver client = Tang.Factory.getTang().newInjector(nameResolverConf).getInstance(NameClient.class)) { for (final Identifier id : idToAddrMap.keySet()) { client.register(id, idToAddrMap.get(id)); } // wait final Set<Identifier> ids = idToAddrMap.keySet(); busyWait(server, ids.size(), ids); // lookup final Identifier id1 = this.factory.getNewInstance("task1"); final Identifier id2 = this.factory.getNewInstance("task2"); final Map<Identifier, InetSocketAddress> respMap = new HashMap<>(); InetSocketAddress addr1 = client.lookup(id1); respMap.put(id1, addr1); InetSocketAddress addr2 = client.lookup(id2); respMap.put(id2, addr2); for (final Identifier id : respMap.keySet()) { LOG.log(Level.FINEST, "Mapping: {0} -> {1}", new Object[]{id, respMap.get(id)}); } Assert.assertTrue(isEqual(idToAddrMap, respMap)); // un-registration for (final Identifier id : idToAddrMap.keySet()) { client.unregister(id); } // wait busyWait(server, 0, ids); final Map<Identifier, InetSocketAddress> serverMap = new HashMap<>(); addr1 = server.lookup(id1); if (addr1 != null) { serverMap.put(id1, addr1); } addr2 = server.lookup(id1); if (addr2 != null) { serverMap.put(id2, addr2); } Assert.assertEquals(0, serverMap.size()); } } } private boolean isEqual(final Map<Identifier, InetSocketAddress> map1, final Map<Identifier, InetSocketAddress> map2) { if (map1.size() != map2.size()) { return false; } for (final Identifier id : map1.keySet()) { final InetSocketAddress addr1 = map1.get(id); final InetSocketAddress addr2 = map2.get(id); if (!addr1.equals(addr2)) { return false; } } return true; } private void busyWait(final NameServer server, final int expected, final Set<Identifier> ids) { int count = 0; for (;;) { final Iterable<NameAssignment> nas = server.lookup(ids); for (@SuppressWarnings("unused") final NameAssignment na : nas) { ++count; } if (count == expected) { break; } count = 0; } } }
/** * The MIT License * Copyright (c) 2015 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * 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 ee.ria.xroad.common.util; import lombok.extern.slf4j.Slf4j; import org.apache.xml.security.c14n.Canonicalizer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.InputStream; import java.io.StringWriter; import java.util.Optional; /** * Contains various XML-related utility methods. */ @Slf4j public final class XmlUtils { private XmlUtils() { } /** * Creates a new document object from the given input stream containing the document XML. * @param documentXml the input stream containing the XML * @return the created document object * @throws Exception if an error occurs */ public static Document parseDocument(InputStream documentXml) throws Exception { return parseDocument(documentXml, true); } /** * Creates a new document object from the given input stream containing the document XML. * @param documentXml the input stream containing the XML * @param namespaceAware flag indicating namespace awareness * @return the created document object * @throws Exception if an error occurs */ public static Document parseDocument(InputStream documentXml, boolean namespaceAware) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(namespaceAware); dbf.setIgnoringComments(true); dbf.setValidating(false); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); return dbf.newDocumentBuilder().parse(documentXml); } /** * Returns String representation of the the XML node (document or element). * @param node the node * @return string representation of the input * @throws Exception if an error occurs */ public static String toXml(Node node) throws Exception { Source source = new DOMSource(node); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); Transformer t = TransformerFactory.newInstance().newTransformer(); t.transform(source, result); return writer.toString(); } /** * Returns the first element matching the given tag name. * @param doc the document from which to search the element * @param tagName the name of the tag to match * @return optional containing the element or empty if the element cannot be found */ public static Optional<Element> getFirstElementByTagName(Document doc, String tagName) { NodeList nodes = doc.getElementsByTagName(tagName); return nodes.getLength() > 0 ? Optional.ofNullable((Element) nodes.item(0)) : Optional.empty(); } /** * Returns an element matching the given xpath expression and using the specified namespace context. * @param parent the parent element from which to search * @param xpathExpr the xpath expression * @param nsCtx the namespace context (can be null) * @return the element or null if the element cannot be found or the xpath expression is invalid */ public static Element getElementXPathNS(Element parent, String xpathExpr, NamespaceContext nsCtx) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if (nsCtx != null) { xpath.setNamespaceContext(nsCtx); } return (Element) xpath.evaluate(xpathExpr, parent, XPathConstants.NODE); } catch (XPathExpressionException e) { log.warn("Element not found with getElementXPathNS {}", e); return null; } } /** * Returns a list of elements matching the given xpath expression and using the specified namespace context. * @param parent the parent element from which to search * @param xpathExpr the xpath expression * @param nsCtx the namespace context (can be null) * @return the elements or null if the element cannot be found or the xpath expression is invalid */ public static NodeList getElementsXPathNS(Element parent, String xpathExpr, NamespaceContext nsCtx) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if (nsCtx != null) { xpath.setNamespaceContext(nsCtx); } return (NodeList) xpath.evaluate(xpathExpr, parent, XPathConstants.NODESET); } catch (XPathExpressionException e) { log.warn("Element not found with getElementXPathNS {}", e); return null; } } /** * Returns the element that has an ID attribute matching the input. * The search is performed using XPath evaluation. * @param doc the document * @param id the id * @return the element or null, if the element cannot be found */ public static Element getElementById(Document doc, String id) { if (id.startsWith("#")) { id = id.substring(1); } try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); return (Element) xpath.evaluate("//*[@Id = '" + id + "']", doc, XPathConstants.NODE); } catch (XPathExpressionException e) { log.warn("Element not found with getElementXPathNS {}", e); return null; } } /** * Calculates and return the result of canonicalization of the specified node, using the specified * canonicalization method. * @param algorithmUri the URI of the canonicalization algorithm that is known to the class Canonicalizer. * @param node the node to canonicalize * @return the c14n result. * @throws Exception if any errors occur */ public static byte[] canonicalize(String algorithmUri, Node node) throws Exception { return Canonicalizer.getInstance(algorithmUri).canonicalizeSubtree(node); } /** * Pretty prints the document to string using default charset. * @param document the document * @return printed document in String form * @throws Exception if any errors occur */ public static String prettyPrintXml(Document document) throws Exception { return prettyPrintXml(document, "UTF-8"); } /** * Pretty prints the document to string using specified charset. * @param document the document * @param charset the charset * @return printed document in String form * @throws Exception if any errors occur */ public static String prettyPrintXml(Document document, String charset) throws Exception { StringWriter stringWriter = new StringWriter(); StreamResult output = new StreamResult(stringWriter); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, charset); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(document), output); return output.getWriter().toString().trim(); } }
/* * Copyright 2014 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.social.connect.web; import java.util.Collections; import java.util.List; import javax.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.GenericTypeResolver; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionFactory; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.support.OAuth1ConnectionFactory; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.support.URIBuilder; import org.springframework.stereotype.Controller; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.view.RedirectView; /** * Spring MVC Controller for handling the provider user sign-in flow. * <ul> * <li>POST /signin/{providerId} - Initiate user sign-in with {providerId}.</li> * <li>GET /signin/{providerId}?oauth_token&amp;oauth_verifier||code - Receive {providerId} authentication callback and establish the connection.</li> * </ul> * @author Keith Donald */ @Controller @RequestMapping("/signin") public class ProviderSignInController implements InitializingBean { private final static Log logger = LogFactory.getLog(ProviderSignInController.class); private final ConnectionFactoryLocator connectionFactoryLocator; private final UsersConnectionRepository usersConnectionRepository; private final MultiValueMap<Class<?>, ProviderSignInInterceptor<?>> signInInterceptors = new LinkedMultiValueMap<Class<?>, ProviderSignInInterceptor<?>>(); private final SignInAdapter signInAdapter; private String applicationUrl; private String signInUrl = "/signin"; private String signUpUrl = "/signup"; private String postSignInUrl = "/"; private ConnectSupport connectSupport; private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); /** * Creates a new provider sign-in controller. * @param connectionFactoryLocator the locator of {@link ConnectionFactory connection factories} used to support provider sign-in. * Note: this reference should be a serializable proxy to a singleton-scoped target instance. * This is because {@link ProviderSignInAttempt} are session-scoped objects that hold ConnectionFactoryLocator references. * If these references cannot be serialized, NotSerializableExceptions can occur at runtime. * @param usersConnectionRepository the global store for service provider connections across all users. * Note: this reference should be a serializable proxy to a singleton-scoped target instance. * @param signInAdapter handles user sign-in */ @Inject public ProviderSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository, SignInAdapter signInAdapter) { this.connectionFactoryLocator = connectionFactoryLocator; this.usersConnectionRepository = usersConnectionRepository; this.signInAdapter = signInAdapter; } /** * Configure the list of sign in interceptors that should receive callbacks during the sign in process. * Convenient when an instance of this class is configured using a tool that supports JavaBeans-based configuration. * @param interceptors the sign in interceptors to add */ public void setSignInInterceptors(List<ProviderSignInInterceptor<?>> interceptors) { for (ProviderSignInInterceptor<?> interceptor : interceptors) { addSignInInterceptor(interceptor); } } /** * Sets the URL of the application's sign in page. * Defaults to "/signin". * @param signInUrl the signIn URL */ public void setSignInUrl(String signInUrl) { this.signInUrl = signInUrl; } /** * Sets the URL to redirect the user to if no local user account can be mapped when signing in using a provider. * Defaults to "/signup". * @param signUpUrl the signUp URL */ public void setSignUpUrl(String signUpUrl) { this.signUpUrl = signUpUrl; } /** * Sets the default URL to redirect the user to after signing in using a provider. * Defaults to "/". * @param postSignInUrl the postSignIn URL */ public void setPostSignInUrl(String postSignInUrl) { this.postSignInUrl = postSignInUrl; } /** * Configures the base secure URL for the application this controller is being used in e.g. <code>https://myapp.com</code>. Defaults to null. * If specified, will be used to generate OAuth callback URLs. * If not specified, OAuth callback URLs are generated from web request info. * You may wish to set this property if requests into your application flow through a proxy to your application server. * In this case, the request URI may contain a scheme, host, and/or port value that points to an internal server not appropriate for an external callback URL. * If you have this problem, you can set this property to the base external URL for your application and it will be used to construct the callback URL instead. * @param applicationUrl the application URL value */ public void setApplicationUrl(String applicationUrl) { this.applicationUrl = applicationUrl; } /** * Sets a strategy to use when persisting information that is to survive past the boundaries of a request. * The default strategy is to set the data as attributes in the HTTP Session. * @param sessionStrategy the session strategy. */ public void setSessionStrategy(SessionStrategy sessionStrategy) { this.sessionStrategy = sessionStrategy; } /** * Adds a ConnectInterceptor to receive callbacks during the connection process. * Useful for programmatic configuration. * @param interceptor the connect interceptor to add */ public void addSignInInterceptor(ProviderSignInInterceptor<?> interceptor) { Class<?> serviceApiType = GenericTypeResolver.resolveTypeArgument(interceptor.getClass(), ProviderSignInInterceptor.class); signInInterceptors.add(serviceApiType, interceptor); } /** * Process a sign-in form submission by commencing the process of establishing a connection to the provider on behalf of the user. * For OAuth1, fetches a new request token from the provider, temporarily stores it in the session, then redirects the user to the provider's site for authentication authorization. * For OAuth2, redirects the user to the provider's site for authentication authorization. * @param providerId the provider ID to authorize against * @param request the request * @return a RedirectView to the provider's authorization page or to the application's signin page if there is an error */ @RequestMapping(value="/{providerId}", method=RequestMethod.POST) public RedirectView signIn(@PathVariable String providerId, NativeWebRequest request) { ConnectionFactory<?> connectionFactory = connectionFactoryLocator.getConnectionFactory(providerId); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); preSignIn(connectionFactory, parameters, request); try { return new RedirectView(connectSupport.buildOAuthUrl(connectionFactory, request, parameters)); } catch (Exception e) { logger.error("Exception while building authorization URL: ", e); return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString()); } } /** * Process the authentication callback from an OAuth 1 service provider. * Called after the member authorizes the authentication, generally done once by having he or she click "Allow" in their web browser at the provider's site. * Handles the provider sign-in callback by first determining if a local user account is associated with the connected provider account. * If so, signs the local user in by delegating to {@link SignInAdapter#signIn(String, Connection, NativeWebRequest)} * If not, redirects the user to a signup page to create a new account with {@link ProviderSignInAttempt} context exposed in the HttpSession. * @param providerId the provider ID to authorize against * @param request the request * @return a RedirectView to the provider's authorization page or to the application's signin page if there is an error * @see ProviderSignInAttempt * @see ProviderSignInUtils */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="oauth_token") public RedirectView oauth1Callback(@PathVariable String providerId, NativeWebRequest request) { try { OAuth1ConnectionFactory<?> connectionFactory = (OAuth1ConnectionFactory<?>) connectionFactoryLocator.getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { logger.error("Exception while completing OAuth 1.0(a) connection: ", e); return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString()); } } /** * Process the authentication callback from an OAuth 2 service provider. * Called after the user authorizes the authentication, generally done once by having he or she click "Allow" in their web browser at the provider's site. * Handles the provider sign-in callback by first determining if a local user account is associated with the connected provider account. * If so, signs the local user in by delegating to {@link SignInAdapter#signIn(String, Connection, NativeWebRequest)}. * If not, redirects the user to a signup page to create a new account with {@link ProviderSignInAttempt} context exposed in the HttpSession. * @see ProviderSignInAttempt * @see ProviderSignInUtils * @param providerId the provider ID to authorize against * @param code the OAuth 2 authorization code * @param request the web request * @return A RedirectView to the target page or the signInUrl if an error occurs */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="code") public RedirectView oauth2Callback(@PathVariable String providerId, @RequestParam("code") String code, NativeWebRequest request) { try { OAuth2ConnectionFactory<?> connectionFactory = (OAuth2ConnectionFactory<?>) connectionFactoryLocator.getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { logger.error("Exception while completing OAuth 2 connection: ", e); return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString()); } } /** * Process an error callback from an OAuth 2 authorization as described at http://tools.ietf.org/html/rfc6749#section-4.1.2.1. * Called after upon redirect from an OAuth 2 provider when there is some sort of error during authorization, typically because the user denied authorization. * Simply carries the error parameters through to the sign-in page. * @param providerId The Provider ID * @param error An error parameter sent on the redirect from the provider * @param errorDescription An optional error description sent from the provider * @param errorUri An optional error URI sent from the provider * @param request The web request * @return a RedirectView to the signInUrl */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="error") public RedirectView oauth2ErrorCallback(@PathVariable String providerId, @RequestParam("error") String error, @RequestParam(value="error_description", required=false) String errorDescription, @RequestParam(value="error_uri", required=false) String errorUri, NativeWebRequest request) { logger.warn("Error during authorization: " + error); URIBuilder uriBuilder = URIBuilder.fromUri(signInUrl).queryParam("error", error); if (errorDescription != null ) { uriBuilder.queryParam("error_description", errorDescription); } if (errorUri != null ) { uriBuilder.queryParam("error_uri", errorUri); } return redirect(uriBuilder.build().toString()); } /** * Process the authentication callback when neither the oauth_token or code parameter is given, likely indicating that the user denied authorization with the provider. * Redirects to application's sign in URL, as set in the signInUrl property. * @return A RedirectView to the sign in URL */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET) public RedirectView canceledAuthorizationCallback() { return redirect(signInUrl); } // From InitializingBean public void afterPropertiesSet() throws Exception { this.connectSupport = new ConnectSupport(sessionStrategy); this.connectSupport.setUseAuthenticateUrl(true); if (this.applicationUrl != null) { this.connectSupport.setApplicationUrl(applicationUrl); } }; // internal helpers private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory, NativeWebRequest request) { List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection); if (userIds.size() == 0) { ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection, connectionFactoryLocator, usersConnectionRepository); sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt); return redirect(signUpUrl); } else if (userIds.size() == 1) { usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection); String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request); postSignIn(connectionFactory, connection, (WebRequest) request); return originalUrl != null ? redirect(originalUrl) : redirect(postSignInUrl); } else { return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "multiple_users").build().toString()); } } private RedirectView redirect(String url) { return new RedirectView(url, true); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void preSignIn(ConnectionFactory<?> connectionFactory, MultiValueMap<String, String> parameters, WebRequest request) { for (ProviderSignInInterceptor interceptor : interceptingSignInTo(connectionFactory)) { interceptor.preSignIn(connectionFactory, parameters, request); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void postSignIn(ConnectionFactory<?> connectionFactory, Connection<?> connection, WebRequest request) { for (ProviderSignInInterceptor interceptor : interceptingSignInTo(connectionFactory)) { interceptor.postSignIn(connection, request); } } private List<ProviderSignInInterceptor<?>> interceptingSignInTo(ConnectionFactory<?> connectionFactory) { Class<?> serviceType = GenericTypeResolver.resolveTypeArgument(connectionFactory.getClass(), ConnectionFactory.class); List<ProviderSignInInterceptor<?>> typedInterceptors = signInInterceptors.get(serviceType); if (typedInterceptors == null) { typedInterceptors = Collections.emptyList(); } return typedInterceptors; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos.implementation.query; import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosDiagnostics; import com.azure.cosmos.CosmosException; import com.azure.cosmos.implementation.ClientSideRequestStatistics; import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.DiagnosticsClientContext; import com.azure.cosmos.implementation.DocumentClientRetryPolicy; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.PartitionKeyRange; import com.azure.cosmos.implementation.QueryMetrics; import com.azure.cosmos.implementation.RequestChargeTracker; import com.azure.cosmos.implementation.Resource; import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.RxDocumentServiceRequest; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.Utils.ValueHolder; import com.azure.cosmos.implementation.apachecommons.lang.tuple.ImmutablePair; import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl; import com.azure.cosmos.models.CosmosQueryRequestOptions; import com.azure.cosmos.models.FeedResponse; import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.SqlQuerySpec; import com.fasterxml.jackson.core.JsonProcessingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.concurrent.Queues; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import java.util.stream.Collectors; /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ public class ParallelDocumentQueryExecutionContext<T extends Resource> extends ParallelDocumentQueryExecutionContextBase<T> { private static final Logger logger = LoggerFactory.getLogger(ParallelDocumentQueryExecutionContext.class); private final CosmosQueryRequestOptions cosmosQueryRequestOptions; private final Map<FeedRangeEpkImpl, String> partitionKeyRangeToContinuationTokenMap; private ParallelDocumentQueryExecutionContext( DiagnosticsClientContext diagnosticsClientContext, IDocumentQueryClient client, ResourceType resourceTypeEnum, Class<T> resourceType, SqlQuerySpec query, CosmosQueryRequestOptions cosmosQueryRequestOptions, String resourceLink, String rewrittenQuery, String collectionRid, boolean isContinuationExpected, boolean getLazyFeedResponse, UUID correlatedActivityId) { super(diagnosticsClientContext, client, resourceTypeEnum, resourceType, query, cosmosQueryRequestOptions, resourceLink, rewrittenQuery, isContinuationExpected, getLazyFeedResponse, correlatedActivityId); this.cosmosQueryRequestOptions = cosmosQueryRequestOptions; partitionKeyRangeToContinuationTokenMap = new HashMap<>(); } public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync( DiagnosticsClientContext diagnosticsClientContext, IDocumentQueryClient client, PipelinedDocumentQueryParams<T> initParams) { ParallelDocumentQueryExecutionContext<T> context = new ParallelDocumentQueryExecutionContext<T>(diagnosticsClientContext, client, initParams.getResourceTypeEnum(), initParams.getResourceType(), initParams.getQuery(), initParams.getCosmosQueryRequestOptions(), initParams.getResourceLink(), initParams.getQueryInfo().getRewrittenQuery(), initParams.getCollectionRid(), initParams.isContinuationExpected(), initParams.isGetLazyResponseFeed(), initParams.getCorrelatedActivityId()); context.setTop(initParams.getTop()); try { context.initialize( initParams.getCollectionRid(), initParams.getFeedRanges(), initParams.getInitialPageSize(), ModelBridgeInternal.getRequestContinuationFromQueryRequestOptions(initParams.getCosmosQueryRequestOptions())); return Flux.just(context); } catch (CosmosException dce) { return Flux.error(dce); } } public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createReadManyQueryAsync( DiagnosticsClientContext diagnosticsClientContext, IDocumentQueryClient queryClient, String collectionResourceId, SqlQuerySpec sqlQuery, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap, CosmosQueryRequestOptions cosmosQueryRequestOptions, String collectionRid, String collectionLink, UUID activityId, Class<T> klass, ResourceType resourceTypeEnum) { ParallelDocumentQueryExecutionContext<T> context = new ParallelDocumentQueryExecutionContext<T>(diagnosticsClientContext, queryClient, resourceTypeEnum, klass, sqlQuery, cosmosQueryRequestOptions, collectionLink, sqlQuery.getQueryText(), collectionRid, false, false, activityId); context .initializeReadMany(queryClient, collectionResourceId, sqlQuery, rangeQueryMap, cosmosQueryRequestOptions, activityId, collectionRid); return Flux.just(context); } private void initialize( String collectionRid, List<FeedRangeEpkImpl> feedRanges, int initialPageSize, String continuationToken) { // Generate the corresponding continuation token map. if (continuationToken == null) { // If the user does not give a continuation token, // then just start the query from the first partition. for (FeedRangeEpkImpl feedRangeEpk : feedRanges) { partitionKeyRangeToContinuationTokenMap.put(feedRangeEpk, null); } } else { // Figure out which partitions to resume from: // If a continuation token is given then we need to figure out partition key // range it maps to // in order to filter the partition key ranges. // For example if suppliedCompositeContinuationToken.RANGE.Min == // partition3.RANGE.Min, // then we know that partitions 0, 1, 2 are fully drained. // Check to see if composite continuation token is a valid JSON. ValueHolder<CompositeContinuationToken> outCompositeContinuationToken = new ValueHolder<>(); if (!CompositeContinuationToken.tryParse(continuationToken, outCompositeContinuationToken)) { String message = String.format("INVALID JSON in continuation token %s for Parallel~Context", continuationToken); throw BridgeInternal.createCosmosException(HttpConstants.StatusCodes.BADREQUEST, message); } CompositeContinuationToken compositeContinuationToken = outCompositeContinuationToken.v; PartitionMapper.PartitionMapping<CompositeContinuationToken> partitionMapping = PartitionMapper.getPartitionMapping(feedRanges, Collections.singletonList(compositeContinuationToken)); // Skip all the partitions left of the target range, since they have already been drained fully. populatePartitionToContinuationMap(partitionMapping.getTargetMapping()); populatePartitionToContinuationMap(partitionMapping.getMappingRightOfTarget()); } super.initialize(collectionRid, partitionKeyRangeToContinuationTokenMap, initialPageSize, this.querySpec); } private void populatePartitionToContinuationMap( Map<FeedRangeEpkImpl, CompositeContinuationToken> partitionMapping) { for (Map.Entry<FeedRangeEpkImpl, CompositeContinuationToken> entry : partitionMapping.entrySet()) { if (entry.getValue() != null) { partitionKeyRangeToContinuationTokenMap.put(entry.getKey(), entry.getValue().getToken()); } else { partitionKeyRangeToContinuationTokenMap.put(entry.getKey(), /*continuation*/ null); } } } /* private List<PartitionKeyRange> getPartitionKeyRangesForContinuation( CompositeContinuationToken compositeContinuationToken, List<PartitionKeyRange> partitionKeyRanges) { Map<FeedRangeEpkImpl, String> partitionRangeIdToTokenMap = new HashMap<>(); ValueHolder<Map<FeedRangeEpkImpl, String>> outPartitionRangeIdToTokenMap = new ValueHolder<>(partitionRangeIdToTokenMap); // Find the partition key range we left off on and fill the range to continuation token map int startIndex = this.findTargetRangeAndExtractContinuationTokens(this.feedRanges, compositeContinuationToken.getRange(), outPartitionRangeIdToTokenMap, compositeContinuationToken.getToken()); List<PartitionKeyRange> rightHandSideRanges = new ArrayList<PartitionKeyRange>(); for (int i = startIndex; i < partitionKeyRanges.size(); i++) { PartitionKeyRange range = partitionKeyRanges.get(i); if (partitionRangeIdToTokenMap.containsKey(range.getId())) { this.partitionKeyRangeToContinuationTokenMap.put(range, compositeContinuationToken.getToken()); } rightHandSideRanges.add(partitionKeyRanges.get(i)); } return rightHandSideRanges; } */ private static class EmptyPagesFilterTransformer<T extends Resource> implements Function<Flux<DocumentProducer<T>.DocumentProducerFeedResponse>, Flux<FeedResponse<T>>> { private final RequestChargeTracker tracker; private DocumentProducer<T>.DocumentProducerFeedResponse previousPage; private final CosmosQueryRequestOptions cosmosQueryRequestOptions; private final UUID correlatedActivityId; private ConcurrentMap<String, QueryMetrics> emptyPageQueryMetricsMap = new ConcurrentHashMap<>(); private CosmosDiagnostics cosmosDiagnostics; public EmptyPagesFilterTransformer(RequestChargeTracker tracker, CosmosQueryRequestOptions options, UUID correlatedActivityId) { if (tracker == null) { throw new IllegalArgumentException("Request Charge Tracker must not be null."); } this.tracker = tracker; this.previousPage = null; this.cosmosQueryRequestOptions = options; this.correlatedActivityId = correlatedActivityId; } private DocumentProducer<T>.DocumentProducerFeedResponse plusCharge( DocumentProducer<T>.DocumentProducerFeedResponse documentProducerFeedResponse, double charge) { FeedResponse<T> page = documentProducerFeedResponse.pageResult; Map<String, String> headers = new HashMap<>(page.getResponseHeaders()); double pageCharge = page.getRequestCharge(); pageCharge += charge; headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, String.valueOf(pageCharge)); FeedResponse<T> newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.getResults(), headers, BridgeInternal.queryMetricsFromFeedResponse(page), ModelBridgeInternal.getQueryPlanDiagnosticsContext(page), false, false, page.getCosmosDiagnostics()); documentProducerFeedResponse.pageResult = newPage; return documentProducerFeedResponse; } private DocumentProducer<T>.DocumentProducerFeedResponse addCompositeContinuationToken( DocumentProducer<T>.DocumentProducerFeedResponse documentProducerFeedResponse, String compositeContinuationToken) { FeedResponse<T> page = documentProducerFeedResponse.pageResult; Map<String, String> headers = new HashMap<>(page.getResponseHeaders()); headers.put(HttpConstants.HttpHeaders.CONTINUATION, compositeContinuationToken); FeedResponse<T> newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.getResults(), headers, BridgeInternal.queryMetricsFromFeedResponse(page), ModelBridgeInternal.getQueryPlanDiagnosticsContext(page), false, false, page.getCosmosDiagnostics() ); documentProducerFeedResponse.pageResult = newPage; return documentProducerFeedResponse; } private static Map<String, String> headerResponse( double requestCharge) { return Utils.immutableMapOf(HttpConstants.HttpHeaders.REQUEST_CHARGE, String.valueOf(requestCharge)); } @Override public Flux<FeedResponse<T>> apply(Flux<DocumentProducer<T>.DocumentProducerFeedResponse> source) { // Emit an empty page so the downstream observables know when there are no more // results. return source.filter(documentProducerFeedResponse -> { if (documentProducerFeedResponse.pageResult.getResults().isEmpty() && !ModelBridgeInternal .getEmptyPagesAllowedFromQueryRequestOptions(this.cosmosQueryRequestOptions)) { // filter empty pages and accumulate charge tracker.addCharge(documentProducerFeedResponse.pageResult.getRequestCharge()); ConcurrentMap<String, QueryMetrics> currentQueryMetrics = BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse.pageResult); QueryMetrics.mergeQueryMetricsMap(emptyPageQueryMetricsMap, currentQueryMetrics); cosmosDiagnostics = documentProducerFeedResponse.pageResult.getCosmosDiagnostics(); if (ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .isEmptyPageDiagnosticsEnabled(cosmosQueryRequestOptions)) { logEmptyPageDiagnostics( cosmosDiagnostics, this.correlatedActivityId, documentProducerFeedResponse.pageResult.getActivityId()); } return false; } return true; }).map(documentProducerFeedResponse -> { //Combining previous empty page query metrics with current non empty page query metrics if (!emptyPageQueryMetricsMap.isEmpty()) { ConcurrentMap<String, QueryMetrics> currentQueryMetrics = BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse.pageResult); QueryMetrics.mergeQueryMetricsMap(currentQueryMetrics, emptyPageQueryMetricsMap); emptyPageQueryMetricsMap.clear(); } // Add the request charge double charge = tracker.getAndResetCharge(); if (charge > 0) { return new ValueHolder<>(plusCharge(documentProducerFeedResponse, charge)); } else { return new ValueHolder<>(documentProducerFeedResponse); } }).concatWith(Flux.just(new ValueHolder<>(null))).map(heldValue -> { DocumentProducer<T>.DocumentProducerFeedResponse documentProducerFeedResponse = heldValue.v; // CREATE pairs from the stream to allow the observables downstream to "peek" // 1, 2, 3, null -> (null, 1), (1, 2), (2, 3), (3, null) ImmutablePair<DocumentProducer<T>.DocumentProducerFeedResponse, DocumentProducer<T>.DocumentProducerFeedResponse> previousCurrent = new ImmutablePair<>( this.previousPage, documentProducerFeedResponse); this.previousPage = documentProducerFeedResponse; return previousCurrent; }).skip(1).map(currentNext -> { // remove the (null, 1) // Add the continuation token based on the current and next page. DocumentProducer<T>.DocumentProducerFeedResponse current = currentNext.left; DocumentProducer<T>.DocumentProducerFeedResponse next = currentNext.right; String compositeContinuationToken; String backendContinuationToken = current.pageResult.getContinuationToken(); if (backendContinuationToken == null) { // We just finished reading the last document from a partition if (next == null) { // It was the last partition and we are done compositeContinuationToken = null; } else { // It wasn't the last partition, so we need to give the next range, but with a // null continuation CompositeContinuationToken compositeContinuationTokenDom = new CompositeContinuationToken(null, next.sourceFeedRange.getRange()); compositeContinuationToken = compositeContinuationTokenDom.toJson(); } } else { // We are in the middle of reading a partition, // so give back this partition with a backend continuation token CompositeContinuationToken compositeContinuationTokenDom = new CompositeContinuationToken( backendContinuationToken, current.sourceFeedRange.getRange()); compositeContinuationToken = compositeContinuationTokenDom.toJson(); } DocumentProducer<T>.DocumentProducerFeedResponse page; page = current; page = this.addCompositeContinuationToken(page, compositeContinuationToken); return page; }).map(documentProducerFeedResponse -> { // Unwrap the documentProducerFeedResponse and get back the feedResponse return documentProducerFeedResponse.pageResult; }).switchIfEmpty(Flux.defer(() -> { // create an empty page if there is no result return Flux.just(BridgeInternal.createFeedResponseWithQueryMetrics(Utils.immutableListOf(), headerResponse(tracker.getAndResetCharge()), emptyPageQueryMetricsMap, null, false, false, cosmosDiagnostics)); })); } } static void logEmptyPageDiagnostics( CosmosDiagnostics cosmosDiagnostics, UUID correlatedActivityId, String activityId) { List<ClientSideRequestStatistics> requestStatistics = BridgeInternal.getClientSideRequestStatisticsList(cosmosDiagnostics); try { if (logger.isInfoEnabled()) { logger.info( "Empty page request diagnostics for correlatedActivityId [{}] - activityId [{}] - [{}]", correlatedActivityId, activityId, Utils.getSimpleObjectMapper().writeValueAsString(requestStatistics)); } } catch (JsonProcessingException e) { logger.warn("Failed to log empty page diagnostics. ", e); } } @Override public Flux<FeedResponse<T>> drainAsync( int maxPageSize) { List<Flux<DocumentProducer<T>.DocumentProducerFeedResponse>> obs = this.documentProducers // Get the stream. .stream() // Start from the left most partition first. .sorted(Comparator.comparing(dp -> dp.feedRange.getRange().getMin())) // For each partition get it's stream of results. .map(DocumentProducer::produceAsync) // Merge results from all partitions. .collect(Collectors.toList()); int fluxConcurrency = fluxSequentialMergeConcurrency(cosmosQueryRequestOptions, obs.size()); int fluxPrefetch = fluxSequentialMergePrefetch(cosmosQueryRequestOptions, obs.size(), maxPageSize, fluxConcurrency); logger.debug("ParallelQuery: flux mergeSequential" + " concurrency {}, prefetch {}", fluxConcurrency, fluxPrefetch); return Flux.mergeSequential(obs, fluxConcurrency, fluxPrefetch) .transformDeferred(new EmptyPagesFilterTransformer<>(new RequestChargeTracker(), this.cosmosQueryRequestOptions, correlatedActivityId)); } @Override public Flux<FeedResponse<T>> executeAsync() { return this.drainAsync(ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(cosmosQueryRequestOptions)); } protected DocumentProducer<T> createDocumentProducer( String collectionRid, PartitionKeyRange targetRange, String initialContinuationToken, int initialPageSize, CosmosQueryRequestOptions cosmosQueryRequestOptions, SqlQuerySpec querySpecForInit, Map<String, String> commonRequestHeaders, TriFunction<FeedRangeEpkImpl, String, Integer, RxDocumentServiceRequest> createRequestFunc, Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc, Callable<DocumentClientRetryPolicy> createRetryPolicyFunc, FeedRangeEpkImpl feedRange) { return new DocumentProducer<T>(client, collectionRid, cosmosQueryRequestOptions, createRequestFunc, executeFunc, targetRange, collectionRid, createRetryPolicyFunc, resourceType, correlatedActivityId, initialPageSize, initialContinuationToken, top, feedRange); } private int fluxSequentialMergeConcurrency(CosmosQueryRequestOptions options, int numberOfPartitions) { int parallelism = options.getMaxDegreeOfParallelism(); if (parallelism < 0) { parallelism = Configs.getCPUCnt(); } else if (parallelism == 0) { parallelism = 1; } return Math.min(numberOfPartitions, parallelism); } private int fluxSequentialMergePrefetch(CosmosQueryRequestOptions options, int numberOfPartitions, int pageSize, int fluxConcurrency) { int maxBufferedItemCount = options.getMaxBufferedItemCount(); if (maxBufferedItemCount <= 0) { maxBufferedItemCount = Math.min(Configs.getCPUCnt() * numberOfPartitions * pageSize, 100_000); } int fluxPrefetch = Math.max(maxBufferedItemCount / (Math.max(fluxConcurrency * pageSize, 1)), 1); return Math.min(fluxPrefetch, Queues.XS_BUFFER_SIZE); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.flink.runtime.jobmanager; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Identify; import akka.actor.PoisonPill; import akka.actor.Props; import akka.japi.pf.FI; import akka.japi.pf.ReceiveBuilder; import akka.pattern.Patterns; import akka.testkit.CallingThreadDispatcher; import akka.testkit.JavaTestKit; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.core.fs.FSDataInputStream; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.akka.AkkaUtils; import org.apache.flink.runtime.akka.ListeningBehaviour; import org.apache.flink.runtime.blob.BlobServer; import org.apache.flink.runtime.blob.BlobService; import org.apache.flink.runtime.checkpoint.CheckpointIDCounter; import org.apache.flink.runtime.checkpoint.CheckpointMetaData; import org.apache.flink.runtime.checkpoint.CheckpointMetrics; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.CheckpointRecoveryFactory; import org.apache.flink.runtime.checkpoint.CompletedCheckpoint; import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore; import org.apache.flink.runtime.checkpoint.StandaloneCheckpointIDCounter; import org.apache.flink.runtime.checkpoint.SubtaskState; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.execution.librarycache.BlobLibraryCacheManager; import org.apache.flink.runtime.executiongraph.restart.FixedDelayRestartStrategy; import org.apache.flink.runtime.executiongraph.restart.RestartStrategyFactory; import org.apache.flink.runtime.highavailability.HighAvailabilityServices; import org.apache.flink.runtime.highavailability.TestingHighAvailabilityServices; import org.apache.flink.runtime.instance.ActorGateway; import org.apache.flink.runtime.instance.AkkaActorGateway; import org.apache.flink.runtime.instance.InstanceManager; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobgraph.tasks.ExternalizedCheckpointSettings; import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings; import org.apache.flink.runtime.jobgraph.tasks.StatefulTask; import org.apache.flink.runtime.jobmanager.scheduler.Scheduler; import org.apache.flink.runtime.leaderelection.LeaderElectionService; import org.apache.flink.runtime.leaderelection.TestingLeaderElectionService; import org.apache.flink.runtime.leaderelection.TestingLeaderRetrievalService; import org.apache.flink.runtime.messages.JobManagerMessages; import org.apache.flink.runtime.metrics.MetricRegistry; import org.apache.flink.runtime.state.ChainedStateHandle; import org.apache.flink.runtime.state.SharedStateRegistry; import org.apache.flink.runtime.state.StreamStateHandle; import org.apache.flink.runtime.state.TaskStateHandles; import org.apache.flink.runtime.state.memory.ByteStreamStateHandle; import org.apache.flink.runtime.taskmanager.TaskManager; import org.apache.flink.runtime.testingUtils.TestingJobManager; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages; import org.apache.flink.runtime.testingUtils.TestingMessages; import org.apache.flink.runtime.testingUtils.TestingTaskManager; import org.apache.flink.runtime.testingUtils.TestingTaskManagerMessages; import org.apache.flink.runtime.testingUtils.TestingUtils; import org.apache.flink.runtime.testutils.RecoverableCompletedCheckpointStore; import org.apache.flink.runtime.util.TestByteStreamStateHandleDeepCompare; import org.apache.flink.util.InstantiationUtil; import org.apache.flink.util.TestLogger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import scala.Int; import scala.Option; import scala.PartialFunction; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Deadline; import scala.concurrent.duration.FiniteDuration; import scala.runtime.BoxedUnit; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JobManagerHARecoveryTest extends TestLogger { private static ActorSystem system; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass public static void setup() { system = AkkaUtils.createLocalActorSystem(new Configuration()); } @AfterClass public static void teardown() { JavaTestKit.shutdownActorSystem(system); } /** * Tests that the persisted job is not removed from the SubmittedJobGraphStore if the JobManager * loses its leadership. Furthermore, it tests that the job manager can recover the job from * the SubmittedJobGraphStore and checkpoint state is recovered as well. */ @Test public void testJobRecoveryWhenLosingLeadership() throws Exception { FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); FiniteDuration jobRecoveryTimeout = new FiniteDuration(3, TimeUnit.SECONDS); Deadline deadline = new FiniteDuration(2, TimeUnit.MINUTES).fromNow(); Configuration flinkConfiguration = new Configuration(); UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); int slots = 2; ActorRef archive = null; ActorRef jobManager = null; ActorRef taskManager = null; flinkConfiguration.setString(HighAvailabilityOptions.HA_MODE, "zookeeper"); flinkConfiguration.setString(HighAvailabilityOptions.HA_STORAGE_PATH, temporaryFolder.newFolder().toString()); flinkConfiguration.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, slots); try { Scheduler scheduler = new Scheduler(TestingUtils.defaultExecutionContext()); MySubmittedJobGraphStore mySubmittedJobGraphStore = new MySubmittedJobGraphStore(); CompletedCheckpointStore checkpointStore = new RecoverableCompletedCheckpointStore(); CheckpointIDCounter checkpointCounter = new StandaloneCheckpointIDCounter(); CheckpointRecoveryFactory checkpointStateFactory = new MyCheckpointRecoveryFactory(checkpointStore, checkpointCounter); TestingLeaderElectionService myLeaderElectionService = new TestingLeaderElectionService(); TestingLeaderRetrievalService myLeaderRetrievalService = new TestingLeaderRetrievalService( null, null); TestingHighAvailabilityServices testingHighAvailabilityServices = new TestingHighAvailabilityServices(); testingHighAvailabilityServices.setJobMasterLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID, myLeaderRetrievalService); InstanceManager instanceManager = new InstanceManager(); instanceManager.addInstanceListener(scheduler); archive = system.actorOf(JobManager.getArchiveProps(MemoryArchivist.class, 10, Option.<Path>empty())); Props jobManagerProps = Props.create( TestingJobManager.class, flinkConfiguration, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), instanceManager, scheduler, new BlobLibraryCacheManager(new BlobServer(flinkConfiguration), 3600000), archive, new FixedDelayRestartStrategy.FixedDelayRestartStrategyFactory(Int.MaxValue(), 100), timeout, myLeaderElectionService, mySubmittedJobGraphStore, checkpointStateFactory, jobRecoveryTimeout, Option.apply(null)); jobManager = system.actorOf(jobManagerProps); ActorGateway gateway = new AkkaActorGateway(jobManager, leaderSessionID); taskManager = TaskManager.startTaskManagerComponentsAndActor( flinkConfiguration, ResourceID.generate(), system, testingHighAvailabilityServices, "localhost", Option.apply("taskmanager"), true, TestingTaskManager.class); ActorGateway tmGateway = new AkkaActorGateway(taskManager, leaderSessionID); Future<Object> tmAlive = tmGateway.ask(TestingMessages.getAlive(), deadline.timeLeft()); Await.ready(tmAlive, deadline.timeLeft()); JobVertex sourceJobVertex = new JobVertex("Source"); sourceJobVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceJobVertex.setParallelism(slots); JobGraph jobGraph = new JobGraph("TestingJob", sourceJobVertex); List<JobVertexID> vertexId = Collections.singletonList(sourceJobVertex.getID()); jobGraph.setSnapshotSettings(new JobCheckpointingSettings( vertexId, vertexId, vertexId, 100L, 10L * 60L * 1000L, 0L, 1, ExternalizedCheckpointSettings.none(), null, true)); BlockingStatefulInvokable.initializeStaticHelpers(slots); Future<Object> isLeader = gateway.ask( TestingJobManagerMessages.getNotifyWhenLeader(), deadline.timeLeft()); Future<Object> isConnectedToJobManager = tmGateway.ask( new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager), deadline.timeLeft()); // tell jobManager that he's the leader myLeaderElectionService.isLeader(leaderSessionID); // tell taskManager who's the leader myLeaderRetrievalService.notifyListener(gateway.path(), leaderSessionID); Await.ready(isLeader, deadline.timeLeft()); Await.ready(isConnectedToJobManager, deadline.timeLeft()); // submit blocking job Future<Object> jobSubmitted = gateway.ask( new JobManagerMessages.SubmitJob(jobGraph, ListeningBehaviour.DETACHED), deadline.timeLeft()); Await.ready(jobSubmitted, deadline.timeLeft()); // Wait for some checkpoints to complete BlockingStatefulInvokable.awaitCompletedCheckpoints(); Future<Object> jobRemoved = gateway.ask(new TestingJobManagerMessages.NotifyWhenJobRemoved(jobGraph.getJobID()), deadline.timeLeft()); // Revoke leadership myLeaderElectionService.notLeader(); // check that the job gets removed from the JobManager Await.ready(jobRemoved, deadline.timeLeft()); // but stays in the submitted job graph store assertTrue(mySubmittedJobGraphStore.contains(jobGraph.getJobID())); Future<Object> jobRunning = gateway.ask(new TestingJobManagerMessages.NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.RUNNING), deadline.timeLeft()); // Make JobManager again a leader myLeaderElectionService.isLeader(newLeaderSessionID); // tell the TaskManager about it myLeaderRetrievalService.notifyListener(gateway.path(), newLeaderSessionID); // wait that the job is recovered and reaches state RUNNING Await.ready(jobRunning, deadline.timeLeft()); Future<Object> jobFinished = gateway.ask(new TestingJobManagerMessages.NotifyWhenJobRemoved(jobGraph.getJobID()), deadline.timeLeft()); BlockingInvokable.unblock(); // wait til the job has finished Await.ready(jobFinished, deadline.timeLeft()); // check that the job has been removed from the submitted job graph store assertFalse(mySubmittedJobGraphStore.contains(jobGraph.getJobID())); // Check that state has been recovered long[] recoveredStates = BlockingStatefulInvokable.getRecoveredStates(); for (long state : recoveredStates) { boolean isExpected = state >= BlockingStatefulInvokable.NUM_CHECKPOINTS_TO_COMPLETE; assertTrue("Did not recover checkpoint state correctly, expecting >= " + BlockingStatefulInvokable.NUM_CHECKPOINTS_TO_COMPLETE + ", but state was " + state, isExpected); } } finally { if (archive != null) { archive.tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.tell(PoisonPill.getInstance(), ActorRef.noSender()); } } } /** * Tests that a failing job recovery won't cause other job recoveries to fail. */ @Test public void testFailingJobRecovery() throws Exception { final FiniteDuration timeout = new FiniteDuration(10, TimeUnit.SECONDS); final FiniteDuration jobRecoveryTimeout = new FiniteDuration(0, TimeUnit.SECONDS); Deadline deadline = new FiniteDuration(1, TimeUnit.MINUTES).fromNow(); final Configuration flinkConfiguration = new Configuration(); UUID leaderSessionID = UUID.randomUUID(); ActorRef jobManager = null; JobID jobId1 = new JobID(); JobID jobId2 = new JobID(); // set HA mode to zookeeper so that we try to recover jobs flinkConfiguration.setString(HighAvailabilityOptions.HA_MODE, "zookeeper"); try { final SubmittedJobGraphStore submittedJobGraphStore = mock(SubmittedJobGraphStore.class); SubmittedJobGraph submittedJobGraph = mock(SubmittedJobGraph.class); when(submittedJobGraph.getJobId()).thenReturn(jobId2); when(submittedJobGraphStore.getJobIds()).thenReturn(Arrays.asList(jobId1, jobId2)); // fail the first job recovery when(submittedJobGraphStore.recoverJobGraph(eq(jobId1))).thenThrow(new Exception("Test exception")); // succeed the second job recovery when(submittedJobGraphStore.recoverJobGraph(eq(jobId2))).thenReturn(submittedJobGraph); final TestingLeaderElectionService myLeaderElectionService = new TestingLeaderElectionService(); final Collection<JobID> recoveredJobs = new ArrayList<>(2); Props jobManagerProps = Props.create( TestingFailingHAJobManager.class, flinkConfiguration, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), mock(InstanceManager.class), mock(Scheduler.class), new BlobLibraryCacheManager(mock(BlobService.class), 1 << 20), ActorRef.noSender(), new FixedDelayRestartStrategy.FixedDelayRestartStrategyFactory(Int.MaxValue(), 100), timeout, myLeaderElectionService, submittedJobGraphStore, mock(CheckpointRecoveryFactory.class), jobRecoveryTimeout, Option.<MetricRegistry>apply(null), recoveredJobs).withDispatcher(CallingThreadDispatcher.Id()); jobManager = system.actorOf(jobManagerProps); Future<Object> started = Patterns.ask(jobManager, new Identify(42), deadline.timeLeft().toMillis()); Await.ready(started, deadline.timeLeft()); // make the job manager the leader --> this triggers the recovery of all jobs myLeaderElectionService.isLeader(leaderSessionID); // check that we have successfully recovered the second job assertThat(recoveredJobs, containsInAnyOrder(jobId2)); } finally { TestingUtils.stopActor(jobManager); } } static class TestingFailingHAJobManager extends JobManager { private final Collection<JobID> recoveredJobs; public TestingFailingHAJobManager( Configuration flinkConfiguration, ScheduledExecutorService futureExecutor, Executor ioExecutor, InstanceManager instanceManager, Scheduler scheduler, BlobLibraryCacheManager libraryCacheManager, ActorRef archive, RestartStrategyFactory restartStrategyFactory, FiniteDuration timeout, LeaderElectionService leaderElectionService, SubmittedJobGraphStore submittedJobGraphs, CheckpointRecoveryFactory checkpointRecoveryFactory, FiniteDuration jobRecoveryTimeout, Option<MetricRegistry> metricsRegistry, Collection<JobID> recoveredJobs) { super( flinkConfiguration, futureExecutor, ioExecutor, instanceManager, scheduler, libraryCacheManager, archive, restartStrategyFactory, timeout, leaderElectionService, submittedJobGraphs, checkpointRecoveryFactory, jobRecoveryTimeout, metricsRegistry); this.recoveredJobs = recoveredJobs; } @Override public PartialFunction<Object, BoxedUnit> handleMessage() { return ReceiveBuilder.match( JobManagerMessages.RecoverSubmittedJob.class, new FI.UnitApply<JobManagerMessages.RecoverSubmittedJob>() { @Override public void apply(JobManagerMessages.RecoverSubmittedJob submitJob) throws Exception { recoveredJobs.add(submitJob.submittedJobGraph().getJobId()); } }).matchAny(new FI.UnitApply<Object>() { @Override public void apply(Object o) throws Exception { TestingFailingHAJobManager.super.handleMessage().apply(o); } }).build(); } } static class MyCheckpointRecoveryFactory implements CheckpointRecoveryFactory { private final CompletedCheckpointStore store; private final CheckpointIDCounter counter; public MyCheckpointRecoveryFactory(CompletedCheckpointStore store, CheckpointIDCounter counter) { this.store = store; this.counter = counter; } @Override public void start() { } @Override public void stop() { } @Override public CompletedCheckpointStore createCheckpointStore(JobID jobId, int maxNumberOfCheckpointsToRetain, ClassLoader userClassLoader) throws Exception { return store; } @Override public CheckpointIDCounter createCheckpointIDCounter(JobID jobId) throws Exception { return counter; } } static class MySubmittedJobGraphStore implements SubmittedJobGraphStore { Map<JobID, SubmittedJobGraph> storedJobs = new HashMap<>(); @Override public void start(SubmittedJobGraphListener jobGraphListener) throws Exception { } @Override public void stop() throws Exception { } @Override public SubmittedJobGraph recoverJobGraph(JobID jobId) throws Exception { if (storedJobs.containsKey(jobId)) { return storedJobs.get(jobId); } else { return null; } } @Override public void putJobGraph(SubmittedJobGraph jobGraph) throws Exception { storedJobs.put(jobGraph.getJobId(), jobGraph); } @Override public void removeJobGraph(JobID jobId) throws Exception { storedJobs.remove(jobId); } @Override public Collection<JobID> getJobIds() throws Exception { return storedJobs.keySet(); } boolean contains(JobID jobId) { return storedJobs.containsKey(jobId); } } public static class BlockingInvokable extends AbstractInvokable { private static boolean blocking = true; private static Object lock = new Object(); @Override public void invoke() throws Exception { while (blocking) { synchronized (lock) { lock.wait(); } } } public static void unblock() { blocking = false; synchronized (lock) { lock.notifyAll(); } } } public static class BlockingStatefulInvokable extends BlockingInvokable implements StatefulTask { private static final int NUM_CHECKPOINTS_TO_COMPLETE = 5; private static volatile CountDownLatch completedCheckpointsLatch = new CountDownLatch(1); private static volatile long[] recoveredStates = new long[0]; private int completedCheckpoints = 0; @Override public void setInitialState( TaskStateHandles taskStateHandles) throws Exception { int subtaskIndex = getIndexInSubtaskGroup(); if (subtaskIndex < recoveredStates.length) { try (FSDataInputStream in = taskStateHandles.getLegacyOperatorState().get(0).openInputStream()) { recoveredStates[subtaskIndex] = InstantiationUtil.deserializeObject(in, getUserCodeClassLoader()); } } } @Override public boolean triggerCheckpoint(CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) throws Exception { ByteStreamStateHandle byteStreamStateHandle = new TestByteStreamStateHandleDeepCompare( String.valueOf(UUID.randomUUID()), InstantiationUtil.serializeObject(checkpointMetaData.getCheckpointId())); ChainedStateHandle<StreamStateHandle> chainedStateHandle = new ChainedStateHandle<StreamStateHandle>(Collections.singletonList(byteStreamStateHandle)); SubtaskState checkpointStateHandles = new SubtaskState(chainedStateHandle, null, null, null, null); getEnvironment().acknowledgeCheckpoint( checkpointMetaData.getCheckpointId(), new CheckpointMetrics(0L, 0L, 0L, 0L), checkpointStateHandles); return true; } @Override public void triggerCheckpointOnBarrier(CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics) throws Exception { throw new UnsupportedOperationException("should not be called!"); } @Override public void abortCheckpointOnBarrier(long checkpointId, Throwable cause) { throw new UnsupportedOperationException("should not be called!"); } @Override public void notifyCheckpointComplete(long checkpointId) { if (completedCheckpoints++ > NUM_CHECKPOINTS_TO_COMPLETE) { completedCheckpointsLatch.countDown(); } } public static void initializeStaticHelpers(int numSubtasks) { completedCheckpointsLatch = new CountDownLatch(numSubtasks); recoveredStates = new long[numSubtasks]; } public static void awaitCompletedCheckpoints() throws InterruptedException { completedCheckpointsLatch.await(); } public static long[] getRecoveredStates() { return recoveredStates; } } }
/* * Copyright 2011, The gwtquery team. * * 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.gwt.query.rebind; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.ext.Generator; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.TreeLogger.Type; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JArrayType; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.JMethod; import com.google.gwt.core.ext.typeinfo.JParameter; import com.google.gwt.core.ext.typeinfo.JParameterizedType; import com.google.gwt.core.ext.typeinfo.JType; import com.google.gwt.core.ext.typeinfo.TypeOracle; import com.google.gwt.query.client.Function; import com.google.gwt.query.client.IsProperties; import com.google.gwt.query.client.Properties; import com.google.gwt.query.client.builders.JsonBuilder; import com.google.gwt.query.client.builders.JsonBuilderBase; import com.google.gwt.query.client.builders.JsonFactory; import com.google.gwt.query.client.builders.Name; import com.google.gwt.query.client.js.JsUtils; import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; import com.google.gwt.user.rebind.SourceWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** */ public class JsonBuilderGenerator extends Generator { static JClassType functionType; static JClassType jsonBuilderType; static JClassType settingsType; static JClassType jsType; static JClassType listType; static JClassType stringType; static JClassType jsonFactoryType; public static String capitalize(String s) { if (s.length() == 0) return s; return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } public static String classNameToJsonName(String name) { return deCapitalize(name.replaceAll("^.*[\\.\\$_]", "")); } public static String deCapitalize(String s) { return s == null || s.isEmpty() ? s : (s.substring(0, 1).toLowerCase() + (s.length() > 1 ? s.substring(1) : "")); } TypeOracle oracle; public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String requestedClass) throws UnableToCompleteException { oracle = generatorContext.getTypeOracle(); JClassType clazz = oracle.findType(requestedClass); jsonBuilderType = oracle.findType(JsonBuilder.class.getName()); settingsType = oracle.findType(IsProperties.class.getName()); stringType = oracle.findType(String.class.getName()); jsType = oracle.findType(JavaScriptObject.class.getName()); listType = oracle.findType(List.class.getName()); functionType = oracle.findType(Function.class.getName()); jsonFactoryType = oracle.findType(JsonFactory.class.getName()); String t[] = generateClassName(clazz); boolean isFactory = clazz.isAssignableTo(jsonFactoryType); SourceWriter sw = getSourceWriter(treeLogger, generatorContext, t[0], t[1], isFactory, requestedClass); if (sw != null) { if (isFactory) { generateCreateMethod(sw, treeLogger); } else { Set<String> attrs = new HashSet<String>(); for (JMethod method : clazz.getInheritableMethods()) { String methName = method.getName(); // skip method from JsonBuilder if (jsonBuilderType.findMethod(method.getName(), method.getParameterTypes()) != null || settingsType.findMethod(method.getName(), method.getParameterTypes()) != null) { continue; } Name nameAnnotation = method.getAnnotation(Name.class); String name = nameAnnotation != null ? nameAnnotation.value() : methName.replaceFirst("^(get|set)", ""); if (nameAnnotation == null) { name = name.substring(0, 1).toLowerCase() + name.substring(1); } attrs.add(name); generateMethod(sw, method, name, treeLogger); } generateFieldNamesMethod(sw, attrs, treeLogger); generateToJsonMethod(sw, t[3], treeLogger); } sw.commit(treeLogger); } return t[2]; } public String[] generateClassName(JType t) { String[] ret = new String[4]; JClassType c = t.isClassOrInterface(); ret[0] = c.getPackage().getName(); ret[1] = c.getName().replace('.', '_') + "_JsonBuilder"; ret[2] = ret[0] + "." + ret[1]; ret[3] = classNameToJsonName(c.getName()); return ret; } public void generateFieldNamesMethod(SourceWriter sw, Collection<String> attrs, TreeLogger logger) { String ret = ""; for (Iterator<String> it = attrs.iterator(); it.hasNext();) { ret += (ret.isEmpty() ? "" : ",") + "\"" + it.next() + "\""; } sw.println("{ fieldNames = new String[]{" + ret + "}; }"); } public void generateMethod(SourceWriter sw, JMethod method, String name, TreeLogger logger) throws UnableToCompleteException { String ifaceName = method.getEnclosingType().getQualifiedSourceName(); String retType = method.getReturnType().getParameterizedQualifiedSourceName(); sw.print("public final " + retType + " " + method.getName()); JParameter[] params = method.getParameters(); if (params.length == 0) { JArrayType arr = method.getReturnType().isArray(); JParameterizedType list = method.getReturnType().isParameterized(); sw.println("() {"); sw.indent(); if (retType.matches("(java.lang.Boolean|boolean)")) { sw.println("return p.getBoolean(\"" + name + "\");"); } else if (retType.matches("java.util.Date")) { sw.println("return new Date(java.lang.Long.parseLong(p.getStr(\"" + name + "\")));"); } else if (method.getReturnType().isPrimitive() != null) { sw.println("return (" + retType + ")p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Character")) { sw.println("return (char) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Byte")) { sw.println("return (byte) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Integer")) { sw.println("return (int) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Float")) { sw.println("return p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Double")) { sw.println("return (double) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Long")) { sw.println("return (long) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Byte")) { sw.println("return (byte) p.getFloat(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), stringType)) { sw.println("return p.getStr(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), jsonBuilderType)) { String q = method.getReturnType().getQualifiedSourceName(); sw.println("return " + "((" + q + ")GWT.create(" + q + ".class))" + ".load(getPropertiesBase(\"" + name + "\"));"); } else if (isTypeAssignableTo(method.getReturnType(), settingsType)) { String q = method.getReturnType().getQualifiedSourceName(); sw.println("return " + "((" + q + ")getPropertiesBase(\"" + name + "\"));"); } else if (retType.equals(Properties.class.getName())) { sw.println("return getPropertiesBase(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), jsType)) { sw.println("return p.getJavaScriptObject(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), functionType)) { sw.println("return p.getFunction(\"" + name + "\");"); } else if (arr != null || list != null) { JType type = arr != null ? arr.getComponentType() : list.getTypeArgs()[0]; boolean buildType = isTypeAssignableTo(type, jsonBuilderType); String t = type.getQualifiedSourceName(); sw.println("JsArrayMixed a = p.getArray(\"" + name + "\");"); sw.println("int l = a == null ? 0 : a.length();"); String ret; if (buildType) { sw.println(t + "[] r = new " + t + "[l];"); sw.println("JsObjectArray<?> a1 = p.getArray(\"" + name + "\").cast();"); sw.println("int l1 = r.length;"); sw.println("for (int i = 0 ; i < l1 ; i++) {"); sw.println(" Object w = a1.get(i);"); sw.println(" " + t + " instance = GWT.create(" + t + ".class);"); sw.println(" r[i] = instance.load(w);"); sw.println("}"); ret = "r"; } else { ret = "getArrayBase(\"" + name + "\", new " + t + "[l], " + t + ".class)"; } if (arr != null) { sw.println("return " + ret + ";"); } else { sw.println("return Arrays.asList(" + ret + ");"); } } else if (method.getReturnType().isEnum() != null) { sw.println("return " + method.getReturnType().getQualifiedSourceName() + ".valueOf(p.getStr(\"" + name + "\"));"); } else { sw.println("System.err.println(\"JsonBuilderGenerator WARN: unknown return type " + retType + " " + ifaceName + "." + name + "()\"); "); // We return the object because probably the user knows how to handle it sw.println("return p.get(\"" + name + "\");"); } sw.outdent(); sw.println("}"); } else if (params.length == 1) { JType type = params[0].getType(); JArrayType arr = type.isArray(); JParameterizedType list = type.isParameterized(); sw.print("(" + type.getParameterizedQualifiedSourceName() + " a)"); sw.println("{"); sw.indent(); if (arr != null || list != null) { String a = "a"; if (list != null) { a = "a.toArray(new " + list.getTypeArgs()[0].getQualifiedSourceName() + "[0])"; } sw.println("setArrayBase(\"" + name + "\", " + a + ");"); } else if (type.getParameterizedQualifiedSourceName().matches("java.util.Date")) { sw.println("p.setNumber(\"" + name + "\", a.getTime());"); } else if (type .getParameterizedQualifiedSourceName() .matches( "(java.lang.(Character|Long|Double|Integer|Float|Byte)|(char|long|double|int|float|byte))")) { sw.println("p.setNumber(\"" + name + "\", a);"); } else if (type.getParameterizedQualifiedSourceName().matches("(java.lang.Boolean|boolean)")) { sw.println("p.setBoolean(\"" + name + "\", a);"); } else if (type.getParameterizedQualifiedSourceName().matches( "com.google.gwt.query.client.Function")) { sw.println("p.setFunction(\"" + name + "\", a);"); } else if (type.isEnum() != null) { sw.println("p.set(\"" + name + "\", a.name());"); } else { sw.println("set(\"" + name + "\", a);"); } if (!"void".equals(retType)) { if (isTypeAssignableTo(method.getReturnType(), method.getEnclosingType())) { sw.println("return this;"); } else { sw.println("return null;"); } } sw.outdent(); sw.println("}"); } } public void generateToJsonMethod(SourceWriter sw, String name, TreeLogger logger) { sw.println("public final String getJsonName() {return \"" + name + "\";}"); } protected SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext context, String packageName, String className, boolean isFactory, String... interfaceNames) { PrintWriter printWriter = context.tryCreate(logger, packageName, className); if (printWriter == null) { return null; } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( packageName, className); if (!isFactory) { composerFactory.setSuperclass(JsonBuilderBase.class.getName() + "<" + packageName + "." + className + ">"); } composerFactory.addImport("com.google.gwt.query.client.js.*"); composerFactory.addImport("com.google.gwt.query.client.*"); composerFactory.addImport("com.google.gwt.core.client.*"); composerFactory.addImport("com.google.gwt.dom.client.*"); composerFactory.addImport("java.util.*"); for (String interfaceName : interfaceNames) { composerFactory.addImplementedInterface(interfaceName); } return composerFactory.createSourceWriter(context, printWriter); } public boolean isTypeAssignableTo(JType t, JClassType o) { JClassType c = t.isClassOrInterface(); return (c != null && c.isAssignableTo(o)); } private void generateCreateMethod(SourceWriter sw, TreeLogger logger) { sw.println("public <T extends " + JsonBuilder.class.getName() + "> T create(Class<T> clz) {"); sw.indent(); ArrayList<JClassType> types = new ArrayList<JClassType>(); for (JClassType t : oracle.getTypes()) { if (t.isInterface() != null && t.isAssignableTo(jsonBuilderType)) { if (t.isPublic()) { sw.println("if (clz == " + t.getQualifiedSourceName() + ".class) return GWT.<T>create(" + t.getQualifiedSourceName() + ".class);"); } else { logger.log(Type.WARN, t.getQualifiedSourceName() + " is not public"); } types.add(t); } } sw.println("return null;"); sw.outdent(); sw.println("}"); sw.println("public " + IsProperties.class.getName() + " create(String s) {"); sw.indent(); sw.println("return (" + IsProperties.class.getName() + ")" + JsUtils.class.getName() + ".parseJSON(s);"); sw.outdent(); sw.println("}"); sw.println("public " + IsProperties.class.getName() + " create() {"); sw.indent(); sw.println("return " + Properties.class.getName() + ".create();"); sw.outdent(); sw.println("}"); } }
/* This file is part of DPM, licensed under the MIT License (MIT). Copyright (c) 2014 Team 7 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. */ import lejos.nxt.*; /** * Performs navigation commands on a separate thread, which allows for sensor monitoring to be done on the calling thread. Commands can be aborted or the calling thread can be blocked until they * complete. Only one command at a time can be issued, any current command will be aborted. * <p/> * THREAD SAFE */ public class Navigation extends Thread { // Motor speed constants private static final int MOTOR_SPEED = 200; private static final int MOTOR_ACCELERATION = 1000; // Robot design contants private static final float CLAW_DOWN_EXTENSION = 4; // Motors (left and right) private final NXTRegulatedMotor leftMotor; private final NXTRegulatedMotor rightMotor; // Odometer instance private final Odometer odometer; // Properties for thread control and command execution private final Object condition = new Object(); private volatile boolean navigating = false; private volatile Runnable command = null; private volatile Thread runner = null; // Whether or not to use special forward navigation when carrying blocks private volatile boolean clawDownMode = false; /** * Created a new navigation class from the odometer to use to obtain position information for the robot. * * @param odometer The odometer that will provide the position information */ public Navigation(NXTRegulatedMotor leftMotor, NXTRegulatedMotor rightMotor, Odometer odometer) { this.leftMotor = leftMotor; this.rightMotor = rightMotor; this.odometer = odometer; } /** * Runs the navigation commands. */ public void run() { // Register the current thread as the runner, so we can interrupt it runner = Thread.currentThread(); while (true) { // Wait util a command is sent while (command == null) { try { synchronized (condition) { // Set navigation to false and start waiting navigating = false; condition.wait(); } } catch (InterruptedException ignored) { } } // Get the command and remove it Runnable c = command; command = null; // Execute it c.run(); } } /** * A special mode which reduces forward motion a bit to account for a longer robot caused by the claw being down. * * @param enable Whether or not to enable the claw down mode */ public void enableClawDownMode(boolean enable) { clawDownMode = enable; } /** * Travel by a relative distance in centimeters at the default speed. * * @param x The x distance * @param y The y distance */ public void travelBy(float x, float y) { travelBy(x, y, MOTOR_SPEED); } /** * Travel by a relative distance in centimeters at the desired speed. * * @param x The x distance * @param y The y distance * @param speed The speed */ public void travelBy(float x, float y, int speed) { Odometer.Position pos = odometer.getPosition(); travelTo(pos.x + x, pos.y + y, speed); } /** * Travel to absolute coordinates in centimeters at the default speed. * * @param x The x coordinate * @param y The y coordinate */ public void travelTo(float x, float y) { travelTo(x, y, MOTOR_SPEED); } /** * Travel to absolute coordinates in centimeters at the desired speed. * * @param x The x coordinate * @param y The y coordinate * @param speed The speed */ public void travelTo(float x, float y, int speed) { command = new Travel(x, y, speed); startCommand(); } /** * Turns by a relative angle in radians at the default speed. * * @param theta The angle */ public void turnBy(float theta) { turnBy(theta, MOTOR_SPEED); } /** * Turns by a relative angle in radians at the desired speed. * * @param theta The angle * @param speed The speed */ public void turnBy(float theta, int speed) { turnTo(odometer.getTheta() + theta, speed); } /** * Turns to an absolute angle in radians at the default speed. * * @param theta The angle */ public void turnTo(float theta) { turnTo(theta, MOTOR_SPEED); } /** * Turns to an absolute angle in radians at the desired speed. * * @param theta The angle * @param speed The speed */ public void turnTo(float theta, int speed) { command = new Turn(theta, speed); startCommand(); } /** * Moves backward by the specified distance at the default speed. * * @param distance The distance to travel backward */ public void backward(float distance) { backward(distance, MOTOR_SPEED); } /** * Moves backward by the specified distance at the desired speed. * * @param distance The distance to travel backward * @param speed The speed */ public void backward(float distance, int speed) { forward(-distance, speed); } /** * Moves forward by the specified distance at the default speed. * * @param distance The distance to travel forward */ public void forward(float distance) { forward(distance, MOTOR_SPEED); } /** * Moves forward by the specified distance at the desired speed. * * @param distance The distance to travel forward * @param speed The speed */ public void forward(float distance, int speed) { float theta = odometer.getTheta(); float x = (float) Math.cos(theta) * distance; float y = (float) Math.sin(theta) * distance; travelBy(x, y, speed); } /** * Return true if robot is navigating (command is under execution) * * @return Whether or not the robot it navigating */ public boolean isNavigating() { return navigating; } /** * Wait until navigation is over, by yielding the calling thread until {@link #isNavigating()} returns false. */ public void waitUntilDone() { while (navigating) { Thread.yield(); } } /** * Aborts any navigation in progress. */ public void abort() { if (navigating) { runner.interrupt(); } } /** * Getter for the odometer * * @return the odometer */ public Odometer getOdometer() { return odometer; } // Starts a navigation command private void startCommand() { if (navigating) { // Interrupt it running runner.interrupt(); } else { // Else set navigation state and notify runner synchronized (condition) { navigating = true; condition.notify(); } } } private void doTravel(float x, float y, int speed) { // Set motor speeds and acceleration leftMotor.setSpeed(speed); leftMotor.setAcceleration(MOTOR_ACCELERATION); rightMotor.setSpeed(speed); rightMotor.setAcceleration(MOTOR_ACCELERATION); // Find delta of movement float differenceX = x - odometer.getX(); float differenceY = y - odometer.getY(); // Compute movement: find turn angle and travel distance float theta = (float) Math.atan2(differenceY, differenceX); float distance = (float) Math.sqrt(differenceX * differenceX + differenceY * differenceY); // Negate values if going backwards will be faster if (getAngleDiff(theta, odometer.getTheta()) > (clawDownMode ? Pi.THREE_QUARTER : Pi.ONE_HALF)) { theta = Pi.wrapAngle(theta - Pi.ONE); distance = -distance; } else if (clawDownMode) { distance -= CLAW_DOWN_EXTENSION; } // Do turn doTurn(theta, speed); // Calculate the rotation to apply to the wheels int rotationDegreesLeft = (int) Math.round(Math.toDegrees(distance / Wheel.LEFT_RADIUS)); int rotationDegreesRight = (int) Math.round(Math.toDegrees(distance / Wheel.RIGHT_RADIUS)); // Move the robot leftMotor.rotate(rotationDegreesLeft, true); rightMotor.rotate(rotationDegreesRight, true); // Wait for completion while (leftMotor.isMoving() || rightMotor.isMoving()) { // check for thread interruption, aka command abort if (interrupted()) { // end early break; } Thread.yield(); } endCommand(); } private void doTurn(float theta, int speed) { // Set motor speeds and acceleration leftMotor.setSpeed(speed); leftMotor.setAcceleration(MOTOR_ACCELERATION); rightMotor.setSpeed(speed); rightMotor.setAcceleration(MOTOR_ACCELERATION); // Find min angle difference float difference = theta - odometer.getTheta(); if (difference >= Pi.ONE) { difference = -Pi.TWO + difference; } else if (difference <= -Pi.ONE) { difference = Pi.TWO + difference; } // Compute wheel rotation in angle float wheelRotationLeft = (difference * Wheel.DISTANCE / Wheel.LEFT_RADIUS) / 2; float wheelRotationRight = (difference * Wheel.DISTANCE / Wheel.RIGHT_RADIUS) / 2; int rotationDegreesLeft = (int) Math.round(Math.toDegrees(wheelRotationLeft)); int rotationDegreesRight = (int) Math.round(Math.toDegrees(wheelRotationRight)); // Rotate leftMotor.rotate(-rotationDegreesLeft, true); rightMotor.rotate(rotationDegreesRight, true); // Wait for completion while (leftMotor.isMoving() || rightMotor.isMoving()) { // check for thread interruption, aka command abort if (interrupted()) { // end early break; } Thread.yield(); } endCommand(); } private void endCommand() { // Stop travel leftMotor.stop(true); rightMotor.stop(false); } // Get the absolute difference between two angles private static double getAngleDiff(float a, float b) { // Convert to vectors and use dot product to compute angle in between return Math.abs((float) Math.acos(Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b))); } // A command to travel to absolute coordinates private class Travel implements Runnable { private final float x, y; private final int speed; private Travel(float x, float y, int speed) { this.x = x; this.y = y; this.speed = speed; } public void run() { doTravel(x, y, speed); } } // A command to rotate to an absolute angle private class Turn implements Runnable { private final float theta; private final int speed; private Turn(float theta, int speed) { this.theta = Pi.wrapAngle(theta); this.speed = speed; } public void run() { doTurn(theta, speed); } } }
/** * Copyright 2010-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 ch.ralscha.extdirectspring.controller; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.Cookie; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import ch.ralscha.extdirectspring.bean.ExtDirectResponse; import ch.ralscha.extdirectspring.provider.FormInfo; import ch.ralscha.extdirectspring.provider.RemoteProviderSimpleNamed.ResultObject; import ch.ralscha.extdirectspring.provider.RemoteProviderSimpleNamed.TestObject; import ch.ralscha.extdirectspring.provider.Row; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration("classpath:/testApplicationContext.xml") public class RouterControllerSimpleNamedTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @BeforeAll public static void beforeTest() { Locale.setDefault(Locale.US); } @BeforeEach public void setupMockMvc() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void testNoParameters() { ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method1", "method1() called", null); } @Test public void testNoParametersWithRequestParameter() { Map<String, Object> params = new LinkedHashMap<>(); params.put("requestparameter", "aValue"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method1", "method1() called", params); } @Test public void testNonStrictMethod1() { Map<String, Object> params = new LinkedHashMap<>(); params.put("d", 2.2); params.put("s", "anotherString"); params.put("i", 23); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "nonStrictMethod1", "nonStrictMethod1() called-23-2.200-anotherString", params); } @Test public void testNonStrictMethod2() { Map<String, Object> params = new LinkedHashMap<>(); params.put("d", 2.2); params.put("i", 23); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "nonStrictMethod2", "nonStrictMethod2() called-23-2.200-null", params); } @Test public void testNonStrictMethod3() { List<Cookie> cookies = new ArrayList<>(); cookies.add(new Cookie("aSimpleCookie", "cookie")); HttpHeaders headers = new HttpHeaders(); headers.add("aSimpleHeader", "header"); Map<String, Object> params = new LinkedHashMap<>(); params.put("i", 17); ControllerUtil.sendAndReceiveNamed(this.mockMvc, headers, cookies, "remoteProviderSimpleNamed", "nonStrictMethod3", "nonStrictMethod3() called-17-cookie-header", params); } @Test public void testWithParameters() { Map<String, Object> params = new LinkedHashMap<>(); params.put("d", 2.1); params.put("s", "aString"); params.put("i", 30); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method2", "method2() called-30-2.100-aString", params); } @Test public void testWithWrongParameters() { Map<String, Object> params = new LinkedHashMap<>(); params.put("i", 20); params.put("de", 2.1); params.put("s", "aString"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method2", null, params); } @Test public void testWithMissingParameters() { Map<String, Object> params = new LinkedHashMap<>(); params.put("i", 20); params.put("s", "aString"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method2", null, params); } @Test public void testWithParametersWithTypeConversion() { Map<String, Object> params = new LinkedHashMap<>(); params.put("i", "30"); params.put("s", 100.45); params.put("d", "3.141"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method2", "method2() called-30-3.141-100.45", params); } @Test public void testResultTrue() { Map<String, Object> params = new LinkedHashMap<>(); params.put("userName", "ralph"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method3", Boolean.TRUE, params); } @Test public void testResultFalse() { Map<String, Object> params = new LinkedHashMap<>(); params.put("userName", "joe"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method3", Boolean.FALSE, params); } @Test public void testResultNull() { Map<String, Object> params = new LinkedHashMap<>(); params.put("userName", "martin"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method3", Void.TYPE, params); } @Test public void testIntParameterAndResult() { Map<String, Object> params = new LinkedHashMap<>(); params.put("a", 10); params.put("b", 20); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method4", 30, params); } @Test public void testIntParameterAndResultWithTypeConversion() { Map<String, Object> params = new LinkedHashMap<>(); params.put("b", "40"); params.put("a", "30"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method4", 70, params); } @Test public void testReturnsObject() { Map<String, Object> params = new LinkedHashMap<>(); params.put("d", 7.34); FormInfo info = (FormInfo) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method5", FormInfo.class, params); assertThat(info.getBack()).isEqualTo(7.34); assertThat(info.isAdmin()).isEqualTo(Boolean.FALSE); assertThat(info.getAge()).isEqualTo(32); assertThat(info.getName()).isEqualTo("John"); assertThat(info.getSalary()).isEqualTo(new BigDecimal("8720.2")); assertThat(info.getBirthday()) .isEqualTo(new GregorianCalendar(1986, Calendar.JULY, 22).getTime()); } @Test public void testSupportedArguments() { ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method6", 42, null); } @Test public void testTypeConversion() { Map<String, Object> params = new LinkedHashMap<>(); params.put("flag", "true"); params.put("aCharacter", "c"); params.put("workflow", "PENDING"); params.put("aInt", "14"); params.put("aLong", "21"); params.put("aByte", "2"); params.put("aDouble", "3.14"); params.put("aFloat", "10.01"); params.put("aShort", "1"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method7", "method7() called-true-c-PENDING-14-21-3.14-10.01-1-2", params); } @Test public void testMixParameterAndSupportedParameters() { Map<String, Object> params = new LinkedHashMap<>(); params.put("aLong", "21"); params.put("aDouble", "3.14"); params.put("aFloat", "10.01"); params.put("flag", "true"); params.put("aCharacter", "c"); params.put("workflow", "PENDING"); params.put("aInt", "14"); params.put("aShort", "1"); params.put("aByte", "2"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method10", "method10() called-true-c-PENDING-14-21-3.14-10.01-1-2", params); } @Test public void testTypeConversionWithObjects() { Row aRow = new Row(104, "myRow", true, "100.45"); Map<String, Object> params = new LinkedHashMap<>(); params.put("aRow", aRow); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method9", "Row [id=104, name=myRow, admin=true, salary=100.45]", params); } @Test @SuppressWarnings("unchecked") public void testWithConversion() { LocalDate todayDate = LocalDate.now(); OffsetDateTime todayDateTime = OffsetDateTime.now(); Map<String, Object> params = new LinkedHashMap<>(); params.put("endDate", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(todayDateTime)); params.put("aDate", DateTimeFormatter.ISO_DATE.format(todayDate)); params.put("normalParameter", "normalParameter"); params.put("percent", "99.9%"); Map<String, Object> resultMap = (Map<String, Object>) ControllerUtil .sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "method11", Map.class, params); assertThat(resultMap.get("endDate")).isEqualTo( Long.valueOf(todayDateTime.toInstant().getEpochSecond()).intValue()); assertThat(resultMap.get("localDate")) .isEqualTo(DateTimeFormatter.ISO_DATE.format(todayDate)); assertThat(resultMap.get("percent")).isEqualTo(0.999); assertThat(resultMap.get("normalParameter")).isEqualTo("normalParameter"); assertThat(resultMap.get("remoteAddr")).isEqualTo("127.0.0.1"); } @Test public void testDifferentParameterNames() { ResultObject expectedResult = new ResultObject("Miller", 10, Boolean.TRUE); Map<String, Object> params = new LinkedHashMap<>(); params.put("lastName", expectedResult.getName()); params.put("theAge", expectedResult.getAge()); params.put("active", expectedResult.getActive()); ResultObject result = (ResultObject) ControllerUtil.sendAndReceiveNamed( this.mockMvc, "remoteProviderSimpleNamed", "methodRP1", ResultObject.class, params); assertThat(result).isEqualTo(expectedResult); } @Test public void testCollections() { Map<String, Object> params = new LinkedHashMap<>(); params.put("name", "first"); TestObject ce = new TestObject(23, "Meier", Boolean.FALSE, new BigDecimal("100.23")); params.put("collections", Collections.singleton(ce)); String result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection1", String.class, params); assertThat(result).isEqualTo( "1->first;[TestObject [id=23, name=Meier, active=false, amount=100.23]]"); params = new LinkedHashMap<>(); params.put("name", "2nd"); List<TestObject> list = new ArrayList<>(); list.add(new TestObject(1, "One", Boolean.TRUE, new BigDecimal("1.1"))); list.add(new TestObject(2, "Two", Boolean.FALSE, new BigDecimal("1.2"))); list.add(new TestObject(3, "Three", Boolean.TRUE, new BigDecimal("1.3"))); params.put("collections", list); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection1", String.class, params); assertThat(result).isEqualTo( "1->2nd;[TestObject [id=1, name=One, active=true, amount=1.1], TestObject [id=2, name=Two, active=false, amount=1.2], TestObject [id=3, name=Three, active=true, amount=1.3]]"); params = new LinkedHashMap<>(); params.put("name", "3rd"); params.put("collections", Collections.emptyList()); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection1", String.class, params); assertThat(result).isEqualTo("1->3rd;[]"); params = new LinkedHashMap<>(); params.put("name", "4"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection1", null, params); params = new LinkedHashMap<>(); params.put("name", "4"); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection2", String.class, params); assertThat(result).isEqualTo("2->4;null"); } @Test public void testCollectionsWithoutGeneric() { Map<String, Object> params = new LinkedHashMap<>(); params.put("name", "Joan1"); TestObject ce = new TestObject(33, "Meier", Boolean.TRUE, new BigDecimal("33.334")); params.put("collections", Collections.singleton(ce)); String result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection3", String.class, params); assertThat(result) .isEqualTo("3->Joan1;[{id=33, name=Meier, active=true, amount=33.334}]"); params = new LinkedHashMap<>(); params.put("name", "Joan2"); List<TestObject> list = new ArrayList<>(); list.add(new TestObject(1, "1", Boolean.TRUE, new BigDecimal("1.1"))); list.add(new TestObject(2, "2", Boolean.FALSE, new BigDecimal("1.2"))); list.add(new TestObject(3, "3", Boolean.TRUE, new BigDecimal("1.3"))); params.put("collections", list); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection3", String.class, params); assertThat(result).isEqualTo( "3->Joan2;[{id=1, name=1, active=true, amount=1.1}, {id=2, name=2, active=false, amount=1.2}, {id=3, name=3, active=true, amount=1.3}]"); params = new LinkedHashMap<>(); params.put("name", "Joan3"); params.put("collections", Collections.emptyList()); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodCollection3", String.class, params); assertThat(result).isEqualTo("3->Joan3;[]"); } @Test public void testArrays() { Map<String, Object> params = new LinkedHashMap<>(); params.put("name", "arr1"); TestObject ce = new TestObject(23, "Meier", Boolean.FALSE, new BigDecimal("100.23")); params.put("array", Collections.singleton(ce)); String result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray1", String.class, params); assertThat(result).isEqualTo( "3->arr1;TestObject [id=23, name=Meier, active=false, amount=100.23]-"); params = new LinkedHashMap<>(); params.put("name", "arr2"); List<TestObject> list = new ArrayList<>(); list.add(new TestObject(1, "One", Boolean.TRUE, new BigDecimal("1.1"))); list.add(new TestObject(2, "Two", Boolean.FALSE, new BigDecimal("1.2"))); list.add(new TestObject(3, "Three", Boolean.TRUE, new BigDecimal("1.3"))); params.put("array", list); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray1", String.class, params); assertThat(result).isEqualTo( "3->arr2;TestObject [id=1, name=One, active=true, amount=1.1]-TestObject [id=2, name=Two, active=false, amount=1.2]-TestObject [id=3, name=Three, active=true, amount=1.3]-"); params = new LinkedHashMap<>(); params.put("name", "arr3"); params.put("array", Collections.emptyList()); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray1", String.class, params); assertThat(result).isEqualTo("3->arr3;"); params = new LinkedHashMap<>(); params.put("name", "arr4"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray1", null, params); params = new LinkedHashMap<>(); params.put("name", "arr4"); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray2", String.class, params); assertThat(result).isEqualTo("4->arr4;"); } @Test public void testArraysEllipsis() { Map<String, Object> params = new LinkedHashMap<>(); params.put("name", "arre1"); TestObject ce = new TestObject(24, "Kiere", Boolean.FALSE, new BigDecimal("1001.23")); params.put("array", Collections.singleton(ce)); String result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray3", String.class, params); assertThat(result).isEqualTo( "5->arre1;TestObject [id=24, name=Kiere, active=false, amount=1001.23]-"); params = new LinkedHashMap<>(); params.put("name", "arre2"); List<TestObject> list = new ArrayList<>(); list.add(new TestObject(1, "One1", Boolean.TRUE, new BigDecimal("1.1"))); list.add(new TestObject(2, "Two2", Boolean.FALSE, new BigDecimal("1.2"))); list.add(new TestObject(3, "Three3", Boolean.TRUE, new BigDecimal("1.3"))); params.put("array", list); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray3", String.class, params); assertThat(result).isEqualTo( "5->arre2;TestObject [id=1, name=One1, active=true, amount=1.1]-TestObject [id=2, name=Two2, active=false, amount=1.2]-TestObject [id=3, name=Three3, active=true, amount=1.3]-"); params = new LinkedHashMap<>(); params.put("name", "arre3"); params.put("array", Collections.emptyList()); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray3", String.class, params); assertThat(result).isEqualTo("5->arre3;"); params = new LinkedHashMap<>(); params.put("name", "arre4"); ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray3", null, params); params = new LinkedHashMap<>(); params.put("name", "arre4"); result = (String) ControllerUtil.sendAndReceiveNamed(this.mockMvc, "remoteProviderSimpleNamed", "methodArray4", String.class, params); assertThat(result).isEqualTo("6->arre4;"); } @Test public void testDefaultValues() throws Exception { List<String> multiRequests = new ArrayList<>(); Map<String, Object> params = new LinkedHashMap<>(); params.put("lastName", "Olstead"); params.put("theAge", "33"); params.put("active", Boolean.FALSE); String edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 2, params, null); multiRequests.add(edRequest); MvcResult result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); List<ExtDirectResponse> responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 2, new ResultObject("Olstead", 33, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("theAge", "33"); params.put("active", Boolean.FALSE); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 3, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 3, new ResultObject("myName", 33, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("lastName", "Olstead"); params.put("active", Boolean.FALSE); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 4, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 4, new ResultObject("Olstead", 20, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("lastName", "Olstead"); params.put("theAge", 36); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 5, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 5, new ResultObject("Olstead", 36, Boolean.TRUE), responses); params = new LinkedHashMap<>(); params.put("active", Boolean.FALSE); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 6, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 6, new ResultObject("myName", 20, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("lastName", "Miller"); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 7, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 7, new ResultObject("Miller", 20, Boolean.TRUE), responses); params = new LinkedHashMap<>(); params.put("theAge", 55); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 8, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 8, new ResultObject("myName", 55, Boolean.TRUE), responses); params = new LinkedHashMap<>(); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP2", true, 9, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP2", 9, new ResultObject("myName", 20, Boolean.TRUE), responses); StringBuilder sb = new StringBuilder(); sb.append("["); for (String requests : multiRequests) { sb.append(requests); sb.append(","); } sb.replace(sb.length() - 1, sb.length(), "]"); result = ControllerUtil.performRouterRequest(this.mockMvc, sb.toString()); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertThat(responses).hasSize(8); assertResponse("remoteProviderSimpleNamed", "methodRP2", 2, new ResultObject("Olstead", 33, Boolean.FALSE), responses.subList(0, 1)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 3, new ResultObject("myName", 33, Boolean.FALSE), responses.subList(1, 2)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 4, new ResultObject("Olstead", 20, Boolean.FALSE), responses.subList(2, 3)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 5, new ResultObject("Olstead", 36, Boolean.TRUE), responses.subList(3, 4)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 6, new ResultObject("myName", 20, Boolean.FALSE), responses.subList(4, 5)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 7, new ResultObject("Miller", 20, Boolean.TRUE), responses.subList(5, 6)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 8, new ResultObject("myName", 55, Boolean.TRUE), responses.subList(6, 7)); assertResponse("remoteProviderSimpleNamed", "methodRP2", 9, new ResultObject("myName", 20, Boolean.TRUE), responses.subList(7, 8)); } @Test public void testOptionalNoDefaultValue() throws Exception { List<String> multiRequests = new ArrayList<>(); Map<String, Object> params = new LinkedHashMap<>(); params.put("lastName", "Olstead"); params.put("theAge", "33"); params.put("active", Boolean.FALSE); String edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 2, params, null); multiRequests.add(edRequest); MvcResult result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); List<ExtDirectResponse> responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 2, new ResultObject("Olstead", 33, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("theAge", "33"); params.put("active", Boolean.FALSE); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 3, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 3, new ResultObject(null, 33, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("lastName", "Olstead"); params.put("active", Boolean.FALSE); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 4, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 4, new ResultObject("Olstead", null, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("lastName", "Olstead"); params.put("theAge", 36); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 5, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 5, new ResultObject("Olstead", 36, null), responses); params = new LinkedHashMap<>(); params.put("active", Boolean.FALSE); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 6, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 6, new ResultObject(null, null, Boolean.FALSE), responses); params = new LinkedHashMap<>(); params.put("lastName", "Miller"); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 7, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 7, new ResultObject("Miller", null, null), responses); params = new LinkedHashMap<>(); params.put("theAge", 55); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 8, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 8, new ResultObject(null, 55, null), responses); params = new LinkedHashMap<>(); edRequest = ControllerUtil.createEdsRequest("remoteProviderSimpleNamed", "methodRP3", true, 9, params, null); multiRequests.add(edRequest); result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertResponse("remoteProviderSimpleNamed", "methodRP3", 9, new ResultObject(null, null, null), responses); StringBuilder sb = new StringBuilder(); sb.append("["); for (String requests : multiRequests) { sb.append(requests); sb.append(","); } sb.replace(sb.length() - 1, sb.length(), "]"); result = ControllerUtil.performRouterRequest(this.mockMvc, sb.toString()); responses = ControllerUtil .readDirectResponses(result.getResponse().getContentAsByteArray()); assertThat(responses).hasSize(8); assertResponse("remoteProviderSimpleNamed", "methodRP3", 2, new ResultObject("Olstead", 33, Boolean.FALSE), responses.subList(0, 1)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 3, new ResultObject(null, 33, Boolean.FALSE), responses.subList(1, 2)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 4, new ResultObject("Olstead", null, Boolean.FALSE), responses.subList(2, 3)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 5, new ResultObject("Olstead", 36, null), responses.subList(3, 4)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 6, new ResultObject(null, null, Boolean.FALSE), responses.subList(4, 5)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 7, new ResultObject("Miller", null, null), responses.subList(5, 6)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 8, new ResultObject(null, 55, null), responses.subList(6, 7)); assertResponse("remoteProviderSimpleNamed", "methodRP3", 9, new ResultObject(null, null, null), responses.subList(7, 8)); } @Test public void testCookie() { List<Cookie> cookies = new ArrayList<>(); cookies.add(new Cookie("aSimpleCookie", "ralph")); Map<String, Object> params = new HashMap<>(); params.put("i", 99L); ControllerUtil.sendAndReceiveNamed(this.mockMvc, null, cookies, "remoteProviderSimpleNamed", "withCookie", "99:ralph", params); params = new HashMap<>(); params.put("i", 102L); ControllerUtil.sendAndReceiveNamed(this.mockMvc, null, null, "remoteProviderSimpleNamed", "withCookie", "102:defaultCookie", params); cookies = new ArrayList<>(); cookies.add(new Cookie("aSimpleCookie", "ralph2")); params = new HashMap<>(); params.put("i", 102L); ControllerUtil.sendAndReceiveNamed(this.mockMvc, null, cookies, "remoteProviderSimpleNamed", "withRequiredCookie", "102:ralph2", params); params = new HashMap<>(); params.put("i", 102L); ControllerUtil.sendAndReceiveNamed(this.mockMvc, null, null, "remoteProviderSimpleNamed", "withRequiredCookie", null, params); } @Test public void testRequestHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("aSimpleHeader", "theHeaderValue"); Map<String, Object> params = new HashMap<>(); params.put("bd", new BigDecimal("1.1")); ControllerUtil.sendAndReceiveNamed(this.mockMvc, headers, null, "remoteProviderSimpleNamed", "withRequestHeader", "1.1:theHeaderValue", params); params = new HashMap<>(); params.put("bd", new BigDecimal("1.2")); ControllerUtil.sendAndReceiveNamed(this.mockMvc, null, null, "remoteProviderSimpleNamed", "withRequestHeader", "1.2:defaultHeader", params); headers = new HttpHeaders(); headers.add("aSimpleHeader", "theHeaderValue2"); params = new HashMap<>(); params.put("bd", new BigDecimal("1.2")); ControllerUtil.sendAndReceiveNamed(this.mockMvc, headers, null, "remoteProviderSimpleNamed", "withRequiredRequestHeader", "1.2:theHeaderValue2", params); params = new HashMap<>(); params.put("bd", new BigDecimal("1.3")); ControllerUtil.sendAndReceiveNamed(this.mockMvc, null, null, "remoteProviderSimpleNamed", "withRequiredRequestHeader", null, params); } private static void assertResponse(String bean, String method, int tid, ResultObject expectedResult, List<ExtDirectResponse> responses) { assertThat(responses).hasSize(1); ExtDirectResponse resp = responses.get(0); assertThat(resp.getAction()).isEqualTo(bean); assertThat(resp.getMethod()).isEqualTo(method); assertThat(resp.getTid()).isEqualTo(tid); assertThat(resp.getType()).isEqualTo("rpc"); assertThat(resp.getWhere()).isNull(); assertThat(resp.getMessage()).isNull(); ResultObject result = ControllerUtil.convertValue(resp.getResult(), ResultObject.class); assertThat(result).isEqualTo(expectedResult); } }
/* * Copyright 2012-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.boot.actuate.autoconfigure.security.servlet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.web.PathMappedEndpoints; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPathProvider; import org.springframework.boot.security.servlet.ApplicationContextRequestMatcher; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; /** * Factory that can be used to create a {@link RequestMatcher} for actuator endpoint * locations. * * @author Madhura Bhave * @author Phillip Webb * @since 2.0.0 */ public final class EndpointRequest { private static final RequestMatcher EMPTY_MATCHER = (request) -> false; private EndpointRequest() { } /** * Returns a matcher that includes all {@link Endpoint actuator endpoints}. It also * includes the links endpoint which is present at the base path of the actuator * endpoints. The {@link EndpointRequestMatcher#excluding(Class...) excluding} method * can be used to further remove specific endpoints if required. For example: * <pre class="code"> * EndpointRequest.toAnyEndpoint().excluding(ShutdownEndpoint.class) * </pre> * @return the configured {@link RequestMatcher} */ public static EndpointRequestMatcher toAnyEndpoint() { return new EndpointRequestMatcher(true); } /** * Returns a matcher that includes the specified {@link Endpoint actuator endpoints}. * For example: <pre class="code"> * EndpointRequest.to(ShutdownEndpoint.class, HealthEndpoint.class) * </pre> * @param endpoints the endpoints to include * @return the configured {@link RequestMatcher} */ public static EndpointRequestMatcher to(Class<?>... endpoints) { return new EndpointRequestMatcher(endpoints, false); } /** * Returns a matcher that includes the specified {@link Endpoint actuator endpoints}. * For example: <pre class="code"> * EndpointRequest.to("shutdown", "health") * </pre> * @param endpoints the endpoints to include * @return the configured {@link RequestMatcher} */ public static EndpointRequestMatcher to(String... endpoints) { return new EndpointRequestMatcher(endpoints, false); } /** * Returns a matcher that matches only on the links endpoint. It can be used when * security configuration for the links endpoint is different from the other * {@link Endpoint actuator endpoints}. The * {@link EndpointRequestMatcher#excludingLinks() excludingLinks} method can be used * in combination with this to remove the links endpoint from * {@link EndpointRequest#toAnyEndpoint() toAnyEndpoint}. For example: * <pre class="code"> * EndpointRequest.toLinks() * </pre> * @return the configured {@link RequestMatcher} */ public static LinksRequestMatcher toLinks() { return new LinksRequestMatcher(); } /** * Base class for supported request matchers. */ private abstract static class AbstractRequestMatcher extends ApplicationContextRequestMatcher<WebApplicationContext> { private volatile RequestMatcher delegate; AbstractRequestMatcher() { super(WebApplicationContext.class); } @Override protected final void initialized(Supplier<WebApplicationContext> context) { this.delegate = createDelegate(context.get()); } @Override protected final boolean matches(HttpServletRequest request, Supplier<WebApplicationContext> context) { return this.delegate.matches(request); } private RequestMatcher createDelegate(WebApplicationContext context) { try { String servletPath = getServletPath(context); RequestMatcherFactory requestMatcherFactory = (StringUtils .hasText(servletPath) ? new RequestMatcherFactory(servletPath) : RequestMatcherFactory.withEmptyServletPath()); return createDelegate(context, requestMatcherFactory); } catch (NoSuchBeanDefinitionException ex) { return EMPTY_MATCHER; } } private String getServletPath(WebApplicationContext context) { try { return context.getBean(DispatcherServletPathProvider.class) .getServletPath(); } catch (NoSuchBeanDefinitionException ex) { return ""; } } protected abstract RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory); } /** * The request matcher used to match against {@link Endpoint actuator endpoints}. */ public static final class EndpointRequestMatcher extends AbstractRequestMatcher { private final List<Object> includes; private final List<Object> excludes; private final boolean includeLinks; private EndpointRequestMatcher(boolean includeLinks) { this(Collections.emptyList(), Collections.emptyList(), includeLinks); } private EndpointRequestMatcher(Class<?>[] endpoints, boolean includeLinks) { this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), includeLinks); } private EndpointRequestMatcher(String[] endpoints, boolean includeLinks) { this(Arrays.asList((Object[]) endpoints), Collections.emptyList(), includeLinks); } private EndpointRequestMatcher(List<Object> includes, List<Object> excludes, boolean includeLinks) { this.includes = includes; this.excludes = excludes; this.includeLinks = includeLinks; } public EndpointRequestMatcher excluding(Class<?>... endpoints) { List<Object> excludes = new ArrayList<>(this.excludes); excludes.addAll(Arrays.asList((Object[]) endpoints)); return new EndpointRequestMatcher(this.includes, excludes, this.includeLinks); } public EndpointRequestMatcher excluding(String... endpoints) { List<Object> excludes = new ArrayList<>(this.excludes); excludes.addAll(Arrays.asList((Object[]) endpoints)); return new EndpointRequestMatcher(this.includes, excludes, this.includeLinks); } public EndpointRequestMatcher excludingLinks() { return new EndpointRequestMatcher(this.includes, this.excludes, false); } @Override protected RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory) { PathMappedEndpoints pathMappedEndpoints = context .getBean(PathMappedEndpoints.class); Set<String> paths = new LinkedHashSet<>(); if (this.includes.isEmpty()) { paths.addAll(pathMappedEndpoints.getAllPaths()); } streamPaths(this.includes, pathMappedEndpoints).forEach(paths::add); streamPaths(this.excludes, pathMappedEndpoints).forEach(paths::remove); List<RequestMatcher> delegateMatchers = getDelegateMatchers( requestMatcherFactory, paths); if (this.includeLinks && StringUtils.hasText(pathMappedEndpoints.getBasePath())) { delegateMatchers.add( requestMatcherFactory.antPath(pathMappedEndpoints.getBasePath())); } return new OrRequestMatcher(delegateMatchers); } private Stream<String> streamPaths(List<Object> source, PathMappedEndpoints pathMappedEndpoints) { return source.stream().filter(Objects::nonNull).map(this::getEndpointId) .map(pathMappedEndpoints::getPath); } private String getEndpointId(Object source) { if (source instanceof String) { return (String) source; } if (source instanceof Class) { return getEndpointId((Class<?>) source); } throw new IllegalStateException("Unsupported source " + source); } private String getEndpointId(Class<?> source) { Endpoint annotation = AnnotatedElementUtils.getMergedAnnotation(source, Endpoint.class); Assert.state(annotation != null, () -> "Class " + source + " is not annotated with @Endpoint"); return annotation.id(); } private List<RequestMatcher> getDelegateMatchers( RequestMatcherFactory requestMatcherFactory, Set<String> paths) { return paths.stream() .map((path) -> requestMatcherFactory.antPath(path, "/**")) .collect(Collectors.toList()); } } /** * The request matcher used to match against the links endpoint. */ public static final class LinksRequestMatcher extends AbstractRequestMatcher { @Override protected RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory) { WebEndpointProperties properties = context .getBean(WebEndpointProperties.class); if (StringUtils.hasText(properties.getBasePath())) { return requestMatcherFactory.antPath(properties.getBasePath()); } return EMPTY_MATCHER; } } /** * Factory used to create a {@link RequestMatcher}. */ private static class RequestMatcherFactory { private final String servletPath; private static final RequestMatcherFactory EMPTY_SERVLET_PATH = new RequestMatcherFactory( ""); RequestMatcherFactory(String servletPath) { this.servletPath = servletPath; } RequestMatcher antPath(String... parts) { String pattern = (this.servletPath.equals("/") ? "" : this.servletPath); for (String part : parts) { pattern += part; } return new AntPathRequestMatcher(pattern); } static RequestMatcherFactory withEmptyServletPath() { return EMPTY_SERVLET_PATH; } } }
/* * Autopsy Forensic Browser * * Copyright 2011-2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.coordinationservice; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.ZooDefs; import org.openide.util.Lookup; import org.sleuthkit.autopsy.coordinationservice.utils.CoordinationServiceUtils; import org.sleuthkit.autopsy.core.UserPreferences; /** * A coordination service for maintaining configuration information and * providing distributed synchronization using a shared hierarchical namespace * of nodes. */ @ThreadSafe public final class CoordinationService { private static final int SESSION_TIMEOUT_MILLISECONDS = 300000; private static final int CONNECTION_TIMEOUT_MILLISECONDS = 300000; private static final int PORT_OFFSET = 1000; // When run in Solr, ZooKeeper defaults to Solr port + 1000 private static final String DEFAULT_NAMESPACE_ROOT = "autopsy"; @GuardedBy("CoordinationService.class") private static CoordinationService instance; private final CuratorFramework curator; @GuardedBy("categoryNodeToPath") private final Map<String, String> categoryNodeToPath; /** * Gets the coordination service for maintaining configuration information * and providing distributed synchronization using a shared hierarchical * namespace of nodes. * * @return The corrdination service. * * @throws CoordinationServiceException */ public synchronized static CoordinationService getInstance() throws CoordinationServiceException { if (null == instance) { String rootNode; Collection<? extends CoordinationServiceNamespace> providers = Lookup.getDefault().lookupAll(CoordinationServiceNamespace.class); Iterator<? extends CoordinationServiceNamespace> it = providers.iterator(); if (it.hasNext()) { rootNode = it.next().getNamespaceRoot(); } else { rootNode = DEFAULT_NAMESPACE_ROOT; } try { instance = new CoordinationService(rootNode); } catch (IOException | KeeperException | CoordinationServiceException ex) { throw new CoordinationServiceException("Failed to create coordination service", ex); } catch (InterruptedException ex) { /* * The interrupted exception should be propagated to support * task cancellation. To avoid a public API change here, restore * the interrupted flag and then throw the InterruptedException * in its wrapper. */ Thread.currentThread().interrupt(); throw new CoordinationServiceException("Failed to create coordination service", ex); } } return instance; } /** * Constructs an instance of the coordination service for a specific * namespace. * * @param rootNodeName The name of the root node that defines the namespace. * * @throws Exception (calls Curator methods that throw Exception instead of * more specific exceptions) */ private CoordinationService(String rootNodeName) throws InterruptedException, IOException, KeeperException, CoordinationServiceException { // read ZK connection info String hostName = UserPreferences.getZkServerHost(); String port = UserPreferences.getZkServerPort(); if (hostName.isEmpty() || port.isEmpty()) { // use defaults for embedded ZK that runs on Solr server hostName = UserPreferences.getIndexingServerHost(); int portInt = Integer.valueOf(UserPreferences.getIndexingServerPort()) + PORT_OFFSET; port = Integer.toString(portInt); } if (false == CoordinationServiceUtils.isZooKeeperAccessible(hostName, port)) { throw new CoordinationServiceException("Unable to access ZooKeeper"); } // We are using ZK for all coordination/locking, so ZK connection info cannot be changed. // A reboot is required in order to use a different ZK server for coordination services. /* * Connect to ZooKeeper via Curator. */ RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); String connectString = hostName + ":" + port; curator = CuratorFrameworkFactory.newClient(connectString, SESSION_TIMEOUT_MILLISECONDS, CONNECTION_TIMEOUT_MILLISECONDS, retryPolicy); curator.start(); /* * Create the top-level root and category nodes. */ String rootNode = rootNodeName; if (!rootNode.startsWith("/")) { rootNode = "/" + rootNode; } categoryNodeToPath = new ConcurrentHashMap<>(); for (CategoryNode node : CategoryNode.values()) { String nodePath = rootNode + "/" + node.getDisplayName(); try { curator.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).forPath(nodePath); } catch (KeeperException ex) { if (ex.code() != KeeperException.Code.NODEEXISTS) { throw ex; } } catch (Exception ex) { throw new CoordinationServiceException("Curator experienced an error", ex); } categoryNodeToPath.put(node.getDisplayName(), nodePath); } } /** * Tries to get an exclusive lock on a node path appended to a category path * in the namespace managed by this coordination service. Blocks until the * lock is obtained or the time out expires. * * IMPORTANT: The lock needs to be released in the same thread in which it * is acquired. * * @param category The desired category in the namespace. * @param nodePath The node path to use as the basis for the lock. * @param timeOut Length of the time out. * @param timeUnit Time unit for the time out. * * @return The lock, or null if lock acquisition timed out. * * @throws CoordinationServiceException If there is an error during lock * acquisition. * @throws InterruptedException If interrupted while blocked during * lock acquisition. */ public Lock tryGetExclusiveLock(CategoryNode category, String nodePath, int timeOut, TimeUnit timeUnit) throws CoordinationServiceException, InterruptedException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { InterProcessReadWriteLock lock = new InterProcessReadWriteLock(curator, fullNodePath); if (lock.writeLock().acquire(timeOut, timeUnit)) { return new Lock(nodePath, lock.writeLock()); } else { return null; } } catch (Exception ex) { if (ex instanceof InterruptedException) { throw (InterruptedException) ex; } else { throw new CoordinationServiceException(String.format("Failed to get exclusive lock for %s", fullNodePath), ex); } } } /** * Tries to get an exclusive lock on a node path appended to a category path * in the namespace managed by this coordination service. Returns * immediately if the lock can not be acquired. * * IMPORTANT: The lock needs to be released in the same thread in which it * is acquired. * * @param category The desired category in the namespace. * @param nodePath The node path to use as the basis for the lock. * * @return The lock, or null if the lock could not be obtained. * * @throws CoordinationServiceException If there is an error during lock * acquisition. */ public Lock tryGetExclusiveLock(CategoryNode category, String nodePath) throws CoordinationServiceException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { InterProcessReadWriteLock lock = new InterProcessReadWriteLock(curator, fullNodePath); if (!lock.writeLock().acquire(0, TimeUnit.SECONDS)) { return null; } return new Lock(nodePath, lock.writeLock()); } catch (Exception ex) { throw new CoordinationServiceException(String.format("Failed to get exclusive lock for %s", fullNodePath), ex); } } /** * Tries to get a shared lock on a node path appended to a category path in * the namespace managed by this coordination service. Blocks until the lock * is obtained or the time out expires. * * IMPORTANT: The lock needs to be released in the same thread in which it * is acquired. * * @param category The desired category in the namespace. * @param nodePath The node path to use as the basis for the lock. * @param timeOut Length of the time out. * @param timeUnit Time unit for the time out. * * @return The lock, or null if lock acquisition timed out. * * @throws CoordinationServiceException If there is an error during lock * acquisition. * @throws InterruptedException If interrupted while blocked during * lock acquisition. */ public Lock tryGetSharedLock(CategoryNode category, String nodePath, int timeOut, TimeUnit timeUnit) throws CoordinationServiceException, InterruptedException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { InterProcessReadWriteLock lock = new InterProcessReadWriteLock(curator, fullNodePath); if (lock.readLock().acquire(timeOut, timeUnit)) { return new Lock(nodePath, lock.readLock()); } else { return null; } } catch (Exception ex) { if (ex instanceof InterruptedException) { throw (InterruptedException) ex; } else { throw new CoordinationServiceException(String.format("Failed to get shared lock for %s", fullNodePath), ex); } } } /** * Tries to get a shared lock on a node path appended to a category path in * the namespace managed by this coordination service. Returns immediately * if the lock can not be acquired. * * IMPORTANT: The lock needs to be released in the same thread in which it * is acquired. * * @param category The desired category in the namespace. * @param nodePath The node path to use as the basis for the lock. * * @return The lock, or null if the lock could not be obtained. * * @throws CoordinationServiceException If there is an error during lock * acquisition. */ public Lock tryGetSharedLock(CategoryNode category, String nodePath) throws CoordinationServiceException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { InterProcessReadWriteLock lock = new InterProcessReadWriteLock(curator, fullNodePath); if (!lock.readLock().acquire(0, TimeUnit.SECONDS)) { return null; } return new Lock(nodePath, lock.readLock()); } catch (Exception ex) { throw new CoordinationServiceException(String.format("Failed to get shared lock for %s", fullNodePath), ex); } } /** * Retrieve the data associated with the specified node. * * @param category The desired category in the namespace. * @param nodePath The node to retrieve the data for. * * @return The data associated with the node, if any, or null if the node * has not been created yet. * * @throws CoordinationServiceException If there is an error setting the * node data. * @throws InterruptedException If interrupted while blocked during * setting of node data. */ public byte[] getNodeData(CategoryNode category, String nodePath) throws CoordinationServiceException, InterruptedException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { return curator.getData().forPath(fullNodePath); } catch (NoNodeException ex) { return null; } catch (Exception ex) { if (ex instanceof InterruptedException) { throw (InterruptedException) ex; } else { throw new CoordinationServiceException(String.format("Failed to get data for %s", fullNodePath), ex); } } } /** * Store the given data with the specified node. * * @param category The desired category in the namespace. * @param nodePath The node to associate the data with. * @param data The data to store with the node. * * @throws CoordinationServiceException If there is an error setting the * node data. * @throws InterruptedException If interrupted while blocked during * setting of node data. */ public void setNodeData(CategoryNode category, String nodePath, byte[] data) throws CoordinationServiceException, InterruptedException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { curator.setData().forPath(fullNodePath, data); } catch (Exception ex) { if (ex instanceof InterruptedException) { throw (InterruptedException) ex; } else { throw new CoordinationServiceException(String.format("Failed to set data for %s", fullNodePath), ex); } } } /** * Deletes a specified node. * * @param category The desired category in the namespace. * @param nodePath The node to be deleted. * * @throws CoordinationServiceException If there is an error deleting the * node. * @throws java.lang.InterruptedException If a thread interrupt occurs while * blocked waiting for the operation * to complete. */ public void deleteNode(CategoryNode category, String nodePath) throws CoordinationServiceException, InterruptedException { String fullNodePath = getFullyQualifiedNodePath(category, nodePath); try { curator.delete().forPath(fullNodePath); } catch (Exception ex) { if (ex instanceof InterruptedException) { throw (InterruptedException) ex; } else { throw new CoordinationServiceException(String.format("Failed to delete node %s", fullNodePath), ex); } } } /** * Gets a list of the child nodes of a category in the namespace. * * @param category The desired category in the namespace. * * @return A list of child node names. * * @throws CoordinationServiceException If there is an error getting the * node list. * @throws java.lang.InterruptedException If a thread interrupt occurs while * blocked waiting for the operation * to complete. */ public List<String> getNodeList(CategoryNode category) throws CoordinationServiceException, InterruptedException { try { List<String> list = curator.getChildren().forPath(categoryNodeToPath.get(category.getDisplayName())); return list; } catch (Exception ex) { if (ex instanceof InterruptedException) { throw (InterruptedException) ex; } else { throw new CoordinationServiceException(String.format("Failed to get node list for %s", category.getDisplayName()), ex); } } } /** * Creates a node path within a given category. * * @param category A category node. * @param nodePath A node path relative to a category node path. * * @return */ private String getFullyQualifiedNodePath(CategoryNode category, String nodePath) { // nodePath on Unix systems starts with a "/" and ZooKeeper doesn't like two slashes in a row if (nodePath.startsWith("/")) { return categoryNodeToPath.get(category.getDisplayName()) + nodePath.toUpperCase(); } else { return categoryNodeToPath.get(category.getDisplayName()) + "/" + nodePath.toUpperCase(); } } /** * Exception type thrown by the coordination service. */ public final static class CoordinationServiceException extends Exception { private static final long serialVersionUID = 1L; private CoordinationServiceException(String message) { super(message); } private CoordinationServiceException(String message, Throwable cause) { super(message, cause); } } /** * An opaque encapsulation of a lock for use in distributed synchronization. * Instances are obtained by calling a get lock method and must be passed to * a release lock method. */ public static class Lock implements AutoCloseable { /** * This implementation uses the Curator read/write lock. see * http://curator.apache.org/curator-recipes/shared-reentrant-read-write-lock.html */ private final InterProcessMutex interProcessLock; private final String nodePath; private Lock(String nodePath, InterProcessMutex lock) { this.nodePath = nodePath; this.interProcessLock = lock; } public String getNodePath() { return nodePath; } public void release() throws CoordinationServiceException { try { this.interProcessLock.release(); } catch (Exception ex) { throw new CoordinationServiceException(String.format("Failed to release the lock on %s", nodePath), ex); } } @Override public void close() throws CoordinationServiceException { release(); } } /** * Category nodes are the immediate children of the root node of a shared * hierarchical namespace managed by a coordination service. */ public enum CategoryNode { CASES("cases"), MANIFESTS("manifests"), CONFIG("config"), CENTRAL_REPO("centralRepository"), HEALTH_MONITOR("healthMonitor"); private final String displayName; private CategoryNode(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } } }
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Creation Date: Sep 13, 2012 * *******************************************************************************/ package org.oscm.reportingservice.business; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.oscm.dataservice.local.DataService; import org.oscm.reportingservice.business.model.supplierrevenushare.RDORevenueShareDetail; import org.oscm.reportingservice.business.model.supplierrevenushare.RDORevenueShareSummary; import org.oscm.reportingservice.business.model.supplierrevenushare.RDOSupplierRevenueShareCurrency; import org.oscm.reportingservice.business.model.supplierrevenushare.RDOSupplierRevenueShareReport; import org.oscm.reportingservice.business.model.supplierrevenushare.RDOSupplierRevenueShareReports; import org.oscm.reportingservice.dao.PartnerRevenueDao; import org.oscm.reportingservice.dao.PartnerRevenueDao.ReportData; import org.oscm.stream.Streams; import org.oscm.string.Strings; import org.oscm.test.DateTimeHandling; /** * @author tokoda * */ public class SupplierRevenueShareBuilderTest { private DataService ds; private HashMap<String, String> serviceIdMap; private HashMap<String, String> marketplaceNameMap; private HashMap<String, String> serviceNameMap; private static final String TEMPLATE_SERVICE_KEY_1 = "11111"; private static final String TEMPLATE_SERVICE_ID_1 = "templateService1"; private static final String TEMPLATE_SERVICE_KEY_2 = "22222"; private static final String TEMPLATE_SERVICE_ID_2 = "templateService2"; private static final String TEMPLATE_SERVICE_KEY_3 = "33333"; private static final String TEMPLATE_SERVICE_ID_3 = "templateService3"; private static final String TEMPLATE_SERVICE_KEY_4 = "44444"; private static final String TEMPLATE_SERVICE_ID_4 = "templateService4"; private static final String TEMPLATE_SERVICE_KEY_5 = "55555"; private static final String TEMPLATE_SERVICE_ID_5 = "templateService5"; private static final String TEMPLATE_SERVICE_KEY_6 = "66666"; private static final String TEMPLATE_SERVICE_ID_6 = "templateService6"; @Before public void setup() { ds = mock(DataService.class); serviceIdMap = new HashMap<String, String>(); serviceIdMap.put(TEMPLATE_SERVICE_KEY_1, TEMPLATE_SERVICE_ID_1); serviceIdMap.put(TEMPLATE_SERVICE_KEY_2, TEMPLATE_SERVICE_ID_2); serviceIdMap.put(TEMPLATE_SERVICE_KEY_3, TEMPLATE_SERVICE_ID_3); serviceIdMap.put(TEMPLATE_SERVICE_KEY_4, TEMPLATE_SERVICE_ID_4); serviceIdMap.put(TEMPLATE_SERVICE_KEY_5, TEMPLATE_SERVICE_ID_5); serviceIdMap.put(TEMPLATE_SERVICE_KEY_6, TEMPLATE_SERVICE_ID_6); marketplaceNameMap = new HashMap<String, String>(); marketplaceNameMap.put("mp1", "marketplaceName1"); marketplaceNameMap.put("mp2", "marketplaceName2"); marketplaceNameMap.put("mp3", "MarktplatzName3"); serviceNameMap = new HashMap<String, String>(); serviceNameMap.put(TEMPLATE_SERVICE_ID_1, "service name 1"); serviceNameMap.put(TEMPLATE_SERVICE_ID_2, "service name 2"); serviceNameMap.put(TEMPLATE_SERVICE_ID_3, "service name 3"); serviceNameMap.put(TEMPLATE_SERVICE_ID_4, "service name 4"); } private PartnerRevenueDao givenReportData(String address, String name, String id, long start, long end, String xmlFilePath) throws Exception { ReportData rd = new PartnerRevenueDao(null).new ReportData(); rd.setAddress(address); rd.setName(name); rd.setOrganizationId(id); rd.setPeriodEnd(end); rd.setPeriodStart(start); rd.setResultXml(readXmlFromFile(new File(xmlFilePath))); PartnerRevenueDao sqlResult = new PartnerRevenueDao(ds); sqlResult.getReportData().add(rd); return sqlResult; } private PartnerRevenueDao givenReportData() throws Exception { return givenReportData("address", "name", "id", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare.xml"); } private PartnerRevenueDao givenReportData3() throws Exception { return givenReportData("address", "name", "id", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare3.xml"); } private PartnerRevenueDao givenReportData5() throws Exception { return givenReportData("address", "name", "id", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare5.xml"); } private PartnerRevenueDao givenMultipleReportData() throws Exception { ReportData rd1 = new PartnerRevenueDao(null).new ReportData(); rd1.setAddress("address1"); rd1.setName("name1"); rd1.setOrganizationId("id1"); rd1.setPeriodStart(DateTimeHandling .calculateMillis("2012-07-01 00:00:00")); rd1.setPeriodEnd(DateTimeHandling .calculateMillis("2012-06-01 00:00:00")); rd1.setResultXml(readXmlFromFile(new File( "javares/SupplierRevenueShare.xml"))); ReportData rd2 = new PartnerRevenueDao(null).new ReportData(); rd2.setAddress("address2"); rd2.setName("name2"); rd2.setOrganizationId("id2"); rd2.setPeriodStart(DateTimeHandling .calculateMillis("2012-07-01 00:00:00")); rd2.setPeriodEnd(DateTimeHandling .calculateMillis("2012-06-01 00:00:00")); rd2.setResultXml(readXmlFromFile(new File( "javares/SupplierRevenueShare2.xml"))); ReportData rd3 = new PartnerRevenueDao(null).new ReportData(); rd3.setAddress("address3"); rd3.setName("name3"); rd3.setOrganizationId("id3"); rd3.setPeriodStart(DateTimeHandling .calculateMillis("2012-07-01 00:00:00")); rd3.setPeriodEnd(DateTimeHandling .calculateMillis("2012-06-01 00:00:00")); rd3.setResultXml(readXmlFromFile(new File( "javares/SupplierRevenueShare3.xml"))); PartnerRevenueDao sqlResult = new PartnerRevenueDao(ds); sqlResult.getReportData().add(rd1); sqlResult.getReportData().add(rd2); sqlResult.getReportData().add(rd3); return sqlResult; } private static String readXmlFromFile(File testFile) throws FileNotFoundException, InterruptedException, IOException { FileInputStream is = null; try { is = new FileInputStream(testFile); String billingResult = Strings.toString(Streams.readFrom(is)); return billingResult; } finally { Streams.close(is); } } @Test public void buildRreports_nullReportDataList() throws Exception { // given List<ReportData> reportData = null; // when RDOSupplierRevenueShareReports supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, reportData, null, null, null).buildReports(); // then assertNotNull(supplierReport); assertTrue(supplierReport.getReports().isEmpty()); } @Test public void buildReports_emptyReportDataList() throws Exception { // given List<ReportData> reportData = new ArrayList<PartnerRevenueDao.ReportData>(); // when RDOSupplierRevenueShareReports supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, reportData, null, null, null).buildReports(); // then assertNotNull(supplierReport); assertTrue(supplierReport.getReports().isEmpty()); } @Test public void buildReports() throws Exception { // given PartnerRevenueDao sqlResult = givenMultipleReportData(); // when RDOSupplierRevenueShareReports supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildReports(); // then assertEquals(3, supplierReport.getReports().size()); assertTrue(supplierReport.getServerTimeZone().startsWith("UTC")); assertEquals("name1 (id1)", supplierReport.getReports().get(0) .getSupplier()); assertEquals(2, supplierReport.getReports().get(0).getCurrencies() .size()); assertEquals("name2 (id2)", supplierReport.getReports().get(1) .getSupplier()); assertEquals("name3 (id3)", supplierReport.getReports().get(2) .getSupplier()); assertEquals(1, supplierReport.getReports().get(1).getCurrencies() .size()); } @Test public void buildSingleReport_nullReportDataList() throws Exception { // given List<ReportData> reportData = null; // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, reportData, null, null, null) .buildSingleReport(); // then assertNotNull(supplierReport); assertTrue(supplierReport.getCurrencies().isEmpty()); } @Test public void buildSingleReport_emptyReportDataList() throws Exception { // given List<ReportData> reportData = new ArrayList<PartnerRevenueDao.ReportData>(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, reportData, null, null, null) .buildSingleReport(); // then assertNotNull(supplierReport); assertTrue(supplierReport.getCurrencies().isEmpty()); } @Test public void buildSingleReport_header() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData("address", "name", "cb1a8642", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare.xml"); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then assertEquals("name (cb1a8642)", supplierReport.getSupplier()); assertEquals("2012-06-01 00:00:00", supplierReport.getPeriodStart()); assertEquals("2012-07-01 00:00:00", supplierReport.getPeriodEnd()); assertEquals("address", supplierReport.getAddress()); assertTrue(supplierReport.getServerTimeZone().startsWith("UTC")); } @Test public void buildSingleReport3_header() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData("address", "name", "cb1a8642", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare3.xml"); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then assertEquals("name (cb1a8642)", supplierReport.getSupplier()); assertEquals("2012-06-01 00:00:00", supplierReport.getPeriodStart()); assertEquals("2012-07-01 00:00:00", supplierReport.getPeriodEnd()); assertEquals("address", supplierReport.getAddress()); } @Test public void buildSingleReport_directRevenueShareSummary_opShare() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurDirectSummaries = report .getCurrencies().get(0).getDirectRevenueSummaries(); assertEquals( "5.00%", getRevenueShareSummaries(eurDirectSummaries, "direct_mode_service").getOperatorRevenuePercentage()); assertEquals( "30.00", getRevenueShareSummaries(eurDirectSummaries, "direct_mode_service").getOperatorRevenue()); assertEquals( "8.00%", getRevenueShareSummaries(eurDirectSummaries, "direct_mode_service2").getOperatorRevenuePercentage()); assertEquals( "4.80", getRevenueShareSummaries(eurDirectSummaries, "direct_mode_service2").getOperatorRevenue()); List<RDORevenueShareSummary> usdDirectSummaries = report .getCurrencies().get(1).getDirectRevenueSummaries(); assertEquals( "10.00%", getRevenueShareSummaries(usdDirectSummaries, "templateService4") .getOperatorRevenuePercentage()); assertEquals( "0.00", getRevenueShareSummaries(usdDirectSummaries, "templateService4") .getOperatorRevenue()); } private RDORevenueShareSummary getRevenueShareSummaries( List<RDORevenueShareSummary> details, String serviceId) { for (RDORevenueShareSummary d : details) { if (d.getService().contains(serviceId)) { return d; } } return null; } private RDORevenueShareSummary getRevenueShareSummariesByMarketplaceId( List<RDORevenueShareSummary> details, String marketplace) { marketplace = marketplaceNameMap.get(marketplace); for (RDORevenueShareSummary d : details) { if (d.getMarketplace().contains(marketplace)) { return d; } } return null; } @Test public void buildSingleReport_directRevenueShareDetails_opShare() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareDetail> eurDirectDetails = report.getCurrencies() .get(0).getDirectRevenueShareDetails(); assertEquals(4, eurDirectDetails.size()); RDORevenueShareDetail detail = getRevenueShareDetail(eurDirectDetails, "f278913568", "direct_mode_service"); assertEquals("20.00", detail.getOperatorRevenue()); assertEquals("5.00%", detail.getOperatorRevenuePercentage()); detail = getRevenueShareDetail(eurDirectDetails, "h285673122", "direct_mode_service"); assertEquals("10.00", detail.getOperatorRevenue()); assertEquals("5.00%", detail.getOperatorRevenuePercentage()); detail = getRevenueShareDetail(eurDirectDetails, "f278913568", "direct_mode_service2"); assertEquals("3.20", detail.getOperatorRevenue()); assertEquals("8.00%", detail.getOperatorRevenuePercentage()); detail = getRevenueShareDetail(eurDirectDetails, "h285673122", "direct_mode_service2"); assertEquals("1.60", detail.getOperatorRevenue()); assertEquals("8.00%", detail.getOperatorRevenuePercentage()); } private RDORevenueShareDetail getRevenueShareDetail( List<RDORevenueShareDetail> details, String customerId, String serviceId) { for (RDORevenueShareDetail d : details) { if (d.getCustomer().contains(customerId) && d.getService().equals(serviceId)) { return d; } } return null; } @Test public void buildSingleReport_brokerRevenueShareSummary_opShare() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurBrokerSummaries = report .getCurrencies().get(0).getBrokerRevenueSummaries(); RDORevenueShareSummary rss = getRevenueShareSummariesByMarketplaceId( eurBrokerSummaries, "mp1"); assertEquals("5.00%", rss.getOperatorRevenuePercentage()); assertEquals("35.00", rss.getOperatorRevenue()); rss = getRevenueShareSummariesByMarketplaceId(eurBrokerSummaries, "mp2"); assertEquals("10.00%", rss.getOperatorRevenuePercentage()); assertEquals("7.00", rss.getOperatorRevenue()); List<RDORevenueShareSummary> usdDirectSummaries = report .getCurrencies().get(1).getBrokerRevenueSummaries(); rss = getRevenueShareSummariesByMarketplaceId(usdDirectSummaries, "mp3"); assertEquals("10.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.20", rss.getOperatorRevenue()); } @Test public void brokerRevenueShareSummary_sumUpServicesOfOneBroker() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData(); ReportData rd = sqlResult.getReportData().get(0); rd.setResultXml(rd.getResultXml().replaceAll("id=\"broker2\"", "id=\"broker1\"")); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurBrokerSummaries = report .getCurrencies().get(0).getBrokerRevenueSummaries(); RDORevenueShareSummary rss = getRevenueShareSummariesByMarketplaceId( eurBrokerSummaries, "mp1"); assertEquals("NameBroker1 (broker1)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("20.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("260.00", rss.getMarketplaceRevenue()); assertEquals("10.00", rss.getPartnerProvisionPercentage()); assertEquals("280.00", rss.getPartnerProvision()); assertEquals("760.00", rss.getRevenueMinusShares()); assertEquals("1300.00", rss.getRevenue()); rss = eurBrokerSummaries.get(1); assertEquals("NameBroker3 (broker3)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("10.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("9.00", rss.getMarketplaceRevenue()); assertEquals("80.00", rss.getPartnerProvisionPercentage()); assertEquals("72.00", rss.getPartnerProvision()); assertEquals("9.00", rss.getRevenueMinusShares()); assertEquals("90.00", rss.getRevenue()); rss = getRevenueShareSummariesByMarketplaceId(eurBrokerSummaries, "mp2"); assertEquals("NameBroker1 (broker1)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("20.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("80.00", rss.getMarketplaceRevenue()); assertEquals("60.00", rss.getPartnerProvisionPercentage()); assertEquals("240.00", rss.getPartnerProvision()); assertEquals("80.00", rss.getRevenueMinusShares()); assertEquals("400.00", rss.getRevenue()); List<RDORevenueShareSummary> usdDirectSummaries = report .getCurrencies().get(1).getBrokerRevenueSummaries(); rss = getRevenueShareSummariesByMarketplaceId(usdDirectSummaries, "mp3"); assertEquals("NameBroker4 (broker4)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("50.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("1.00", rss.getMarketplaceRevenue()); assertEquals("60.00", rss.getPartnerProvisionPercentage()); assertEquals("1.20", rss.getPartnerProvision()); assertEquals("-0.20", rss.getRevenueMinusShares()); assertEquals("2.00", rss.getRevenue()); } @Test public void brokerRevenueShareSummary_sumUpServicesOfOneBroker2() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData(); ReportData rd = sqlResult.getReportData().get(0); rd.setResultXml(rd.getResultXml().replaceAll("id=\"broker3\"", "id=\"broker2\"")); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurBrokerSummaries = report .getCurrencies().get(0).getBrokerRevenueSummaries(); RDORevenueShareSummary rss = getRevenueShareSummariesByMarketplaceId( eurBrokerSummaries, "mp1"); assertEquals("NameBroker1 (broker1)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("20.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("100.00", rss.getMarketplaceRevenue()); assertEquals("40.00", rss.getPartnerProvisionPercentage()); assertEquals("200.00", rss.getPartnerProvision()); assertEquals("200.00", rss.getRevenueMinusShares()); assertEquals("500.00", rss.getRevenue()); rss = eurBrokerSummaries.get(1); assertEquals("NameBroker2 (broker2)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("10.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("169.00", rss.getMarketplaceRevenue()); assertEquals("80.00", rss.getPartnerProvisionPercentage()); assertEquals("152.00", rss.getPartnerProvision()); assertEquals("569.00", rss.getRevenueMinusShares()); assertEquals("890.00", rss.getRevenue()); rss = getRevenueShareSummariesByMarketplaceId(eurBrokerSummaries, "mp2"); assertEquals("NameBroker1 (broker1)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("20.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("80.00", rss.getMarketplaceRevenue()); assertEquals("60.00", rss.getPartnerProvisionPercentage()); assertEquals("240.00", rss.getPartnerProvision()); assertEquals("80.00", rss.getRevenueMinusShares()); assertEquals("400.00", rss.getRevenue()); List<RDORevenueShareSummary> usdDirectSummaries = report .getCurrencies().get(1).getBrokerRevenueSummaries(); rss = getRevenueShareSummariesByMarketplaceId(usdDirectSummaries, "mp3"); assertEquals("NameBroker4 (broker4)", rss.getPartner()); assertEquals("0.00%", rss.getOperatorRevenuePercentage()); assertEquals("0.00", rss.getOperatorRevenue()); assertEquals("50.00%", rss.getMarketplaceRevenuePercentage()); assertEquals("1.00", rss.getMarketplaceRevenue()); assertEquals("60.00", rss.getPartnerProvisionPercentage()); assertEquals("1.20", rss.getPartnerProvision()); assertEquals("-0.20", rss.getRevenueMinusShares()); assertEquals("2.00", rss.getRevenue()); } @Test public void buildSingleReport_brokerRevenueShareDetails_opShare() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareDetail> eurBrokerDetails = report.getCurrencies() .get(0).getBrokerRevenueShareDetails(); RDORevenueShareDetail detail = getRevenueShareDetail(eurBrokerDetails, "a92537743", "broker_mode_service"); assertEquals("35.00", detail.getOperatorRevenue()); assertEquals("5.00%", detail.getOperatorRevenuePercentage()); detail = getRevenueShareDetail(eurBrokerDetails, "a92537743", "broker_mode_service2"); assertEquals("7.00", detail.getOperatorRevenue()); assertEquals("10.00%", detail.getOperatorRevenuePercentage()); } @Test public void buildSingleReport_resellerRevenueShareSummary_opShare() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurResellerSummaries = report .getCurrencies().get(0).getResellerRevenueSummaries(); RDORevenueShareSummary rss = getRevenueShareSummariesByMarketplaceId( eurResellerSummaries, "mp1"); assertEquals("10.00%", rss.getOperatorRevenuePercentage()); assertEquals("80.00", rss.getOperatorRevenue()); rss = getRevenueShareSummariesByMarketplaceId(eurResellerSummaries, "mp2"); assertEquals("10.00%", rss.getOperatorRevenuePercentage()); assertEquals("8.00", rss.getOperatorRevenue()); List<RDORevenueShareSummary> usdResellerSummaries = report .getCurrencies().get(1).getResellerRevenueSummaries(); rss = getRevenueShareSummariesByMarketplaceId(usdResellerSummaries, "mp3"); assertEquals("10.00%", rss.getOperatorRevenuePercentage()); assertEquals("1.30", rss.getOperatorRevenue()); } @Test public void buildSingleReport_resellerRevenueShareDetails_opShare() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareDetail> eurResellerDetails = report.getCurrencies() .get(0).getResellerRevenueShareDetails(); RDORevenueShareDetail detail = getRevenueShareDetail( eurResellerDetails, "r12957322", "reseller_mode_service"); assertEquals("80.00", detail.getOperatorRevenue()); assertEquals("10.00%", detail.getOperatorRevenuePercentage()); detail = getRevenueShareDetail(eurResellerDetails, "r12957322", "reseller_mode_service2"); assertEquals("8.00", detail.getOperatorRevenue()); assertEquals("10.00%", detail.getOperatorRevenuePercentage()); } @Test public void buildSingleReport_directRevenueShareSummary_revShareAmount() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurDirectSummaries = report .getCurrencies().get(0).getDirectRevenueSummaries(); assertEquals(2, eurDirectSummaries.size()); RDORevenueShareSummary summary = getRevenueShareSummaries( eurDirectSummaries, "direct_mode_service"); assertEquals("480.00", summary.getRevenueMinusShares()); summary = getRevenueShareSummaries(eurDirectSummaries, "direct_mode_service2"); assertEquals("46.20", summary.getRevenueMinusShares()); } @Test public void buildSingleReport_directRevenueShareSummary_revShareAmount_oldKeyName() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData5(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> usdDirectSummaries = report .getCurrencies().get(1).getDirectRevenueSummaries(); assertEquals(2, usdDirectSummaries.size()); RDORevenueShareSummary summary = getRevenueShareSummaries( usdDirectSummaries, "direct_mode_service"); assertEquals("480.00", summary.getRevenueMinusShares()); summary = getRevenueShareSummaries(usdDirectSummaries, "direct_mode_service2"); assertEquals("46.20", summary.getRevenueMinusShares()); } @Test public void buildSingleReport_directRevenueShareDetails_revShareAmount() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareDetail> eurDirectDetails = report.getCurrencies() .get(0).getDirectRevenueShareDetails(); RDORevenueShareDetail detail = getRevenueShareDetail(eurDirectDetails, "f278913568", "direct_mode_service"); assertEquals("320.00", detail.getRevenueMinusShares()); detail = getRevenueShareDetail(eurDirectDetails, "h285673122", "direct_mode_service"); assertEquals("175.00", detail.getRevenueMinusShares()); } @Test public void buildSingleReport_brokerRevenueShareSummary_revShareAmount() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurBrokerSummaries = report .getCurrencies().get(0).getBrokerRevenueSummaries(); assertEquals(2, eurBrokerSummaries.size()); RDORevenueShareSummary summary = getRevenueShareSummariesByMarketplaceId( eurBrokerSummaries, "mp1"); assertEquals("525.00", summary.getRevenueMinusShares()); summary = getRevenueShareSummariesByMarketplaceId(eurBrokerSummaries, "mp2"); assertEquals("49.00", summary.getRevenueMinusShares()); } @Test public void buildSingleReport_brokerRevenueShareSummary_revShareAmount_oldKeyName() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData5(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> usdBrokerSummaries = report .getCurrencies().get(1).getBrokerRevenueSummaries(); assertEquals(2, usdBrokerSummaries.size()); RDORevenueShareSummary summary = getRevenueShareSummariesByMarketplaceId( usdBrokerSummaries, "mp1"); assertEquals("525.00", summary.getRevenueMinusShares()); summary = getRevenueShareSummariesByMarketplaceId(usdBrokerSummaries, "mp2"); assertEquals("49.00", summary.getRevenueMinusShares()); } @Test public void buildSingleReport_brokerRevenueShareDetails_revShareAmount() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareDetail> eurBrokerDetails = report.getCurrencies() .get(0).getBrokerRevenueShareDetails(); RDORevenueShareDetail detail = getRevenueShareDetail(eurBrokerDetails, "a92537743", "broker_mode_service"); assertEquals("525.00", detail.getRevenueMinusShares()); detail = getRevenueShareDetail(eurBrokerDetails, "a92537743", "broker_mode_service2"); assertEquals("56.00", detail.getRevenueMinusShares()); } @Test public void buildSingleReport_resellerRevenueShareSummary_revShareAmount() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> eurResellerSummaries = report .getCurrencies().get(0).getResellerRevenueSummaries(); assertEquals(2, eurResellerSummaries.size()); RDORevenueShareSummary summary = getRevenueShareSummariesByMarketplaceId( eurResellerSummaries, "mp1"); assertEquals("520.00", summary.getRevenueMinusShares()); summary = getRevenueShareSummariesByMarketplaceId(eurResellerSummaries, "mp2"); assertEquals("59.00", summary.getRevenueMinusShares()); } @Test public void buildSingleReport_resellerRevenueShareSummary_revShareAmount_oldKeyName() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData5(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareSummary> usdResellerSummaries = report .getCurrencies().get(1).getResellerRevenueSummaries(); assertEquals(2, usdResellerSummaries.size()); RDORevenueShareSummary summary = getRevenueShareSummariesByMarketplaceId( usdResellerSummaries, "mp1"); assertEquals("520.00", summary.getRevenueMinusShares()); summary = getRevenueShareSummariesByMarketplaceId(usdResellerSummaries, "mp2"); assertEquals("52.00", summary.getRevenueMinusShares()); } @Test public void buildSingleReport_resellerRevenueShareDetails_revShareAmount() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then List<RDORevenueShareDetail> eurResellerDetails = report.getCurrencies() .get(0).getResellerRevenueShareDetails(); RDORevenueShareDetail detail = getRevenueShareDetail( eurResellerDetails, "r12957322", "reseller_mode_service"); assertEquals("600.00", detail.getRevenueMinusShares()); detail = getRevenueShareDetail(eurResellerDetails, "r12957322", "reseller_mode_service2"); assertEquals("60.00", detail.getRevenueMinusShares()); } @Test public void buildSingleReport_overview_direct() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then RDOSupplierRevenueShareCurrency eur = report.getCurrencies().get(0); assertEquals("34.80", eur.getDirectProvisionToOperator()); assertEquals("542.70", eur.getDirectTotalRemainingRevenue()); RDOSupplierRevenueShareCurrency usd = report.getCurrencies().get(1); assertEquals("0.00", usd.getDirectProvisionToOperator()); assertEquals("0.99", usd.getDirectTotalRemainingRevenue()); } @Test public void buildSingleReport_overview_broker() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then RDOSupplierRevenueShareCurrency eur = report.getCurrencies().get(0); assertEquals("42.00", eur.getBrokerProvisionToOperator()); assertEquals("618.00", eur.getBrokerTotalRemainingRevenue()); RDOSupplierRevenueShareCurrency usd = report.getCurrencies().get(1); assertEquals("0.20", usd.getBrokerProvisionToOperator()); assertEquals("-0.40", usd.getBrokerTotalRemainingRevenue()); } @Test public void buildSingleReport_overview_reseller() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport report = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then RDOSupplierRevenueShareCurrency eur = report.getCurrencies().get(0); assertEquals("88.00", eur.getResellerProvisionToOperator()); assertEquals("689.50", eur.getResellerTotalRemainingRevenue()); RDOSupplierRevenueShareCurrency usd = report.getCurrencies().get(1); assertEquals("1.30", usd.getResellerProvisionToOperator()); assertEquals("-3.40", usd.getResellerTotalRemainingRevenue()); } @Test public void buildSingleReport_overview() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then assertEquals(2, supplierReport.getCurrencies().size()); RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); assertEquals("EUR", currencyEUR.getCurrency()); assertEquals("4091.00", currencyEUR.getTotalRevenue()); assertEquals("1790.00", currencyEUR.getBrokerTotalRevenue()); assertEquals("43.75%", currencyEUR.getBrokerPercentageRevenue()); assertEquals("1700.00", currencyEUR.getResellerTotalRevenue()); assertEquals("41.55%", currencyEUR.getResellerPercentageRevenue()); assertEquals("349.00", currencyEUR.getBrokerProvisionToMarketplaceOwner()); assertEquals("1010.00", currencyEUR.getResellerProvisionToMarketplaceOwner()); assertEquals("120.01", currencyEUR.getDirectProvisionToMarketplaceOwner()); RDOSupplierRevenueShareCurrency currencyUSD = supplierReport .getCurrencies().get(1); assertEquals("USD", currencyUSD.getCurrency()); assertEquals("16.00", currencyUSD.getTotalRevenue()); assertEquals("2.00", currencyUSD.getBrokerTotalRevenue()); assertEquals("12.50%", currencyUSD.getBrokerPercentageRevenue()); assertEquals("13.00", currencyUSD.getResellerTotalRevenue()); assertEquals("81.25%", currencyUSD.getResellerPercentageRevenue()); assertEquals("349.00", currencyEUR.getBrokerProvisionToMarketplaceOwner()); assertEquals("1010.00", currencyEUR.getResellerProvisionToMarketplaceOwner()); assertEquals("120.01", currencyEUR.getDirectProvisionToMarketplaceOwner()); } @Test public void buildSingleReport_overview3() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then assertEquals(2, supplierReport.getCurrencies().size()); RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); assertEquals("EUR", currencyEUR.getCurrency()); assertEquals("1850.20", currencyEUR.getTotalRemainingRevenue()); assertEquals("2310.00", currencyEUR.getTotalRevenue()); assertEquals("770.00", currencyEUR.getBrokerTotalRevenue()); assertEquals("33.33%", currencyEUR.getBrokerPercentageRevenue()); assertEquals("880.00", currencyEUR.getResellerTotalRevenue()); assertEquals("38.10%", currencyEUR.getResellerPercentageRevenue()); assertEquals("99.00", currencyEUR.getDirectProvisionToMarketplaceOwner()); assertEquals("115.50", currencyEUR.getBrokerProvisionToMarketplaceOwner()); assertEquals("132.00", currencyEUR.getResellerProvisionToMarketplaceOwner()); RDOSupplierRevenueShareCurrency currencyUSD = supplierReport .getCurrencies().get(1); assertEquals("USD", currencyUSD.getCurrency()); assertEquals("-2.81", currencyUSD.getTotalRemainingRevenue()); assertEquals("16.00", currencyUSD.getTotalRevenue()); assertEquals("2.00", currencyUSD.getBrokerTotalRevenue()); assertEquals("12.50%", currencyUSD.getBrokerPercentageRevenue()); assertEquals("13.00", currencyUSD.getResellerTotalRevenue()); assertEquals("81.25%", currencyUSD.getResellerPercentageRevenue()); assertEquals("1.00", currencyUSD.getBrokerProvisionToMarketplaceOwner()); } @Test public void buildSingleReport_buildRevenueSummaries() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); // then // currency: EUR, 2 marketplaces with 2 direct/broker/reseller services // each RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); assertEquals(2, currencyEUR.getDirectRevenueSummaries().size()); assertEquals(2, currencyEUR.getBrokerRevenueSummaries().size()); assertEquals(2, currencyEUR.getResellerRevenueSummaries().size()); RDORevenueShareSummary eu_drs1 = currencyEUR .getDirectRevenueSummaries().get(0); assertEquals("EUR", eu_drs1.getCurrency()); assertEquals("marketplaceName1", eu_drs1.getMarketplace()); assertEquals("90.00", eu_drs1.getMarketplaceRevenue()); assertEquals("15.00%", eu_drs1.getMarketplaceRevenuePercentage()); assertEquals("600.00", eu_drs1.getRevenue()); RDORevenueShareSummary us_drs2 = currencyEUR .getDirectRevenueSummaries().get(1); assertEquals("EUR", us_drs2.getCurrency()); assertEquals("marketplaceName2", us_drs2.getMarketplace()); assertEquals("9.00", us_drs2.getMarketplaceRevenue()); assertEquals("15.00%", us_drs2.getMarketplaceRevenuePercentage()); assertEquals("60.00", us_drs2.getRevenue()); // currency: USD, 1 marketplace RDOSupplierRevenueShareCurrency currencyUSD = supplierReport .getCurrencies().get(1); assertEquals(1, currencyUSD.getDirectRevenueSummaries().size()); assertEquals(1, currencyUSD.getBrokerRevenueSummaries().size()); assertEquals(1, currencyUSD.getResellerRevenueSummaries().size()); RDORevenueShareSummary brs1 = currencyUSD.getBrokerRevenueSummaries() .get(0); assertEquals("USD", brs1.getCurrency()); assertEquals("MarktplatzName3", brs1.getMarketplace()); assertEquals("1.00", brs1.getMarketplaceRevenue()); assertEquals("50.00%", brs1.getMarketplaceRevenuePercentage()); } @Test public void buildRevenueShareDetail_directNewXML() throws Exception { PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); List<RDORevenueShareDetail> directDetails = currencyEUR .getDirectRevenueShareDetails(); assertEquals(4, directDetails.size()); RDORevenueShareDetail revenueDetail = directDetails.get(0); assertEquals("EUR", revenueDetail.getCurrency()); assertEquals("customerA (f278913568)", revenueDetail.getCustomer()); assertEquals("marketplaceName1", revenueDetail.getMarketplace()); assertEquals("60.00", revenueDetail.getMarketplaceRevenue()); assertEquals("15.00%", revenueDetail.getMarketplaceSharePercentage()); assertEquals("", revenueDetail.getPartnerRevenue()); assertEquals("", revenueDetail.getPartnerSharePercentage()); assertEquals("400.00", revenueDetail.getRevenue()); assertEquals("direct_mode_service", revenueDetail.getService()); } @Test public void buildRevenueShareDetail_brokerNewXML() throws Exception { PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); List<RDORevenueShareDetail> brokerDetails = currencyEUR .getBrokerRevenueShareDetails(); assertEquals(2, brokerDetails.size()); RDORevenueShareDetail revenueDetail = brokerDetails.get(0); assertEquals("EUR", revenueDetail.getCurrency()); assertEquals("customerC (a92537743)", revenueDetail.getCustomer()); assertEquals("marketplaceName1", revenueDetail.getMarketplace()); assertEquals("105.00", revenueDetail.getMarketplaceRevenue()); assertEquals("15.00%", revenueDetail.getMarketplaceSharePercentage()); assertEquals("35.00", revenueDetail.getPartnerRevenue()); assertEquals("5.00%", revenueDetail.getPartnerSharePercentage()); assertEquals("700.00", revenueDetail.getRevenue()); assertEquals("broker_mode_service", revenueDetail.getService()); } @Test public void buildRevenueShareDetail_resellerNewXML() throws Exception { PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); List<RDORevenueShareDetail> resellerDetails = currencyEUR .getResellerRevenueShareDetails(); assertEquals(2, resellerDetails.size()); RDORevenueShareDetail revenueDetail = resellerDetails.get(0); assertEquals("EUR", revenueDetail.getCurrency()); assertEquals("customerD (r12957322)", revenueDetail.getCustomer()); assertEquals("marketplaceName1", revenueDetail.getMarketplace()); assertEquals("120.00", revenueDetail.getMarketplaceRevenue()); assertEquals("15.00%", revenueDetail.getMarketplaceSharePercentage()); assertEquals("80.00", revenueDetail.getPartnerRevenue()); assertEquals("10.00%", revenueDetail.getPartnerSharePercentage()); assertEquals("800.00", revenueDetail.getRevenue()); assertEquals("reseller_mode_service", revenueDetail.getService()); } // no RevenueShareDetail included in the xml @Test public void buildRevenueShareDetail_resellerOldXML() throws Exception { PartnerRevenueDao sqlResult = givenReportData3(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); RDOSupplierRevenueShareCurrency currencyUSD = supplierReport .getCurrencies().get(1); List<RDORevenueShareDetail> resellerDetails = currencyUSD .getResellerRevenueShareDetails(); assertEquals(0, resellerDetails.size()); } @Test public void createOrganizationDisplayName_OrganizationNameNotExisting() { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); // when String displayName = builder.createOrganizationDisplayName("id"); // then assertEquals("id", displayName); } @Test public void createOrganizationDisplayName_OrganizationNameExisting() { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); builder.organizationNameMap.put("id", "name"); // when String displayName = builder.createOrganizationDisplayName("id"); // then assertEquals("name (id)", displayName); } @Test public void computePercentage() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); // when String percentage = builder.computePercentage("100.00", "10.00"); // then assertEquals("10.00%", percentage); } @Test public void computePercentage_zeroTotalValue() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); // when String percentage = builder.computePercentage("0.00", "10.00"); // then assertEquals("0.00%", percentage); } @Test public void computePercentage_zeroValue() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); // when String percentage = builder.computePercentage("100.00", "0.00"); // then assertEquals("0.00%", percentage); } @Test public void computePercentage_valueGreater() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); // when String percentage = builder.computePercentage("10.00", "100.00"); // then assertEquals("1000.00%", percentage); } @Test(expected = NullPointerException.class) public void isServiceRevenueValid_serviceRevenueIsNull() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); String serviceRevenue = null; // when builder.isServiceRevenueValid(serviceRevenue); } @Test public void isServiceRevenueValid_serviceRevenueIsZero() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); String serviceRevenue = "0.00"; // when boolean revenueValid = builder.isServiceRevenueValid(serviceRevenue); // then assertFalse(revenueValid); } @Test public void isServiceRevenueValid_serviceRevenueIsGreaterThanZero() throws Exception { // given SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( null, null, null, null, null); String serviceRevenue = "0.01"; // when boolean revenueValid = builder.isServiceRevenueValid(serviceRevenue); // then assertTrue(revenueValid); } @Test public void buildReports_summary_serviceWithZeroAmount() throws Exception { // given PartnerRevenueDao reportData = givenReportData("address", "name", "id", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare4.xml"); SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( Locale.ENGLISH, reportData.getReportData(), null, marketplaceNameMap, serviceNameMap); // when RDOSupplierRevenueShareReports report = builder.buildReports(); // then List<RDORevenueShareSummary> services = report.getReports().get(0) .getCurrencies().get(0).getDirectRevenueSummaries(); assertEquals(1, services.size()); assertEquals("600.00", services.get(0).getRevenue()); } @Test public void buildReports_shareDetails_serviceWithZeroAmount() throws Exception { // given PartnerRevenueDao reportData = givenReportData("address", "name", "id", DateTimeHandling.calculateMillis("2012-06-01 00:00:00"), DateTimeHandling.calculateMillis("2012-07-01 00:00:00"), "javares/SupplierRevenueShare4.xml"); SupplierRevenueShareBuilder builder = new SupplierRevenueShareBuilder( Locale.ENGLISH, reportData.getReportData(), null, marketplaceNameMap, serviceNameMap); // when RDOSupplierRevenueShareReports report = builder.buildReports(); // then List<RDORevenueShareDetail> shareDetails = report.getReports().get(0) .getCurrencies().get(0).getDirectRevenueShareDetails(); assertEquals(2, shareDetails.size()); assertEquals("400.00", shareDetails.get(0).getRevenue()); assertEquals("200.00", shareDetails.get(1).getRevenue()); } @Test public void buildSingleReport_computeRemainingRevenue_newXml() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData5(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); RDOSupplierRevenueShareCurrency currencyEUR = supplierReport .getCurrencies().get(0); // then assertEquals("EUR", currencyEUR.getCurrency()); assertEquals("526.20", currencyEUR.getDirectTotalRemainingRevenue()); assertEquals("574.00", currencyEUR.getBrokerTotalRemainingRevenue()); assertEquals("572.00", currencyEUR.getResellerTotalRemainingRevenue()); assertEquals("1672.20", currencyEUR.getTotalRemainingRevenue()); } @Test public void buildSingleReport_computeRemainingRevenue_oldXml() throws Exception { // given PartnerRevenueDao sqlResult = givenReportData5(); // when RDOSupplierRevenueShareReport supplierReport = new SupplierRevenueShareBuilder( Locale.ENGLISH, sqlResult.getReportData(), serviceIdMap, marketplaceNameMap, serviceNameMap).buildSingleReport(); RDOSupplierRevenueShareCurrency currencyUSD = supplierReport .getCurrencies().get(1); // then assertEquals("USD", currencyUSD.getCurrency()); assertEquals("526.20", currencyUSD.getDirectTotalRemainingRevenue()); assertEquals("574.00", currencyUSD.getBrokerTotalRemainingRevenue()); assertEquals("572.00", currencyUSD.getResellerTotalRemainingRevenue()); assertEquals("1672.20", currencyUSD.getTotalRemainingRevenue()); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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.msf4j.example; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Contact; import io.swagger.annotations.Info; import io.swagger.annotations.License; import io.swagger.annotations.SwaggerDefinition; import org.wso2.msf4j.Request; import org.wso2.msf4j.example.exception.DuplicateSymbolException; import org.wso2.msf4j.example.exception.SymbolNotFoundException; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.CookieParam; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.OPTIONS; 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.Context; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; /** * StockQuote sample. This service will be available at. * http://localhost:8080/stockquote */ @Api(value = "stockquote") @SwaggerDefinition( info = @Info( title = "Stockquote Swagger Definition", version = "1.0", description = "Stock quote service", license = @License(name = "Apache 2.0", url = "http://www.apache.org/licenses/LICENSE-2.0"), contact = @Contact( name = "Afkham Azeez", email = "azeez@wso2.com", url = "http://wso2.com" )) ) @Path("/stockquote") public class StockQuoteService { // Map that stores stocks (symbol -> stock). private Map<String, Stock> stockQuotes = new HashMap<>(); /** * Add initial stocks IBM, GOOG, AMZN. */ public StockQuoteService() { stockQuotes.put("IBM", new Stock("IBM", "International Business Machines", 149.62, 150.78, 149.18)); stockQuotes.put("GOOG", new Stock("GOOG", "Alphabet Inc.", 652.30, 657.81, 643.15)); stockQuotes.put("AMZN", new Stock("AMZN", "Amazon.com", 548.90, 553.20, 543.10)); } /** * Retrieve a stock for a given symbol. * http://localhost:8080/stockquote/IBM * * @param symbol Stock symbol will be taken from the path parameter. * @return Response */ @GET @Path("/{symbol}") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Return stock quote corresponding to the symbol", notes = "Returns HTTP 404 if the symbol is not found") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid stock item found"), @ApiResponse(code = 404, message = "Stock item not found")}) public Response getQuote(@ApiParam(value = "Symbol", required = true) @PathParam("symbol") String symbol) throws SymbolNotFoundException { System.out.println("Getting symbol using PathParam..."); Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException("Symbol " + symbol + " not found"); } return Response.ok().entity(stock).cookie(new NewCookie("symbol", symbol)).build(); } /** * Retrieve metainformation about the entity implied by the request. * curl -i -X HEAD http://localhost:8080/stockquote/IBM * * @return Response */ @HEAD @Path("/{symbol}") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Returns headers of corresponding GET request ", notes = "Returns metainformation contained in the HTTP header identical to the corresponding GET Request") public Response getMetaInformationForQuote(@ApiParam(value = "Symbol", required = true) @PathParam("symbol") String symbol) throws SymbolNotFoundException { Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException(); } return Response.ok().build(); } /** * Retrieve a stock for a given symbol using a cookie. * This method demonstrates the CookieParam JAXRS annotation in action. * * curl -v --header "Cookie: symbol=IBM" http://localhost:8080/stockquote * * @param symbol Stock symbol will be taken from the symbol cookie. * @return Response */ @GET @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Return stock quote corresponding to the symbol", notes = "Returns HTTP 404 if the symbol is not found") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid stock item found"), @ApiResponse(code = 404, message = "Stock item not found")}) public Response getQuoteUsingCookieParam(@ApiParam(value = "Symbol", required = true) @CookieParam("symbol") String symbol) throws SymbolNotFoundException { System.out.println("Getting symbol using CookieParam..."); Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException("Symbol " + symbol + " not found"); } return Response.ok().entity(stock).build(); } /** * Add a new stock. * curl -v -X POST -H "Content-Type:application/json" \ * -d '{"symbol":"BAR","name": "Bar Inc.", \ * "last":149.62,"low":150.78,"high":149.18, * "createdByHost":"10.100.1.192"}' \ * http://localhost:8080/stockquote * * @param stock Stock object will be created from the request Json body. */ @POST @Consumes("application/json") @ApiOperation( value = "Add a stock item", notes = "Add a valid stock item") public void addStock(@ApiParam(value = "Stock object", required = true) Stock stock) throws DuplicateSymbolException { String symbol = stock.getSymbol(); if (stockQuotes.containsKey(symbol)) { throw new DuplicateSymbolException("Symbol " + symbol + " already exists"); } stockQuotes.put(symbol, stock); } /** * Retrieve all stocks. * http://localhost:8080/stockquote/all * * @return All stocks will be sent to the client as Json/xml * according to the Accept header of the request. */ @GET @Path("/all") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Get all stocks", notes = "Returns all stock items", response = Stocks.class, responseContainer = "List") public Stocks getAllStocks(@Context Request request) { request.getHeaders().getAll().forEach(entry -> System.out.println(entry.getName() + "=" + entry.getValue())); return new Stocks(stockQuotes.values()); } /** * Retrieve information on what methods are allowed on the Request-URI. * curl -i -X OPTIONS http://localhost:8080/stockquote/all * * @return Response */ @OPTIONS @Path("/all") @ApiOperation( value = "Get supported reuest methods", notes = "Return a response with headers that show the supported HTTP Requests on the Request-URI") public Response getCommunicationInformationForRequestURI(){ return Response.ok().header("Access-Control-Allow-Methods","GET,OPTIONS").build(); } }
/** ################################################################################ # Copyright 2012 The SCAPE Project Consortium # # This software is copyrighted by the SCAPE Project Consortium. # The SCAPE project is co-funded by the European Union under # FP7 ICT-2009.4.1 (Grant Agreement number 270137). # # 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 eu.scape_project.tool.toolwrapper.toolwrapper_bash_generator; import java.io.File; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.util.List; import java.util.Properties; import java.util.UUID; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.log4j.Logger; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import eu.scape_project.tool.toolwrapper.core.ToolWrapperCommandline; import eu.scape_project.tool.toolwrapper.core.ToolWrapperGenerator; import eu.scape_project.tool.toolwrapper.core.configuration.Constants; import eu.scape_project.tool.toolwrapper.core.exceptions.ErrorParsingCmdArgsException; import eu.scape_project.tool.toolwrapper.core.exceptions.SpecParsingException; import eu.scape_project.tool.toolwrapper.core.utils.Utils; import eu.scape_project.tool.toolwrapper.data.components_spec.Characterisation; import eu.scape_project.tool.toolwrapper.data.components_spec.Component; import eu.scape_project.tool.toolwrapper.data.components_spec.Components; import eu.scape_project.tool.toolwrapper.data.components_spec.MigrationAction; import eu.scape_project.tool.toolwrapper.data.components_spec.QAObjectComparison; import eu.scape_project.tool.toolwrapper.data.components_spec.QAPropertyComparison; import eu.scape_project.tool.toolwrapper.data.tool_spec.Input; import eu.scape_project.tool.toolwrapper.data.tool_spec.Operation; import eu.scape_project.tool.toolwrapper.data.tool_spec.Output; import eu.scape_project.tool.toolwrapper.data.tool_spec.Parameter; import eu.scape_project.tool.toolwrapper.data.tool_spec.ParameterPossibleValue; import eu.scape_project.tool.toolwrapper.data.tool_spec.Tool; /** * Class that generates, from a toolspec, a bash wrapper and a Taverna workflow. * Additionally, if a component spec is provided, extra annotations are added to * the generated Taverna workflow in order to be able to integrate the SCAPE * Component Catalog */ public class BashWrapperGenerator extends ToolWrapperCommandline implements ToolWrapperGenerator { private static Logger log = Logger.getLogger(BashWrapperGenerator.class); private Tool tool; private Operation operation; private String wrapperName; private Template bashWrapperTemplate; private String generationDate; private Components components; private Component component; /** Public empty constructor (setting all instance variables to null) */ public BashWrapperGenerator() { super(); tool = null; components = null; component = null; operation = null; wrapperName = null; bashWrapperTemplate = null; SimpleDateFormat sdf = new SimpleDateFormat(Constants.FULL_DATE_WITH_TIMEZONE); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); generationDate = sdf.format(new Date()); Options options = super.getOptions(); Option opt = new Option("c", "components", true, "components spec file location"); opt.setRequired(false); options.addOption(opt); } public void setOperation(Operation operation) { this.operation = operation; } private void setComponent(Component component) { this.component = component; } private void setComponents(Components components) { this.components = components; } public void setWrapperName(String wrapperName) { this.wrapperName = wrapperName; } public String getWrapperName() { return wrapperName; } /** * Method that implements all the logic of creating a bash wrapper and * Taverna workflow (in both cases using Velocity templates) * * @param tool * tool from which the artifact(s) is being created * @param operation * if the artifact(s) is related to a particular * {@link Operation} * @param outputDirectory * directory where to place the created artifact(s) * * */ @Override public boolean generateWrapper(Tool tool, Operation operation, File outputDirectory) { this.tool = tool; this.operation = operation; boolean res = true; initVelocity(); // verify if the needed directories exist or can be created. then // load the bash wrapper template if (verifyNeededDirectories(outputDirectory) && loadBashWrapperTemplate()) { VelocityContext wrapperContext = new VelocityContext(); // add bash related information to the template context addGeneralElementsToContext(wrapperContext); addUsageInformationToContext(wrapperContext); addCommandInformationToContext(wrapperContext); // generate the bash wrapper res = res && generateBashWrapper(wrapperContext, outputDirectory); // generate the Taverna workflow res = res && generateWorkflow(wrapperContext, outputDirectory); } else { res = false; } return res; } private boolean verifyNeededDirectories(File outputDirectory) { boolean res = true; if (!outputDirectory.exists() && !outputDirectory.mkdir()) { log.error("The directory \"" + outputDirectory.getAbsolutePath() + "\" cannot be created..."); res = false; } else { res = res && verifyAndCreateNeededDirectory(new File(outputDirectory, Constants.BASHGENERATOR_WRAPPER_OUTDIRNAME)); res = res && verifyAndCreateNeededDirectory(new File(outputDirectory, Constants.BASHGENERATOR_WORKFLOW_OUTDIRNAME)); res = res && verifyAndCreateNeededDirectory(new File(outputDirectory, Constants.BASHGENERATOR_INSTALL_OUTDIRNAME)); } return res; } private boolean verifyAndCreateNeededDirectory(File directory) { boolean res = true; boolean operationResult = (directory.exists() || directory.mkdir()); res = res && operationResult; if (!operationResult) { log.error("The directory \"" + directory + "\" either not exists or cannot be created..."); } return res; } private boolean generateBashWrapper(VelocityContext context, File outputDirectory) { // merge the template context and the template itself StringWriter bashWrapperSW = new StringWriter(); bashWrapperTemplate.merge(context, bashWrapperSW); return Utils.writeTemplateContent(outputDirectory, Constants.BASHGENERATOR_WRAPPER_OUTDIRNAME, operation.getName(), bashWrapperSW, true); } private boolean generateWorkflow(VelocityContext context, File outputDirectory) { boolean success = true; Template workflowTemplate = null; // normal workflow if (component == null) { workflowTemplate = loadVelocityTemplateFromResources("workflow_template.vm"); } else { // component workflow, i.e. with semantic annotations workflowTemplate = loadComponentTemplate(context); if (workflowTemplate == null) { return false; } } UUID randomUUID = UUID.randomUUID(); context.put("uniqID", randomUUID); StringWriter sw = new StringWriter(); workflowTemplate.merge(context, sw); Utils.writeTemplateContent(outputDirectory, Constants.BASHGENERATOR_WORKFLOW_OUTDIRNAME, operation.getName() + Constants.BASHGENERATOR_WORKFLOW_EXTENSION, sw, false); return success; } private Template loadComponentTemplate(VelocityContext context) { Template workflowTemplate = null; if (component instanceof MigrationAction) { workflowTemplate = loadVelocityTemplateFromResources("migration_workflow_template.vm"); context.put("migrationAction", component); } else if (component instanceof Characterisation) { workflowTemplate = loadVelocityTemplateFromResources("characterisation_workflow_template.vm"); context.put("characterisation", component); } else if (component instanceof QAObjectComparison) { if (!canQAObjectComparisonWorkflowWithComponentsBeGenerated()) { return null; } workflowTemplate = loadVelocityTemplateFromResources("qaObjectComparison_workflow_template.vm"); context.put("qaObjectComparison", component); } else if (component instanceof QAPropertyComparison) { // as generating QAPropertyComparison component doesn't make sense // for the Toolwrapper, // just return null return null; } return workflowTemplate; } private boolean canQAObjectComparisonWorkflowWithComponentsBeGenerated() { boolean res = true; // qaObjectComparison can only have 2 inputs (that will be // annotated as SourcePath1Port and SourcePath2Port) if (operation.getInputs().getInput().size() != 2) { res = false; log.error("[ERROR] Cannot generate a workflow with components for more than 2 input ports!"); } QAObjectComparison qaObjectComparison = (QAObjectComparison) component; if (qaObjectComparison.getAcceptedMimetype().size() != 2) { res = false; log.error("[ERROR] As can only exist 2 input ports, the number of accepted mimetypes also needs to be 2, which relate precisely with those 2 input ports!"); } return res; } private void addCommandInformationToContext(VelocityContext wrapperContext) { String command = operation.getCommand(); VelocityContext contextForCommand = new VelocityContext(); StringBuilder wrapperParameters = new StringBuilder(); wrapperContext.put("listOfInputs", operation.getInputs().getInput()); int i = 1; List<String> verifyRequiredArguments = new ArrayList<String>(); for (Input input : operation.getInputs().getInput()) { if (contextForCommand.containsKey(input.getName())) { log.error("Operation \"" + operation.getName() + "\" already contains an input called \"" + input.getName() + "\"..."); } if (input.isRequired()) { verifyRequiredArguments.add("${input_files" + i + Constants.BASHGENERATOR_ARRAY_FINAL_STR); } contextForCommand.put(input.getName(), wrapWithDoubleQuotes("${input_files" + i + Constants.BASHGENERATOR_ARRAY_FINAL_STR)); wrapperParameters.append("-i %%" + input.getName() + "_inner%% "); i++; } i = 1; wrapperContext .put("listOfParams", operation.getInputs().getParameter()); for (Parameter parameter : operation.getInputs().getParameter()) { if (contextForCommand.containsKey(parameter.getName())) { log.error("Operation \"" + operation.getName() + "\" already contains an parameter called \"" + parameter.getName() + "\"..."); } if (parameter.isRequired()) { verifyRequiredArguments.add("${param_files" + i + Constants.BASHGENERATOR_ARRAY_FINAL_STR); } contextForCommand.put(parameter.getName(), "${param_files" + i + Constants.BASHGENERATOR_ARRAY_FINAL_STR); wrapperParameters.append("-p %%" + parameter.getName() + "_inner%% "); i++; } wrapperContext.put("listOfOutputs", operation.getOutputs().getOutput()); i = 1; for (Output output : operation.getOutputs().getOutput()) { if (contextForCommand.containsKey(output.getName())) { log.error("Operation \"" + operation.getName() + "\" already contains an output called \"" + output.getName() + "\"..."); } if (output.isRequired()) { verifyRequiredArguments.add("${output_files" + i + Constants.BASHGENERATOR_ARRAY_FINAL_STR); } contextForCommand.put(output.getName(), wrapWithDoubleQuotes("${output_files" + i + Constants.BASHGENERATOR_ARRAY_FINAL_STR)); wrapperParameters.append("-o %%" + output.getName() + "_inner%% "); i++; } wrapperContext .put("verify_required_arguments", verifyRequiredArguments); wrapperContext.put("wrapperParameters", wrapperParameters.toString()); StringWriter w = new StringWriter(); contextForCommand.put("param", ""); Velocity.evaluate(contextForCommand, w, "command", command); wrapperContext.put("command", w); } private void addUsageInformationToContext(VelocityContext wrapperContext) { wrapperContext.put("usageDescription", operation.getDescription()); addInputUsageInformationToContext(wrapperContext); addParamUsageInformationToContext(wrapperContext); addOutputUsageInformationToContext(wrapperContext); } private void addInputUsageInformationToContext( VelocityContext wrapperContext) { if (operation.getInputs().getStdin() != null) { wrapperContext.put("usageInputParameter", "-i STDIN"); wrapperContext.put("usageInputParameterDescription", "-i STDIN > Read input from the STDIN"); } else { // user input parameters StringBuilder uip = new StringBuilder(""); // user input parameters description to print on the bash usage // function StringBuilder uipd = new StringBuilder(""); // user input parameters description for man page StringBuilder uipdman = new StringBuilder(""); int i = 0; for (Input input : operation.getInputs().getInput()) { String value = "-i " + input.getName() + (i == 0 ? "|STDIN" : ""); uip.append((uip.length() == 0 ? "" : " ")); if (input.isRequired()) { uip.append(value); } else { uip.append("[" + value + "]"); } String inputDescription = value + " > " + input.getDescription() + (i == 0 ? " OR Read input from the STDIN" : ""); uipd.append((uipd.length() != 0 ? "\n\t" : "") + inputDescription); uipdman.append(inputDescription + "\n\n"); i++; } wrapperContext.put("usageInputParameter", uip.toString()); wrapperContext.put("usageInputParameterDescription", uipd.toString()); wrapperContext.put("usageInputParameterDescriptionForMan", uipdman.toString()); } } private void addParamUsageInformationToContext( VelocityContext wrapperContext) { // user input parameters StringBuilder uip = new StringBuilder(""); // user input parameters description to print on the bash usage function StringBuilder uipd = new StringBuilder(""); // user input parameters description for man page StringBuilder uipdman = new StringBuilder(""); for (Parameter param : operation.getInputs().getParameter()) { String value = "-p " + param.getName(); uip.append((uip.length() == 0 ? "" : " ")); if (param.isRequired()) { uip.append(value); } else { uip.append("[" + value + "]"); } String paramDescription = value + " > " + param.getDescription(); uipd.append((uipd.length() != 0 ? "\n\t" : "") + paramDescription); uipdman.append(paramDescription + "\n\n"); for (ParameterPossibleValue possibleValue : param .getPossibleValue()) { uipd.append((uipd.length() != 0 ? "\n\t\t" : "") + "\\\"" + possibleValue.getValue() + "\\\" > " + possibleValue.getDescription()); uipdman.append("\t\\\"" + possibleValue.getValue() + "\\\" > " + possibleValue.getDescription() + "\n\n"); } } wrapperContext.put("usageParamParameter", uip.toString()); wrapperContext.put("usageParamParameterDescription", uipd.toString()); wrapperContext.put("usageParamParameterDescriptionForMan", uipdman.toString()); } private void addOutputUsageInformationToContext( VelocityContext wrapperContext) { if (operation.getOutputs().getStdout() != null) { wrapperContext.put("usageOutputParameter", "-o STDOUT"); wrapperContext.put("usageOutputParameterDescription", "-o STDOUT > Write output to the STDOUT"); } else { // user input parameters StringBuilder uip = new StringBuilder(""); // user input parameters description to print on the bash usage // function StringBuilder uipd = new StringBuilder(""); // user input parameters description for man page StringBuilder uipdman = new StringBuilder(""); int i = 0; for (Output output : operation.getOutputs().getOutput()) { String value = "-o " + output.getName() + (i == 0 ? "|STDOUT" : ""); uip.append((uip.length() == 0 ? "" : " ")); if (output.isRequired()) { uip.append(value); } else { uip.append("[" + value + "]"); } String outputDescription = value + " > " + output.getDescription() + (i == 0 ? " OR Write output to the STDOUT" : ""); uipd.append((uipd.length() != 0 ? "\n\t" : "") + outputDescription); uipdman.append(outputDescription + "\n\n"); i++; } wrapperContext.put("usageOutputParameter", uip.toString()); wrapperContext.put("usageOutputParameterDescription", uipd.toString()); wrapperContext.put("usageOutputParameterDescriptionForMan", uipdman.toString()); } } private void initVelocity() { Properties p = new Properties(); p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); p.setProperty("runtime.log.logsystem.log4j.logger", "org.apache.velocity"); Velocity.init(p); } private boolean loadBashWrapperTemplate() { bashWrapperTemplate = loadVelocityTemplateFromResources("wrapper_template.vm"); return bashWrapperTemplate != null; } private Template loadVelocityTemplateFromResources(String templatePath) { Template template = null; try { template = Velocity.getTemplate(templatePath, "UTF-8"); } catch (ResourceNotFoundException e) { log.error(e); } catch (ParseErrorException e) { log.error(e); } return template; } private String wrapWithDoubleQuotes(String in) { return "\"" + in + "\""; } private void addGeneralElementsToContext(VelocityContext context) { context.put("toolName", tool.getName()); context.put("toolHomepage", tool.getHomepage()); context.put("toolVersion", tool.getVersion()); context.put("toolInstallation", tool.getInstallation()); context.put("wrapperName", wrapperName); context.put("generationDate", generationDate); context.put("operation", operation); context.put("components", components); context.put("component", component); context.put("esc", new org.apache.velocity.tools.generic.EscapeTool()); } private void copySpecsToInstallDir(File outputDir, File toolSpec, File componentSpec) { Utils.copyFile(toolSpec, new File(outputDir.getAbsoluteFile() + File.separator + Constants.BASHGENERATOR_INSTALL_OUTDIRNAME, toolSpec.getName()), false); if (componentSpec != null) { Utils.copyFile(componentSpec, new File(outputDir.getAbsoluteFile() + File.separator + Constants.BASHGENERATOR_INSTALL_OUTDIRNAME, componentSpec.getName()), false); } } /** * Main method that parses the parameters, and for each operation generates * a bash wrapper and a Taverna workflow * * @param args * command-line provided arguments */ public static void main(String[] args) { BashWrapperGenerator bwg = new BashWrapperGenerator(); int exitCode = 0; try { ImmutablePair<CommandLine, Tool> pair = bwg .processToolWrapperGenerationRequest(args); CommandLine cmd = null; Tool tool = null; Components components = null; if (pair != null) { cmd = pair.getLeft(); tool = pair.getRight(); File toolFile = cmd.hasOption("t") ? new File( cmd.getOptionValue("t")) : null; File componentsFile = cmd.hasOption("c") ? new File( cmd.getOptionValue("c")) : null; File outputdirFile = cmd.hasOption("o") ? new File( cmd.getOptionValue("o")) : null; // try to create a component instance if provided the components // spec file location if (componentsFile != null) { components = eu.scape_project.tool.toolwrapper.data.components_spec.utils.Utils .createComponents(componentsFile.getAbsolutePath()); bwg.setComponents(components); } if (componentsFile == null || components != null) { bwg.copySpecsToInstallDir(outputdirFile, toolFile, componentsFile); for (Operation operation : tool.getOperations() .getOperation()) { // just to make sure it doesn't have an older value bwg.setComponent(null); if (components != null) { for (Component component : components .getComponent()) { if (component.getName().equalsIgnoreCase( operation.getName())) { bwg.setComponent(component); break; } } } // define wrapper name as operation name bwg.setWrapperName(operation.getName()); // generate the wrapper and Taverna workflow boolean generationOK = bwg.generateWrapper(tool, operation, outputdirFile); if (generationOK) { log.info("Ouputs for operation \"" + operation.getName() + "\"" + " generated with success!"); } else { log.error("[ERROR] Error generating outputs for operation \"" + operation.getName() + "\""); } } } else { log.error("[ERROR] Error loading components file!"); exitCode = 3; } } } catch (ErrorParsingCmdArgsException e) { log.error("[ERROR] " + e.getMessage()); bwg.printUsage(); exitCode = 2; } catch (SpecParsingException e) { log.error("[ERROR] " + e.getMessage(), e); bwg.printUsage(); exitCode = 1; } System.exit(exitCode); } }
package org.hisp.dhis.dataelement; /* * 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 com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.CombinationGenerator; import org.hisp.dhis.common.DataDimensionType; import org.hisp.dhis.common.DxfNamespaces; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.MergeMode; import org.hisp.dhis.common.MetadataObject; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Abyot Aselefew */ @JacksonXmlRootElement( localName = "categoryCombo", namespace = DxfNamespaces.DXF_2_0 ) public class DataElementCategoryCombo extends BaseIdentifiableObject implements MetadataObject { public static final String DEFAULT_CATEGORY_COMBO_NAME = "default"; /** * A set with categories. */ private List<DataElementCategory> categories = new ArrayList<>(); /** * A set of category option combinations. Use getSortedOptionCombos() to get a * sorted list of category option combinations. */ private Set<DataElementCategoryOptionCombo> optionCombos = new HashSet<>(); /** * Type of data dimension. Category combinations of type DISAGGREGATION can * be linked to data elements, whereas type ATTRIBUTE can be linked to data * sets. */ private DataDimensionType dataDimensionType; /** * Indicates whether to skip total values for the categories in reports. */ private boolean skipTotal; // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- public DataElementCategoryCombo() { } public DataElementCategoryCombo( String name, DataDimensionType dataDimensionType ) { this.name = name; this.dataDimensionType = dataDimensionType; } public DataElementCategoryCombo( String name, DataDimensionType dataDimensionType, List<DataElementCategory> categories ) { this( name, dataDimensionType ); this.categories = categories; } // ------------------------------------------------------------------------- // Logic // ------------------------------------------------------------------------- @JsonProperty( "isDefault" ) public boolean isDefault() { return DEFAULT_CATEGORY_COMBO_NAME.equals( name ); } /** * Indicates whether this category combo has at least one category, has at * least one category option combo and that all categories have at least one * category option. */ public boolean isValid() { if ( categories == null || categories.isEmpty() ) { return false; } for ( DataElementCategory category : categories ) { if ( category == null || category.getCategoryOptions() == null || category.getCategoryOptions().isEmpty() ) { return false; } } return true; } public List<DataElementCategoryOption> getCategoryOptions() { final List<DataElementCategoryOption> categoryOptions = new ArrayList<>(); for ( DataElementCategory category : categories ) { categoryOptions.addAll( category.getCategoryOptions() ); } return categoryOptions; } public boolean doTotal() { return optionCombos != null && optionCombos.size() > 1 && !skipTotal; } public boolean doSubTotals() { return categories != null && categories.size() > 1; } public DataElementCategoryOption[][] getCategoryOptionsAsArray() { DataElementCategoryOption[][] arrays = new DataElementCategoryOption[categories.size()][]; int i = 0; for ( DataElementCategory category : categories ) { arrays[i++] = new ArrayList<>( category.getCategoryOptions() ).toArray( new DataElementCategoryOption[0] ); } return arrays; } public List<DataElementCategoryOptionCombo> generateOptionCombosList() { List<DataElementCategoryOptionCombo> list = new ArrayList<>(); CombinationGenerator<DataElementCategoryOption> generator = new CombinationGenerator<>( getCategoryOptionsAsArray() ); while ( generator.hasNext() ) { DataElementCategoryOptionCombo optionCombo = new DataElementCategoryOptionCombo(); optionCombo.setCategoryOptions( new HashSet<>( generator.getNext() ) ); optionCombo.setCategoryCombo( this ); list.add( optionCombo ); } return list; } public List<DataElementCategoryOptionCombo> getSortedOptionCombos() { List<DataElementCategoryOptionCombo> list = new ArrayList<>(); CombinationGenerator<DataElementCategoryOption> generator = new CombinationGenerator<>( getCategoryOptionsAsArray() ); while ( generator.hasNext() ) { List<DataElementCategoryOption> categoryOptions = generator.getNext(); Set<DataElementCategoryOption> categoryOptionSet = new HashSet<>( categoryOptions ); for ( DataElementCategoryOptionCombo optionCombo : optionCombos ) { Set<DataElementCategoryOption> persistedCategoryOptions = new HashSet<>( optionCombo.getCategoryOptions() ); if ( categoryOptionSet.equals( persistedCategoryOptions ) ) { list.add( optionCombo ); continue; } } } return list; } public void generateOptionCombos() { this.optionCombos = new HashSet<>( generateOptionCombosList() ); for ( DataElementCategoryOptionCombo optionCombo : optionCombos ) { for ( DataElementCategoryOption categoryOption : optionCombo.getCategoryOptions() ) { categoryOption.addCategoryOptionCombo( optionCombo ); } } } public boolean hasOptionCombos() { return optionCombos != null && !optionCombos.isEmpty(); } // ------------------------------------------------------------------------- // Logic // ------------------------------------------------------------------------- public void addDataElementCategory( DataElementCategory category ) { categories.add( category ); category.getCategoryCombos().add( this ); } public void removeDataElementCategory( DataElementCategory category ) { categories.remove( category ); category.getCategoryCombos().remove( this ); } public void removeAllCategories() { for ( DataElementCategory category : categories ) { category.getCategoryCombos().remove( this ); } categories.clear(); } // ------------------------------------------------------------------------- // Getters and setters // ------------------------------------------------------------------------- @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) @JacksonXmlElementWrapper( localName = "categories", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "category", namespace = DxfNamespaces.DXF_2_0 ) public List<DataElementCategory> getCategories() { return categories; } public void setCategories( List<DataElementCategory> categories ) { this.categories = categories; } @JsonProperty( "categoryOptionCombos" ) @JsonSerialize( contentAs = BaseIdentifiableObject.class ) @JacksonXmlElementWrapper( localName = "categoryOptionCombos", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "categoryOptionCombo", namespace = DxfNamespaces.DXF_2_0 ) public Set<DataElementCategoryOptionCombo> getOptionCombos() { return optionCombos; } public void setOptionCombos( Set<DataElementCategoryOptionCombo> optionCombos ) { this.optionCombos = optionCombos; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public DataDimensionType getDataDimensionType() { return dataDimensionType; } public void setDataDimensionType( DataDimensionType dataDimensionType ) { this.dataDimensionType = dataDimensionType; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isSkipTotal() { return skipTotal; } public void setSkipTotal( boolean skipTotal ) { this.skipTotal = skipTotal; } @Override public void mergeWith( IdentifiableObject other, MergeMode mergeMode ) { super.mergeWith( other, mergeMode ); if ( other.getClass().isInstance( this ) ) { DataElementCategoryCombo categoryCombo = (DataElementCategoryCombo) other; skipTotal = categoryCombo.isSkipTotal(); if ( mergeMode.isReplace() ) { dataDimensionType = categoryCombo.getDataDimensionType(); } else if ( mergeMode.isMerge() ) { dataDimensionType = categoryCombo.getDataDimensionType() == null ? dataDimensionType : categoryCombo.getDataDimensionType(); } removeAllCategories(); categoryCombo.getCategories().forEach( this::addDataElementCategory ); } } }
/* * Copyright 2011 gitblit.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 com.gitblit; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * Constant values used by Gitblit. * * @author James Moger * */ public class Constants { public static final String NAME = "Gitblit"; public static final String FULL_NAME = "Gitblit - a pure Java Git solution"; @Deprecated public static final String ADMIN_ROLE = "#admin"; @Deprecated public static final String FORK_ROLE = "#fork"; @Deprecated public static final String CREATE_ROLE = "#create"; @Deprecated public static final String NOT_FEDERATED_ROLE = "#notfederated"; @Deprecated public static final String NO_ROLE = "#none"; public static final String EXTERNAL_ACCOUNT = "#externalAccount"; public static final String PROPERTIES_FILE = "gitblit.properties"; public static final String DEFAULT_USER_REPOSITORY_PREFIX = "~"; public static final String R_PATH = "/r/"; public static final String GIT_PATH = "/git/"; public static final String REGEX_SHA256 = "[a-fA-F0-9]{64}"; /** * This regular expression is used when searching for "mentions" in tickets * (when someone writes @thisOtherUser) */ public static final String REGEX_TICKET_MENTION = "\\B@(?<user>[^\\s]+)\\b"; public static final String ZIP_PATH = "/zip/"; public static final String SYNDICATION_PATH = "/feed/"; public static final String FEDERATION_PATH = "/federation/"; public static final String RPC_PATH = "/rpc/"; public static final String PAGES = "/pages/"; public static final String SPARKLESHARE_INVITE_PATH = "/sparkleshare/"; public static final String RAW_PATH = "/raw/"; public static final String PT_PATH = "/pt"; public static final String BRANCH_GRAPH_PATH = "/graph/"; public static final String BORDER = "*****************************************************************"; public static final String BORDER2 = "#################################################################"; public static final String FEDERATION_USER = "$gitblit"; public static final String PROPOSAL_EXT = ".json"; public static final String ENCODING = "UTF-8"; public static final int LEN_SHORTLOG = 78; public static final int LEN_SHORTLOG_REFS = 60; public static final int LEN_FILESTORE_META_MIN = 125; public static final int LEN_FILESTORE_META_MAX = 146; public static final String DEFAULT_BRANCH = "default"; public static final String CONFIG_GITBLIT = "gitblit"; public static final String CONFIG_CUSTOM_FIELDS = "customFields"; public static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssZ"; public static final String baseFolder = "baseFolder"; public static final String baseFolder$ = "${" + baseFolder + "}"; public static final String contextFolder$ = "${contextFolder}"; public static final String HEAD = "HEAD"; public static final String R_META = "refs/meta/"; public static final String R_HEADS = "refs/heads/"; public static final String R_NOTES = "refs/notes/"; public static final String R_CHANGES = "refs/changes/"; public static final String R_PULL = "refs/pull/"; public static final String R_TAGS = "refs/tags/"; public static final String R_REMOTES = "refs/remotes/"; public static final String R_FOR = "refs/for/"; public static final String R_TICKET = "refs/heads/ticket/"; public static final String R_TICKETS_PATCHSETS = "refs/tickets/"; public static final String R_MASTER = "refs/heads/master"; public static final String MASTER = "master"; public static final String R_DEVELOP = "refs/heads/develop"; public static final String DEVELOP = "develop"; public static final String ATTRIB_AUTHTYPE = NAME + ":authentication-type"; public static final String ATTRIB_AUTHUSER = NAME + ":authenticated-user"; public static final String R_LFS = "info/lfs/"; public static String getVersion() { String v = Constants.class.getPackage().getImplementationVersion(); if (v == null) { return "0.0.0-SNAPSHOT"; } return v; } public static String getGitBlitVersion() { return NAME + " v" + getVersion(); } public static String getBuildDate() { return getManifestValue("build-date", "PENDING"); } public static String getASCIIArt() { StringBuilder sb = new StringBuilder(); sb.append(" _____ _ _ _ _ _ _").append('\n'); sb.append(" | __ \\(_)| | | | | |(_)| |").append('\n'); sb.append(" | | \\/ _ | |_ | |__ | | _ | |_").append('\n'); sb.append(" | | __ | || __|| '_ \\ | || || __|").append(" ").append("http://gitblit.com").append('\n'); sb.append(" | |_\\ \\| || |_ | |_) || || || |_").append(" ").append("@gitblit").append('\n'); sb.append(" \\____/|_| \\__||_.__/ |_||_| \\__|").append(" ").append(Constants.getVersion()).append('\n'); return sb.toString(); } private static String getManifestValue(String attrib, String defaultValue) { Class<?> clazz = Constants.class; String className = clazz.getSimpleName() + ".class"; String classPath = clazz.getResource(className).toString(); if (!classPath.startsWith("jar")) { // Class not from JAR return defaultValue; } try { String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attr = manifest.getMainAttributes(); String value = attr.getValue(attrib); return value; } catch (Exception e) { } return defaultValue; } public static enum Role { NONE, ADMIN, CREATE, FORK, NOT_FEDERATED; public String getRole() { return "#" + name().replace("_", "").toLowerCase(); } @Override public String toString() { return getRole(); } } /** * Enumeration representing the four access restriction levels. */ public static enum AccessRestrictionType { NONE, PUSH, CLONE, VIEW; private static final AccessRestrictionType [] AUTH_TYPES = { PUSH, CLONE, VIEW }; public static AccessRestrictionType fromName(String name) { for (AccessRestrictionType type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return NONE; } public static List<AccessRestrictionType> choices(boolean allowAnonymousPush) { if (allowAnonymousPush) { return Arrays.asList(values()); } return Arrays.asList(AUTH_TYPES); } public boolean exceeds(AccessRestrictionType type) { return this.ordinal() > type.ordinal(); } public boolean atLeast(AccessRestrictionType type) { return this.ordinal() >= type.ordinal(); } @Override public String toString() { return name(); } public boolean isValidPermission(AccessPermission permission) { switch (this) { case VIEW: // VIEW restriction // all access permissions are valid return true; case CLONE: // CLONE restriction // only CLONE or greater access permissions are valid return permission.atLeast(AccessPermission.CLONE); case PUSH: // PUSH restriction // only PUSH or greater access permissions are valid return permission.atLeast(AccessPermission.PUSH); case NONE: // NO access restriction // all access permissions are invalid return false; } return false; } } /** * Enumeration representing the types of authorization control for an * access restricted resource. */ public static enum AuthorizationControl { AUTHENTICATED, NAMED; public static AuthorizationControl fromName(String name) { for (AuthorizationControl type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return NAMED; } @Override public String toString() { return name(); } } /** * Enumeration representing the types of federation tokens. */ public static enum FederationToken { ALL, USERS_AND_REPOSITORIES, REPOSITORIES; public static FederationToken fromName(String name) { for (FederationToken type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return REPOSITORIES; } @Override public String toString() { return name(); } } /** * Enumeration representing the types of federation requests. */ public static enum FederationRequest { POKE, PROPOSAL, PULL_REPOSITORIES, PULL_USERS, PULL_TEAMS, PULL_SETTINGS, PULL_SCRIPTS, STATUS; public static FederationRequest fromName(String name) { for (FederationRequest type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return PULL_REPOSITORIES; } @Override public String toString() { return name(); } } /** * Enumeration representing the statii of federation requests. */ public static enum FederationPullStatus { PENDING, FAILED, SKIPPED, PULLED, MIRRORED, NOCHANGE, EXCLUDED; public static FederationPullStatus fromName(String name) { for (FederationPullStatus type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return PENDING; } @Override public String toString() { return name(); } } /** * Enumeration representing the federation types. */ public static enum FederationStrategy { EXCLUDE, FEDERATE_THIS, FEDERATE_ORIGIN; public static FederationStrategy fromName(String name) { for (FederationStrategy type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return FEDERATE_THIS; } public boolean exceeds(FederationStrategy type) { return this.ordinal() > type.ordinal(); } public boolean atLeast(FederationStrategy type) { return this.ordinal() >= type.ordinal(); } @Override public String toString() { return name(); } } /** * Enumeration representing the possible results of federation proposal * requests. */ public static enum FederationProposalResult { ERROR, FEDERATION_DISABLED, MISSING_DATA, NO_PROPOSALS, NO_POKE, ACCEPTED; @Override public String toString() { return name(); } } /** * Enumeration representing the possible remote procedure call requests from * a client. */ public static enum RpcRequest { // Order is important here. anything after LIST_SETTINGS requires // administrator privileges and web.allowRpcManagement. CLEAR_REPOSITORY_CACHE, REINDEX_TICKETS, GET_PROTOCOL, LIST_REPOSITORIES, LIST_BRANCHES, GET_USER, FORK_REPOSITORY, LIST_SETTINGS, CREATE_REPOSITORY, EDIT_REPOSITORY, DELETE_REPOSITORY, LIST_USERS, CREATE_USER, EDIT_USER, DELETE_USER, LIST_TEAMS, CREATE_TEAM, EDIT_TEAM, DELETE_TEAM, LIST_REPOSITORY_MEMBERS, SET_REPOSITORY_MEMBERS, LIST_REPOSITORY_TEAMS, SET_REPOSITORY_TEAMS, LIST_REPOSITORY_MEMBER_PERMISSIONS, SET_REPOSITORY_MEMBER_PERMISSIONS, LIST_REPOSITORY_TEAM_PERMISSIONS, SET_REPOSITORY_TEAM_PERMISSIONS, LIST_FEDERATION_REGISTRATIONS, LIST_FEDERATION_RESULTS, LIST_FEDERATION_PROPOSALS, LIST_FEDERATION_SETS, EDIT_SETTINGS, LIST_STATUS; public static RpcRequest fromName(String name) { for (RpcRequest type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return null; } public boolean exceeds(RpcRequest type) { return this.ordinal() > type.ordinal(); } @Override public String toString() { return name(); } } /** * Enumeration of the search types. */ public static enum SearchType { AUTHOR, COMMITTER, COMMIT; public static SearchType forName(String name) { for (SearchType type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return COMMIT; } @Override public String toString() { return name().toLowerCase(); } } /** * Enumeration of the feed content object types. */ public static enum FeedObjectType { COMMIT, TAG; public static FeedObjectType forName(String name) { for (FeedObjectType type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return COMMIT; } @Override public String toString() { return name().toLowerCase(); } } /** * The types of objects that can be indexed and queried. */ public static enum SearchObjectType { commit, blob; public static SearchObjectType fromName(String name) { for (SearchObjectType value : values()) { if (value.name().equals(name)) { return value; } } return null; } } /** * The access permissions available for a repository. */ public static enum AccessPermission { NONE("N"), EXCLUDE("X"), VIEW("V"), CLONE("R"), PUSH("RW"), CREATE("RWC"), DELETE("RWD"), REWIND("RW+"), OWNER("RW+"); public static final AccessPermission [] NEWPERMISSIONS = { EXCLUDE, VIEW, CLONE, PUSH, CREATE, DELETE, REWIND }; public static final AccessPermission [] SSHPERMISSIONS = { VIEW, CLONE, PUSH }; public static AccessPermission LEGACY = REWIND; public final String code; private AccessPermission(String code) { this.code = code; } public boolean atMost(AccessPermission perm) { return ordinal() <= perm.ordinal(); } public boolean atLeast(AccessPermission perm) { return ordinal() >= perm.ordinal(); } public boolean exceeds(AccessPermission perm) { return ordinal() > perm.ordinal(); } public String asRole(String repository) { return code + ":" + repository; } @Override public String toString() { return code; } public static AccessPermission permissionFromRole(String role) { String [] fields = role.split(":", 2); if (fields.length == 1) { // legacy/undefined assume full permissions return AccessPermission.LEGACY; } else { // code:repository return AccessPermission.fromCode(fields[0]); } } public static String repositoryFromRole(String role) { String [] fields = role.split(":", 2); if (fields.length == 1) { // legacy/undefined assume full permissions return role; } else { // code:repository return fields[1]; } } public static AccessPermission fromCode(String code) { for (AccessPermission perm : values()) { if (perm.code.equalsIgnoreCase(code)) { return perm; } } return AccessPermission.NONE; } } public static enum RegistrantType { REPOSITORY, USER, TEAM; } public static enum PermissionType { MISSING, ANONYMOUS, EXPLICIT, TEAM, REGEX, OWNER, ADMINISTRATOR; } public static enum GCStatus { READY, COLLECTING; public boolean exceeds(GCStatus s) { return ordinal() > s.ordinal(); } } public static enum AuthenticationType { PUBLIC_KEY, CREDENTIALS, COOKIE, CERTIFICATE, CONTAINER, HTTPHEADER; public boolean isStandard() { return ordinal() <= COOKIE.ordinal(); } } public static enum AccountType { LOCAL, CONTAINER, LDAP, REDMINE, SALESFORCE, WINDOWS, PAM, HTPASSWD, HTTPHEADER; public static AccountType fromString(String value) { for (AccountType type : AccountType.values()) { if (type.name().equalsIgnoreCase(value)) { return type; } } return AccountType.LOCAL; } public boolean isLocal() { return this == LOCAL; } } public static enum CommitMessageRenderer { PLAIN, MARKDOWN; public static CommitMessageRenderer fromName(String name) { for (CommitMessageRenderer renderer : values()) { if (renderer.name().equalsIgnoreCase(name)) { return renderer; } } return CommitMessageRenderer.PLAIN; } } public static enum Transport { // ordered for url advertisements, assuming equal access permissions SSH, HTTPS, HTTP, GIT; public static Transport fromString(String value) { for (Transport t : values()) { if (t.name().equalsIgnoreCase(value)) { return t; } } return null; } public static Transport fromUrl(String url) { int delim = url.indexOf("://"); if (delim == -1) { // if no protocol is specified, SSH is assumed by git clients return SSH; } String scheme = url.substring(0, delim); return fromString(scheme); } } /** * The type of merge Gitblit will use when merging a ticket to the integration branch. * <p> * The default type is MERGE_ALWAYS. * <p> * This is modeled after the Gerrit SubmitType. */ public static enum MergeType { /** Allows a merge only if it can be fast-forward merged into the integration branch. */ FAST_FORWARD_ONLY, /** Uses a fast-forward merge if possible, other wise a merge commit is created. */ MERGE_IF_NECESSARY, // Future REBASE_IF_NECESSARY, /** Always merge with a merge commit, even when a fast-forward would be possible. */ MERGE_ALWAYS, // Future? CHERRY_PICK ; public static final MergeType DEFAULT_MERGE_TYPE = MERGE_ALWAYS; public static MergeType fromName(String name) { for (MergeType type : values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return DEFAULT_MERGE_TYPE; } } @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Unused { } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.regionserver; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.HBaseTestCase; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.testclassification.RegionServerTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.CollectionBackedScanner; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; @Category({RegionServerTests.class, SmallTests.class}) public class TestKeyValueHeap extends HBaseTestCase { private static final boolean PRINT = false; List<KeyValueScanner> scanners = new ArrayList<KeyValueScanner>(); private byte[] row1; private byte[] fam1; private byte[] col1; private byte[] data; private byte[] row2; private byte[] fam2; private byte[] col2; private byte[] col3; private byte[] col4; private byte[] col5; @Before public void setUp() throws Exception { super.setUp(); data = Bytes.toBytes("data"); row1 = Bytes.toBytes("row1"); fam1 = Bytes.toBytes("fam1"); col1 = Bytes.toBytes("col1"); row2 = Bytes.toBytes("row2"); fam2 = Bytes.toBytes("fam2"); col2 = Bytes.toBytes("col2"); col3 = Bytes.toBytes("col3"); col4 = Bytes.toBytes("col4"); col5 = Bytes.toBytes("col5"); } @Test public void testSorted() throws IOException{ //Cases that need to be checked are: //1. The "smallest" KeyValue is in the same scanners as current //2. Current scanner gets empty List<Cell> l1 = new ArrayList<Cell>(); l1.add(new KeyValue(row1, fam1, col5, data)); l1.add(new KeyValue(row2, fam1, col1, data)); l1.add(new KeyValue(row2, fam1, col2, data)); scanners.add(new Scanner(l1)); List<Cell> l2 = new ArrayList<Cell>(); l2.add(new KeyValue(row1, fam1, col1, data)); l2.add(new KeyValue(row1, fam1, col2, data)); scanners.add(new Scanner(l2)); List<Cell> l3 = new ArrayList<Cell>(); l3.add(new KeyValue(row1, fam1, col3, data)); l3.add(new KeyValue(row1, fam1, col4, data)); l3.add(new KeyValue(row1, fam2, col1, data)); l3.add(new KeyValue(row1, fam2, col2, data)); l3.add(new KeyValue(row2, fam1, col3, data)); scanners.add(new Scanner(l3)); List<KeyValue> expected = new ArrayList<KeyValue>(); expected.add(new KeyValue(row1, fam1, col1, data)); expected.add(new KeyValue(row1, fam1, col2, data)); expected.add(new KeyValue(row1, fam1, col3, data)); expected.add(new KeyValue(row1, fam1, col4, data)); expected.add(new KeyValue(row1, fam1, col5, data)); expected.add(new KeyValue(row1, fam2, col1, data)); expected.add(new KeyValue(row1, fam2, col2, data)); expected.add(new KeyValue(row2, fam1, col1, data)); expected.add(new KeyValue(row2, fam1, col2, data)); expected.add(new KeyValue(row2, fam1, col3, data)); //Creating KeyValueHeap KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparator.COMPARATOR); List<Cell> actual = new ArrayList<Cell>(); while(kvh.peek() != null){ actual.add(kvh.next()); } assertEquals(expected.size(), actual.size()); for(int i=0; i<expected.size(); i++){ assertEquals(expected.get(i), actual.get(i)); if(PRINT){ System.out.println("expected " +expected.get(i)+ "\nactual " +actual.get(i) +"\n"); } } //Check if result is sorted according to Comparator for(int i=0; i<actual.size()-1; i++){ int ret = CellComparator.COMPARATOR.compare(actual.get(i), actual.get(i+1)); assertTrue(ret < 0); } } @Test public void testSeek() throws IOException { //Cases: //1. Seek KeyValue that is not in scanner //2. Check that smallest that is returned from a seek is correct List<Cell> l1 = new ArrayList<Cell>(); l1.add(new KeyValue(row1, fam1, col5, data)); l1.add(new KeyValue(row2, fam1, col1, data)); l1.add(new KeyValue(row2, fam1, col2, data)); scanners.add(new Scanner(l1)); List<Cell> l2 = new ArrayList<Cell>(); l2.add(new KeyValue(row1, fam1, col1, data)); l2.add(new KeyValue(row1, fam1, col2, data)); scanners.add(new Scanner(l2)); List<Cell> l3 = new ArrayList<Cell>(); l3.add(new KeyValue(row1, fam1, col3, data)); l3.add(new KeyValue(row1, fam1, col4, data)); l3.add(new KeyValue(row1, fam2, col1, data)); l3.add(new KeyValue(row1, fam2, col2, data)); l3.add(new KeyValue(row2, fam1, col3, data)); scanners.add(new Scanner(l3)); List<KeyValue> expected = new ArrayList<KeyValue>(); expected.add(new KeyValue(row2, fam1, col1, data)); //Creating KeyValueHeap KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparator.COMPARATOR); KeyValue seekKv = new KeyValue(row2, fam1, null, null); kvh.seek(seekKv); List<Cell> actual = new ArrayList<Cell>(); actual.add(kvh.peek()); assertEquals(expected.size(), actual.size()); for(int i=0; i<expected.size(); i++){ assertEquals(expected.get(i), actual.get(i)); if(PRINT){ System.out.println("expected " +expected.get(i)+ "\nactual " +actual.get(i) +"\n"); } } } @Test public void testScannerLeak() throws IOException { // Test for unclosed scanners (HBASE-1927) List<Cell> l1 = new ArrayList<Cell>(); l1.add(new KeyValue(row1, fam1, col5, data)); l1.add(new KeyValue(row2, fam1, col1, data)); l1.add(new KeyValue(row2, fam1, col2, data)); scanners.add(new Scanner(l1)); List<Cell> l2 = new ArrayList<Cell>(); l2.add(new KeyValue(row1, fam1, col1, data)); l2.add(new KeyValue(row1, fam1, col2, data)); scanners.add(new Scanner(l2)); List<Cell> l3 = new ArrayList<Cell>(); l3.add(new KeyValue(row1, fam1, col3, data)); l3.add(new KeyValue(row1, fam1, col4, data)); l3.add(new KeyValue(row1, fam2, col1, data)); l3.add(new KeyValue(row1, fam2, col2, data)); l3.add(new KeyValue(row2, fam1, col3, data)); scanners.add(new Scanner(l3)); List<Cell> l4 = new ArrayList<Cell>(); scanners.add(new Scanner(l4)); //Creating KeyValueHeap KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparator.COMPARATOR); while(kvh.next() != null); for(KeyValueScanner scanner : scanners) { assertTrue(((Scanner)scanner).isClosed()); } } private static class Scanner extends CollectionBackedScanner { private Iterator<Cell> iter; private Cell current; private boolean closed = false; public Scanner(List<Cell> list) { super(list); } public void close(){ closed = true; } public boolean isClosed() { return closed; } } }
/* * #%L * ImageJ2 software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2022 ImageJ2 developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package net.imagej.display; import java.util.ArrayList; import java.util.List; import net.imagej.ChannelCollection; import net.imagej.Data; import net.imagej.Dataset; import net.imagej.DrawingTool; import net.imagej.Position; import net.imagej.options.OptionsOverlay; import net.imagej.overlay.CompositeOverlay; import net.imagej.overlay.Overlay; import net.imagej.overlay.OverlaySettings; import net.imagej.render.RenderingService; import net.imglib2.Cursor; import net.imglib2.IterableInterval; import net.imglib2.RealInterval; import net.imglib2.RealRandomAccess; import net.imglib2.RealRandomAccessibleRealInterval; import net.imglib2.roi.RegionOfInterest; import net.imglib2.type.logic.BitType; import net.imglib2.view.IntervalView; import net.imglib2.view.RandomAccessibleOnRealRandomAccessible; import net.imglib2.view.Views; import org.scijava.display.Display; import org.scijava.display.DisplayService; import org.scijava.object.ObjectService; import org.scijava.options.OptionsService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.scijava.util.RealRect; /** * Default service for working with {@link Overlay}s. * * @author Curtis Rueden * @author Barry DeZonia */ @Plugin(type = Service.class) public final class DefaultOverlayService extends AbstractService implements OverlayService { @Parameter private ObjectService objectService; @Parameter private DisplayService displayService; @Parameter private ImageDisplayService imageDisplayService; @Parameter private OptionsService optionsService; @Parameter private RenderingService renderingService; private OverlaySettings defaultSettings; private OverlayInfoList overlayInfo; // -- OverlayService methods -- @Override public ObjectService getObjectService() { return objectService; } @Override public List<Overlay> getOverlays() { return objectService.getObjects(Overlay.class); } @Override public List<Overlay> getOverlays(final ImageDisplay display, final boolean selectedOnly) { final ArrayList<Overlay> overlays = new ArrayList<>(); for (final DataView view : display) { if (selectedOnly && !view.isSelected()) { // ignore non-selected objects continue; } final Data data = view.getData(); if (!(data instanceof Overlay)) continue; // ignore non-overlays final Overlay overlay = (Overlay) data; overlays.add(overlay); } return overlays; } @Override public List<Overlay> getOverlays(final ImageDisplay display) { return getOverlays(display, false); } @Override public void addOverlays(final ImageDisplay display, final List<? extends Overlay> overlays) { for (final Overlay overlay : overlays) { display.display(overlay); } } @Override public void removeOverlay(final ImageDisplay display, final Overlay overlay) { final ArrayList<DataView> overlayViews = new ArrayList<>(); final List<DataView> views = display; for (final DataView view : views) { final Data data = view.getData(); if (data == overlay) overlayViews.add(view); } for (final DataView view : overlayViews) { display.remove(view); view.dispose(); } display.update(); } @Override public void removeOverlay(final Overlay overlay) { final List<ImageDisplay> imgDisps = objectService.getObjects(ImageDisplay.class); for (final ImageDisplay disp : imgDisps) removeOverlay(disp, overlay); } @Override public RealRect getSelectionBounds(final ImageDisplay display) { // TODO - Compute bounds over N dimensions, not just two. // determine XY bounding box by checking all data objects double xMin = Double.POSITIVE_INFINITY; double xMax = Double.NEGATIVE_INFINITY; double yMin = Double.POSITIVE_INFINITY; double yMax = Double.NEGATIVE_INFINITY; for (final DataView view : display) { if (!view.isSelected()) continue; final Data data = view.getData(); final double min0 = data.realMin(0); final double max0 = data.realMax(0); final double min1 = data.realMin(1); final double max1 = data.realMax(1); if (min0 < xMin) xMin = min0; if (max0 > xMax) xMax = max0; if (min1 < yMin) yMin = min1; if (max1 > yMax) yMax = max1; } // get total XY extents of the display final double totalMinX = display.realMin(0); final double totalMaxX = display.realMax(0); final double totalMinY = display.realMin(1); final double totalMaxY = display.realMax(1); // use entire XY extents if values are out of bounds if (xMin < totalMinX || xMin > totalMaxX) xMin = totalMinX; if (xMax < totalMinX || xMax > totalMaxX) xMax = totalMaxX; if (yMin < totalMinY || yMin > totalMaxY) yMin = totalMinY; if (yMax < totalMinY || yMax > totalMaxY) yMax = totalMaxY; // swap reversed bounds if (xMin > xMax) { final double temp = xMin; xMin = xMax; xMax = temp; } if (yMin > yMax) { final double temp = yMin; yMin = yMax; yMax = temp; } return new RealRect(xMin, yMin, xMax - xMin, yMax - yMin); } @Override public OverlaySettings getDefaultSettings() { if (defaultSettings == null) { defaultSettings = new OverlaySettings(); final OptionsOverlay overlayOptions = optionsService.getOptions(OptionsOverlay.class); overlayOptions.updateSettings(defaultSettings); } return defaultSettings; } @Override public void drawOverlay(final Overlay o, final ImageDisplay display, final ChannelCollection channels) { draw(o, imageDisplayService.getActiveDataset(display), imageDisplayService .getActivePosition(display), channels, new OverlayOutliner()); } @Override public void drawOverlay(final Overlay o, final Dataset ds, final Position position, final ChannelCollection channels) { draw(o, ds, position, channels, new OverlayOutliner()); } @Override public void fillOverlay(final Overlay o, final ImageDisplay display, final ChannelCollection channels) { draw(o, imageDisplayService.getActiveDataset(display), imageDisplayService .getActivePosition(display), channels, new OverlayFiller()); } @Override public void fillOverlay(final Overlay o, final Dataset ds, final Position position, final ChannelCollection channels) { draw(o, ds, position, channels, new OverlayFiller()); } @Override public ImageDisplay getFirstDisplay(final Overlay o) { final List<Display<?>> displays = displayService.getDisplays(); for (final Display<?> display : displays) { if (display instanceof ImageDisplay) { final List<Overlay> displayOverlays = getOverlays((ImageDisplay) display); if (displayOverlays.contains(o)) return (ImageDisplay) display; } } return null; } @Override public List<ImageDisplay> getDisplays(final Overlay o) { final ArrayList<ImageDisplay> containers = new ArrayList<>(); final List<Display<?>> displays = displayService.getDisplays(); for (final Display<?> display : displays) { if (!(display instanceof ImageDisplay)) continue; final ImageDisplay imageDisplay = (ImageDisplay) display; for (final DataView view : imageDisplay) { final Data data = view.getData(); if (!(data instanceof Overlay)) continue; final Overlay overlay = (Overlay) data; if (overlay == o) containers.add(imageDisplay); } } return containers; } // TODO - assumes first selected overlay view is the only one. bad? @Override public Overlay getActiveOverlay(final ImageDisplay disp) { for (final DataView view : disp) { if (view.isSelected() && view instanceof OverlayView) { return ((OverlayView) view).getData(); } } return null; } @Override public OverlayInfoList getOverlayInfo() { if (overlayInfo == null) { overlayInfo = new OverlayInfoList(); } return overlayInfo; } @Override public void divideCompositeOverlay(final CompositeOverlay overlay) { final List<Overlay> subcomponents = overlay.getSubcomponents(); // to each display that owns the composite // reference the original overlays (if not already) final List<ImageDisplay> owners = getDisplays(overlay); for (final ImageDisplay owner : owners) { boolean changes = false; final List<Overlay> displayOverlays = getOverlays(owner); for (final Overlay subcomponent : subcomponents) { if (!displayOverlays.contains(subcomponent)) { owner.display(subcomponent); changes = true; } } if (changes) owner.update(); } // delete the composite overlay removeOverlay(overlay); } // -- Helper methods -- private void draw(final Overlay o, final Dataset ds, final Position position, final ChannelCollection channels, final Drawer drawer) { // TODO What null items should be checked here? Return silently if any are // null? Currently check only for null Dataset? Others likely result in // NullPointerExceptions. OK? if (ds == null) return; final DrawingTool tool = new DrawingTool(ds, renderingService); final long[] pp = new long[position.numDimensions()]; position.localize(pp); final long[] fullPos = new long[pp.length + 2]; for (int i = 2; i < fullPos.length; i++) fullPos[i] = pp[i - 2]; tool.setPosition(fullPos); tool.setChannels(channels); drawer.draw(o, tool); ds.update(); } // -- Helper classes -- private interface Drawer { void draw(Overlay o, DrawingTool tool); } private static class OverlayOutliner implements Drawer { @Override public void draw(final Overlay o, final DrawingTool tool) { final RegionOfInterest region = o.getRegionOfInterest(); final IterableInterval<BitType> ii = iterableInterval(region); final long[] max = new long[region.numDimensions()]; ii.max(max); final Cursor<BitType> cursor = ii.localizingCursor(); final RealRandomAccess<BitType> accessor = region.realRandomAccess(); long[] pos = new long[region.numDimensions()]; while (cursor.hasNext()) { cursor.fwd(); cursor.localize(pos); accessor.setPosition(pos); if (accessor.get().get() && isBorderPixel(accessor, pos, max[0], max[1])) { tool.drawPixel(pos[0], pos[1]); } } } private boolean isBorderPixel(final RealRandomAccess<BitType> accessor, final long[] pos, final long maxX, final long maxY) { if (pos[0] == 0) return true; if (pos[0] == maxX) return true; if (pos[1] == 0) return true; if (pos[1] == maxY) return true; accessor.setPosition(pos[0] - 1, 0); if (!accessor.get().get()) return true; accessor.setPosition(pos[0] + 1, 0); if (!accessor.get().get()) return true; accessor.setPosition(pos[0], 0); accessor.setPosition(pos[1] - 1, 1); if (!accessor.get().get()) return true; accessor.setPosition(pos[1] + 1, 1); if (!accessor.get().get()) return true; return false; } } private static class OverlayFiller implements Drawer { @Override public void draw(final Overlay o, final DrawingTool tool) { final RegionOfInterest region = o.getRegionOfInterest(); final Cursor<BitType> cursor = iterableInterval(region).localizingCursor(); long[] pos = new long[region.numDimensions()]; while (cursor.hasNext()) { cursor.fwd(); cursor.localize(pos); if (cursor.get().get()) tool.drawPixel(pos[0], pos[1]); } } } // TODO: Consider contributing this method to net.imglib2.view.Views. // See also: net.imglib2.roi.IterableRegionOfInterest private static <T> IterableInterval<T> iterableInterval( final RealRandomAccessibleRealInterval<T> realInterval) { final RandomAccessibleOnRealRandomAccessible<T> raster = Views.raster(realInterval); final IntervalView<T> interval = Views.interval(raster, findMin(realInterval), findMax(realInterval)); return Views.iterable(interval); } private static long[] findMin(final RealInterval realInterval) { final long[] boundMin = new long[realInterval.numDimensions()]; for (int i = 0; i < boundMin.length; i++) { boundMin[i] = (long) Math.floor(realInterval.realMin(i)); } return boundMin; } private static long[] findMax(final RealInterval realInterval) { final long[] boundMax = new long[realInterval.numDimensions()]; for (int i = 0; i < boundMax.length; i++) { boundMax[i] = (long) Math.ceil(realInterval.realMax(i)); } return boundMax; } }
/* * Copyright 2000-2013 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.ui; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.ItemRemovable; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.TableCellEditor; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import java.awt.*; import java.util.ArrayList; import java.util.List; public class TableUtil { private TableUtil() { } public interface ItemChecker { boolean isOperationApplyable(@NotNull TableModel model, int row); } @NotNull public static List<Object[]> removeSelectedItems(@NotNull JTable table) { return removeSelectedItems(table, null); } public static void selectRows(@NotNull JTable table, @NotNull int[] viewRows) { ListSelectionModel selectionModel = table.getSelectionModel(); selectionModel.clearSelection(); int count = table.getRowCount(); for (int row : viewRows) { if (row >= 0 && row < count) { selectionModel.addSelectionInterval(row, row); } } } public static void scrollSelectionToVisible(@NotNull JTable table){ ListSelectionModel selectionModel = table.getSelectionModel(); int maxSelectionIndex = selectionModel.getMaxSelectionIndex(); int minSelectionIndex = selectionModel.getMinSelectionIndex(); final int maxColumnSelectionIndex = Math.max(0, table.getColumnModel().getSelectionModel().getMinSelectionIndex()); final int minColumnSelectionIndex = Math.max(0, table.getColumnModel().getSelectionModel().getMaxSelectionIndex()); if(maxSelectionIndex == -1){ return; } Rectangle minCellRect = table.getCellRect(minSelectionIndex, minColumnSelectionIndex, false); Rectangle maxCellRect = table.getCellRect(maxSelectionIndex, maxColumnSelectionIndex, false); Point selectPoint = minCellRect.getLocation(); int allHeight = maxCellRect.y + maxCellRect.height - minCellRect.y; allHeight = Math.min(allHeight, table.getVisibleRect().height); table.scrollRectToVisible(new Rectangle(selectPoint, new Dimension(minCellRect.width / 2,allHeight))); } @NotNull public static List<Object[]> removeSelectedItems(@NotNull JTable table, @Nullable ItemChecker applyable) { final TableModel model = table.getModel(); if (!(model instanceof ItemRemovable)) { throw new RuntimeException("model must be instance of ItemRemovable"); } if (table.getSelectionModel().isSelectionEmpty()) { return new ArrayList<Object[]>(0); } final List<Object[]> removedItems = new SmartList<Object[]>(); final ItemRemovable itemRemovable = (ItemRemovable)model; final int columnCount = model.getColumnCount(); doRemoveSelectedItems(table, new ItemRemovable() { @Override public void removeRow(int index) { Object[] row = new Object[columnCount]; for (int column = 0; column < columnCount; column++) { row[column] = model.getValueAt(index, column); } removedItems.add(row); itemRemovable.removeRow(index); } }, applyable); return ContainerUtil.reverse(removedItems); } public static boolean doRemoveSelectedItems(@NotNull JTable table, @NotNull ItemRemovable itemRemovable, @Nullable ItemChecker applyable) { if (table.isEditing()) { table.getCellEditor().stopCellEditing(); } ListSelectionModel selectionModel = table.getSelectionModel(); int minSelectionIndex = selectionModel.getMinSelectionIndex(); int maxSelectionIndex = selectionModel.getMaxSelectionIndex(); if (minSelectionIndex == -1 || maxSelectionIndex == -1) { return false; } TableModel model = table.getModel(); boolean removed = false; for (int index = maxSelectionIndex; index >= 0; index--) { if (selectionModel.isSelectedIndex(index) && (applyable == null || applyable.isOperationApplyable(model, index))) { itemRemovable.removeRow(index); removed = true; } } if (!removed) { return false; } int count = model.getRowCount(); if (count == 0) { table.clearSelection(); } else if (selectionModel.getMinSelectionIndex() == -1) { if (minSelectionIndex >= model.getRowCount()) { selectionModel.setSelectionInterval(model.getRowCount() - 1, model.getRowCount() - 1); } else { selectionModel.setSelectionInterval(minSelectionIndex, minSelectionIndex); } } return true; } public static int moveSelectedItemsUp(@NotNull JTable table) { if (table.isEditing()){ table.getCellEditor().stopCellEditing(); } TableModel model = table.getModel(); ListSelectionModel selectionModel = table.getSelectionModel(); int counter = 0; for(int row = 0; row < model.getRowCount(); row++){ if (selectionModel.isSelectedIndex(row)) { counter++; for (int column = 0; column < model.getColumnCount(); column++) { Object temp = model.getValueAt(row, column); model.setValueAt(model.getValueAt(row - 1, column), row, column); model.setValueAt(temp, row - 1, column); } selectionModel.removeSelectionInterval(row, row); selectionModel.addSelectionInterval(row - 1, row - 1); } } Rectangle cellRect = table.getCellRect(selectionModel.getMinSelectionIndex(), 0, true); if (cellRect != null) { table.scrollRectToVisible(cellRect); } table.repaint(); return counter; } public static int moveSelectedItemsDown(@NotNull JTable table) { if (table.isEditing()){ table.getCellEditor().stopCellEditing(); } TableModel model = table.getModel(); ListSelectionModel selectionModel = table.getSelectionModel(); int counter = 0; for(int row = model.getRowCount() - 1; row >= 0 ; row--){ if (selectionModel.isSelectedIndex(row)) { counter++; for (int column = 0; column < model.getColumnCount(); column++) { Object temp = model.getValueAt(row, column); model.setValueAt(model.getValueAt(row + 1, column), row, column); model.setValueAt(temp, row + 1, column); } selectionModel.removeSelectionInterval(row, row); selectionModel.addSelectionInterval(row + 1, row + 1); } } Rectangle cellRect = table.getCellRect(selectionModel.getMaxSelectionIndex(), 0, true); if (cellRect != null) { table.scrollRectToVisible(cellRect); } table.repaint(); return counter; } public static void editCellAt(@NotNull JTable table, int row, int column) { if (table.editCellAt(row, column)) { final Component component = table.getEditorComponent(); if (component != null) { component.requestFocus(); } } } public static void stopEditing(@NotNull JTable table) { if (table.isEditing()) { final TableCellEditor cellEditor = table.getCellEditor(); if (cellEditor != null) { cellEditor.stopCellEditing(); } int row = table.getSelectedRow(); int column = table.getSelectedColumn(); if (row >= 0 && column >= 0) { TableCellEditor editor = table.getCellEditor(row, column); if (editor != null) { editor.stopCellEditing(); //Object value = editor.getCellEditorValue(); // //table.setValueAt(value, row, column); } } } } public static void ensureSelectionExists(@NotNull JTable table) { if (table.getSelectedRow() != -1 || table.getRowCount() == 0) return; table.setRowSelectionInterval(0, 0); } public static void setupCheckboxColumn(@NotNull JTable table, int columnIndex) { setupCheckboxColumn(table.getColumnModel().getColumn(columnIndex)); } public static void setupCheckboxColumn(@NotNull TableColumn column) { int checkboxWidth = new JCheckBox().getPreferredSize().width; column.setResizable(false); column.setPreferredWidth(checkboxWidth); column.setMaxWidth(checkboxWidth); column.setMinWidth(checkboxWidth); } public static void updateScroller(@NotNull JTable table, boolean temporaryHideVerticalScrollBar) { JScrollPane scrollPane = UIUtil.getParentOfType(JScrollPane.class, table); if (scrollPane != null) { if (temporaryHideVerticalScrollBar) { final JScrollBar bar = scrollPane.getVerticalScrollBar(); if (bar == null || !bar.isVisible()) { scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); } } scrollPane.revalidate(); scrollPane.repaint(); } } }
/* * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * * Copyright @ 2015 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.ice4j.ice; import org.ice4j.*; import org.ice4j.attribute.*; import org.ice4j.message.*; import org.ice4j.security.*; import org.ice4j.stack.*; import org.jitsi.utils.logging2.*; /** * The class that would be handling and responding to incoming connectivity * checks. * * @author Emil Ivov * @author Lyubomir Marinov */ class ConnectivityCheckServer implements RequestListener, CredentialsAuthority { /** * The agent that created us. */ private final Agent parentAgent; /** * The indicator which determines whether this * <tt>ConnectivityCheckServer</tt> is currently started. */ private boolean started = false; /** * The <tt>StunStack </tt> that we will use for connectivity checks. */ private final StunStack stunStack; /** * A flag that determines whether we have received a STUN request or not. */ private boolean alive = false; /** * The {@link Logger} used by {@link ConnectivityCheckServer} instances. */ private Logger logger; /** * Creates a new <tt>ConnectivityCheckServer</tt> setting * <tt>parentAgent</tt> as the agent that will be used for retrieving * information such as user fragments for example. * * @param parentAgent the <tt>Agent</tt> that is creating this instance. */ public ConnectivityCheckServer(Agent parentAgent) { this.parentAgent = parentAgent; logger = parentAgent.getLogger().createChildLogger(this.getClass().getName()); stunStack = this.parentAgent.getStunStack(); stunStack.getCredentialsManager().registerAuthority(this); start(); } /** * Returns a boolean value indicating whether we have received a STUN * request or not. * * Note that this should NOT be taken as an indication that the negotiation * has succeeded, it merely indicates that we have received ANY STUN * request, even invalid ones (e.g. with the wrong username or ufrag). It is * completely unrelated/independent from the ICE spec and it's only meant to * be used for debugging purposes. * * @return a boolean value indicating whether we have received a STUN * request or not. */ boolean isAlive() { return alive; } /** * Handles the {@link Request} delivered in <tt>evt</tt> by possibly * queuing a triggered check and sending a success or an error response * depending on how processing goes. * * @param evt the {@link StunMessageEvent} containing the {@link Request} * that we need to process. * * @throws IllegalArgumentException if the request is malformed and the * stack needs to reply with a 400 Bad Request response. */ public void processRequest(StunMessageEvent evt) throws IllegalArgumentException { logger.trace(() -> "Received request " + evt); alive = true; Request request = (Request)evt.getMessage(); //ignore incoming requests that are not meant for the local user. //normally the stack will get rid of faulty user names but we could //still see messages not meant for this server if both peers or running //on this same instance of the stack. UsernameAttribute uname = (UsernameAttribute)request .getAttribute(Attribute.USERNAME); if ( uname == null || !checkLocalUserName(new String(uname.getUsername()))) { return; } //detect role conflicts if ( ( parentAgent.isControlling() && request.containsAttribute(Attribute.ICE_CONTROLLING)) || ( ! parentAgent.isControlling() && request.containsAttribute(Attribute.ICE_CONTROLLED))) { if (!repairRoleConflict(evt)) return; } long priority = 0; boolean useCandidate = request.containsAttribute(Attribute.USE_CANDIDATE); String username = new String(uname.getUsername()); //caller gave us the entire username. String remoteUfrag = null; String localUFrag = null; priority = extractPriority(request); int colon = username.indexOf(":"); remoteUfrag = username.substring(0, colon); //tell our address handler we saw a new remote address; parentAgent.incomingCheckReceived(evt.getRemoteAddress(), evt.getLocalAddress(), priority, remoteUfrag, localUFrag, useCandidate); Response response = MessageFactory.createBindingResponse( request, evt.getRemoteAddress()); /* add USERNAME and MESSAGE-INTEGRITY attribute in the response */ /* The responses utilize the same usernames and passwords as the * requests */ Attribute usernameAttribute = AttributeFactory.createUsernameAttribute(uname.getUsername()); response.putAttribute(usernameAttribute); Attribute messageIntegrityAttribute = AttributeFactory.createMessageIntegrityAttribute( new String(uname.getUsername())); response.putAttribute(messageIntegrityAttribute); try { stunStack.sendResponse(evt.getTransactionID().getBytes(), response, evt.getLocalAddress(), evt.getRemoteAddress()); } catch (Exception e) { logger.info("Failed to send " + response + " through " + evt.getLocalAddress() + "\n" + e.toString()); //try to trigger a 500 response although if this one failed, //then chances are the 500 will fail too. throw new RuntimeException("Failed to send a response", e); } } /** * Returns the value of the {@link PriorityAttribute} in <tt>request</tt> if * there is one or throws an <tt>IllegalArgumentException</tt> with the * corresponding message. * * @param request the {@link Request} whose priority we'd like to obtain. * * @return the value of the {@link PriorityAttribute} in <tt>request</tt> if * there is one * * @throws IllegalArgumentException if the request does not contain a * PRIORITY attribute and the stack needs to respond with a 400 Bad Request * {@link Response}. */ private long extractPriority(Request request) throws IllegalArgumentException { //make sure we have a priority attribute and ignore otherwise. PriorityAttribute priorityAttr = (PriorityAttribute)request.getAttribute(Attribute.PRIORITY); //apply tie-breaking //extract priority if (priorityAttr == null) { logger.debug(() -> "Received a connectivity check with" + "no PRIORITY attribute. Discarding."); throw new IllegalArgumentException("Missing PRIORITY attribute!"); } return priorityAttr.getPriority(); } /** * Resolves a role conflicts by either sending a <tt>487 Role Conflict</tt> * response or by changing this server's parent agent role. The method * returns <tt>true</tt> if the role conflict is silently resolved and * processing can continue. It returns <tt>false</tt> if we had to reply * with a 487 and processing needs to stop until a repaired request is * received. * * @param evt the {@link StunMessageEvent} containing the * <tt>ICE-CONTROLLING</tt> or <tt>ICE-CONTROLLED</tt> attribute that * allowed us to detect the role conflict. * * @return <tt>true</tt> if the role conflict is silently resolved and * processing can continue and <tt>false</tt> otherwise. */ private boolean repairRoleConflict(StunMessageEvent evt) { final Message req = evt.getMessage(); final boolean selfIceControlling = parentAgent.isControlling(); // If the agent is in the controlling role, and the // ICE-CONTROLLING attribute is present in the request: final boolean bothControllingConflict = selfIceControlling && req.containsAttribute(Attribute.ICE_CONTROLLING); // If the agent is in the controlled role, and the ICE-CONTROLLED // attribute is present in the request: final boolean bothControlledConflict = !selfIceControlling && req.containsAttribute(Attribute.ICE_CONTROLLED); if (!(bothControllingConflict || bothControlledConflict)) { // we don't have a role conflict return true; } final long selfTieBreaker = parentAgent.getTieBreaker(); final IceControlAttribute theirIceControl = bothControllingConflict ? (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLING) : (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLED); final long theirTieBreaker = theirIceControl.getTieBreaker(); // If the agent's tie-breaker is larger than or equal to the // contents of the ICE control attribute, the agent generates // a Binding error response and includes an ERROR-CODE attribute // with a value of 487 (Role Conflict) but retains its role. if (Long.compareUnsigned(selfTieBreaker, theirTieBreaker) >= 0) { final UsernameAttribute requestUserName = (UsernameAttribute)req .getAttribute(Attribute.USERNAME); final Response response = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.ROLE_CONFLICT); final Attribute messageIntegrityAttribute = AttributeFactory.createMessageIntegrityAttribute( new String(requestUserName.getUsername())); response.putAttribute(messageIntegrityAttribute); try { stunStack.sendResponse( evt.getTransactionID().getBytes(), response, evt.getLocalAddress(), evt.getRemoteAddress()); return false; } catch(Exception exc) { //rethrow so that we would send a 500 response instead. throw new RuntimeException("Failed to send a 487", exc); } } //If the agent's tie-breaker is less than the contents of the //ICE control attribute, the agent toggles its ICE control role. else { final String selfNextControlState = selfIceControlling ? "controlled" : "controlling"; logger.trace(() -> "Switching to " + selfNextControlState + " because " + " theirTieBreaker= " + theirTieBreaker + " and " + "selfTieBreaker= " + selfTieBreaker); parentAgent.setControlling(!selfIceControlling); return true; } } /** * Verifies whether <tt>username</tt> is currently known to this server * and returns <tt>true</tt> if so. Returns <tt>false</tt> otherwise. * * @param username the user name whose validity we'd like to check. * * @return <tt>true</tt> if <tt>username</tt> is known to this * <tt>ConnectivityCheckServer</tt> and <tt>false</tt> otherwise. */ public boolean checkLocalUserName(String username) { String ufrag = null; int colon = username.indexOf(":"); if (colon < 0) { //caller gave us a ufrag ufrag = username; } else { //caller gave us the entire username. ufrag = username.substring(0, colon); } return ufrag.equals(parentAgent.getLocalUfrag()); } /** * Implements the {@link CredentialsAuthority#getLocalKey(String)} method in * a way that would return this handler's parent agent password if * <tt>username</tt> is either the local ufrag or the username that the * agent's remote peer was expected to use. * * @param username the local ufrag that we should return a password for. * * @return this handler's parent agent local password if <tt>username</tt> * equals the local ufrag and <tt>null</tt> otherwise. */ public byte[] getLocalKey(String username) { return checkLocalUserName(username) ? parentAgent.getLocalPassword().getBytes() : null; } /** * Implements the {@link CredentialsAuthority#getRemoteKey(String, String)} * method in a way that would return this handler's parent agent remote * password if <tt>username</tt> is either the remote ufrag or the username * that we are expected to use when querying the remote peer. * * @param username the remote ufrag that we should return a password for. * @param media the media name that we want to get remote key. * * @return this handler's parent agent remote password if <tt>username</tt> * equals the remote ufrag and <tt>null</tt> otherwise. */ public byte[] getRemoteKey(String username, String media) { IceMediaStream stream = parentAgent.getStream(media); if (stream == null) { return null; } //support both the case where username is the local fragment or the //entire user name. int colon = username.indexOf(":"); if (colon < 0) { //caller gave us a ufrag if (username.equals(stream.getRemoteUfrag())) return stream.getRemotePassword().getBytes(); } else { //caller gave us the entire username. if (username.equals(parentAgent.generateLocalUserName(media))) { if (stream.getRemotePassword() != null) return stream.getRemotePassword().getBytes(); } } return null; } /** * Starts this <tt>ConnectivityCheckServer</tt>. If it is not currently * running, does nothing. */ public void start() { if (!started) { stunStack.addRequestListener(this); started = true; } } /** * Stops this <tt>ConnectivityCheckServer</tt>. A stopped * <tt>ConnectivityCheckServer</tt> can be restarted by calling * {@link #start()} on it. */ public void stop() { stunStack.removeRequestListener(this); started = false; } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.actions; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.find.FindSettings; import com.intellij.find.impl.FindDialog; import com.intellij.find.impl.FindInProjectUtil; import com.intellij.icons.AllIcons; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.scopeChooser.ScopeChooserCombo; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.psi.search.SearchScope; import com.intellij.ui.IdeBorderFactory; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.regex.PatternSyntaxException; /** * @author max */ public class LayoutProjectCodeDialog extends DialogWrapper implements ReformatFilesOptions { private static @NonNls final String HELP_ID = "Reformat Code on Directory Dialog"; private final Project myProject; private final String myText; private final boolean myEnableOnlyVCSChangedTextCb; private final LastRunReformatCodeOptionsProvider myLastRunOptions; private JLabel myTitle; protected JCheckBox myIncludeSubdirsCb; private JCheckBox myUseScopeFilteringCb; private ScopeChooserCombo myScopeCombo; private JCheckBox myEnableFileNameFilterCb; private ComboBox myFileFilter; private JCheckBox myCbOptimizeImports; private JCheckBox myCbRearrangeEntries; private JCheckBox myCbOnlyVcsChangedRegions; private JPanel myWholePanel; private JPanel myOptionsPanel; private JPanel myFiltersPanel; private JLabel myMaskWarningLabel; public LayoutProjectCodeDialog(@NotNull Project project, @NotNull String title, @NotNull String text, boolean enableOnlyVCSChangedTextCb) { super(project, false); myText = text; myProject = project; myEnableOnlyVCSChangedTextCb = enableOnlyVCSChangedTextCb; myLastRunOptions = new LastRunReformatCodeOptionsProvider(PropertiesComponent.getInstance()); setOKButtonText(CodeInsightBundle.message("reformat.code.accept.button.text")); setTitle(title); init(); } @Override protected JComponent createCenterPanel() { myTitle.setText(myText); myOptionsPanel.setBorder(IdeBorderFactory.createTitledBorder(CodeInsightBundle.message("reformat.directory.dialog.options"))); myFiltersPanel.setBorder(IdeBorderFactory.createTitledBorder(CodeInsightBundle.message("reformat.directory.dialog.filters"))); myMaskWarningLabel.setIcon(AllIcons.General.Warning); myMaskWarningLabel.setVisible(false); myIncludeSubdirsCb.setVisible(shouldShowIncludeSubdirsCb()); initFileTypeFilter(); initScopeFilter(); restoreCbsStates(); return myWholePanel; } private void restoreCbsStates() { myCbOptimizeImports.setSelected(myLastRunOptions.getLastOptimizeImports()); myCbRearrangeEntries.setSelected(myLastRunOptions.getLastRearrangeCode()); myCbOnlyVcsChangedRegions.setEnabled(myEnableOnlyVCSChangedTextCb); myCbOnlyVcsChangedRegions.setSelected( myEnableOnlyVCSChangedTextCb && myLastRunOptions.getLastTextRangeType() == TextRangeType.VCS_CHANGED_TEXT ); } private void initScopeFilter() { myUseScopeFilteringCb.setSelected(false); myScopeCombo.setEnabled(false); myUseScopeFilteringCb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myScopeCombo.setEnabled(myUseScopeFilteringCb.isSelected()); } }); } private void initFileTypeFilter() { FindDialog.initFileFilter(myFileFilter, myEnableFileNameFilterCb); myEnableFileNameFilterCb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateMaskWarning(); } }); myFileFilter.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updateMaskWarning(); } }); } private void updateMaskWarning() { if (myEnableFileNameFilterCb.isSelected()) { String mask = (String)myFileFilter.getEditor().getItem(); if (mask == null || !isMaskValid(mask)) { showWarningAndDisableOK(); return; } } if (myMaskWarningLabel.isVisible()) { clearWarningAndEnableOK(); } } private void showWarningAndDisableOK() { myMaskWarningLabel.setVisible(true); setOKActionEnabled(false); } private void clearWarningAndEnableOK() { myMaskWarningLabel.setVisible(false); setOKActionEnabled(true); } private static boolean isMaskValid(@NotNull String mask) { try { FindInProjectUtil.createFileMaskCondition(mask); return true; } catch (PatternSyntaxException e) { return false; } } @Override public boolean isRearrangeCode() { return myCbRearrangeEntries.isSelected(); } @Override protected String getHelpId() { return HELP_ID; } @Override protected void doOKAction() { super.doOKAction(); myLastRunOptions.saveOptimizeImportsState(isOptimizeImports()); myLastRunOptions.saveRearrangeCodeState(isRearrangeCode()); if (myEnableOnlyVCSChangedTextCb) { myLastRunOptions.saveProcessVcsChangedTextState(getTextRangeType() == TextRangeType.VCS_CHANGED_TEXT); } } @Override public boolean isOptimizeImports() { return myCbOptimizeImports.isSelected(); } @Override @Nullable public String getFileTypeMask() { if (myEnableFileNameFilterCb.isSelected()) { return (String)myFileFilter.getSelectedItem(); } return null; } protected void createUIComponents() { myScopeCombo = new ScopeChooserCombo(myProject, false, false, FindSettings.getInstance().getDefaultScopeName()); Disposer.register(myDisposable, myScopeCombo); } @Nullable @Override public SearchScope getSearchScope() { if (myUseScopeFilteringCb.isSelected()) { return myScopeCombo.getSelectedScope(); } return null; } protected boolean shouldShowIncludeSubdirsCb() { return false; } @Override public TextRangeType getTextRangeType() { return myCbOnlyVcsChangedRegions.isEnabled() && myCbOnlyVcsChangedRegions.isSelected() ? TextRangeType.VCS_CHANGED_TEXT : TextRangeType.WHOLE_FILE; } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.ntp; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconImageCallback; import org.chromium.chrome.browser.favicon.FaviconHelper.IconAvailabilityCallback; import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback; import org.chromium.chrome.browser.ntp.LogoBridge.Logo; import org.chromium.chrome.browser.ntp.LogoBridge.LogoObserver; import org.chromium.chrome.browser.ntp.MostVisitedItem.MostVisitedItemManager; import org.chromium.chrome.browser.ntp.NewTabPage.OnSearchBoxScrollListener; import org.chromium.chrome.browser.ntp.cards.NewTabPageAdapter; import org.chromium.chrome.browser.ntp.cards.NewTabPageListItem; import org.chromium.chrome.browser.ntp.cards.NewTabPageRecyclerView; import org.chromium.chrome.browser.ntp.snippets.SnippetsBridge; import org.chromium.chrome.browser.profiles.MostVisitedSites.MostVisitedURLsObserver; import org.chromium.chrome.browser.util.MathUtils; import org.chromium.chrome.browser.util.ViewUtils; import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.ui.base.DeviceFormFactor; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import jp.tomorrowkey.android.gifplayer.BaseGifImage; /** * The native new tab page, represented by some basic data such as title and url, and an Android * View that displays the page. */ public class NewTabPageView extends FrameLayout implements MostVisitedURLsObserver, OnLayoutChangeListener { private static final int SHADOW_COLOR = 0x11000000; private static final long SNAP_SCROLL_DELAY_MS = 30; private static final String TAG = "Ntp"; /** * Indicates which UI mode we are using. Should be checked when manipulating some members, as * they may be unused or {@code null} depending on the mode. */ private boolean mUseCardsUi; // Note: Only one of these will be valid at a time, depending on if we are using the old NTP // (NewTabPageScrollView) or the new NTP with cards (NewTabPageRecyclerView). private NewTabPageScrollView mScrollView; private NewTabPageRecyclerView mRecyclerView; private NewTabPageLayout mNewTabPageLayout; private LogoView mSearchProviderLogoView; private View mSearchBoxView; private ImageView mVoiceSearchButton; private MostVisitedLayout mMostVisitedLayout; private View mMostVisitedPlaceholder; private View mNoSearchLogoSpacer; /** Adapter for {@link #mRecyclerView}. Will be {@code null} when using the old UI */ private NewTabPageAdapter mNewTabPageAdapter; private OnSearchBoxScrollListener mSearchBoxScrollListener; private NewTabPageManager mManager; private UiConfig mUiConfig; private MostVisitedDesign mMostVisitedDesign; private MostVisitedItem[] mMostVisitedItems; private boolean mFirstShow = true; private boolean mSearchProviderHasLogo = true; private boolean mHasReceivedMostVisitedSites; private boolean mPendingSnapScroll; /** * The number of asynchronous tasks that need to complete before the page is done loading. * This starts at one to track when the view is finished attaching to the window. */ private int mPendingLoadTasks = 1; private boolean mLoadHasCompleted; private float mUrlFocusChangePercent; private boolean mDisableUrlFocusChangeAnimations; /** Flag used to request some layout changes after the next layout pass is completed. */ private boolean mTileCountChanged; private boolean mSnapshotMostVisitedChanged; private int mSnapshotWidth; private int mSnapshotHeight; private int mSnapshotScrollY; /** * Manages the view interaction with the rest of the system. */ public interface NewTabPageManager extends MostVisitedItemManager { /** @return Whether the location bar is shown in the NTP. */ boolean isLocationBarShownInNTP(); /** @return Whether voice search is enabled and the microphone should be shown. */ boolean isVoiceSearchEnabled(); /** @return Whether the toolbar at the bottom of the NTP is enabled and should be shown. */ boolean isToolbarEnabled(); /** @return Whether the omnibox 'Search or type URL' text should be shown. */ boolean isFakeOmniboxTextEnabledTablet(); /** @return Whether context menus should allow the option to open a link in a new window. */ boolean isOpenInNewWindowEnabled(); /** @return Whether context menus should allow the option to open a link in incognito. */ boolean isOpenInIncognitoEnabled(); /** Opens the bookmarks page in the current tab. */ void navigateToBookmarks(); /** Opens the recent tabs page in the current tab. */ void navigateToRecentTabs(); /** * Opens a URL in the current tab and records related metrics. * @param url the URL to open */ void openSnippet(String url); /** Opens a URL in the current tab. */ void openUrl(String url); /** Opens a URL in a new window. */ void openUrlInNewWindow(String url); /** Opens a URL in a new tab. */ void openUrlInNewTab(String url, boolean incognito); /** * Animates the search box up into the omnibox and bring up the keyboard. * @param beginVoiceSearch Whether to begin a voice search. * @param pastedText Text to paste in the omnibox after it's been focused. May be null. */ void focusSearchBox(boolean beginVoiceSearch, String pastedText); /** * Gets the list of most visited sites. * @param observer The observer to be notified with the list of sites. * @param numResults The maximum number of sites to retrieve. */ void setMostVisitedURLsObserver(MostVisitedURLsObserver observer, int numResults); /** * Gets the favicon image for a given URL. * @param url The URL of the site whose favicon is being requested. * @param size The desired size of the favicon in pixels. * @param faviconCallback The callback to be notified when the favicon is available. */ void getLocalFaviconImageForURL( String url, int size, FaviconImageCallback faviconCallback); /** * Gets the large icon (e.g. favicon or touch icon) for a given URL. * @param url The URL of the site whose icon is being requested. * @param size The desired size of the icon in pixels. * @param callback The callback to be notified when the icon is available. */ void getLargeIconForUrl(String url, int size, LargeIconCallback callback); /** * Checks if an icon with the given URL is available. If not, * downloads it and stores it as a favicon/large icon for the given {@code pageUrl}. * @param pageUrl The URL of the site whose icon is being requested. * @param iconUrl The URL of the favicon/large icon. * @param isLargeIcon Whether the {@code iconUrl} represents a large icon or favicon. * @param callback The callback to be notified when the favicon has been checked. */ void ensureIconIsAvailable(String pageUrl, String iconUrl, boolean isLargeIcon, boolean isTemporary, IconAvailabilityCallback callback); /** * Checks if the pages with the given URLs are available offline. * @param pageUrls The URLs of the sites whose offline availability is requested. * @param callback Fired when the results are available. */ void getUrlsAvailableOffline(Set<String> pageUrls, Callback<Set<String>> callback); /** * Called when the user clicks on the logo. * @param isAnimatedLogoShowing Whether the animated GIF logo is playing. */ void onLogoClicked(boolean isAnimatedLogoShowing); /** * Gets the default search provider's logo and calls logoObserver with the result. * @param logoObserver The callback to notify when the logo is available. */ void getSearchProviderLogo(LogoObserver logoObserver); /** * Called when the NTP has completely finished loading (all views will be inflated * and any dependent resources will have been loaded). * @param mostVisitedItems The MostVisitedItem shown on the NTP. Used to record metrics. */ void onLoadingComplete(MostVisitedItem[] mostVisitedItems); } /** * Default constructor required for XML inflation. */ public NewTabPageView(Context context, AttributeSet attrs) { super(context, attrs); } /** * Initializes the NTP. This must be called immediately after inflation, before this object is * used in any other way. * * @param manager NewTabPageManager used to perform various actions when the user interacts * with the page. * @param searchProviderHasLogo Whether the search provider has a logo. * @param snippetsBridge The optional bridge, that can be used to interact with the snippets. */ public void initialize(NewTabPageManager manager, boolean searchProviderHasLogo, SnippetsBridge snippetsBridge) { mManager = manager; mUiConfig = new UiConfig(this); ViewStub stub = (ViewStub) findViewById(R.id.new_tab_page_layout_stub); mUseCardsUi = snippetsBridge != null; if (mUseCardsUi) { stub.setLayoutResource(R.layout.new_tab_page_recycler_view); mRecyclerView = (NewTabPageRecyclerView) stub.inflate(); // Don't attach now, the recyclerView itself will determine when to do it. mNewTabPageLayout = (NewTabPageLayout) LayoutInflater.from(getContext()) .inflate(R.layout.new_tab_page_layout, mRecyclerView, false); mNewTabPageLayout.setUseCardsUiEnabled(mUseCardsUi); mRecyclerView.setAboveTheFoldView(mNewTabPageLayout); // Tailor the LayoutParams for the snippets UI, as the configuration in the XML is // made for the ScrollView UI. ViewGroup.LayoutParams params = mNewTabPageLayout.getLayoutParams(); params.height = ViewGroup.LayoutParams.WRAP_CONTENT; } else { stub.setLayoutResource(R.layout.new_tab_page_scroll_view); mScrollView = (NewTabPageScrollView) stub.inflate(); mScrollView.setBackgroundColor( NtpColorUtils.getBackgroundColorResource(getResources(), false)); mScrollView.enableBottomShadow(SHADOW_COLOR); mNewTabPageLayout = (NewTabPageLayout) findViewById(R.id.ntp_content); } mMostVisitedDesign = new MostVisitedDesign(getContext()); mMostVisitedLayout = (MostVisitedLayout) mNewTabPageLayout.findViewById(R.id.most_visited_layout); mMostVisitedDesign.initMostVisitedLayout(searchProviderHasLogo); mSearchProviderLogoView = (LogoView) mNewTabPageLayout.findViewById(R.id.search_provider_logo); mSearchBoxView = mNewTabPageLayout.findViewById(R.id.search_box); mNoSearchLogoSpacer = mNewTabPageLayout.findViewById(R.id.no_search_logo_spacer); initializeSearchBoxTextView(); initializeVoiceSearchButton(); initializeToolbar(); mNewTabPageLayout.addOnLayoutChangeListener(this); setSearchProviderHasLogo(searchProviderHasLogo); mPendingLoadTasks++; mManager.setMostVisitedURLsObserver( this, mMostVisitedDesign.getNumberOfTiles(searchProviderHasLogo)); // Set up snippets if (mUseCardsUi) { mNewTabPageAdapter = new NewTabPageAdapter(mManager, mNewTabPageLayout, snippetsBridge, mUiConfig); mRecyclerView.setAdapter(mNewTabPageAdapter); // Set up swipe-to-dismiss ItemTouchHelper helper = new ItemTouchHelper(mNewTabPageAdapter.getItemTouchCallbacks()); helper.attachToRecyclerView(mRecyclerView); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { private boolean mScrolledOnce = false; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState != RecyclerView.SCROLL_STATE_DRAGGING) return; RecordUserAction.record("MobileNTP.Snippets.Scrolled"); if (mScrolledOnce) return; mScrolledOnce = true; NewTabPageUma.recordSnippetAction(NewTabPageUma.SNIPPETS_ACTION_SCROLLED); } }); initializeSearchBoxRecyclerViewScrollHandling(); } else { initializeSearchBoxScrollHandling(); } } /** * Sets up the hint text and event handlers for the search box text view. */ private void initializeSearchBoxTextView() { final TextView searchBoxTextView = (TextView) mSearchBoxView .findViewById(R.id.search_box_text); String hintText = getResources().getString(R.string.search_or_type_url); if (!DeviceFormFactor.isTablet(getContext()) || mManager.isFakeOmniboxTextEnabledTablet()) { searchBoxTextView.setHint(hintText); } else { searchBoxTextView.setContentDescription(hintText); } searchBoxTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.focusSearchBox(false, null); } }); searchBoxTextView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) return; mManager.focusSearchBox(false, s.toString()); searchBoxTextView.setText(""); } }); } private void initializeVoiceSearchButton() { mVoiceSearchButton = (ImageView) mNewTabPageLayout.findViewById(R.id.voice_search_button); mVoiceSearchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.focusSearchBox(true, null); } }); } /** * Sets up event listeners for the bottom toolbar if it is enabled. Removes the bottom toolbar * if it is disabled. */ private void initializeToolbar() { NewTabPageToolbar toolbar = (NewTabPageToolbar) findViewById(R.id.ntp_toolbar); if (mManager.isToolbarEnabled()) { toolbar.getRecentTabsButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.navigateToRecentTabs(); } }); toolbar.getBookmarksButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.navigateToBookmarks(); } }); } else { ((ViewGroup) toolbar.getParent()).removeView(toolbar); MarginLayoutParams params = (MarginLayoutParams) getWrapperView().getLayoutParams(); params.bottomMargin = 0; } } private void updateSearchBoxOnScroll() { if (mDisableUrlFocusChangeAnimations) return; if (mSearchBoxScrollListener != null) { mSearchBoxScrollListener.onNtpScrollChanged(getToolbarTransitionPercentage()); } } /** * Calculates the percentage (between 0 and 1) of the transition from the search box to the * omnibox at the top of the New Tab Page, which is determined by the amount of scrolling and * the position of the search box. * * @return the transition percentage */ private float getToolbarTransitionPercentage() { // During startup the view may not be fully initialized, so we only calculate the current // percentage if some basic view properties (height of the containing view, position of the // search box) are sane. if (getWrapperView().getHeight() == 0) return 0f; int searchBoxTop = mSearchBoxView.getTop(); if (searchBoxTop == 0) return 0f; // For all other calculations, add the search box padding, because it defines where the // visible "border" of the search box is. searchBoxTop += mSearchBoxView.getPaddingTop(); if (!mUseCardsUi) { return MathUtils.clamp(getVerticalScroll() / (float) searchBoxTop, 0f, 1f); } if (!mRecyclerView.isFirstItemVisible()) { // getVerticalScroll is valid only for the RecyclerView if the first item is // visible. If the first item is not visible, we know the toolbar transition // should be 100%. return 1f; } final int scrollY = getVerticalScroll(); final float transitionLength = getResources().getDimension(R.dimen.ntp_search_box_transition_length); // |scrollY - searchBoxTop| gives the distance the search bar is from the top of the screen. return MathUtils.clamp( (scrollY - searchBoxTop + transitionLength) / transitionLength, 0f, 1f); } private ViewGroup getWrapperView() { return mUseCardsUi ? mRecyclerView : mScrollView; } /** * Get the number of listed items (visible or not) for the given type. * @param newTabPageListItemViewType the item type to count. */ public int getViewCountMatchingViewType( @NewTabPageListItem.ViewType int newTabPageListItemViewType) { int viewCount = 0; int adapterSize = mNewTabPageAdapter.getItemCount(); for (int i = 0; i < adapterSize; i++) { if (mNewTabPageAdapter.getItemViewType(i) == newTabPageListItemViewType) { viewCount++; } } return viewCount; } /** * Sets up scrolling when snippets are enabled. It adds scroll listeners and touch listeners to * the RecyclerView. */ private void initializeSearchBoxRecyclerViewScrollHandling() { final Runnable mSnapScrollRunnable = new Runnable() { @Override public void run() { assert mPendingSnapScroll; mPendingSnapScroll = false; mRecyclerView.snapScroll(mSearchBoxView, getVerticalScroll(), getHeight()); } }; mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (mPendingSnapScroll) { mRecyclerView.removeCallbacks(mSnapScrollRunnable); mRecyclerView.postDelayed(mSnapScrollRunnable, SNAP_SCROLL_DELAY_MS); } updateSearchBoxOnScroll(); mRecyclerView.updatePeekingCard(); mRecyclerView.updateSnippetsHeaderDisplay(); } }); mRecyclerView.setOnTouchListener(new OnTouchListener() { @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { mRecyclerView.removeCallbacks(mSnapScrollRunnable); if (event.getActionMasked() == MotionEvent.ACTION_CANCEL || event.getActionMasked() == MotionEvent.ACTION_UP) { mPendingSnapScroll = true; mRecyclerView.postDelayed(mSnapScrollRunnable, SNAP_SCROLL_DELAY_MS); } else { mPendingSnapScroll = false; } return false; } }); } /** * Sets up scrolling when snippets are disabled. It adds scroll and touch listeners to the * scroll view. */ private void initializeSearchBoxScrollHandling() { final Runnable mSnapScrollRunnable = new Runnable() { @Override public void run() { if (!mPendingSnapScroll) return; int scrollY = mScrollView.getScrollY(); int dividerTop = mMostVisitedLayout.getTop() - mNewTabPageLayout.getPaddingTop(); if (scrollY > 0 && scrollY < dividerTop) { mScrollView.smoothScrollTo(0, scrollY < (dividerTop / 2) ? 0 : dividerTop); } mPendingSnapScroll = false; } }; mScrollView.setOnScrollListener(new NewTabPageScrollView.OnScrollListener() { @Override public void onScrollChanged(int l, int t, int oldl, int oldt) { if (mPendingSnapScroll) { mScrollView.removeCallbacks(mSnapScrollRunnable); mScrollView.postDelayed(mSnapScrollRunnable, SNAP_SCROLL_DELAY_MS); } updateSearchBoxOnScroll(); } }); mScrollView.setOnTouchListener(new OnTouchListener() { @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { mScrollView.removeCallbacks(mSnapScrollRunnable); if (event.getActionMasked() == MotionEvent.ACTION_CANCEL || event.getActionMasked() == MotionEvent.ACTION_UP) { mPendingSnapScroll = true; mScrollView.postDelayed(mSnapScrollRunnable, SNAP_SCROLL_DELAY_MS); } else { mPendingSnapScroll = false; } return false; } }); } /** * Decrements the count of pending load tasks and notifies the manager when the page load * is complete. */ private void loadTaskCompleted() { assert mPendingLoadTasks > 0; mPendingLoadTasks--; if (mPendingLoadTasks == 0) { if (mLoadHasCompleted) { assert false; } else { mLoadHasCompleted = true; mManager.onLoadingComplete(mMostVisitedItems); // Load the logo after everything else is finished, since it's lower priority. loadSearchProviderLogo(); } } } /** * Loads the search provider logo (e.g. Google doodle), if any. */ private void loadSearchProviderLogo() { mManager.getSearchProviderLogo(new LogoObserver() { @Override public void onLogoAvailable(Logo logo, boolean fromCache) { if (logo == null && fromCache) return; mSearchProviderLogoView.setMananger(mManager); mSearchProviderLogoView.updateLogo(logo); mSnapshotMostVisitedChanged = true; } }); } /** * Changes the layout depending on whether the selected search provider (e.g. Google, Bing) * has a logo. * @param hasLogo Whether the search provider has a logo. */ public void setSearchProviderHasLogo(boolean hasLogo) { if (hasLogo == mSearchProviderHasLogo) return; mSearchProviderHasLogo = hasLogo; mMostVisitedDesign.setSearchProviderHasLogo(mMostVisitedLayout, hasLogo); // Hide or show all the views above the Most Visited items. int visibility = hasLogo ? View.VISIBLE : View.GONE; int childCount = mNewTabPageLayout.getChildCount(); for (int i = 0; i < childCount; i++) { View child = mNewTabPageLayout.getChildAt(i); if (child == mMostVisitedLayout) break; // Don't change the visibility of a ViewStub as that will automagically inflate it. if (child instanceof ViewStub) continue; child.setVisibility(visibility); } updateMostVisitedPlaceholderVisibility(); onUrlFocusAnimationChanged(); mSnapshotMostVisitedChanged = true; } /** * Updates whether the NewTabPage should animate on URL focus changes. * @param disable Whether to disable the animations. */ void setUrlFocusAnimationsDisabled(boolean disable) { if (disable == mDisableUrlFocusChangeAnimations) return; mDisableUrlFocusChangeAnimations = disable; if (!disable) onUrlFocusAnimationChanged(); } /** * Shows a progressbar indicating the animated logo is being downloaded. */ void showLogoLoadingView() { mSearchProviderLogoView.showLoadingView(); } /** * Starts playing the given animated GIF logo. */ void playAnimatedLogo(BaseGifImage gifImage) { mSearchProviderLogoView.playAnimatedLogo(gifImage); } /** * @return Whether URL focus animations are currently disabled. */ boolean urlFocusAnimationsDisabled() { return mDisableUrlFocusChangeAnimations; } /** * Specifies the percentage the URL is focused during an animation. 1.0 specifies that the URL * bar has focus and has completed the focus animation. 0 is when the URL bar is does not have * any focus. * * @param percent The percentage of the URL bar focus animation. */ void setUrlFocusChangeAnimationPercent(float percent) { mUrlFocusChangePercent = percent; onUrlFocusAnimationChanged(); } /** * @return The percentage that the URL bar is focused during an animation. */ @VisibleForTesting float getUrlFocusChangeAnimationPercent() { return mUrlFocusChangePercent; } private void onUrlFocusAnimationChanged() { if (mDisableUrlFocusChangeAnimations) return; float percent = mSearchProviderHasLogo ? mUrlFocusChangePercent : 0; int basePosition = getVerticalScroll() + mNewTabPageLayout.getPaddingTop(); int target; if (mUseCardsUi) { // Cards UI: translate so that the search box is at the top, but only upwards. target = Math.max(basePosition, mSearchBoxView.getBottom() - mSearchBoxView.getPaddingBottom()); } else { // Otherwise: translate so that Most Visited is right below the omnibox. target = mMostVisitedLayout.getTop(); } mNewTabPageLayout.setTranslationY(percent * (basePosition - target)); } /** * Updates the opacity of the search box when scrolling. * * @param alpha opacity (alpha) value to use. */ public void setSearchBoxAlpha(float alpha) { mSearchBoxView.setAlpha(alpha); } /** * Updates the opacity of the search provider logo when scrolling. * * @param alpha opacity (alpha) value to use. */ public void setSearchProviderLogoAlpha(float alpha) { mSearchProviderLogoView.setAlpha(alpha); } /** * Get the bounds of the search box in relation to the top level NewTabPage view. * * @param bounds The current drawing location of the search box. * @param translation The translation applied to the search box by the parent view hierarchy up * to the NewTabPage view. */ void getSearchBoxBounds(Rect bounds, Point translation) { int searchBoxX = (int) mSearchBoxView.getX(); int searchBoxY = (int) mSearchBoxView.getY(); bounds.set(searchBoxX + mSearchBoxView.getPaddingLeft(), searchBoxY + mSearchBoxView.getPaddingTop(), searchBoxX + mSearchBoxView.getWidth() - mSearchBoxView.getPaddingRight(), searchBoxY + mSearchBoxView.getHeight() - mSearchBoxView.getPaddingBottom()); translation.set(0, 0); View view = mSearchBoxView; while (true) { view = (View) view.getParent(); if (view == null) { // The |mSearchBoxView| is not a child of this view. This can happen if the // RecyclerView detaches the NewTabPageLayout after it has been scrolled out of // view. Set the translation to the minimum Y value as an approximation. translation.y = Integer.MIN_VALUE; break; } translation.offset(-view.getScrollX(), -view.getScrollY()); if (view == this) break; translation.offset((int) view.getX(), (int) view.getY()); } bounds.offset(translation.x, translation.y); } /** * Sets the listener for search box scroll changes. * @param listener The listener to be notified on changes. */ void setSearchBoxScrollListener(OnSearchBoxScrollListener listener) { mSearchBoxScrollListener = listener; if (mSearchBoxScrollListener != null) updateSearchBoxOnScroll(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); assert mManager != null; if (mFirstShow) { loadTaskCompleted(); mFirstShow = false; } else { // Trigger a scroll update when reattaching the window to signal the toolbar that // it needs to reset the NTP state. if (mManager.isLocationBarShownInNTP()) updateSearchBoxOnScroll(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); setUrlFocusChangeAnimationPercent(0f); } /** * Update the visibility of the voice search button based on whether the feature is currently * enabled. */ void updateVoiceSearchButtonVisibility() { mVoiceSearchButton.setVisibility(mManager.isVoiceSearchEnabled() ? VISIBLE : GONE); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (visibility == VISIBLE) { updateVoiceSearchButtonVisibility(); } } /** * @see org.chromium.chrome.browser.compositor.layouts.content. * InvalidationAwareThumbnailProvider#shouldCaptureThumbnail() */ boolean shouldCaptureThumbnail() { if (getWidth() == 0 || getHeight() == 0) return false; return mSnapshotMostVisitedChanged || getWidth() != mSnapshotWidth || getHeight() != mSnapshotHeight || getVerticalScroll() != mSnapshotScrollY; } /** * @see org.chromium.chrome.browser.compositor.layouts.content. * InvalidationAwareThumbnailProvider#captureThumbnail(Canvas) */ void captureThumbnail(Canvas canvas) { mSearchProviderLogoView.endFadeAnimation(); ViewUtils.captureBitmap(this, canvas); mSnapshotWidth = getWidth(); mSnapshotHeight = getHeight(); mSnapshotScrollY = getVerticalScroll(); mSnapshotMostVisitedChanged = false; } // OnLayoutChangeListener overrides @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int oldHeight = oldBottom - oldTop; int newHeight = bottom - top; if (oldHeight == newHeight && !mTileCountChanged) return; mTileCountChanged = false; // Re-apply the url focus change amount after a rotation to ensure the views are correctly // placed with their new layout configurations. onUrlFocusAnimationChanged(); updateSearchBoxOnScroll(); if (mUseCardsUi) { mRecyclerView.updatePeekingCard(); mRecyclerView.updateSnippetsHeaderDisplay(); // The positioning of elements may have been changed (since the elements expand to fill // the available vertical space), so adjust the scroll. mRecyclerView.snapScroll(mSearchBoxView, getVerticalScroll(), getHeight()); } } // MostVisitedURLsObserver implementation @Override public void onMostVisitedURLsAvailable(final String[] titles, final String[] urls, final String[] whitelistIconPaths, final int[] sources) { Set<String> urlSet = new HashSet<>(Arrays.asList(urls)); // TODO(https://crbug.com/607573): We should show offline-available content in a nonblocking // way so that responsiveness of the NTP does not depend on ready availability of offline // pages. mManager.getUrlsAvailableOffline(urlSet, new Callback<Set<String>>() { @Override public void onResult(Set<String> offlineUrls) { onOfflineUrlsAvailable(titles, urls, whitelistIconPaths, offlineUrls, sources); } }); } private void onOfflineUrlsAvailable(final String[] titles, final String[] urls, final String[] whitelistIconPaths, final Set<String> offlineUrls, final int[] sources) { mMostVisitedLayout.removeAllViews(); MostVisitedItem[] oldItems = mMostVisitedItems; int oldItemCount = oldItems == null ? 0 : oldItems.length; mMostVisitedItems = new MostVisitedItem[titles.length]; final boolean isInitialLoad = !mHasReceivedMostVisitedSites; LayoutInflater inflater = LayoutInflater.from(getContext()); // Add the most visited items to the page. for (int i = 0; i < titles.length; i++) { final String url = urls[i]; final String title = titles[i]; final String whitelistIconPath = whitelistIconPaths[i]; final int source = sources[i]; boolean offlineAvailable = offlineUrls.contains(url); // Look for an existing item to reuse. MostVisitedItem item = null; for (int j = 0; j < oldItemCount; j++) { MostVisitedItem oldItem = oldItems[j]; if (oldItem != null && TextUtils.equals(url, oldItem.getUrl()) && TextUtils.equals(title, oldItem.getTitle()) && offlineAvailable == oldItem.isOfflineAvailable() && whitelistIconPath.equals(oldItem.getWhitelistIconPath())) { item = oldItem; item.setIndex(i); oldItems[j] = null; break; } } // If nothing can be reused, create a new item. if (item == null) { item = new MostVisitedItem(mManager, title, url, whitelistIconPath, offlineAvailable, i, source); View view = mMostVisitedDesign.createMostVisitedItemView(inflater, item, isInitialLoad); item.initView(view); } mMostVisitedItems[i] = item; mMostVisitedLayout.addView(item.getView()); } mHasReceivedMostVisitedSites = true; updateMostVisitedPlaceholderVisibility(); if (mUrlFocusChangePercent == 1f && oldItemCount != mMostVisitedItems.length) { // If the number of NTP Tile rows change while the URL bar is focused, the icons' // position will be wrong. Schedule the translation to be updated. mTileCountChanged = true; } if (isInitialLoad) { loadTaskCompleted(); // The page contents are initially hidden; otherwise they'll be drawn centered on the // page before the most visited sites are available and then jump upwards to make space // once the most visited sites are available. mNewTabPageLayout.setVisibility(View.VISIBLE); } mSnapshotMostVisitedChanged = true; } @Override public void onPopularURLsAvailable( String[] urls, String[] faviconUrls, String[] largeIconUrls) { for (int i = 0; i < urls.length; i++) { final String url = urls[i]; boolean useLargeIcon = !largeIconUrls[i].isEmpty(); // Only fetch one of favicon or large icon based on what is required on the NTP. // The other will be fetched on visiting the site. String iconUrl = useLargeIcon ? largeIconUrls[i] : faviconUrls[i]; if (iconUrl.isEmpty()) continue; IconAvailabilityCallback callback = new IconAvailabilityCallback() { @Override public void onIconAvailabilityChecked(boolean newlyAvailable) { if (newlyAvailable) { mMostVisitedDesign.onIconUpdated(url); } } }; mManager.ensureIconIsAvailable( url, iconUrl, useLargeIcon, /*isTemporary=*/false, callback); } } /** * Shows the most visited placeholder ("Nothing to see here") if there are no most visited * items and there is no search provider logo. */ private void updateMostVisitedPlaceholderVisibility() { boolean showPlaceholder = mHasReceivedMostVisitedSites && mMostVisitedLayout.getChildCount() == 0 && !mSearchProviderHasLogo; mNoSearchLogoSpacer.setVisibility( (mSearchProviderHasLogo || showPlaceholder) ? View.GONE : View.INVISIBLE); if (showPlaceholder) { if (mMostVisitedPlaceholder == null) { ViewStub mostVisitedPlaceholderStub = (ViewStub) mNewTabPageLayout .findViewById(R.id.most_visited_placeholder_stub); mMostVisitedPlaceholder = mostVisitedPlaceholderStub.inflate(); } mMostVisitedLayout.setVisibility(GONE); mMostVisitedPlaceholder.setVisibility(VISIBLE); } else if (mMostVisitedPlaceholder != null) { mMostVisitedLayout.setVisibility(VISIBLE); mMostVisitedPlaceholder.setVisibility(GONE); } } /** * The design for most visited tiles: each tile shows a large icon and the site's title. */ private class MostVisitedDesign { private static final int NUM_TILES = 8; private static final int NUM_TILES_NO_LOGO = 12; private static final int MAX_ROWS = 2; private static final int MAX_ROWS_NO_LOGO = 3; private static final int ICON_CORNER_RADIUS_DP = 4; private static final int ICON_TEXT_SIZE_DP = 20; private static final int ICON_BACKGROUND_COLOR = 0xff787878; private static final int ICON_MIN_SIZE_PX = 48; private int mMinIconSize; private int mDesiredIconSize; private RoundedIconGenerator mIconGenerator; MostVisitedDesign(Context context) { Resources res = context.getResources(); mDesiredIconSize = res.getDimensionPixelSize(R.dimen.most_visited_icon_size); // On ldpi devices, mDesiredIconSize could be even smaller than ICON_MIN_SIZE_PX. mMinIconSize = Math.min(mDesiredIconSize, ICON_MIN_SIZE_PX); int desiredIconSizeDp = Math.round( mDesiredIconSize / res.getDisplayMetrics().density); mIconGenerator = new RoundedIconGenerator( context, desiredIconSizeDp, desiredIconSizeDp, ICON_CORNER_RADIUS_DP, ICON_BACKGROUND_COLOR, ICON_TEXT_SIZE_DP); } public int getNumberOfTiles(boolean searchProviderHasLogo) { return searchProviderHasLogo ? NUM_TILES : NUM_TILES_NO_LOGO; } public void initMostVisitedLayout(boolean searchProviderHasLogo) { mMostVisitedLayout.setMaxRows(searchProviderHasLogo ? MAX_ROWS : MAX_ROWS_NO_LOGO); } public void setSearchProviderHasLogo(View mostVisitedLayout, boolean hasLogo) { int paddingTop = getResources().getDimensionPixelSize(hasLogo ? R.dimen.most_visited_layout_padding_top : R.dimen.most_visited_layout_no_logo_padding_top); mostVisitedLayout.setPadding(0, paddingTop, 0, mMostVisitedLayout.getPaddingBottom()); } class LargeIconCallbackImpl implements LargeIconCallback { private MostVisitedItem mItem; private MostVisitedItemView mItemView; private boolean mIsInitialLoad; public LargeIconCallbackImpl( MostVisitedItem item, MostVisitedItemView itemView, boolean isInitialLoad) { mItem = item; mItemView = itemView; mIsInitialLoad = isInitialLoad; } @Override public void onLargeIconAvailable(Bitmap icon, int fallbackColor) { if (icon == null) { mIconGenerator.setBackgroundColor(fallbackColor); icon = mIconGenerator.generateIconForUrl(mItem.getUrl()); mItemView.setIcon(new BitmapDrawable(getResources(), icon)); mItem.setTileType(fallbackColor == ICON_BACKGROUND_COLOR ? MostVisitedTileType.ICON_DEFAULT : MostVisitedTileType.ICON_COLOR); } else { RoundedBitmapDrawable roundedIcon = RoundedBitmapDrawableFactory.create( getResources(), icon); int cornerRadius = Math.round(ICON_CORNER_RADIUS_DP * getResources().getDisplayMetrics().density * icon.getWidth() / mDesiredIconSize); roundedIcon.setCornerRadius(cornerRadius); roundedIcon.setAntiAlias(true); roundedIcon.setFilterBitmap(true); mItemView.setIcon(roundedIcon); mItem.setTileType(MostVisitedTileType.ICON_REAL); } mSnapshotMostVisitedChanged = true; if (mIsInitialLoad) loadTaskCompleted(); } } public View createMostVisitedItemView( LayoutInflater inflater, MostVisitedItem item, boolean isInitialLoad) { final MostVisitedItemView view = (MostVisitedItemView) inflater.inflate( R.layout.most_visited_item, mMostVisitedLayout, false); view.setTitle(TitleUtil.getTitleForDisplay(item.getTitle(), item.getUrl())); view.setOfflineAvailable(item.isOfflineAvailable()); LargeIconCallback iconCallback = new LargeIconCallbackImpl(item, view, isInitialLoad); if (isInitialLoad) mPendingLoadTasks++; if (!loadWhitelistIcon(item, iconCallback)) { mManager.getLargeIconForUrl(item.getUrl(), mMinIconSize, iconCallback); } return view; } private boolean loadWhitelistIcon(MostVisitedItem item, LargeIconCallback iconCallback) { if (item.getWhitelistIconPath().isEmpty()) return false; Bitmap bitmap = BitmapFactory.decodeFile(item.getWhitelistIconPath()); if (bitmap == null) { Log.d(TAG, "Image decoding failed: %s", item.getWhitelistIconPath()); return false; } iconCallback.onLargeIconAvailable(bitmap, Color.BLACK); return true; } public void onIconUpdated(final String url) { if (mMostVisitedItems == null) return; // Find a matching most visited item. for (MostVisitedItem item : mMostVisitedItems) { if (item.getUrl().equals(url)) { LargeIconCallback iconCallback = new LargeIconCallbackImpl( item, (MostVisitedItemView) item.getView(), false); mManager.getLargeIconForUrl(url, mMinIconSize, iconCallback); break; } } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mNewTabPageLayout != null) { mNewTabPageLayout.setParentViewportHeight(MeasureSpec.getSize(heightMeasureSpec)); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mUseCardsUi) { mRecyclerView.updatePeekingCard(); mRecyclerView.updateSnippetsHeaderDisplay(); } } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // When the viewport configuration changes, we want to update the display style so that the // observers are aware of the new available space. Another moment to do this update could // be through a OnLayoutChangeListener, but then we get notified of the change after the // layout pass, which means that the new style will only be visible after layout happens // again. We prefer updating here to avoid having to require that additional layout pass. mUiConfig.updateDisplayStyle(); } private int getVerticalScroll() { if (mUseCardsUi) { return mRecyclerView.computeVerticalScrollOffset(); } else { return mScrollView.getScrollY(); } } }
package net.sf.jabref.gui.externalfiles; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import net.sf.jabref.Globals; import net.sf.jabref.gui.BasePanel; import net.sf.jabref.gui.filelist.FileListEntry; import net.sf.jabref.gui.filelist.FileListTableModel; import net.sf.jabref.gui.keyboard.KeyBinding; import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.io.FileUtil; import net.sf.jabref.logic.xmp.XMPUtil; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.FieldName; import com.jgoodies.forms.builder.ButtonBarBuilder; /** * * This action goes through all selected entries in the BasePanel, and attempts * to write the XMP data to the external pdf. */ public class WriteXMPAction extends AbstractWorker { private final BasePanel panel; private Collection<BibEntry> entries; private BibDatabase database; private OptionsDialog optDiag; private boolean goOn = true; private int skipped; private int entriesChanged; private int errors; public WriteXMPAction(BasePanel panel) { this.panel = panel; } @Override public void init() { database = panel.getDatabase(); // Get entries and check if it makes sense to perform this operation entries = panel.getSelectedEntries(); if (entries.isEmpty()) { entries = database.getEntries(); if (entries.isEmpty()) { JOptionPane.showMessageDialog(panel, Localization.lang("This operation requires one or more entries to be selected."), Localization.lang("Write XMP-metadata"), JOptionPane.ERROR_MESSAGE); goOn = false; return; } else { int response = JOptionPane.showConfirmDialog(panel, Localization.lang("Write XMP-metadata for all PDFs in current database?"), Localization.lang("Write XMP-metadata"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response != JOptionPane.YES_OPTION) { goOn = false; return; } } } errors = entriesChanged = skipped = 0; if (optDiag == null) { optDiag = new OptionsDialog(panel.frame()); } optDiag.open(); panel.output(Localization.lang("Writing XMP-metadata...")); } @Override public void run() { if (!goOn) { return; } for (BibEntry entry : entries) { // Make a list of all PDFs linked from this entry: List<File> files = new ArrayList<>(); // First check the (legacy) "pdf" field: entry.getField(FieldName.PDF) .ifPresent( pdf -> FileUtil .expandFilename(pdf, panel.getBibDatabaseContext().getFileDirectory(FieldName.PDF, Globals.prefs.getFileDirectoryPreferences())) .ifPresent(files::add)); // Then check the "file" field: List<String> dirs = panel.getBibDatabaseContext() .getFileDirectory(Globals.prefs.getFileDirectoryPreferences()); if (entry.hasField(FieldName.FILE)) { FileListTableModel tm = new FileListTableModel(); entry.getField(FieldName.FILE).ifPresent(tm::setContent); for (int j = 0; j < tm.getRowCount(); j++) { FileListEntry flEntry = tm.getEntry(j); if ((flEntry.type.isPresent()) && "pdf".equalsIgnoreCase(flEntry.type.get().getName())) { FileUtil.expandFilename(flEntry.link, dirs).ifPresent(files::add); } } } SwingUtilities.invokeLater(() -> optDiag.getProgressArea() .append(entry.getCiteKeyOptional().orElse(Localization.lang("undefined")) + "\n")); if (files.isEmpty()) { skipped++; SwingUtilities.invokeLater(() -> optDiag.getProgressArea() .append(" " + Localization.lang("Skipped - No PDF linked") + ".\n")); } else { for (File file : files) { if (file.exists()) { try { XMPUtil.writeXMP(file, entry, database, Globals.prefs.getXMPPreferences()); SwingUtilities.invokeLater( () -> optDiag.getProgressArea().append(" " + Localization.lang("OK") + ".\n")); entriesChanged++; } catch (Exception e) { SwingUtilities.invokeLater(() -> { optDiag.getProgressArea().append(" " + Localization.lang("Error while writing") + " '" + file.getPath() + "':\n"); optDiag.getProgressArea().append(" " + e.getLocalizedMessage() + "\n"); }); errors++; } } else { skipped++; SwingUtilities.invokeLater(() -> { optDiag.getProgressArea() .append(" " + Localization.lang("Skipped - PDF does not exist") + ":\n"); optDiag.getProgressArea().append(" " + file.getPath() + "\n"); }); } } } if (optDiag.isCanceled()) { SwingUtilities.invokeLater( () -> optDiag.getProgressArea().append("\n" + Localization.lang("Operation canceled.") + "\n")); break; } } SwingUtilities.invokeLater(() -> { optDiag.getProgressArea() .append("\n" + Localization.lang("Finished writing XMP for %0 file (%1 skipped, %2 errors).", String .valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors))); optDiag.done(); }); } @Override public void update() { if (!goOn) { return; } panel.output(Localization.lang("Finished writing XMP for %0 file (%1 skipped, %2 errors).", String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors))); } class OptionsDialog extends JDialog { private final JButton okButton = new JButton(Localization.lang("OK")); private final JButton cancelButton = new JButton(Localization.lang("Cancel")); private boolean canceled; private final JTextArea progressArea; public OptionsDialog(JFrame parent) { super(parent, Localization.lang("Writing XMP-metadata for selected entries..."), false); okButton.setEnabled(false); okButton.addActionListener(e -> dispose()); AbstractAction cancel = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { canceled = true; } }; cancelButton.addActionListener(cancel); InputMap im = cancelButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap am = cancelButton.getActionMap(); im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close"); am.put("close", cancel); progressArea = new JTextArea(15, 60); JScrollPane scrollPane = new JScrollPane(progressArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Dimension d = progressArea.getPreferredSize(); d.height += scrollPane.getHorizontalScrollBar().getHeight() + 15; d.width += scrollPane.getVerticalScrollBar().getWidth() + 15; panel.setSize(d); progressArea.setBackground(Color.WHITE); progressArea.setEditable(false); progressArea.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); progressArea.setText(""); JPanel tmpPanel = new JPanel(); tmpPanel.setBorder(BorderFactory.createEmptyBorder(3, 2, 3, 2)); tmpPanel.add(scrollPane); // progressArea.setPreferredSize(new Dimension(300, 300)); ButtonBarBuilder bb = new ButtonBarBuilder(); bb.addGlue(); bb.addButton(okButton); bb.addRelatedGap(); bb.addButton(cancelButton); bb.addGlue(); JPanel bbPanel = bb.getPanel(); bbPanel.setBorder(BorderFactory.createEmptyBorder(0, 3, 3, 3)); getContentPane().add(tmpPanel, BorderLayout.CENTER); getContentPane().add(bbPanel, BorderLayout.SOUTH); pack(); this.setResizable(false); } public void done() { okButton.setEnabled(true); cancelButton.setEnabled(false); } public void open() { progressArea.setText(""); canceled = false; optDiag.setLocationRelativeTo(panel.frame()); okButton.setEnabled(false); cancelButton.setEnabled(true); okButton.requestFocus(); optDiag.setVisible(true); } public boolean isCanceled() { return canceled; } public JTextArea getProgressArea() { return progressArea; } } }
// 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; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.testing.drivers.Browser.CHROME; import static org.openqa.selenium.testing.drivers.Browser.CHROMIUMEDGE; import static org.openqa.selenium.testing.drivers.Browser.EDGE; import static org.openqa.selenium.testing.drivers.Browser.IE; import static org.openqa.selenium.testing.drivers.Browser.MARIONETTE; import static org.openqa.selenium.testing.drivers.Browser.SAFARI; import org.junit.Test; import org.openqa.selenium.environment.webserver.Page; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.NotYetImplemented; import java.io.File; import java.io.IOException; public class FormHandlingTest extends JUnit4TestBase { @Test public void testShouldClickOnSubmitInputElements() { driver.get(pages.formPage); driver.findElement(By.id("submitButton")).click(); wait.until(titleIs("We Arrive Here")); assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } @Test public void testClickingOnUnclickableElementsDoesNothing() { driver.get(pages.formPage); driver.findElement(By.xpath("//body")).click(); } @Test public void testShouldBeAbleToClickImageButtons() { driver.get(pages.formPage); driver.findElement(By.id("imageButton")).click(); wait.until(titleIs("We Arrive Here")); assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } @Test public void testShouldBeAbleToSubmitForms() { driver.get(pages.formPage); driver.findElement(By.name("login")).submit(); wait.until(titleIs("We Arrive Here")); } @Test public void testShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted() { driver.get(pages.formPage); driver.findElement(By.id("checky")).submit(); wait.until(titleIs("We Arrive Here")); } @Test public void testShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { driver.get(pages.formPage); driver.findElement(By.xpath("//form/p")).submit(); wait.until(titleIs("We Arrive Here")); } @Test @NotYetImplemented(SAFARI) @NotYetImplemented( value = MARIONETTE, reason = "Delegates to JS and so the wrong exception is returned") @NotYetImplemented(EDGE) @NotYetImplemented(value = IE, reason = "Throws JavascriptException: Error from JavaScript: Unable to find owning document") @NotYetImplemented(value = CHROMIUMEDGE, reason = "Throws JavascriptException: Error from JavaScript: Unable to find owning document") @NotYetImplemented(value = CHROME, reason = "Throws JavascriptException: Error from JavaScript: Unable to find owning document") public void testShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("SearchableText")); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(element::submit); } @Test public void testShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { driver.get(pages.javascriptPage); WebElement textarea = driver.findElement(By.id("keyUpArea")); String cheesy = "brie and cheddar"; textarea.sendKeys(cheesy); assertThat(textarea.getAttribute("value")).isEqualTo(cheesy); } @Test public void testSendKeysKeepsCapitalization() { driver.get(pages.javascriptPage); WebElement textarea = driver.findElement(By .id("keyUpArea")); String cheesey = "BrIe And CheDdar"; textarea.sendKeys(cheesey); assertThat(textarea.getAttribute("value")).isEqualTo(cheesey); } @Test @NotYetImplemented(MARIONETTE) @NotYetImplemented(SAFARI) public void testShouldSubmitAFormUsingTheNewlineLiteral() { driver.get(pages.formPage); WebElement nestedForm = driver.findElement(By.id("nested_form")); WebElement input = nestedForm.findElement(By.name("x")); input.sendKeys("\n"); wait.until(titleIs("We Arrive Here")); assertThat(driver.getCurrentUrl()).endsWith("?x=name"); } @Test public void testShouldSubmitAFormUsingTheEnterKey() { driver.get(pages.formPage); WebElement nestedForm = driver.findElement(By.id("nested_form")); WebElement input = nestedForm.findElement(By.name("x")); input.sendKeys(Keys.ENTER); wait.until(titleIs("We Arrive Here")); assertThat(driver.getCurrentUrl()).endsWith("?x=name"); } @Test public void testShouldEnterDataIntoFormFields() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.xpath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.getAttribute("value"); assertThat(originalValue).isEqualTo("change"); element.clear(); element.sendKeys("some text"); element = driver.findElement(By.xpath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.getAttribute("value"); assertThat(newFormValue).isEqualTo("some text"); } @Test public void testShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() throws IOException { driver.get(pages.formPage); WebElement uploadElement = driver.findElement(By.id("upload")); assertThat(uploadElement.getAttribute("value")).isEqualTo(""); File file = File.createTempFile("test", "txt"); file.deleteOnExit(); uploadElement.sendKeys(file.getAbsolutePath()); String uploadPath = uploadElement.getAttribute("value"); assertThat(uploadPath.endsWith(file.getName())).isTrue(); } @Test public void testShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() throws IOException { driver.get(pages.xhtmlFormPage); WebElement uploadElement = driver.findElement(By.id("file")); assertThat(uploadElement.getAttribute("value")).isEqualTo(""); File file = File.createTempFile("test", "txt"); file.deleteOnExit(); uploadElement.sendKeys(file.getAbsolutePath()); String uploadPath = uploadElement.getAttribute("value"); assertThat(uploadPath.endsWith(file.getName())).isTrue(); } @Test @Ignore(value = SAFARI, reason = "Hanging") public void testShouldBeAbleToUploadTheSameFileTwice() throws IOException { File file = File.createTempFile("test", "txt"); file.deleteOnExit(); driver.get(pages.formPage); WebElement uploadElement = driver.findElement(By.id("upload")); assertThat(uploadElement.getAttribute("value")).isEqualTo(""); uploadElement.sendKeys(file.getAbsolutePath()); uploadElement.submit(); driver.get(pages.formPage); uploadElement = driver.findElement(By.id("upload")); assertThat(uploadElement.getAttribute("value")).isEqualTo(""); uploadElement.sendKeys(file.getAbsolutePath()); uploadElement.submit(); // If we get this far, then we're all good. } @Test public void testSendingKeyboardEventsShouldAppendTextInInputs() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("working")); element.sendKeys("some"); String value = element.getAttribute("value"); assertThat(value).isEqualTo("some"); element.sendKeys(" text"); value = element.getAttribute("value"); assertThat(value).isEqualTo("some text"); } @Test @NotYetImplemented(SAFARI) public void testSendingKeyboardEventsShouldAppendTextInInputsWithExistingValue() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("inputWithText")); element.sendKeys(". Some text"); String value = element.getAttribute("value"); assertThat(value).isEqualTo("Example text. Some text"); } @Test @NotYetImplemented(SAFARI) public void testSendingKeyboardEventsShouldAppendTextInTextAreas() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("withText")); element.sendKeys(". Some text"); String value = element.getAttribute("value"); assertThat(value).isEqualTo("Example text. Some text"); } @Test public void testEmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.get(pages.formPage); WebElement emptyTextBox = driver.findElement(By.id("working")); assertThat(emptyTextBox.getAttribute("value")).isEqualTo(""); } @Test @Ignore(value = SAFARI, reason = "Does not support alerts yet") public void handleFormWithJavascriptAction() { String url = appServer.whereIs("form_handling_js_submit.html"); driver.get(url); WebElement element = driver.findElement(By.id("theForm")); element.submit(); Alert alert = wait.until(alertIsPresent()); String text = alert.getText(); alert.accept(); assertThat(text).isEqualTo("Tasty cheese"); } @Test public void testCanClickOnASubmitButton() { checkSubmitButton("internal_explicit_submit"); } @Test public void testCanClickOnASubmitButtonNestedSpan() { checkSubmitButton("internal_span_submit"); } @Test public void testCanClickOnAnImplicitSubmitButton() { checkSubmitButton("internal_implicit_submit"); } @Test @Ignore(IE) public void testCanClickOnAnExternalSubmitButton() { checkSubmitButton("external_explicit_submit"); } @Test @Ignore(IE) public void testCanClickOnAnExternalImplicitSubmitButton() { checkSubmitButton("external_implicit_submit"); } @Test public void canSubmitFormWithSubmitButtonIdEqualToSubmit() { String blank = appServer.create(new Page().withTitle("Submitted Successfully!")); driver.get(appServer.create(new Page().withBody( String.format("<form action='%s'>", blank), " <input type='submit' id='submit' value='Submit'>", "</form>"))); driver.findElement(By.id("submit")).submit(); wait.until(titleIs("Submitted Successfully!")); } @Test public void canSubmitFormWithSubmitButtonNameEqualToSubmit() { String blank = appServer.create(new Page().withTitle("Submitted Successfully!")); driver.get(appServer.create(new Page().withBody( String.format("<form action='%s'>", blank), " <input type='submit' name='submit' value='Submit'>", "</form>"))); driver.findElement(By.name("submit")).submit(); wait.until(titleIs("Submitted Successfully!")); } private void checkSubmitButton(String buttonId) { driver.get(appServer.whereIs("click_tests/html5_submit_buttons.html")); String name = "Gromit"; driver.findElement(By.id("name")).sendKeys(name); driver.findElement(By.id(buttonId)).click(); wait.until(titleIs("Submitted Successfully!")); assertThat(driver.getCurrentUrl()).contains("name="+name); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.catalina.mbeans; import java.util.ArrayList; import java.util.Iterator; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.RuntimeOperationsException; import org.apache.catalina.Group; import org.apache.catalina.Role; import org.apache.catalina.User; import org.apache.catalina.UserDatabase; import org.apache.tomcat.util.modeler.BaseModelMBean; import org.apache.tomcat.util.modeler.ManagedBean; import org.apache.tomcat.util.modeler.Registry; /** * <p>A <strong>ModelMBean</strong> implementation for the * <code>org.apache.catalina.users.MemoryUserDatabase</code> component.</p> * * @author Craig R. McClanahan * @version $Id: MemoryUserDatabaseMBean.java 1140070 2011-06-27 09:27:06Z markt $ */ public class MemoryUserDatabaseMBean extends BaseModelMBean { // ----------------------------------------------------------- Constructors /** * Construct a <code>ModelMBean</code> with default * <code>ModelMBeanInfo</code> information. * * @exception MBeanException if the initializer of an object * throws an exception * @exception RuntimeOperationsException if an IllegalArgumentException * occurs */ public MemoryUserDatabaseMBean() throws MBeanException, RuntimeOperationsException { super(); } // ----------------------------------------------------- Instance Variables /** * The configuration information registry for our managed beans. */ protected Registry registry = MBeanUtils.createRegistry(); /** * The <code>ManagedBean</code> information describing this MBean. */ protected ManagedBean managed = registry.findManagedBean("MemoryUserDatabase"); /** * The <code>ManagedBean</code> information describing Group MBeans. */ protected ManagedBean managedGroup = registry.findManagedBean("Group"); /** * The <code>ManagedBean</code> information describing Group MBeans. */ protected ManagedBean managedRole = registry.findManagedBean("Role"); /** * The <code>ManagedBean</code> information describing User MBeans. */ protected ManagedBean managedUser = registry.findManagedBean("User"); // ------------------------------------------------------------- Attributes /** * Return the MBean Names of all groups defined in this database. */ public String[] getGroups() { UserDatabase database = (UserDatabase) this.resource; ArrayList<String> results = new ArrayList<String>(); Iterator<Group> groups = database.getGroups(); while (groups.hasNext()) { Group group = groups.next(); results.add(findGroup(group.getGroupname())); } return results.toArray(new String[results.size()]); } /** * Return the MBean Names of all roles defined in this database. */ public String[] getRoles() { UserDatabase database = (UserDatabase) this.resource; ArrayList<String> results = new ArrayList<String>(); Iterator<Role> roles = database.getRoles(); while (roles.hasNext()) { Role role = roles.next(); results.add(findRole(role.getRolename())); } return results.toArray(new String[results.size()]); } /** * Return the MBean Names of all users defined in this database. */ public String[] getUsers() { UserDatabase database = (UserDatabase) this.resource; ArrayList<String> results = new ArrayList<String>(); Iterator<User> users = database.getUsers(); while (users.hasNext()) { User user = users.next(); results.add(findUser(user.getUsername())); } return results.toArray(new String[results.size()]); } // ------------------------------------------------------------- Operations /** * Create a new Group and return the corresponding MBean Name. * * @param groupname Group name of the new group * @param description Description of the new group */ public String createGroup(String groupname, String description) { UserDatabase database = (UserDatabase) this.resource; Group group = database.createGroup(groupname, description); try { MBeanUtils.createMBean(group); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating group [" + groupname + "] MBean"); iae.initCause(e); throw iae; } return (findGroup(groupname)); } /** * Create a new Role and return the corresponding MBean Name. * * @param rolename Group name of the new group * @param description Description of the new group */ public String createRole(String rolename, String description) { UserDatabase database = (UserDatabase) this.resource; Role role = database.createRole(rolename, description); try { MBeanUtils.createMBean(role); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating role [" + rolename + "] MBean"); iae.initCause(e); throw iae; } return (findRole(rolename)); } /** * Create a new User and return the corresponding MBean Name. * * @param username User name of the new user * @param password Password for the new user * @param fullName Full name for the new user */ public String createUser(String username, String password, String fullName) { UserDatabase database = (UserDatabase) this.resource; User user = database.createUser(username, password, fullName); try { MBeanUtils.createMBean(user); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception creating user [" + username + "] MBean"); iae.initCause(e); throw iae; } return (findUser(username)); } /** * Return the MBean Name for the specified group name (if any); * otherwise return <code>null</code>. * * @param groupname Group name to look up */ public String findGroup(String groupname) { UserDatabase database = (UserDatabase) this.resource; Group group = database.findGroup(groupname); if (group == null) { return (null); } try { ObjectName oname = MBeanUtils.createObjectName(managedGroup.getDomain(), group); return (oname.toString()); } catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for group [" + groupname + "]"); iae.initCause(e); throw iae; } } /** * Return the MBean Name for the specified role name (if any); * otherwise return <code>null</code>. * * @param rolename Role name to look up */ public String findRole(String rolename) { UserDatabase database = (UserDatabase) this.resource; Role role = database.findRole(rolename); if (role == null) { return (null); } try { ObjectName oname = MBeanUtils.createObjectName(managedRole.getDomain(), role); return (oname.toString()); } catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for role [" + rolename + "]"); iae.initCause(e); throw iae; } } /** * Return the MBean Name for the specified user name (if any); * otherwise return <code>null</code>. * * @param username User name to look up */ public String findUser(String username) { UserDatabase database = (UserDatabase) this.resource; User user = database.findUser(username); if (user == null) { return (null); } try { ObjectName oname = MBeanUtils.createObjectName(managedUser.getDomain(), user); return (oname.toString()); } catch (MalformedObjectNameException e) { IllegalArgumentException iae = new IllegalArgumentException ("Cannot create object name for user [" + username + "]"); iae.initCause(e); throw iae; } } /** * Remove an existing group and destroy the corresponding MBean. * * @param groupname Group name to remove */ public void removeGroup(String groupname) { UserDatabase database = (UserDatabase) this.resource; Group group = database.findGroup(groupname); if (group == null) { return; } try { MBeanUtils.destroyMBean(group); database.removeGroup(group); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying group [" + groupname + "] MBean"); iae.initCause(e); throw iae; } } /** * Remove an existing role and destroy the corresponding MBean. * * @param rolename Role name to remove */ public void removeRole(String rolename) { UserDatabase database = (UserDatabase) this.resource; Role role = database.findRole(rolename); if (role == null) { return; } try { MBeanUtils.destroyMBean(role); database.removeRole(role); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying role [" + rolename + "] MBean"); iae.initCause(e); throw iae; } } /** * Remove an existing user and destroy the corresponding MBean. * * @param username User name to remove */ public void removeUser(String username) { UserDatabase database = (UserDatabase) this.resource; User user = database.findUser(username); if (user == null) { return; } try { MBeanUtils.destroyMBean(user); database.removeUser(user); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user [" + username + "] MBean"); iae.initCause(e); throw iae; } } }
/** * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.internal.operators.observable; import static org.mockito.Mockito.*; import org.junit.*; import org.mockito.InOrder; import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.BiPredicate; import io.reactivex.observers.TestObserver; import io.reactivex.subjects.PublishSubject; public class ObservableSequenceEqualTest { @Test public void test1Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.just("one", "two", "three")).toObservable(); verifyResult(o, true); } @Test public void test2Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.just("one", "two", "three", "four")).toObservable(); verifyResult(o, false); } @Test public void test3Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three", "four"), Observable.just("one", "two", "three")).toObservable(); verifyResult(o, false); } @Test public void testWithError1Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.concat(Observable.just("one"), Observable.<String> error(new TestException())), Observable.just("one", "two", "three")).toObservable(); verifyError(o); } @Test public void testWithError2Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.concat(Observable.just("one"), Observable.<String> error(new TestException()))).toObservable(); verifyError(o); } @Test public void testWithError3Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.concat(Observable.just("one"), Observable.<String> error(new TestException())), Observable.concat(Observable.just("one"), Observable.<String> error(new TestException()))).toObservable(); verifyError(o); } @Test public void testWithEmpty1Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.<String> empty(), Observable.just("one", "two", "three")).toObservable(); verifyResult(o, false); } @Test public void testWithEmpty2Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.<String> empty()).toObservable(); verifyResult(o, false); } @Test public void testWithEmpty3Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.<String> empty(), Observable.<String> empty()).toObservable(); verifyResult(o, true); } @Test @Ignore("Null values not allowed") public void testWithNull1Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just((String) null), Observable.just("one")).toObservable(); verifyResult(o, false); } @Test @Ignore("Null values not allowed") public void testWithNull2Observable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just((String) null), Observable.just((String) null)).toObservable(); verifyResult(o, true); } @Test public void testWithEqualityErrorObservable() { Observable<Boolean> o = Observable.sequenceEqual( Observable.just("one"), Observable.just("one"), new BiPredicate<String, String>() { @Override public boolean test(String t1, String t2) { throw new TestException(); } }).toObservable(); verifyError(o); } private void verifyResult(Single<Boolean> o, boolean result) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); o.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onSuccess(result); inOrder.verifyNoMoreInteractions(); } private void verifyError(Observable<Boolean> observable) { Observer<Boolean> observer = TestHelper.mockObserver(); observable.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(isA(TestException.class)); inOrder.verifyNoMoreInteractions(); } private void verifyError(Single<Boolean> single) { SingleObserver<Boolean> observer = TestHelper.mockSingleObserver(); single.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(isA(TestException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void prefetchObservable() { Observable.sequenceEqual(Observable.range(1, 20), Observable.range(1, 20), 2) .toObservable() .test() .assertResult(true); } @Test public void disposedObservable() { TestHelper.checkDisposed(Observable.sequenceEqual(Observable.just(1), Observable.just(2)).toObservable()); } @Test public void test1() { Single<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.just("one", "two", "three")); verifyResult(o, true); } @Test public void test2() { Single<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.just("one", "two", "three", "four")); verifyResult(o, false); } @Test public void test3() { Single<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three", "four"), Observable.just("one", "two", "three")); verifyResult(o, false); } @Test public void testWithError1() { Single<Boolean> o = Observable.sequenceEqual( Observable.concat(Observable.just("one"), Observable.<String> error(new TestException())), Observable.just("one", "two", "three")); verifyError(o); } @Test public void testWithError2() { Single<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.concat(Observable.just("one"), Observable.<String> error(new TestException()))); verifyError(o); } @Test public void testWithError3() { Single<Boolean> o = Observable.sequenceEqual( Observable.concat(Observable.just("one"), Observable.<String> error(new TestException())), Observable.concat(Observable.just("one"), Observable.<String> error(new TestException()))); verifyError(o); } @Test public void testWithEmpty1() { Single<Boolean> o = Observable.sequenceEqual( Observable.<String> empty(), Observable.just("one", "two", "three")); verifyResult(o, false); } @Test public void testWithEmpty2() { Single<Boolean> o = Observable.sequenceEqual( Observable.just("one", "two", "three"), Observable.<String> empty()); verifyResult(o, false); } @Test public void testWithEmpty3() { Single<Boolean> o = Observable.sequenceEqual( Observable.<String> empty(), Observable.<String> empty()); verifyResult(o, true); } @Test @Ignore("Null values not allowed") public void testWithNull1() { Single<Boolean> o = Observable.sequenceEqual( Observable.just((String) null), Observable.just("one")); verifyResult(o, false); } @Test @Ignore("Null values not allowed") public void testWithNull2() { Single<Boolean> o = Observable.sequenceEqual( Observable.just((String) null), Observable.just((String) null)); verifyResult(o, true); } @Test public void testWithEqualityError() { Single<Boolean> o = Observable.sequenceEqual( Observable.just("one"), Observable.just("one"), new BiPredicate<String, String>() { @Override public boolean test(String t1, String t2) { throw new TestException(); } }); verifyError(o); } private void verifyResult(Observable<Boolean> o, boolean result) { Observer<Boolean> observer = TestHelper.mockObserver(); o.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onNext(result); inOrder.verify(observer).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void prefetch() { Observable.sequenceEqual(Observable.range(1, 20), Observable.range(1, 20), 2) .test() .assertResult(true); } @Test public void disposed() { TestHelper.checkDisposed(Observable.sequenceEqual(Observable.just(1), Observable.just(2))); } @Test public void simpleInequal() { Observable.sequenceEqual(Observable.just(1), Observable.just(2)) .test() .assertResult(false); } @Test public void simpleInequalObservable() { Observable.sequenceEqual(Observable.just(1), Observable.just(2)) .toObservable() .test() .assertResult(false); } @Test public void onNextCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject<Integer> ps = PublishSubject.create(); final TestObserver<Boolean> to = Observable.sequenceEqual(Observable.never(), ps).test(); Runnable r1 = new Runnable() { @Override public void run() { to.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { ps.onNext(1); } }; TestHelper.race(r1, r2); to.assertEmpty(); } } @Test public void onNextCancelRaceObservable() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final PublishSubject<Integer> ps = PublishSubject.create(); final TestObserver<Boolean> to = Observable.sequenceEqual(Observable.never(), ps).toObservable().test(); Runnable r1 = new Runnable() { @Override public void run() { to.cancel(); } }; Runnable r2 = new Runnable() { @Override public void run() { ps.onNext(1); } }; TestHelper.race(r1, r2); to.assertEmpty(); } } }
package org.nem.ncc.controller; import net.minidev.json.*; import org.hamcrest.core.IsEqual; import org.junit.*; import org.mockito.*; import org.nem.core.connect.HttpPostRequest; import org.nem.core.crypto.*; import org.nem.core.model.*; import org.nem.core.model.ncc.*; import org.nem.core.model.primitive.*; import org.nem.core.node.NodeEndpoint; import org.nem.core.serialization.*; import org.nem.core.time.*; import org.nem.ncc.connector.SimpleNisConnector; import org.nem.ncc.controller.requests.*; import org.nem.ncc.controller.viewmodels.*; import org.nem.ncc.model.NisApiId; import org.nem.ncc.services.*; import org.nem.ncc.test.Utils; import org.nem.ncc.wallet.*; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.*; import java.util.stream.Collectors; public class AccountControllerTest { //region findAccount @Test public void getAccountInfoDelegatesToAccountMapper() { // Arrange: final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); final AccountViewModel originalAccountViewModel = createViewModel(account); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(originalAccountViewModel); // Act: final AccountTimeStampRequest request = new AccountTimeStampRequest(account.getAddress(), null); final AccountViewModel accountViewModel = context.controller.getAccountInfo(request); // Assert: Mockito.verify(context.accountMapper, Mockito.times(1)).toViewModel(account.getAddress()); Assert.assertThat(accountViewModel, IsEqual.equalTo(originalAccountViewModel)); } //endregion //region getAccountTransactions @Test public void getAccountTransactionsDelegatesToAccountMapperForAccountInformation() { // Arrange: final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); final AccountViewModel originalAccountViewModel = createViewModel(account); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(originalAccountViewModel); // Act: final AccountTimeStampRequest request = new AccountTimeStampRequest(account.getAddress(), null); final AccountTransactionsPair pair = context.controller.getAccountTransactions(request); final AccountViewModel accountViewModel = pair.getAccount(); // Assert: Mockito.verify(context.accountMapper, Mockito.times(1)).toViewModel(account.getAddress()); Assert.assertThat(accountViewModel, IsEqual.equalTo(originalAccountViewModel)); } @Test public void getAccountTransactionsDelegatesToAccountServicesForUnconfirmedTransaction() { // Arrange: final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(createViewModel(account)); final List<Transaction> transactions = Arrays.asList( createTransfer(Utils.generateRandomAccount(), Amount.fromNem(124)), createTransfer(account, Amount.fromNem(572)), createTransfer(Utils.generateRandomAccount(), Amount.fromNem(323))); Mockito.when(context.accountServices.getUnconfirmedTransactions(account.getAddress())) .thenReturn(transactions); // Act: final AccountTimeStampRequest request = new AccountTimeStampRequest(account.getAddress(), null); final AccountTransactionsPair pair = context.controller.getAccountTransactions(request); final List<TransferViewModel> transferViewModels = pair.getTransactions(); // Assert: Mockito.verify(context.accountServices, Mockito.times(1)).getUnconfirmedTransactions(account.getAddress()); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getAmount).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(Amount.fromNem(124), Amount.fromNem(572), Amount.fromNem(323)))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getDirection).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(0, 2, 0))); } @Test public void getAccountTransactionsDelegatesToAccountServicesForConfirmedTransaction() { // Arrange: final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(createViewModel(account)); context.setLastBlockHeight(27); final AccountTimeStampRequest request = new AccountTimeStampRequest(account.getAddress(), null); final List<TransactionMetaDataPair> pairs = Arrays.asList( createTransferMetaDataPair(Utils.generateRandomAccount(), Amount.fromNem(124), 19), createTransferMetaDataPair(account, Amount.fromNem(572), 17), createTransferMetaDataPair(Utils.generateRandomAccount(), Amount.fromNem(323), 27)); Mockito.when(context.accountServices.getConfirmedTransactions(account.getAddress(), request.getTimeStamp())) .thenReturn(pairs); // Act: final AccountTransactionsPair pair = context.controller.getAccountTransactions(request); final List<TransferViewModel> transferViewModels = pair.getTransactions(); // Assert: Mockito.verify(context.accountServices, Mockito.times(1)) .getConfirmedTransactions(account.getAddress(), request.getTimeStamp()); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getAmount).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(Amount.fromNem(124), Amount.fromNem(572), Amount.fromNem(323)))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getDirection).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(0, 2, 0))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getConfirmations).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(9L, 11L, 1L))); } @Test public void getAccountTransactionsMergesUnconfirmedAndConfirmedTransactions() { // Arrange: final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(createViewModel(account)); context.setLastBlockHeight(27); final List<Transaction> transactions = Arrays.asList( createTransfer(account, Amount.fromNem(124))); Mockito.when(context.accountServices.getUnconfirmedTransactions(account.getAddress())) .thenReturn(transactions); final AccountTimeStampRequest request = new AccountTimeStampRequest(account.getAddress(), null); final List<TransactionMetaDataPair> pairs = Arrays.asList( createTransferMetaDataPair(Utils.generateRandomAccount(), Amount.fromNem(323), 25)); Mockito.when(context.accountServices.getConfirmedTransactions(account.getAddress(), request.getTimeStamp())) .thenReturn(pairs); // Act: final AccountTransactionsPair pair = context.controller.getAccountTransactions(request); final List<TransferViewModel> transferViewModels = pair.getTransactions(); // Assert: Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getAmount).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(Amount.fromNem(124), Amount.fromNem(323)))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getDirection).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(2, 0))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getConfirmations).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(0L, 3L))); } private static TransactionMetaDataPair createTransferMetaDataPair(final Account sender, final Amount amount, final int blockHeight) { return new TransactionMetaDataPair( createTransfer(sender, amount), new TransactionMetaData(new BlockHeight(blockHeight))); } private static Transaction createTransfer(final Account sender, final Amount amount) { return new TransferTransaction( new TimeInstant(125), sender, Utils.generateRandomAccount(), amount, null); } //endregion //region transactions/unconfirmed @Test public void getAccountTransactionsUnconfirmedDelegatesToAccountServicesForUnconfirmedTransaction() { // Arrange: final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(createViewModel(account)); context.setLastBlockHeight(34); final AccountHashRequest request = new AccountHashRequest(account.getAddress(), null); final List<Transaction> pairs = Arrays.asList( createTransfer(Utils.generateRandomAccount(), Amount.fromNem(124)), createTransfer(account, Amount.fromNem(572)), createTransfer(Utils.generateRandomAccount(), Amount.fromNem(323))); Mockito.when(context.accountServices.getUnconfirmedTransactions(account.getAddress())) .thenReturn(pairs); // Act: final AccountTransactionsPair pair = context.controller.getAccountTransactionsUnconfirmed(request); final List<TransferViewModel> transferViewModels = pair.getTransactions(); // Assert: Mockito.verify(context.accountServices, Mockito.times(1)) .getUnconfirmedTransactions(account.getAddress()); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getAmount).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(Amount.fromNem(124), Amount.fromNem(572), Amount.fromNem(323)))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getDirection).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(0, 2, 0))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getConfirmations).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(0L, 0L, 0L))); } //endregion //region new transaction Handlers @Test public void getAccountTransactionsAllDelegatesToAccountService() { this.assertGetTransactionsDelegateToAccountService( TransactionDirection.ALL, (TestContext ctx) -> ctx.controller::getAccountTransactionsAll); } @Test public void getAccountTransactionsIncomingDelegatesToAccountService() { this.assertGetTransactionsDelegateToAccountService( TransactionDirection.INCOMING, (TestContext ctx) -> ctx.controller::getAccountTransactionsIncoming); } @Test public void getAccountTransactionsOutgoingDelegatesToAccountService() { this.assertGetTransactionsDelegateToAccountService( TransactionDirection.OUTGOING, (TestContext ctx) -> ctx.controller::getAccountTransactionsOutgoing); } private void assertGetTransactionsDelegateToAccountService( final TransactionDirection direction, final Function<TestContext, Function<AccountHashRequest, AccountTransactionsPair>> handlerFactory) { final Account account = Utils.generateRandomAccount(); final TestContext context = new TestContext(); Mockito.when(context.accountMapper.toViewModel(account.getAddress())) .thenReturn(createViewModel(account)); context.setLastBlockHeight(34); final AccountHashRequest request = new AccountHashRequest(account.getAddress(), null); final List<TransactionMetaDataPair> pairs = Arrays.asList( createTransferMetaDataPair(Utils.generateRandomAccount(), Amount.fromNem(124), 19), createTransferMetaDataPair(account, Amount.fromNem(572), 17), createTransferMetaDataPair(Utils.generateRandomAccount(), Amount.fromNem(323), 27)); Mockito.when(context.accountServices.getTransactions(direction, account.getAddress(), request.getHash())) .thenReturn(pairs); // Act: final AccountTransactionsPair pair = handlerFactory.apply(context).apply(request); final List<TransferViewModel> transferViewModels = pair.getTransactions(); // Assert: Mockito.verify(context.accountServices, Mockito.times(1)) .getTransactions(direction, account.getAddress(), request.getHash()); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getAmount).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(Amount.fromNem(124), Amount.fromNem(572), Amount.fromNem(323)))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getDirection).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(0, 2, 0))); Assert.assertThat( transferViewModels.stream().map(TransferViewModel::getConfirmations).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(16L, 18L, 8L))); } //endregion //region getAccountHarvests @Test public void getAccountHarvestsWithoutTimeStampFilterDelegatesToNisConnector() { // Assert: final Address address = Address.fromEncoded("TB2IF4HDMCIMVCT6WYUDXONSUCVMUL4AM373VPR5"); assertHarvestConnectorRequest( new AccountTimeStampRequest(address, null), "address=TB2IF4HDMCIMVCT6WYUDXONSUCVMUL4AM373VPR5"); } @Test public void getAccountHarvestsWithTimeStampFilterDelegatesToNisConnector() { // Assert: final Address address = Address.fromEncoded("TB2IF4HDMCIMVCT6WYUDXONSUCVMUL4AM373VPR5"); assertHarvestConnectorRequest( new AccountTimeStampRequest(address, SystemTimeProvider.getEpochTimeMillis() + 11 * 1000), "address=TB2IF4HDMCIMVCT6WYUDXONSUCVMUL4AM373VPR5&timeStamp=11"); } private static void assertHarvestConnectorRequest( final AccountTimeStampRequest atsRequest, final String queryString) { // Arrange: final TestContext context = new TestContext(); final SerializableList<HarvestInfo> originalHarvestInfos = new SerializableList<>(Arrays.asList( new HarvestInfo(Hash.ZERO, new BlockHeight(7), TimeInstant.ZERO, Amount.ZERO), new HarvestInfo(Hash.ZERO, new BlockHeight(5), TimeInstant.ZERO, Amount.ZERO), new HarvestInfo(Hash.ZERO, new BlockHeight(9), TimeInstant.ZERO, Amount.ZERO) )); Mockito.when(context.connector.get(NisApiId.NIS_REST_ACCOUNT_HARVESTS, queryString)) .thenReturn(new JsonDeserializer(JsonSerializer.serializeToJson(originalHarvestInfos), null)); // Act: final SerializableList<HarvestInfoViewModel> harvestInfos = context.controller.getAccountHarvests(atsRequest); // Assert: Mockito.verify(context.connector, Mockito.times(1)).get(NisApiId.NIS_REST_ACCOUNT_HARVESTS, queryString); Assert.assertThat( harvestInfos.asCollection().stream().map(HarvestInfoViewModel::getBlockHeight).collect(Collectors.toList()), IsEqual.equalTo(Arrays.asList(new BlockHeight(7), new BlockHeight(5), new BlockHeight(9)))); } //endregion //region unlock / lock @Test public void unlockDelegatesToNisConnector() { // Assert: assertPrivateKeyConnectorRequest(AccountController::unlock, NisApiId.NIS_REST_ACCOUNT_UNLOCK); } @Test public void lockDelegatesToNisConnector() { // Assert: assertPrivateKeyConnectorRequest(AccountController::lock, NisApiId.NIS_REST_ACCOUNT_LOCK); } private static void assertPrivateKeyConnectorRequest( final BiConsumer<AccountController, AccountWalletRequest> action, final NisApiId apiId) { // Arrange: final TestContext context = new TestContext(); final Wallet wallet = Mockito.mock(Wallet.class); final KeyPair keyPair = new KeyPair(); final Account account = new Account(new KeyPair(keyPair.getPublicKey())); Mockito.when(context.walletServices.get(new WalletName("wallet"))).thenReturn(wallet); Mockito.when(wallet.getAccountPrivateKey(account.getAddress())).thenReturn(keyPair.getPrivateKey()); // Act: action.accept(context.controller, new AccountWalletRequest(account.getAddress(), new WalletName("wallet"))); final ArgumentCaptor<HttpPostRequest> requestCaptor = ArgumentCaptor.forClass(HttpPostRequest.class); Mockito.verify(context.connector, Mockito.times(1)).voidPost(Mockito.eq(apiId), requestCaptor.capture()); final JSONObject jsonRequest = (JSONObject)JSONValue.parse(requestCaptor.getValue().getPayload()); // Assert: Assert.assertThat(jsonRequest.size(), IsEqual.equalTo(1)); Assert.assertThat( jsonRequest.get("value"), IsEqual.equalTo(keyPair.getPrivateKey().toString())); } //endregion private static AccountViewModel createViewModel(final Account account) { return new AccountViewModel(Utils.createAccountInfoFromAddress(account.getAddress()), AccountStatus.LOCKED, null); } private static class TestContext { private final AccountServices accountServices = Mockito.mock(AccountServices.class); private final AccountMapper accountMapper = Mockito.mock(AccountMapper.class); private final WalletServices walletServices = Mockito.mock(WalletServices.class); private final ChainServices chainServices = Mockito.mock(ChainServices.class); private final SimpleNisConnector connector = Mockito.mock(SimpleNisConnector.class); private final AccountController controller = new AccountController( this.accountServices, this.accountMapper, this.walletServices, this.chainServices, this.connector); private TestContext() { this.setLastBlockHeight(1); } private void setLastBlockHeight(final int height) { Mockito.when(this.chainServices.getLastBlockHeightAsync(NodeEndpoint.fromHost("localhost"))) .thenReturn(CompletableFuture.completedFuture(new BlockHeight(height))); } } }
package com.vies.viesmachines.network; import com.vies.viesmachines.api.ItemsVM; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomize; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomizeActiveModels; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomizeDisplayBanner; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomizePrimarySkinColor; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomizePrimarySkinTexture; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomizeSecondarySkinColor; import com.vies.viesmachines.client.gui.machines.customize.GuiMachineMenuCustomizeSecondarySkinTexture; import com.vies.viesmachines.client.gui.machines.customize.display.GuiMachineMenuCustomizeDisplayBlockItemPg1; import com.vies.viesmachines.client.gui.machines.customize.display.GuiMachineMenuCustomizeDisplayEntityHeadPg1; import com.vies.viesmachines.client.gui.machines.customize.display.GuiMachineMenuCustomizeDisplaySupporterHeadPg1; import com.vies.viesmachines.client.gui.machines.customize.display.GuiMachineMenuCustomizeDisplaySymbolPg1; import com.vies.viesmachines.client.gui.machines.customize.holiday.GuiMachineMenuCustomizeDisplaySymbolPg1Holiday; import com.vies.viesmachines.client.gui.machines.customize.holiday.GuiMachineMenuCustomizeDisplaySymbolPg1HolidayCreative; import com.vies.viesmachines.client.gui.machines.customize.holiday.GuiMachineMenuCustomizePrimarySkinTextureHoliday; import com.vies.viesmachines.client.gui.machines.customize.holiday.GuiMachineMenuCustomizePrimarySkinTextureHolidayCreative; import com.vies.viesmachines.client.gui.machines.customize.holiday.GuiMachineMenuCustomizeSecondarySkinTextureHoliday; import com.vies.viesmachines.client.gui.machines.customize.holiday.GuiMachineMenuCustomizeSecondarySkinTextureHolidayCreative; import com.vies.viesmachines.client.gui.machines.main.GuiMachineMenuMain; import com.vies.viesmachines.client.gui.machines.main.GuiMachineMenuMainSelectMusic; import com.vies.viesmachines.client.gui.machines.main.GuiMachineMenuMainSelectName; import com.vies.viesmachines.client.gui.machines.main.GuiMachineMenuMainSelectProjectile; import com.vies.viesmachines.client.gui.machines.stats.GuiMachineMenuStats; import com.vies.viesmachines.client.gui.misc.GuiRadioExpansionSelectMusic; import com.vies.viesmachines.client.gui.tileentity.GuiTileEntityExtractor; import com.vies.viesmachines.client.gui.tileentity.GuiTileEntityKitFabricator; import com.vies.viesmachines.client.gui.tileentity.GuiTileEntityMachineBeacon; import com.vies.viesmachines.client.gui.tileentity.GuiTileEntityMachineTransmogrifier; import com.vies.viesmachines.common.entity.machines.EntityMachineBase; import com.vies.viesmachines.common.entity.machines.containers.ContainerMachineMenuCustomizeDisplayBanner; import com.vies.viesmachines.common.entity.machines.containers.ContainerMachineMenuMain; import com.vies.viesmachines.common.entity.machines.containers.ContainerMachineMenuMainSelectProjectile; import com.vies.viesmachines.common.entity.machines.containers.ContainerMachineNoSlots; import com.vies.viesmachines.common.items.tools.ContainerToolNoSlots; import com.vies.viesmachines.common.tileentity.TileEntityExtractor; import com.vies.viesmachines.common.tileentity.TileEntityKitFabricator; import com.vies.viesmachines.common.tileentity.TileEntityMachineBeacon; import com.vies.viesmachines.common.tileentity.TileEntityMachineTransmogrifier; import com.vies.viesmachines.common.tileentity.containers.ContainerExtractor; import com.vies.viesmachines.common.tileentity.containers.ContainerKitFabricator; import com.vies.viesmachines.common.tileentity.containers.ContainerMachineBeacon; import com.vies.viesmachines.common.tileentity.containers.ContainerMachineTransmogrifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; public class GuiHandler implements IGuiHandler { public static GuiHandler instance; public static final int GUI_MACHINE_MENU_MAIN = 11; public static final int GUI_MACHINE_MENU_MAIN_SELECT_MUSIC = 12; public static final int GUI_MACHINE_MENU_MAIN_CHANGE_NAME = 13; public static final int GUI_MACHINE_MENU_MAIN_SELECT_PROJECTILE = 14; public static final int GUI_MACHINE_MENU_STATS = 15; public static final int GUI_MACHINE_MENU_CUSTOMIZE = 16; public static final int GUI_MACHINE_MENU_CUSTOMIZE_ACTIVE_MODELS = 17; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_BANNER = 18; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1 = 19; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_BLOCKITEM_PG1 = 20; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_HEAD_PG1 = 21; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SUPPORTERHEAD_PG1 = 22; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1_HOLIDAY = 23; public static final int GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1_HOLIDAY_CREATIVE = 24; public static final int GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE = 25; public static final int GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_COLOR = 26; public static final int GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE_HOLIDAY = 27; public static final int GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE_HOLIDAY_CREATIVE = 28; public static final int GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE = 29; public static final int GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_COLOR = 30; public static final int GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE_HOLIDAY = 31; public static final int GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE_HOLIDAY_CREATIVE = 32; public static final int GUI_APPLIANCE_EXTRACTOR= 33; public static final int GUI_APPLIANCE_KIT_FABRICATOR= 34; public static final int GUI_APPLIANCE_MACHINE_TRANSMOGRIFIER= 35; public static final int GUI_APPLIANCE_MACHINE_BEACON= 36; public static final int GUI_TOOL_RADIO_EXPANSION = 37; public GuiHandler() { instance = this; } @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { // Machine main menu: if (ID == GUI_MACHINE_MENU_MAIN) { return new ContainerMachineMenuMain(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine main menu / selecting music: if (ID == GUI_MACHINE_MENU_MAIN_SELECT_MUSIC) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine main menu / selecting name: if (ID == GUI_MACHINE_MENU_MAIN_CHANGE_NAME) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine main menu / selecting projectile: if (ID == GUI_MACHINE_MENU_MAIN_SELECT_PROJECTILE) { return new ContainerMachineMenuMainSelectProjectile(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine stats menu: if (ID == GUI_MACHINE_MENU_STATS) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu: if (ID == GUI_MACHINE_MENU_CUSTOMIZE) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / active models: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_ACTIVE_MODELS) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / display banner: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_BANNER) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / display banner / display symbol pg1: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / blockitem: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_BLOCKITEM_PG1) { return new ContainerMachineMenuCustomizeDisplayBanner(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / display head: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_HEAD_PG1) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / display supporter head: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SUPPORTERHEAD_PG1) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / holiday: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1_HOLIDAY) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / holiday creative: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1_HOLIDAY_CREATIVE) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / primary skin texture: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / primary skin color: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_COLOR) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / primary skin texture / holiday: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE_HOLIDAY) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / primary skin texture / holiday creative: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE_HOLIDAY_CREATIVE) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / secondary skin texture: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / secondary skin color: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_COLOR) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / secondary skin texture / holiday: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE_HOLIDAY) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / secondary skin texture / holiday creative: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE_HOLIDAY_CREATIVE) { return new ContainerMachineNoSlots(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Extractor: if (ID == GUI_APPLIANCE_EXTRACTOR) { return new ContainerExtractor(player.inventory, world, (TileEntityExtractor)world.getTileEntity(new BlockPos(x, y, z))); } // Kit Fabricator: if (ID == GUI_APPLIANCE_KIT_FABRICATOR) { return new ContainerKitFabricator(player.inventory, world, (TileEntityKitFabricator)world.getTileEntity(new BlockPos(x, y, z))); } // Machine Transmogrifier: if (ID == GUI_APPLIANCE_MACHINE_TRANSMOGRIFIER) { return new ContainerMachineTransmogrifier(player.inventory, world, (TileEntityMachineTransmogrifier)world.getTileEntity(new BlockPos(x, y, z))); } // Machine Beacon: if (ID == GUI_APPLIANCE_MACHINE_BEACON) { return new ContainerMachineBeacon(player.inventory, world, (TileEntityMachineBeacon)world.getTileEntity(new BlockPos(x, y, z))); } //----------//----------//----------//----------//----------// // Tool Radio Expansion: if (ID == GUI_TOOL_RADIO_EXPANSION) { return new ContainerToolNoSlots(player.inventory); } return null; } @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { // Machine main menu: if (ID == GUI_MACHINE_MENU_MAIN) { return new GuiMachineMenuMain(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine main menu / selecting music: if (ID == GUI_MACHINE_MENU_MAIN_SELECT_MUSIC) { return new GuiMachineMenuMainSelectMusic(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine main menu / selecting names: if (ID == GUI_MACHINE_MENU_MAIN_CHANGE_NAME) { return new GuiMachineMenuMainSelectName(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine main menu / selecting projectiles: if (ID == GUI_MACHINE_MENU_MAIN_SELECT_PROJECTILE) { return new GuiMachineMenuMainSelectProjectile(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine stats menu: if (ID == GUI_MACHINE_MENU_STATS) { return new GuiMachineMenuStats(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu: if (ID == GUI_MACHINE_MENU_CUSTOMIZE) { return new GuiMachineMenuCustomize(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / active models: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_ACTIVE_MODELS) { return new GuiMachineMenuCustomizeActiveModels(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / display banner: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_BANNER) { return new GuiMachineMenuCustomizeDisplayBanner(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / display banner / display symbol pg1: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1) { return new GuiMachineMenuCustomizeDisplaySymbolPg1(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / blockitem: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_BLOCKITEM_PG1) { return new GuiMachineMenuCustomizeDisplayBlockItemPg1(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / display head: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_HEAD_PG1) { return new GuiMachineMenuCustomizeDisplayEntityHeadPg1(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / display supporter head: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SUPPORTERHEAD_PG1) { return new GuiMachineMenuCustomizeDisplaySupporterHeadPg1(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / holiday: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1_HOLIDAY) { return new GuiMachineMenuCustomizeDisplaySymbolPg1Holiday(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / display banner / holiday creative: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_DISPLAY_SYMBOL_PG1_HOLIDAY_CREATIVE) { return new GuiMachineMenuCustomizeDisplaySymbolPg1HolidayCreative(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / primary skin texture: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE) { return new GuiMachineMenuCustomizePrimarySkinTexture(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / primary skin color: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_COLOR) { return new GuiMachineMenuCustomizePrimarySkinColor(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / primary skin texture / holiday: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE_HOLIDAY) { return new GuiMachineMenuCustomizePrimarySkinTextureHoliday(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / primary skin texture / holiday creative: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_PRIMARY_SKIN_TEXTURE_HOLIDAY_CREATIVE) { return new GuiMachineMenuCustomizePrimarySkinTextureHolidayCreative(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Machine customize menu / secondary skin texture: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE) { return new GuiMachineMenuCustomizeSecondarySkinTexture(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / secondary skin color: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_COLOR) { return new GuiMachineMenuCustomizeSecondarySkinColor(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / secondary skin texture / holiday: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE_HOLIDAY) { return new GuiMachineMenuCustomizeSecondarySkinTextureHoliday(player.inventory, (EntityMachineBase)player.getRidingEntity()); } // Machine customize menu / secondary skin texture / holiday creative: if (ID == GUI_MACHINE_MENU_CUSTOMIZE_SECONDARY_SKIN_TEXTURE_HOLIDAY_CREATIVE) { return new GuiMachineMenuCustomizeSecondarySkinTextureHolidayCreative(player.inventory, (EntityMachineBase)player.getRidingEntity()); } //----------//----------//----------//----------//----------// // Extractor: if (ID == GUI_APPLIANCE_EXTRACTOR) { return new GuiTileEntityExtractor(player.inventory, world, (TileEntityExtractor)world.getTileEntity(new BlockPos(x, y, z))); } // Kit Fabricator: if (ID == GUI_APPLIANCE_KIT_FABRICATOR) { return new GuiTileEntityKitFabricator(player.inventory, world, (TileEntityKitFabricator)world.getTileEntity(new BlockPos(x, y, z))); } // Machine Transmogrifier: if (ID == GUI_APPLIANCE_MACHINE_TRANSMOGRIFIER) { return new GuiTileEntityMachineTransmogrifier(player.inventory, world, (TileEntityMachineTransmogrifier)world.getTileEntity(new BlockPos(x, y, z))); } // Machine Beacon: if (ID == GUI_APPLIANCE_MACHINE_BEACON) { return new GuiTileEntityMachineBeacon(player.inventory, world, (TileEntityMachineBeacon)world.getTileEntity(new BlockPos(x, y, z))); } //----------//----------//----------//----------//----------// // Tool Radio Expansion: if (ID == GUI_TOOL_RADIO_EXPANSION) { return new GuiRadioExpansionSelectMusic(player, new ItemStack(ItemsVM.TOOL_RADIO_EXPANSION)); } return null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.gobblin.service.modules.core; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.typesafe.config.Config; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecExecutor; import org.apache.gobblin.runtime.api.TopologySpec; import org.apache.gobblin.runtime.spec_executorInstance.InMemorySpecExecutor; import org.apache.gobblin.service.ServiceConfigKeys; import org.apache.gobblin.service.modules.flow.IdentityFlowToJobSpecCompiler; import org.apache.gobblin.service.modules.flowgraph.Dag; import org.apache.gobblin.service.modules.spec.JobExecutionPlan; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.PathUtils; public class IdentityFlowToJobSpecCompilerTest { private static final Logger logger = LoggerFactory.getLogger(IdentityFlowToJobSpecCompilerTest.class); private static final String TEST_TEMPLATE_CATALOG_PATH = "/tmp/gobblinTestTemplateCatalog_" + System.currentTimeMillis(); private static final String TEST_TEMPLATE_CATALOG_URI = "file://" + TEST_TEMPLATE_CATALOG_PATH; private static final String TEST_TEMPLATE_NAME = "test.template"; private static final String TEST_TEMPLATE_URI = "FS:///test.template"; private static final String TEST_SOURCE_NAME = "testSource"; private static final String TEST_SINK_NAME = "testSink"; private static final String TEST_FLOW_GROUP = "testFlowGroup"; private static final String TEST_FLOW_NAME = "testFlowName"; private static final String SPEC_STORE_PARENT_DIR = "/tmp/orchestrator/"; private static final String SPEC_DESCRIPTION = "Test Orchestrator"; private static final String SPEC_VERSION = FlowSpec.Builder.DEFAULT_VERSION; private static final String TOPOLOGY_SPEC_STORE_DIR = "/tmp/orchestrator/topologyTestSpecStore_" + System.currentTimeMillis(); private static final String FLOW_SPEC_STORE_DIR = "/tmp/orchestrator/flowTestSpecStore_" + System.currentTimeMillis(); private IdentityFlowToJobSpecCompiler compilerWithTemplateCalague; private IdentityFlowToJobSpecCompiler compilerWithoutTemplateCalague; @BeforeClass public void setup() throws Exception { // Create dir for template catalog setupDir(TEST_TEMPLATE_CATALOG_PATH); // Create template to use in test List<String> templateEntries = new ArrayList<>(); templateEntries.add("testProperty1 = \"testValue1\""); templateEntries.add("testProperty2 = \"test.Value1\""); templateEntries.add("testProperty3 = 100"); FileUtils.writeLines(new File(TEST_TEMPLATE_CATALOG_PATH + "/" + TEST_TEMPLATE_NAME), templateEntries); // Initialize compiler with template catalog Properties compilerWithTemplateCatalogProperties = new Properties(); compilerWithTemplateCatalogProperties.setProperty(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY, TEST_TEMPLATE_CATALOG_URI); this.compilerWithTemplateCalague = new IdentityFlowToJobSpecCompiler(ConfigUtils.propertiesToConfig(compilerWithTemplateCatalogProperties)); // Add a topology to compiler this.compilerWithTemplateCalague.onAddSpec(initTopologySpec()); // Initialize compiler without template catalog this.compilerWithoutTemplateCalague = new IdentityFlowToJobSpecCompiler(ConfigUtils.propertiesToConfig(new Properties())); // Add a topology to compiler this.compilerWithoutTemplateCalague.onAddSpec(initTopologySpec()); } private void setupDir(String dir) throws Exception { FileUtils.forceMkdir(new File(dir)); } private void cleanUpDir(String dir) throws Exception { File specStoreDir = new File(dir); if (specStoreDir.exists()) { FileUtils.deleteDirectory(specStoreDir); } } private TopologySpec initTopologySpec() { Properties properties = new Properties(); properties.put("specStore.fs.dir", TOPOLOGY_SPEC_STORE_DIR); properties.put("specExecInstance.capabilities", TEST_SOURCE_NAME + ":" + TEST_SINK_NAME); Config config = ConfigUtils.propertiesToConfig(properties); SpecExecutor specExecutorInstance = new InMemorySpecExecutor(config); TopologySpec.Builder topologySpecBuilder = TopologySpec.builder(computeTopologySpecURI(SPEC_STORE_PARENT_DIR, TOPOLOGY_SPEC_STORE_DIR)) .withConfig(config) .withDescription(SPEC_DESCRIPTION) .withVersion(SPEC_VERSION) .withSpecExecutor(specExecutorInstance); return topologySpecBuilder.build(); } private FlowSpec initFlowSpec() { return initFlowSpec(TEST_FLOW_GROUP, TEST_FLOW_NAME, TEST_SOURCE_NAME, TEST_SINK_NAME); } private FlowSpec initFlowSpec(String flowGroup, String flowName, String source, String destination) { Properties properties = new Properties(); properties.put(ConfigurationKeys.JOB_SCHEDULE_KEY, "* * * * *"); properties.put(ConfigurationKeys.FLOW_GROUP_KEY, flowGroup); properties.put(ConfigurationKeys.FLOW_NAME_KEY, flowName); properties.put(ServiceConfigKeys.FLOW_SOURCE_IDENTIFIER_KEY, source); properties.put(ServiceConfigKeys.FLOW_DESTINATION_IDENTIFIER_KEY, destination); Config config = ConfigUtils.propertiesToConfig(properties); FlowSpec.Builder flowSpecBuilder = null; try { flowSpecBuilder = FlowSpec.builder(computeTopologySpecURI(SPEC_STORE_PARENT_DIR, FLOW_SPEC_STORE_DIR)) .withConfig(config) .withDescription("dummy description") .withVersion(SPEC_VERSION) .withTemplate(new URI(TEST_TEMPLATE_URI)); } catch (URISyntaxException e) { throw new RuntimeException(e); } return flowSpecBuilder.build(); } public static URI computeTopologySpecURI(String parent, String current) { // Make sure this is relative return PathUtils.relativizePath(new Path(current), new Path(parent)).toUri(); } @AfterClass public void cleanUp() throws Exception { // Cleanup Template Catalog try { cleanUpDir(TEST_TEMPLATE_CATALOG_PATH); } catch (Exception e) { logger.warn("Could not completely cleanup Template catalog dir"); } // Cleanup ToplogySpec Dir try { cleanUpDir(TOPOLOGY_SPEC_STORE_DIR); } catch (Exception e) { logger.warn("Could not completely cleanup ToplogySpec catalog dir"); } // Cleanup FlowSpec Dir try { cleanUpDir(FLOW_SPEC_STORE_DIR); } catch (Exception e) { logger.warn("Could not completely cleanup FlowSpec catalog dir"); } } @Test public void testCompilerWithTemplateCatalog() { FlowSpec flowSpec = initFlowSpec(); // Run compiler on flowSpec Dag<JobExecutionPlan> jobExecutionPlanDag = this.compilerWithTemplateCalague.compileFlow(flowSpec); // Assert pre-requisites Assert.assertNotNull(jobExecutionPlanDag, "Expected non null dag."); Assert.assertTrue(jobExecutionPlanDag.getNodes().size() == 1, "Exepected 1 executor for FlowSpec."); // Assert FlowSpec compilation Dag.DagNode<JobExecutionPlan> dagNode = jobExecutionPlanDag.getStartNodes().get(0); Spec spec = dagNode.getValue().getJobSpec(); Assert.assertTrue(spec instanceof JobSpec, "Expected JobSpec compiled from FlowSpec."); // Assert JobSpec properties JobSpec jobSpec = (JobSpec) spec; Assert.assertEquals(jobSpec.getConfig().getString("testProperty1"), "testValue1"); Assert.assertEquals(jobSpec.getConfig().getString("testProperty2"), "test.Value1"); Assert.assertEquals(jobSpec.getConfig().getString("testProperty3"), "100"); Assert.assertEquals(jobSpec.getConfig().getString(ServiceConfigKeys.FLOW_SOURCE_IDENTIFIER_KEY), TEST_SOURCE_NAME); Assert.assertFalse(jobSpec.getConfig().hasPath(ConfigurationKeys.JOB_SCHEDULE_KEY)); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.JOB_NAME_KEY), TEST_FLOW_NAME); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.JOB_GROUP_KEY), TEST_FLOW_GROUP); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.FLOW_NAME_KEY), TEST_FLOW_NAME); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.FLOW_GROUP_KEY), TEST_FLOW_GROUP); Assert.assertTrue(jobSpec.getConfig().hasPath(ConfigurationKeys.FLOW_EXECUTION_ID_KEY)); //Assert the start node has no children. Assert.assertEquals(jobExecutionPlanDag.getChildren(dagNode).size(), 0); } @Test public void testCompilerWithoutTemplateCatalog() { FlowSpec flowSpec = initFlowSpec(); // Run compiler on flowSpec Dag<JobExecutionPlan> jobExecutionPlanDag = this.compilerWithoutTemplateCalague.compileFlow(flowSpec); // Assert pre-requisites Assert.assertNotNull(jobExecutionPlanDag, "Expected non null dag."); Assert.assertTrue(jobExecutionPlanDag.getNodes().size() == 1, "Exepected 1 executor for FlowSpec."); // Assert FlowSpec compilation Assert.assertEquals(jobExecutionPlanDag.getStartNodes().size(), 1); Dag.DagNode<JobExecutionPlan> dagNode = jobExecutionPlanDag.getStartNodes().get(0); Spec spec = dagNode.getValue().getJobSpec(); Assert.assertTrue(spec instanceof JobSpec, "Expected JobSpec compiled from FlowSpec."); // Assert JobSpec properties JobSpec jobSpec = (JobSpec) spec; Assert.assertTrue(!jobSpec.getConfig().hasPath("testProperty1")); Assert.assertTrue(!jobSpec.getConfig().hasPath("testProperty2")); Assert.assertTrue(!jobSpec.getConfig().hasPath("testProperty3")); Assert.assertEquals(jobSpec.getConfig().getString(ServiceConfigKeys.FLOW_SOURCE_IDENTIFIER_KEY), TEST_SOURCE_NAME); Assert.assertFalse(jobSpec.getConfig().hasPath(ConfigurationKeys.JOB_SCHEDULE_KEY)); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.JOB_NAME_KEY), TEST_FLOW_NAME); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.JOB_GROUP_KEY), TEST_FLOW_GROUP); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.FLOW_NAME_KEY), TEST_FLOW_NAME); Assert.assertEquals(jobSpec.getConfig().getString(ConfigurationKeys.FLOW_GROUP_KEY), TEST_FLOW_GROUP); Assert.assertTrue(jobSpec.getConfig().hasPath(ConfigurationKeys.FLOW_EXECUTION_ID_KEY)); //Assert the start node has no children. Assert.assertEquals(jobExecutionPlanDag.getChildren(dagNode).size(), 0); } @Test public void testNoJobSpecCompilation() { FlowSpec flowSpec = initFlowSpec(TEST_FLOW_GROUP, TEST_FLOW_NAME, "unsupportedSource", "unsupportedSink"); // Run compiler on flowSpec Dag<JobExecutionPlan> jobExecutionPlanDag = this.compilerWithTemplateCalague.compileFlow(flowSpec); // Assert pre-requisites Assert.assertNotNull(jobExecutionPlanDag, "Expected non null dag."); Assert.assertTrue(jobExecutionPlanDag.getNodes().size() == 0, "Exepected 1 executor for FlowSpec."); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.hyracks.dataflow.std.group.external; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import org.apache.hyracks.api.comm.IFrame; import org.apache.hyracks.api.comm.IFrameTupleAccessor; import org.apache.hyracks.api.comm.IFrameWriter; import org.apache.hyracks.api.comm.VSizeFrame; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.IBinaryComparator; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputer; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputerFactory; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.io.FileReference; import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAccessor; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppenderAccessor; import org.apache.hyracks.dataflow.common.io.RunFileReader; import org.apache.hyracks.dataflow.common.io.RunFileWriter; import org.apache.hyracks.dataflow.std.base.AbstractUnaryOutputSourceOperatorNodePushable; import org.apache.hyracks.dataflow.std.group.AggregateState; import org.apache.hyracks.dataflow.std.group.IAggregatorDescriptor; import org.apache.hyracks.dataflow.std.group.IAggregatorDescriptorFactory; import org.apache.hyracks.dataflow.std.group.ISpillableTable; import org.apache.hyracks.dataflow.std.util.ReferenceEntry; import org.apache.hyracks.dataflow.std.util.ReferencedPriorityQueue; class ExternalGroupMergeOperatorNodePushable extends AbstractUnaryOutputSourceOperatorNodePushable { private final IHyracksTaskContext ctx; private final Object stateId; private final int[] keyFields; private final IBinaryComparator[] comparators; private final INormalizedKeyComputer nmkComputer; private final AggregateState aggregateState; private final ArrayTupleBuilder tupleBuilder; private final int[] storedKeys; private final IAggregatorDescriptor aggregator; private final boolean isOutputSorted; private final int framesLimit; private final RecordDescriptor outRecordDescriptor; /** * Input frames, one for each run file. */ private List<IFrame> inFrames; /** * Output frame. */ private IFrame outFrame, writerFrame; private final FrameTupleAppenderAccessor outAppender; private FrameTupleAppender writerAppender; private LinkedList<RunFileReader> runs; private ExternalGroupState aggState; private ArrayTupleBuilder finalTupleBuilder; /** * how many frames to be read ahead once */ private int runFrameLimit = 1; private int[] currentFrameIndexInRun; private int[] currentRunFrames; ExternalGroupMergeOperatorNodePushable(IHyracksTaskContext ctx, Object stateId, IBinaryComparatorFactory[] comparatorFactories, INormalizedKeyComputerFactory nmkFactory, int[] keyFields, IAggregatorDescriptorFactory mergerFactory, boolean isOutputSorted, int framesLimit, RecordDescriptor outRecordDescriptor) throws HyracksDataException { this.stateId = stateId; this.keyFields = keyFields; comparators = new IBinaryComparator[comparatorFactories.length]; for (int i = 0; i < comparatorFactories.length; ++i) { comparators[i] = comparatorFactories[i].createBinaryComparator(); } this.nmkComputer = nmkFactory == null ? null : nmkFactory.createNormalizedKeyComputer(); int[] keyFieldsInPartialResults = new int[keyFields.length]; for (int i = 0; i < keyFieldsInPartialResults.length; i++) { keyFieldsInPartialResults[i] = i; } aggregator = mergerFactory.createAggregator(ctx, outRecordDescriptor, outRecordDescriptor, keyFields, keyFieldsInPartialResults, writer); aggregateState = aggregator.createAggregateStates(); storedKeys = new int[keyFields.length]; /** * Get the list of the fields in the stored records. */ for (int i = 0; i < keyFields.length; ++i) { storedKeys[i] = i; } tupleBuilder = new ArrayTupleBuilder(outRecordDescriptor.getFields().length); this.ctx = ctx; outAppender = new FrameTupleAppenderAccessor(outRecordDescriptor); this.isOutputSorted = isOutputSorted; this.framesLimit = framesLimit; this.outRecordDescriptor = outRecordDescriptor; } @Override public void initialize() throws HyracksDataException { aggState = (ExternalGroupState) ctx.getStateObject(stateId); runs = aggState.getRuns(); try { writer.open(); if (runs.size() <= 0) { ISpillableTable gTable = aggState.getSpillableTable(); if (gTable != null) { if (isOutputSorted) gTable.sortFrames(); gTable.flushFrames(writer, false); } gTable = null; aggState = null; } else { aggState = null; runs = new LinkedList<RunFileReader>(runs); inFrames = new ArrayList<>(); outFrame = new VSizeFrame(ctx); outAppender.reset(outFrame, true); while (runs.size() > 0) { try { doPass(runs); } catch (Exception e) { throw new HyracksDataException(e); } } inFrames.clear(); } } catch (Exception e) { writer.fail(); throw new HyracksDataException(e); } finally { aggregateState.close(); writer.close(); } } private void doPass(LinkedList<RunFileReader> runs) throws HyracksDataException { FileReference newRun = null; IFrameWriter writer = this.writer; boolean finalPass = false; while (inFrames.size() + 2 < framesLimit) { inFrames.add(new VSizeFrame(ctx)); } int runNumber; if (runs.size() + 2 <= framesLimit) { finalPass = true; runFrameLimit = (framesLimit - 2) / runs.size(); runNumber = runs.size(); } else { runNumber = framesLimit - 2; newRun = ctx.getJobletContext().createManagedWorkspaceFile( ExternalGroupOperatorDescriptor.class.getSimpleName()); writer = new RunFileWriter(newRun, ctx.getIOManager()); writer.open(); } try { currentFrameIndexInRun = new int[runNumber]; currentRunFrames = new int[runNumber]; /** * Create file readers for each input run file, only for * the ones fit into the inFrames */ RunFileReader[] runFileReaders = new RunFileReader[runNumber]; FrameTupleAccessor[] tupleAccessors = new FrameTupleAccessor[inFrames.size()]; Comparator<ReferenceEntry> comparator = createEntryComparator(comparators); ReferencedPriorityQueue topTuples = new ReferencedPriorityQueue(runNumber, comparator, keyFields, nmkComputer); /** * current tuple index in each run */ int[] tupleIndices = new int[runNumber]; for (int i = 0; i < runNumber; i++) { int runIndex = topTuples.peek().getRunid(); tupleIndices[runIndex] = 0; // Load the run file runFileReaders[runIndex] = runs.get(runIndex); runFileReaders[runIndex].open(); currentRunFrames[runIndex] = 0; currentFrameIndexInRun[runIndex] = runIndex * runFrameLimit; for (int j = 0; j < runFrameLimit; j++) { int frameIndex = currentFrameIndexInRun[runIndex] + j; if (runFileReaders[runIndex].nextFrame(inFrames.get(frameIndex))) { tupleAccessors[frameIndex] = new FrameTupleAccessor(outRecordDescriptor); tupleAccessors[frameIndex].reset(inFrames.get(frameIndex).getBuffer()); currentRunFrames[runIndex]++; if (j == 0) setNextTopTuple(runIndex, tupleIndices, runFileReaders, tupleAccessors, topTuples); } else { break; } } } /** * Start merging */ while (!topTuples.areRunsExhausted()) { /** * Get the top record */ ReferenceEntry top = topTuples.peek(); int tupleIndex = top.getTupleIndex(); int runIndex = topTuples.peek().getRunid(); IFrameTupleAccessor fta = top.getAccessor(); int currentTupleInOutFrame = outAppender.getTupleCount() - 1; if (currentTupleInOutFrame < 0 || compareFrameTuples(fta, tupleIndex, outAppender, currentTupleInOutFrame) != 0) { /** * Initialize the first output record Reset the * tuple builder */ tupleBuilder.reset(); for (int k = 0; k < storedKeys.length; k++) { tupleBuilder.addField(fta, tupleIndex, storedKeys[k]); } aggregator.init(tupleBuilder, fta, tupleIndex, aggregateState); if (!outAppender.appendSkipEmptyField(tupleBuilder.getFieldEndOffsets(), tupleBuilder.getByteArray(), 0, tupleBuilder.getSize())) { flushOutFrame(writer, finalPass); if (!outAppender.appendSkipEmptyField(tupleBuilder.getFieldEndOffsets(), tupleBuilder.getByteArray(), 0, tupleBuilder.getSize())) { throw new HyracksDataException( "The partial result is too large to be initialized in a frame."); } } } else { /** * if new tuple is in the same group of the * current aggregator do merge and output to the * outFrame */ aggregator.aggregate(fta, tupleIndex, outAppender, currentTupleInOutFrame, aggregateState); } tupleIndices[runIndex]++; setNextTopTuple(runIndex, tupleIndices, runFileReaders, tupleAccessors, topTuples); } if (outAppender.getTupleCount() > 0) { flushOutFrame(writer, finalPass); outAppender.reset(outFrame, true); } aggregator.close(); runs.subList(0, runNumber).clear(); /** * insert the new run file into the beginning of the run * file list */ if (!finalPass) { runs.add(0, ((RunFileWriter) writer).createDeleteOnCloseReader()); } } finally { if (!finalPass) { writer.close(); } } } private void flushOutFrame(IFrameWriter writer, boolean isFinal) throws HyracksDataException { if (finalTupleBuilder == null) { finalTupleBuilder = new ArrayTupleBuilder(outRecordDescriptor.getFields().length); } if (writerFrame == null) { writerFrame = new VSizeFrame(ctx); } if (writerAppender == null) { writerAppender = new FrameTupleAppender(); writerAppender.reset(writerFrame, true); } for (int i = 0; i < outAppender.getTupleCount(); i++) { finalTupleBuilder.reset(); for (int k = 0; k < storedKeys.length; k++) { finalTupleBuilder.addField(outAppender, i, storedKeys[k]); } if (isFinal) { aggregator.outputFinalResult(finalTupleBuilder, outAppender, i, aggregateState); } else { aggregator.outputPartialResult(finalTupleBuilder, outAppender, i, aggregateState); } if (!writerAppender.appendSkipEmptyField(finalTupleBuilder.getFieldEndOffsets(), finalTupleBuilder.getByteArray(), 0, finalTupleBuilder.getSize())) { writerAppender.flush(writer, true); if (!writerAppender.appendSkipEmptyField(finalTupleBuilder.getFieldEndOffsets(), finalTupleBuilder.getByteArray(), 0, finalTupleBuilder.getSize())) { throw new HyracksDataException("Aggregation output is too large to be fit into a frame."); } } } writerAppender.flush(writer, true); } private void setNextTopTuple(int runIndex, int[] tupleIndices, RunFileReader[] runCursors, FrameTupleAccessor[] tupleAccessors, ReferencedPriorityQueue topTuples) throws HyracksDataException { int runStart = runIndex * runFrameLimit; boolean existNext = false; if (tupleAccessors[currentFrameIndexInRun[runIndex]] == null || runCursors[runIndex] == null) { /** * run already closed */ existNext = false; } else if (currentFrameIndexInRun[runIndex] - runStart < currentRunFrames[runIndex] - 1) { /** * not the last frame for this run */ existNext = true; if (tupleIndices[runIndex] >= tupleAccessors[currentFrameIndexInRun[runIndex]].getTupleCount()) { tupleIndices[runIndex] = 0; currentFrameIndexInRun[runIndex]++; } } else if (tupleIndices[runIndex] < tupleAccessors[currentFrameIndexInRun[runIndex]].getTupleCount()) { /** * the last frame has expired */ existNext = true; } else { /** * If all tuples in the targeting frame have been * checked. */ tupleIndices[runIndex] = 0; currentFrameIndexInRun[runIndex] = runStart; /** * read in batch */ currentRunFrames[runIndex] = 0; for (int j = 0; j < runFrameLimit; j++) { int frameIndex = currentFrameIndexInRun[runIndex] + j; if (runCursors[runIndex].nextFrame(inFrames.get(frameIndex))) { tupleAccessors[frameIndex].reset(inFrames.get(frameIndex).getBuffer()); existNext = true; currentRunFrames[runIndex]++; } else { break; } } } if (existNext) { topTuples.popAndReplace(tupleAccessors[currentFrameIndexInRun[runIndex]], tupleIndices[runIndex]); } else { topTuples.pop(); closeRun(runIndex, runCursors, tupleAccessors); } } /** * Close the run file, and also the corresponding readers and * input frame. * * @param index * @param runCursors * @param tupleAccessor * @throws HyracksDataException */ private void closeRun(int index, RunFileReader[] runCursors, IFrameTupleAccessor[] tupleAccessor) throws HyracksDataException { if (runCursors[index] != null) { runCursors[index].close(); runCursors[index] = null; int frameOffset = index * runFrameLimit; for (int j = 0; j < runFrameLimit; j++) { tupleAccessor[frameOffset + j] = null; } } } private int compareFrameTuples(IFrameTupleAccessor fta1, int j1, IFrameTupleAccessor fta2, int j2) throws HyracksDataException { byte[] b1 = fta1.getBuffer().array(); byte[] b2 = fta2.getBuffer().array(); for (int f = 0; f < keyFields.length; ++f) { int fIdx = f; int s1 = fta1.getTupleStartOffset(j1) + fta1.getFieldSlotsLength() + fta1.getFieldStartOffset(j1, fIdx); int l1 = fta1.getFieldLength(j1, fIdx); int s2 = fta2.getTupleStartOffset(j2) + fta2.getFieldSlotsLength() + fta2.getFieldStartOffset(j2, fIdx); int l2_start = fta2.getFieldStartOffset(j2, fIdx); int l2_end = fta2.getFieldEndOffset(j2, fIdx); int l2 = l2_end - l2_start; int c = comparators[f].compare(b1, s1, l1, b2, s2, l2); if (c != 0) { return c; } } return 0; } private Comparator<ReferenceEntry> createEntryComparator(final IBinaryComparator[] comparators) throws HyracksDataException { return new Comparator<ReferenceEntry>() { @Override public int compare(ReferenceEntry o1, ReferenceEntry o2) { FrameTupleAccessor fta1 = (FrameTupleAccessor) o1.getAccessor(); FrameTupleAccessor fta2 = (FrameTupleAccessor) o2.getAccessor(); int j1 = o1.getTupleIndex(); int j2 = o2.getTupleIndex(); byte[] b1 = fta1.getBuffer().array(); byte[] b2 = fta2.getBuffer().array(); for (int f = 0; f < keyFields.length; ++f) { int fIdx = f; int s1 = fta1.getTupleStartOffset(j1) + fta1.getFieldSlotsLength() + fta1.getFieldStartOffset(j1, fIdx); int l1 = fta1.getFieldEndOffset(j1, fIdx) - fta1.getFieldStartOffset(j1, fIdx); int s2 = fta2.getTupleStartOffset(j2) + fta2.getFieldSlotsLength() + fta2.getFieldStartOffset(j2, fIdx); int l2 = fta2.getFieldEndOffset(j2, fIdx) - fta2.getFieldStartOffset(j2, fIdx); int c; try { c = comparators[f].compare(b1, s1, l1, b2, s2, l2); if (c != 0) { return c; } } catch (HyracksDataException e) { throw new IllegalArgumentException(e); } } return 0; } }; } }
/* * Copyright 2016 The Bazel Authors. 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 com.google.idea.blaze.base.wizard2; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Strings; import com.google.idea.blaze.base.bazel.BuildSystemProvider; import com.google.idea.blaze.base.model.primitives.TargetExpression; import com.google.idea.blaze.base.model.primitives.WorkspacePath; import com.google.idea.blaze.base.projectview.ProjectView; import com.google.idea.blaze.base.projectview.parser.ProjectViewParser; import com.google.idea.blaze.base.projectview.section.ListSection; import com.google.idea.blaze.base.projectview.section.sections.DirectoryEntry; import com.google.idea.blaze.base.projectview.section.sections.DirectorySection; import com.google.idea.blaze.base.projectview.section.sections.TargetSection; import com.google.idea.blaze.base.projectview.section.sections.TextBlock; import com.google.idea.blaze.base.projectview.section.sections.TextBlockSection; import com.google.idea.blaze.base.sync.projectview.RelatedWorkspacePathFinder; import com.google.idea.blaze.base.sync.workspace.WorkspacePathResolver; import com.google.idea.blaze.base.ui.BlazeValidationResult; import com.google.idea.blaze.base.ui.UiUtil; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDialog; import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.TextFieldWithStoredHistory; import java.awt.Dimension; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; /** Generates a project view given a BUILD file */ public class GenerateFromBuildFileSelectProjectViewOption implements BlazeSelectProjectViewOption { private static final String LAST_WORKSPACE_PATH = "generate-from-build-file.last-workspace-path"; private final BlazeNewProjectBuilder builder; private final BlazeWizardUserSettings userSettings; private final TextFieldWithStoredHistory buildFilePathField; private final JComponent component; public GenerateFromBuildFileSelectProjectViewOption(BlazeNewProjectBuilder builder) { this.builder = builder; this.userSettings = builder.getUserSettings(); this.buildFilePathField = new TextFieldWithStoredHistory(LAST_WORKSPACE_PATH); buildFilePathField.setHistorySize(BlazeNewProjectBuilder.HISTORY_SIZE); buildFilePathField.setText(userSettings.get(LAST_WORKSPACE_PATH, "")); JButton button = new JButton("..."); button.addActionListener(action -> chooseWorkspacePath()); int buttonSize = buildFilePathField.getPreferredSize().height; button.setPreferredSize(new Dimension(buttonSize, buttonSize)); JComponent box = UiUtil.createHorizontalBox( HORIZONTAL_LAYOUT_GAP, new JLabel("BUILD file:"), buildFilePathField, button); UiUtil.setPreferredWidth(box, PREFERRED_COMPONENT_WIDTH); this.component = box; } @Override public String getOptionName() { return "generate-from-build-file"; } @Override public String getOptionText() { return "Generate from BUILD file"; } @Override public JComponent getUiComponent() { return component; } @Override public BlazeValidationResult validate() { String buildFilePath = getBuildFilePath(); if (buildFilePath.isEmpty()) { return BlazeValidationResult.failure("BUILD file field cannot be empty."); } if (!WorkspacePath.isValid(buildFilePath)) { return BlazeValidationResult.failure( "Invalid BUILD file path: specify a path relative to the workspace root."); } WorkspacePathResolver workspacePathResolver = builder.getWorkspaceOption().getWorkspacePathResolver(); File file = workspacePathResolver.resolveToFile(new WorkspacePath(buildFilePath)); if (!file.exists()) { return BlazeValidationResult.failure("BUILD file does not exist."); } if (file.isDirectory()) { return BlazeValidationResult.failure("Specified path is a directory, not a file"); } BuildSystemProvider buildSystemProvider = BuildSystemProvider.getBuildSystemProvider(builder.getBuildSystem()); checkState(buildSystemProvider != null); if (!buildSystemProvider.isBuildFile(file.getName())) { return BlazeValidationResult.failure("File must be a BUILD file."); } return BlazeValidationResult.success(); } @Nullable @Override public String getInitialProjectViewText() { WorkspacePathResolver workspacePathResolver = builder.getWorkspaceOption().getWorkspacePathResolver(); WorkspacePath workspacePath = new WorkspacePath(Strings.nullToEmpty(new File(getBuildFilePath()).getParent())); return guessProjectViewFromLocation(workspacePathResolver, workspacePath); } @Override public boolean allowAddDefaultProjectViewValues() { return true; } @Override public String getImportDirectory() { File buildFileParent = new File(getBuildFilePath()).getParentFile(); return buildFileParent != null ? buildFileParent.getName() : null; } @Override public void commit() { userSettings.put(LAST_WORKSPACE_PATH, getBuildFilePath()); buildFilePathField.addCurrentTextToHistory(); } private static String guessProjectViewFromLocation( WorkspacePathResolver workspacePathResolver, WorkspacePath workspacePath) { List<WorkspacePath> workspacePaths = new ArrayList<>(); workspacePaths.add(workspacePath); workspacePaths.addAll( RelatedWorkspacePathFinder.getInstance() .findRelatedWorkspaceDirectories(workspacePathResolver, workspacePath)); ListSection.Builder<DirectoryEntry> directorySectionBuilder = ListSection.builder(DirectorySection.KEY); ListSection.Builder<TargetExpression> targetSectionBuilder = ListSection.builder(TargetSection.KEY); workspacePaths.forEach( path -> { directorySectionBuilder.add(DirectoryEntry.include(path)); targetSectionBuilder.add(TargetExpression.allFromPackageRecursive(path)); }); return ProjectViewParser.projectViewToString( ProjectView.builder() .add(directorySectionBuilder) .add(TextBlockSection.of(TextBlock.newLine())) .add(targetSectionBuilder) .add(TextBlockSection.of(TextBlock.newLine())) .build()); } private String getBuildFilePath() { return buildFilePathField.getText().trim(); } private void chooseWorkspacePath() { BuildSystemProvider buildSystem = BuildSystemProvider.getBuildSystemProvider(builder.getBuildSystem()); assert buildSystem != null; FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false) .withShowHiddenFiles(true) // Show root project view file .withHideIgnored(false) .withTitle("Select BUILD File") .withDescription("Select a BUILD file to synthesize a project view from.") .withFileFilter(virtualFile -> buildSystem.isBuildFile(virtualFile.getName())); FileChooserDialog chooser = FileChooserFactory.getInstance().createFileChooser(descriptor, null, null); WorkspacePathResolver workspacePathResolver = builder.getWorkspaceOption().getWorkspacePathResolver(); File fileBrowserRoot = builder.getWorkspaceOption().getFileBrowserRoot(); File startingLocation = fileBrowserRoot; String buildFilePath = getBuildFilePath(); if (!buildFilePath.isEmpty() && WorkspacePath.isValid(buildFilePath)) { // If the user has typed part of the path then clicked the '...', try to start from the // partial state buildFilePath = StringUtil.trimEnd(buildFilePath, '/'); if (WorkspacePath.isValid(buildFilePath)) { File fileLocation = workspacePathResolver.resolveToFile(new WorkspacePath(buildFilePath)); if (fileLocation.exists() && FileUtil.isAncestor(fileBrowserRoot, fileLocation, true)) { startingLocation = fileLocation; } } } VirtualFile toSelect = LocalFileSystem.getInstance().refreshAndFindFileByPath(startingLocation.getPath()); VirtualFile[] files = chooser.choose(null, toSelect); if (files.length == 0) { return; } VirtualFile file = files[0]; if (!FileUtil.isAncestor(fileBrowserRoot.getPath(), file.getPath(), true)) { Messages.showErrorDialog( String.format("You must choose a BUILD file under %s.", fileBrowserRoot.getPath()), "Cannot Use BUILD File"); return; } String newWorkspacePath = FileUtil.getRelativePath(fileBrowserRoot, new File(file.getPath())); buildFilePathField.setText(newWorkspacePath); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.flink.table.factories; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.table.api.AmbiguousTableFactoryException; import org.apache.flink.table.api.NoMatchingTableFactoryException; import org.apache.flink.table.api.TableException; import org.apache.flink.table.descriptors.Descriptor; import org.apache.flink.table.descriptors.FormatDescriptorValidator; import org.apache.flink.table.descriptors.Schema; import org.apache.flink.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import java.util.stream.Collectors; import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_PROPERTY_VERSION; import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_PROPERTY_VERSION; import static org.apache.flink.table.descriptors.FormatDescriptorValidator.FORMAT_PROPERTY_VERSION; /** Unified class to search for a {@link TableFactory} of provided type and properties. */ public class TableFactoryService { private static final Logger LOG = LoggerFactory.getLogger(TableFactoryService.class); /** * Finds a table factory of the given class and descriptor. * * @param factoryClass desired factory class * @param descriptor descriptor describing the factory configuration * @param <T> factory class type * @return the matching factory */ public static <T extends TableFactory> T find(Class<T> factoryClass, Descriptor descriptor) { Preconditions.checkNotNull(descriptor); return findSingleInternal(factoryClass, descriptor.toProperties(), Optional.empty()); } /** * Finds a table factory of the given class, descriptor, and classloader. * * @param factoryClass desired factory class * @param descriptor descriptor describing the factory configuration * @param classLoader classloader for service loading * @param <T> factory class type * @return the matching factory */ public static <T extends TableFactory> T find( Class<T> factoryClass, Descriptor descriptor, ClassLoader classLoader) { Preconditions.checkNotNull(descriptor); Preconditions.checkNotNull(classLoader); return findSingleInternal( factoryClass, descriptor.toProperties(), Optional.of(classLoader)); } /** * Finds a table factory of the given class and property map. * * @param factoryClass desired factory class * @param propertyMap properties that describe the factory configuration * @param <T> factory class type * @return the matching factory */ public static <T extends TableFactory> T find( Class<T> factoryClass, Map<String, String> propertyMap) { return findSingleInternal(factoryClass, propertyMap, Optional.empty()); } /** * Finds a table factory of the given class, property map, and classloader. * * @param factoryClass desired factory class * @param propertyMap properties that describe the factory configuration * @param classLoader classloader for service loading * @param <T> factory class type * @return the matching factory */ public static <T extends TableFactory> T find( Class<T> factoryClass, Map<String, String> propertyMap, ClassLoader classLoader) { Preconditions.checkNotNull(classLoader); return findSingleInternal(factoryClass, propertyMap, Optional.of(classLoader)); } /** * Finds all table factories of the given class and property map. * * @param factoryClass desired factory class * @param propertyMap properties that describe the factory configuration * @param <T> factory class type * @return all the matching factories */ public static <T extends TableFactory> List<T> findAll( Class<T> factoryClass, Map<String, String> propertyMap) { return findAllInternal(factoryClass, propertyMap, Optional.empty()); } /** * Finds a table factory of the given class, property map, and classloader. * * @param factoryClass desired factory class * @param properties properties that describe the factory configuration * @param classLoader classloader for service loading * @param <T> factory class type * @return the matching factory */ private static <T extends TableFactory> T findSingleInternal( Class<T> factoryClass, Map<String, String> properties, Optional<ClassLoader> classLoader) { List<TableFactory> tableFactories = discoverFactories(classLoader); List<T> filtered = filter(tableFactories, factoryClass, properties); if (filtered.size() > 1) { throw new AmbiguousTableFactoryException( filtered, factoryClass, tableFactories, properties); } else { return filtered.get(0); } } /** * Finds a table factory of the given class, property map, and classloader. * * @param factoryClass desired factory class * @param properties properties that describe the factory configuration * @param classLoader classloader for service loading * @param <T> factory class type * @return the matching factory */ private static <T extends TableFactory> List<T> findAllInternal( Class<T> factoryClass, Map<String, String> properties, Optional<ClassLoader> classLoader) { List<TableFactory> tableFactories = discoverFactories(classLoader); return filter(tableFactories, factoryClass, properties); } /** Filters found factories by factory class and with matching context. */ private static <T extends TableFactory> List<T> filter( List<TableFactory> foundFactories, Class<T> factoryClass, Map<String, String> properties) { Preconditions.checkNotNull(factoryClass); Preconditions.checkNotNull(properties); List<T> classFactories = filterByFactoryClass(factoryClass, properties, foundFactories); List<T> contextFactories = filterByContext(factoryClass, properties, classFactories); return filterBySupportedProperties( factoryClass, properties, classFactories, contextFactories); } /** * Searches for factories using Java service providers. * * @return all factories in the classpath */ private static List<TableFactory> discoverFactories(Optional<ClassLoader> classLoader) { try { List<TableFactory> result = new LinkedList<>(); ClassLoader cl = classLoader.orElse(Thread.currentThread().getContextClassLoader()); ServiceLoader.load(TableFactory.class, cl).iterator().forEachRemaining(result::add); return result; } catch (ServiceConfigurationError e) { LOG.error("Could not load service provider for table factories.", e); throw new TableException("Could not load service provider for table factories.", e); } } /** Filters factories with matching context by factory class. */ @SuppressWarnings("unchecked") private static <T> List<T> filterByFactoryClass( Class<T> factoryClass, Map<String, String> properties, List<TableFactory> foundFactories) { List<TableFactory> classFactories = foundFactories.stream() .filter(p -> factoryClass.isAssignableFrom(p.getClass())) .collect(Collectors.toList()); if (classFactories.isEmpty()) { throw new NoMatchingTableFactoryException( String.format("No factory implements '%s'.", factoryClass.getCanonicalName()), factoryClass, foundFactories, properties); } return (List<T>) classFactories; } /** * Filters for factories with matching context. * * @return all matching factories */ private static <T extends TableFactory> List<T> filterByContext( Class<T> factoryClass, Map<String, String> properties, List<T> classFactories) { List<T> matchingFactories = new ArrayList<>(); ContextBestMatched<T> bestMatched = null; for (T factory : classFactories) { Map<String, String> requestedContext = normalizeContext(factory); Map<String, String> plainContext = new HashMap<>(requestedContext); // we remove the version for now until we have the first backwards compatibility case // with the version we can provide mappings in case the format changes plainContext.remove(CONNECTOR_PROPERTY_VERSION); plainContext.remove(FORMAT_PROPERTY_VERSION); plainContext.remove(CATALOG_PROPERTY_VERSION); // check if required context is met Map<String, Tuple2<String, String>> mismatchedProperties = new HashMap<>(); Map<String, String> missingProperties = new HashMap<>(); for (Map.Entry<String, String> e : plainContext.entrySet()) { if (properties.containsKey(e.getKey())) { String fromProperties = properties.get(e.getKey()); if (!Objects.equals(fromProperties, e.getValue())) { mismatchedProperties.put( e.getKey(), new Tuple2<>(e.getValue(), fromProperties)); } } else { missingProperties.put(e.getKey(), e.getValue()); } } int matchedSize = plainContext.size() - mismatchedProperties.size() - missingProperties.size(); if (matchedSize == plainContext.size()) { matchingFactories.add(factory); } else { if (bestMatched == null || matchedSize > bestMatched.matchedSize) { bestMatched = new ContextBestMatched<>( factory, matchedSize, mismatchedProperties, missingProperties); } } } if (matchingFactories.isEmpty()) { String bestMatchedMessage = null; if (bestMatched != null && bestMatched.matchedSize > 0) { StringBuilder builder = new StringBuilder(); builder.append(bestMatched.factory.getClass().getName()); if (bestMatched.missingProperties.size() > 0) { builder.append("\nMissing properties:"); bestMatched.missingProperties.forEach( (k, v) -> builder.append("\n").append(k).append("=").append(v)); } if (bestMatched.mismatchedProperties.size() > 0) { builder.append("\nMismatched properties:"); bestMatched.mismatchedProperties.entrySet().stream() .filter(e -> e.getValue().f1 != null) .forEach( e -> builder.append( String.format( "\n'%s' expects '%s', but is '%s'", e.getKey(), e.getValue().f0, e.getValue().f1))); } bestMatchedMessage = builder.toString(); } //noinspection unchecked throw new NoMatchingTableFactoryException( "Required context properties mismatch.", bestMatchedMessage, factoryClass, (List<TableFactory>) classFactories, properties); } return matchingFactories; } private static class ContextBestMatched<T extends TableFactory> { private final T factory; private final int matchedSize; /** Key -> (value in factory, value in properties). */ private final Map<String, Tuple2<String, String>> mismatchedProperties; /** Key -> value in factory. */ private final Map<String, String> missingProperties; private ContextBestMatched( T factory, int matchedSize, Map<String, Tuple2<String, String>> mismatchedProperties, Map<String, String> missingProperties) { this.factory = factory; this.matchedSize = matchedSize; this.mismatchedProperties = mismatchedProperties; this.missingProperties = missingProperties; } } /** Prepares the properties of a context to be used for match operations. */ private static Map<String, String> normalizeContext(TableFactory factory) { Map<String, String> requiredContext = factory.requiredContext(); if (requiredContext == null) { throw new TableException( String.format( "Required context of factory '%s' must not be null.", factory.getClass().getName())); } return requiredContext.keySet().stream() .collect(Collectors.toMap(String::toLowerCase, requiredContext::get)); } /** Filters the matching class factories by supported properties. */ private static <T extends TableFactory> List<T> filterBySupportedProperties( Class<T> factoryClass, Map<String, String> properties, List<T> classFactories, List<T> contextFactories) { final List<String> plainGivenKeys = new LinkedList<>(); properties .keySet() .forEach( k -> { // replace arrays with wildcard String key = k.replaceAll(".\\d+", ".#"); // ignore duplicates if (!plainGivenKeys.contains(key)) { plainGivenKeys.add(key); } }); List<T> supportedFactories = new LinkedList<>(); Tuple2<T, List<String>> bestMatched = null; for (T factory : contextFactories) { Set<String> requiredContextKeys = normalizeContext(factory).keySet(); Tuple2<List<String>, List<String>> tuple2 = normalizeSupportedProperties(factory); // ignore context keys List<String> givenContextFreeKeys = plainGivenKeys.stream() .filter(p -> !requiredContextKeys.contains(p)) .collect(Collectors.toList()); List<String> givenFilteredKeys = filterSupportedPropertiesFactorySpecific(factory, givenContextFreeKeys); boolean allTrue = true; List<String> unsupportedKeys = new ArrayList<>(); for (String k : givenFilteredKeys) { if (!(tuple2.f0.contains(k) || tuple2.f1.stream().anyMatch(k::startsWith))) { allTrue = false; unsupportedKeys.add(k); } } if (allTrue) { supportedFactories.add(factory); } else { if (bestMatched == null || unsupportedKeys.size() < bestMatched.f1.size()) { bestMatched = new Tuple2<>(factory, unsupportedKeys); } } } if (supportedFactories.isEmpty()) { String bestMatchedMessage = null; if (bestMatched != null) { bestMatchedMessage = String.format( "%s\nUnsupported property keys:\n%s", bestMatched.f0.getClass().getName(), String.join("\n", bestMatched.f1)); } //noinspection unchecked throw new NoMatchingTableFactoryException( "No factory supports all properties.", bestMatchedMessage, factoryClass, (List<TableFactory>) classFactories, properties); } return supportedFactories; } /** Prepares the supported properties of a factory to be used for match operations. */ private static Tuple2<List<String>, List<String>> normalizeSupportedProperties( TableFactory factory) { List<String> supportedProperties = factory.supportedProperties(); if (supportedProperties == null) { throw new TableException( String.format( "Supported properties of factory '%s' must not be null.", factory.getClass().getName())); } List<String> supportedKeys = supportedProperties.stream().map(String::toLowerCase).collect(Collectors.toList()); // extract wildcard prefixes List<String> wildcards = extractWildcardPrefixes(supportedKeys); return Tuple2.of(supportedKeys, wildcards); } /** Converts the prefix of properties with wildcards (e.g., "format.*"). */ private static List<String> extractWildcardPrefixes(List<String> propertyKeys) { return propertyKeys.stream() .filter(p -> p.endsWith("*")) .map(s -> s.substring(0, s.length() - 1)) .collect(Collectors.toList()); } /** * Performs filtering for special cases (i.e. table format factories with schema derivation). */ private static List<String> filterSupportedPropertiesFactorySpecific( TableFactory factory, List<String> keys) { if (factory instanceof TableFormatFactory) { boolean includeSchema = ((TableFormatFactory) factory).supportsSchemaDerivation(); return keys.stream() .filter( k -> { if (includeSchema) { return k.startsWith(Schema.SCHEMA + ".") || k.startsWith(FormatDescriptorValidator.FORMAT + "."); } else { return k.startsWith(FormatDescriptorValidator.FORMAT + "."); } }) .collect(Collectors.toList()); } else { return keys; } } }
/* * ============================================================================= * * Copyright (c) 2012-2014, The ATTOPARSER team (http://www.attoparser.org) * * 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.attoparser.dom; import java.io.IOException; import java.io.Writer; import java.util.Map; /** * <p> * Static utility class able to write a DOM tree (or a fragment of it) as markup. * </p> * * @author Daniel Fern&aacute;ndez * * @since 2.0.0 * */ public final class DOMWriter { public static void write(final INode node, final Writer writer) throws IOException { if (node == null) { return; } if (node instanceof Text) { writeText((Text)node, writer); return; } if (node instanceof Element) { writeElement((Element)node, writer); return; } if (node instanceof Comment) { writeComment((Comment)node, writer); return; } if (node instanceof CDATASection) { writeCDATASection((CDATASection)node, writer); return; } if (node instanceof DocType) { writeDocType((DocType)node, writer); return; } if (node instanceof Document) { writeDocument((Document)node, writer); return; } if (node instanceof XmlDeclaration) { writeXmlDeclaration((XmlDeclaration)node, writer); return; } if (node instanceof ProcessingInstruction) { writeProcessingInstruction((ProcessingInstruction)node, writer); return; } } public static void writeCDATASection(final CDATASection cdataSection, final Writer writer) throws IOException{ writer.write("<![CDATA["); writer.write(cdataSection.getContent()); writer.write("]]>"); } public static void writeComment(final Comment comment, final Writer writer) throws IOException { writer.write("<!--"); writer.write(comment.getContent()); writer.write("-->"); } public static void writeDocType(final DocType docType, final Writer writer) throws IOException { writer.write("<!DOCTYPE "); writer.write(docType.getRootElementName()); final String publicId = docType.getPublicId(); final String systemId = docType.getSystemId(); final String internalSubset = docType.getInternalSubset(); if (publicId != null || systemId != null) { final String type = (publicId == null? "SYSTEM" : "PUBLIC"); writer.write(' '); writer.write(type); if (publicId != null) { writer.write(' '); writer.write('"'); writer.write(publicId); writer.write('"'); } if (systemId != null) { writer.write(' '); writer.write('"'); writer.write(systemId); writer.write('"'); } } if (internalSubset != null) { writer.write(' '); writer.write('['); writer.write(internalSubset); writer.write(']'); } writer.write('>'); } public static void writeDocument(final Document document, final Writer writer) throws IOException { if (!document.hasChildren()) { return; } for (final INode child : document.getChildren()) { write(child, writer); } } public static void writeElement(final Element element, final Writer writer) throws IOException { writer.write('<'); writer.write(element.getElementName()); if (element.hasAttributes()) { final Map<String,String> attributes = element.getAttributeMap(); for (final Map.Entry<String,String> attributeEntry : attributes.entrySet()) { writer.write(' '); writer.write(attributeEntry.getKey()); writer.write('='); writer.write('"'); writer.write(attributeEntry.getValue()); writer.write('"'); } } if (!element.hasChildren()) { writer.write('/'); writer.write('>'); return; } writer.write('>'); for (final INode child : element.getChildren()) { write(child, writer); } writer.write('<'); writer.write('/'); writer.write(element.getElementName()); writer.write('>'); } public static void writeProcessingInstruction( final ProcessingInstruction processingInstruction, final Writer writer) throws IOException { writer.write('<'); writer.write('?'); writer.write(processingInstruction.getTarget()); final String content = processingInstruction.getContent(); if (content != null) { writer.write(' '); writer.write(content); } writer.write('?'); writer.write('>'); } public static void writeText(final Text text, final Writer writer) throws IOException { validateNotNull(text, "Text node cannot be null"); validateNotNull(writer, "Writer cannot be null"); writer.write(text.getContent()); } public static void writeXmlDeclaration(final XmlDeclaration xmlDeclaration, final Writer writer) throws IOException { validateNotNull(xmlDeclaration, "XML declaration cannot be null"); validateNotNull(writer, "Writer cannot be null"); writer.write("<?xml version=\""); writer.write(xmlDeclaration.getVersion()); writer.write('"'); final String encoding = xmlDeclaration.getEncoding(); if (encoding != null) { writer.write(" encoding=\""); writer.write(encoding); writer.write('"'); } final String standalone = xmlDeclaration.getStandalone(); if (standalone != null) { writer.write(" standalone=\""); writer.write(standalone); writer.write('"'); } writer.write('?'); writer.write('>'); } private static void validateNotNull(final Object obj, final String message) { if (obj == null) { throw new IllegalArgumentException(message); } } private DOMWriter() { super(); } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.text.annotator; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSTaggerME; import opennlp.uima.postag.POSModelResource; import opennlp.uima.postag.POSModelResourceImpl; import opennlp.uima.util.AnnotationComboIterator; import opennlp.uima.util.AnnotationIteratorPair; import opennlp.uima.util.AnnotatorUtil; import opennlp.uima.util.UimaUtil; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Feature; import org.apache.uima.cas.Type; import org.apache.uima.cas.TypeSystem; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.fit.component.CasAnnotator_ImplBase; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.ExternalResourceFactory; import org.apache.uima.resource.ResourceAccessException; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.Level; import org.apache.uima.util.Logger; import org.cleartk.token.type.Sentence; import org.cleartk.token.type.Token; import org.deeplearning4j.text.movingwindow.Util; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class PoStagger extends CasAnnotator_ImplBase { static { //UIMA logging Util.disableLogging(); } private POSTaggerME posTagger; private Type sentenceType; private Type tokenType; private Feature posFeature; private Feature probabilityFeature; private UimaContext context; private Logger logger; /** * Initializes a new instance. * * Note: Use {@link #initialize(UimaContext) } to initialize this instance. Not use the * constructor. */ public PoStagger() { // must not be implemented ! } /** * Initializes the current instance with the given context. * * Note: Do all initialization in this method, do not use the constructor. */ @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); this.context = context; this.logger = context.getLogger(); if (this.logger.isLoggable(Level.INFO)) { this.logger.log(Level.INFO, "Initializing the OpenNLP " + "Part of Speech annotator."); } POSModel model; try { POSModelResource modelResource = (POSModelResource) context.getResourceObject(UimaUtil.MODEL_PARAMETER); model = modelResource.getModel(); } catch (ResourceAccessException e) { throw new ResourceInitializationException(e); } Integer beamSize = AnnotatorUtil.getOptionalIntegerParameter(context, UimaUtil.BEAM_SIZE_PARAMETER); if (beamSize == null) beamSize = POSTaggerME.DEFAULT_BEAM_SIZE; this.posTagger = new POSTaggerME(model, beamSize, 0); } /** * Initializes the type system. */ @Override public void typeSystemInit(TypeSystem typeSystem) throws AnalysisEngineProcessException { // sentence type this.sentenceType = AnnotatorUtil.getRequiredTypeParameter(this.context, typeSystem, UimaUtil.SENTENCE_TYPE_PARAMETER); // token type this.tokenType = AnnotatorUtil.getRequiredTypeParameter(this.context, typeSystem, UimaUtil.TOKEN_TYPE_PARAMETER); // pos feature this.posFeature = AnnotatorUtil.getRequiredFeatureParameter(this.context, this.tokenType, UimaUtil.POS_FEATURE_PARAMETER, CAS.TYPE_NAME_STRING); this.probabilityFeature = AnnotatorUtil.getOptionalFeatureParameter(this.context, this.tokenType, UimaUtil.PROBABILITY_FEATURE_PARAMETER, CAS.TYPE_NAME_DOUBLE); } /** * Performs pos-tagging on the given tcas object. */ @Override public synchronized void process(CAS tcas) { final AnnotationComboIterator comboIterator = new AnnotationComboIterator(tcas, this.sentenceType, this.tokenType); for (AnnotationIteratorPair annotationIteratorPair : comboIterator) { final List<AnnotationFS> sentenceTokenAnnotationList = new LinkedList<>(); final List<String> sentenceTokenList = new LinkedList<>(); for (AnnotationFS tokenAnnotation : annotationIteratorPair.getSubIterator()) { sentenceTokenAnnotationList.add(tokenAnnotation); sentenceTokenList.add(tokenAnnotation.getCoveredText()); } final List<String> posTags = this.posTagger.tag(sentenceTokenList); double posProbabilities[] = null; if (this.probabilityFeature != null) { posProbabilities = this.posTagger.probs(); } final Iterator<String> posTagIterator = posTags.iterator(); final Iterator<AnnotationFS> sentenceTokenIterator = sentenceTokenAnnotationList.iterator(); int index = 0; while (posTagIterator.hasNext() && sentenceTokenIterator.hasNext()) { final String posTag = posTagIterator.next(); final AnnotationFS tokenAnnotation = sentenceTokenIterator.next(); tokenAnnotation.setStringValue(this.posFeature, posTag); if (posProbabilities != null) { tokenAnnotation.setDoubleValue(this.posFeature, posProbabilities[index]); } index++; } // log tokens with pos if (this.logger.isLoggable(Level.FINER)) { final StringBuilder sentenceWithPos = new StringBuilder(); sentenceWithPos.append("\""); for (final Iterator<AnnotationFS> it = sentenceTokenAnnotationList.iterator(); it.hasNext();) { final AnnotationFS token = it.next(); sentenceWithPos.append(token.getCoveredText()); sentenceWithPos.append('\\'); sentenceWithPos.append(token.getStringValue(this.posFeature)); sentenceWithPos.append(' '); } // delete last whitespace if (sentenceWithPos.length() > 1) // not 0 because it contains already the " char sentenceWithPos.setLength(sentenceWithPos.length() - 1); sentenceWithPos.append("\""); this.logger.log(Level.FINER, sentenceWithPos.toString()); } } } /** * Releases allocated resources. */ @Override public void destroy() { this.posTagger = null; } public static AnalysisEngineDescription getDescription(String languageCode) throws ResourceInitializationException { String modelPath = String.format("/models/%s-pos-maxent.bin", languageCode); return AnalysisEngineFactory.createEngineDescription(PoStagger.class, opennlp.uima.util.UimaUtil.MODEL_PARAMETER, ExternalResourceFactory.createExternalResourceDescription(POSModelResourceImpl.class, PoStagger.class.getResource(modelPath).toString()), opennlp.uima.util.UimaUtil.SENTENCE_TYPE_PARAMETER, Sentence.class.getName(), opennlp.uima.util.UimaUtil.TOKEN_TYPE_PARAMETER, Token.class.getName(), opennlp.uima.util.UimaUtil.POS_FEATURE_PARAMETER, "pos"); } }
/* * Copyright (c) 2005-2014, 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.andes.server.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.AMQException; import org.wso2.andes.framing.ContentHeaderBody; import org.wso2.andes.framing.abstraction.MessagePublishInfo; import org.wso2.andes.kernel.ProtocolMessage; import org.wso2.andes.server.AMQChannel; import org.wso2.andes.kernel.slot.Slot; import org.wso2.andes.server.store.StoredMessage; import org.wso2.andes.configuration.qpid.SessionConfig; import org.wso2.andes.server.queue.AMQQueue; import java.util.concurrent.atomic.AtomicInteger; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; /** * A deliverable message. */ public class AMQMessage implements ServerMessage { /** Used for debugging purposes. */ private static final Log _log = LogFactory.getLog(AMQMessage.class); private final AtomicInteger _referenceCount = new AtomicInteger(0); /** Flag to indicate that this message requires 'immediate' delivery. */ private static final byte IMMEDIATE = 0x01; /** * Flag to indicate whether this message has been delivered to a consumer. Used in implementing return functionality * for messages published with the 'immediate' flag. */ private static final byte DELIVERED_TO_CONSUMER = 0x02; private byte _flags = 0; private long _expiration; private final long _size; private ProtocolMessage andesMetadataRef; private Object _sessionIdentifier; private static final byte IMMEDIATE_AND_DELIVERED = (byte) (IMMEDIATE | DELIVERED_TO_CONSUMER); private final StoredMessage<MessageMetaData> _handle; WeakReference<AMQChannel> _channelRef; private boolean isTopicMessage = false; private long publisherSessionID; public AMQMessage(StoredMessage<MessageMetaData> handle) { this(handle, null); } public AMQMessage(StoredMessage<MessageMetaData> handle, WeakReference<AMQChannel> channelRef) { _handle = handle; final MessageMetaData metaData = handle.getMetaData(); _size = metaData.getContentSize(); final MessagePublishInfo messagePublishInfo = metaData.getMessagePublishInfo(); if(messagePublishInfo.isImmediate()) { _flags |= IMMEDIATE; } _channelRef = channelRef; } public void setAndesMetadataReference(ProtocolMessage andesMetadataReference) { this.andesMetadataRef = andesMetadataReference; } public ProtocolMessage getAndesMetadataReference() { return andesMetadataRef; } public String debugIdentity() { return "(HC:" + System.identityHashCode(this) + " ID:" + getMessageId() + " Ref:" + _referenceCount.get() + ")"; } public void setExpiration(final long expiration) { _expiration = expiration; } public boolean isReferenced() { return _referenceCount.get() > 0; } public MessageMetaData getMessageMetaData() { return _handle.getMetaData(); } public ContentHeaderBody getContentHeaderBody() throws AMQException { return getMessageMetaData().getContentHeaderBody(); } public Long getMessageId() { return _handle.getMessageNumber(); } public Slot getSlot(){ return _handle.getSlot(); } /** * Creates a long-lived reference to this message, and increments the count of such references, as an atomic * operation. */ public AMQMessage takeReference() { incrementReference(); // _referenceCount.incrementAndGet(); return this; } public boolean incrementReference() { return incrementReference(1); } /* Threadsafe. Increment the reference count on the message. */ public boolean incrementReference(int count) { if(_referenceCount.addAndGet(count) <= 0) { _referenceCount.addAndGet(-count); return false; } else { return true; } } /** * Threadsafe. This will decrement the reference count and when it reaches zero will remove the message from the * message store. * * * @throws org.wso2.andes.server.queue.MessageCleanupException when an attempt was made to remove the message from the message store and that * failed */ public void decrementReference() { int count = _referenceCount.decrementAndGet(); // note that the operation of decrementing the reference count and then removing the message does not // have to be atomic since the ref count starts at 1 and the exchange itself decrements that after // the message has been passed to all queues. i.e. we are // not relying on the all the increments having taken place before the delivery manager decrements. if (count == 0) { // set the reference count way below 0 so that we can detect that the message has been deleted // this is to guard against the message being spontaneously recreated (from the mgmt console) // by copying from other queues at the same time as it is being removed. _referenceCount.set(Integer.MIN_VALUE/2); // must check if the handle is null since there may be cases where we decide to throw away a message // and the handle has not yet been constructed if (_handle != null) { _handle.remove(); } } /* Removing this else close since it is happening when same massages is tried to discard with two paths 1. SimpleAMQQueue - When ack received 2. AMQ Channel - When unsubscribed else { if (count < 0) { throw new RuntimeException("Reference count for message id " + debugIdentity() + " has gone below 0."); } }*/ } /** * Called selectors to determin if the message has already been sent * * @return _deliveredToConsumer */ public boolean getDeliveredToConsumer() { return (_flags & DELIVERED_TO_CONSUMER) != 0; } public String getRoutingKey() { return getMessageMetaData().getMessagePublishInfo().getRoutingKey().toString(); } public AMQMessageHeader getMessageHeader() { return getMessageMetaData().getMessageHeader(); } public boolean isPersistent() { return getMessageMetaData().isPersistent(); } /** * Called to enforce the 'immediate' flag. * * @returns true if the message is marked for immediate delivery but has not been marked as delivered * to a consumer */ public boolean immediateAndNotDelivered() { return (_flags & IMMEDIATE_AND_DELIVERED) == IMMEDIATE; } public MessagePublishInfo getMessagePublishInfo() throws AMQException { return getMessageMetaData().getMessagePublishInfo(); } public long getArrivalTime() { return getMessageMetaData().getArrivalTime(); } /** * Checks to see if the message has expired. If it has the message is dequeued. * * @param queue The queue to check the expiration against. (Currently not used) * * @return true if the message has expire * * @throws AMQException */ public boolean expired(AMQQueue queue) throws AMQException { if (_expiration != 0L) { long now = System.currentTimeMillis(); return (now > _expiration); } return false; } /** * Called when this message is delivered to a consumer. (used to implement the 'immediate' flag functionality). * And for selector efficiency. */ public void setDeliveredToConsumer() { _flags |= DELIVERED_TO_CONSUMER; } public long getSize() { return _size; } public boolean isImmediate() { return (_flags & IMMEDIATE) == IMMEDIATE; } public long getExpiration() { return _expiration; } public MessageReference newReference() { return new AMQMessageReference(this); } public Long getMessageNumber() { return getMessageId(); } public Object getPublisherIdentifier() { //todo store sessionIdentifier/client id with message in store //Currently the _sessionIdentifier will be null if the message has been // restored from a message Store return _sessionIdentifier; } public void setClientIdentifier(final Object sessionIdentifier) { _sessionIdentifier = sessionIdentifier; } public String toString() { // return "Message[" + debugIdentity() + "]: " + _messageId + "; ref count: " + _referenceCount + "; taken : " + // _taken + " by :" + _takenBySubcription; return "Message[" + debugIdentity() + "]: " + getMessageId() + "; ref count: " + _referenceCount; } public int getContent(ByteBuffer buf, int offset) { return _handle.getContent(offset, buf); } public StoredMessage<MessageMetaData> getStoredMessage() { return _handle; } public SessionConfig getSessionConfig() { return _channelRef == null ? null : ((SessionConfig) _channelRef.get()); } public long getPublisherSessionID() { return publisherSessionID; } public void setPublisherSessionID(long publisherSessionID) { this.publisherSessionID = publisherSessionID; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: encrypted_app_ticket.proto package com.jsteamkit.internals.proto; public final class EncryptedAppTicketOuterClass { private EncryptedAppTicketOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface EncryptedAppTicketOrBuilder extends // @@protoc_insertion_point(interface_extends:EncryptedAppTicket) com.google.protobuf.MessageOrBuilder { /** * <code>optional uint32 ticket_version_no = 1;</code> */ boolean hasTicketVersionNo(); /** * <code>optional uint32 ticket_version_no = 1;</code> */ int getTicketVersionNo(); /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ boolean hasCrcEncryptedticket(); /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ int getCrcEncryptedticket(); /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ boolean hasCbEncrypteduserdata(); /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ int getCbEncrypteduserdata(); /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ boolean hasCbEncryptedAppownershipticket(); /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ int getCbEncryptedAppownershipticket(); /** * <code>optional bytes encrypted_ticket = 5;</code> */ boolean hasEncryptedTicket(); /** * <code>optional bytes encrypted_ticket = 5;</code> */ com.google.protobuf.ByteString getEncryptedTicket(); } /** * Protobuf type {@code EncryptedAppTicket} */ public static final class EncryptedAppTicket extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:EncryptedAppTicket) EncryptedAppTicketOrBuilder { private static final long serialVersionUID = 0L; // Use EncryptedAppTicket.newBuilder() to construct. private EncryptedAppTicket(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private EncryptedAppTicket() { ticketVersionNo_ = 0; crcEncryptedticket_ = 0; cbEncrypteduserdata_ = 0; cbEncryptedAppownershipticket_ = 0; encryptedTicket_ = com.google.protobuf.ByteString.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private EncryptedAppTicket( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; ticketVersionNo_ = input.readUInt32(); break; } case 16: { bitField0_ |= 0x00000002; crcEncryptedticket_ = input.readUInt32(); break; } case 24: { bitField0_ |= 0x00000004; cbEncrypteduserdata_ = input.readUInt32(); break; } case 32: { bitField0_ |= 0x00000008; cbEncryptedAppownershipticket_ = input.readUInt32(); break; } case 42: { bitField0_ |= 0x00000010; encryptedTicket_ = input.readBytes(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return EncryptedAppTicketOuterClass.internal_static_EncryptedAppTicket_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return EncryptedAppTicketOuterClass.internal_static_EncryptedAppTicket_fieldAccessorTable .ensureFieldAccessorsInitialized( EncryptedAppTicketOuterClass.EncryptedAppTicket.class, EncryptedAppTicketOuterClass.EncryptedAppTicket.Builder.class); } private int bitField0_; public static final int TICKET_VERSION_NO_FIELD_NUMBER = 1; private int ticketVersionNo_; /** * <code>optional uint32 ticket_version_no = 1;</code> */ public boolean hasTicketVersionNo() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional uint32 ticket_version_no = 1;</code> */ public int getTicketVersionNo() { return ticketVersionNo_; } public static final int CRC_ENCRYPTEDTICKET_FIELD_NUMBER = 2; private int crcEncryptedticket_; /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ public boolean hasCrcEncryptedticket() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ public int getCrcEncryptedticket() { return crcEncryptedticket_; } public static final int CB_ENCRYPTEDUSERDATA_FIELD_NUMBER = 3; private int cbEncrypteduserdata_; /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ public boolean hasCbEncrypteduserdata() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ public int getCbEncrypteduserdata() { return cbEncrypteduserdata_; } public static final int CB_ENCRYPTED_APPOWNERSHIPTICKET_FIELD_NUMBER = 4; private int cbEncryptedAppownershipticket_; /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ public boolean hasCbEncryptedAppownershipticket() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ public int getCbEncryptedAppownershipticket() { return cbEncryptedAppownershipticket_; } public static final int ENCRYPTED_TICKET_FIELD_NUMBER = 5; private com.google.protobuf.ByteString encryptedTicket_; /** * <code>optional bytes encrypted_ticket = 5;</code> */ public boolean hasEncryptedTicket() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional bytes encrypted_ticket = 5;</code> */ public com.google.protobuf.ByteString getEncryptedTicket() { return encryptedTicket_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeUInt32(1, ticketVersionNo_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeUInt32(2, crcEncryptedticket_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeUInt32(3, cbEncrypteduserdata_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeUInt32(4, cbEncryptedAppownershipticket_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeBytes(5, encryptedTicket_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, ticketVersionNo_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(2, crcEncryptedticket_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(3, cbEncrypteduserdata_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(4, cbEncryptedAppownershipticket_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(5, encryptedTicket_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof EncryptedAppTicketOuterClass.EncryptedAppTicket)) { return super.equals(obj); } EncryptedAppTicketOuterClass.EncryptedAppTicket other = (EncryptedAppTicketOuterClass.EncryptedAppTicket) obj; boolean result = true; result = result && (hasTicketVersionNo() == other.hasTicketVersionNo()); if (hasTicketVersionNo()) { result = result && (getTicketVersionNo() == other.getTicketVersionNo()); } result = result && (hasCrcEncryptedticket() == other.hasCrcEncryptedticket()); if (hasCrcEncryptedticket()) { result = result && (getCrcEncryptedticket() == other.getCrcEncryptedticket()); } result = result && (hasCbEncrypteduserdata() == other.hasCbEncrypteduserdata()); if (hasCbEncrypteduserdata()) { result = result && (getCbEncrypteduserdata() == other.getCbEncrypteduserdata()); } result = result && (hasCbEncryptedAppownershipticket() == other.hasCbEncryptedAppownershipticket()); if (hasCbEncryptedAppownershipticket()) { result = result && (getCbEncryptedAppownershipticket() == other.getCbEncryptedAppownershipticket()); } result = result && (hasEncryptedTicket() == other.hasEncryptedTicket()); if (hasEncryptedTicket()) { result = result && getEncryptedTicket() .equals(other.getEncryptedTicket()); } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasTicketVersionNo()) { hash = (37 * hash) + TICKET_VERSION_NO_FIELD_NUMBER; hash = (53 * hash) + getTicketVersionNo(); } if (hasCrcEncryptedticket()) { hash = (37 * hash) + CRC_ENCRYPTEDTICKET_FIELD_NUMBER; hash = (53 * hash) + getCrcEncryptedticket(); } if (hasCbEncrypteduserdata()) { hash = (37 * hash) + CB_ENCRYPTEDUSERDATA_FIELD_NUMBER; hash = (53 * hash) + getCbEncrypteduserdata(); } if (hasCbEncryptedAppownershipticket()) { hash = (37 * hash) + CB_ENCRYPTED_APPOWNERSHIPTICKET_FIELD_NUMBER; hash = (53 * hash) + getCbEncryptedAppownershipticket(); } if (hasEncryptedTicket()) { hash = (37 * hash) + ENCRYPTED_TICKET_FIELD_NUMBER; hash = (53 * hash) + getEncryptedTicket().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(EncryptedAppTicketOuterClass.EncryptedAppTicket prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code EncryptedAppTicket} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:EncryptedAppTicket) EncryptedAppTicketOuterClass.EncryptedAppTicketOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return EncryptedAppTicketOuterClass.internal_static_EncryptedAppTicket_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return EncryptedAppTicketOuterClass.internal_static_EncryptedAppTicket_fieldAccessorTable .ensureFieldAccessorsInitialized( EncryptedAppTicketOuterClass.EncryptedAppTicket.class, EncryptedAppTicketOuterClass.EncryptedAppTicket.Builder.class); } // Construct using EncryptedAppTicketOuterClass.EncryptedAppTicket.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); ticketVersionNo_ = 0; bitField0_ = (bitField0_ & ~0x00000001); crcEncryptedticket_ = 0; bitField0_ = (bitField0_ & ~0x00000002); cbEncrypteduserdata_ = 0; bitField0_ = (bitField0_ & ~0x00000004); cbEncryptedAppownershipticket_ = 0; bitField0_ = (bitField0_ & ~0x00000008); encryptedTicket_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return EncryptedAppTicketOuterClass.internal_static_EncryptedAppTicket_descriptor; } public EncryptedAppTicketOuterClass.EncryptedAppTicket getDefaultInstanceForType() { return EncryptedAppTicketOuterClass.EncryptedAppTicket.getDefaultInstance(); } public EncryptedAppTicketOuterClass.EncryptedAppTicket build() { EncryptedAppTicketOuterClass.EncryptedAppTicket result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public EncryptedAppTicketOuterClass.EncryptedAppTicket buildPartial() { EncryptedAppTicketOuterClass.EncryptedAppTicket result = new EncryptedAppTicketOuterClass.EncryptedAppTicket(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.ticketVersionNo_ = ticketVersionNo_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.crcEncryptedticket_ = crcEncryptedticket_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.cbEncrypteduserdata_ = cbEncrypteduserdata_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.cbEncryptedAppownershipticket_ = cbEncryptedAppownershipticket_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.encryptedTicket_ = encryptedTicket_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof EncryptedAppTicketOuterClass.EncryptedAppTicket) { return mergeFrom((EncryptedAppTicketOuterClass.EncryptedAppTicket)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(EncryptedAppTicketOuterClass.EncryptedAppTicket other) { if (other == EncryptedAppTicketOuterClass.EncryptedAppTicket.getDefaultInstance()) return this; if (other.hasTicketVersionNo()) { setTicketVersionNo(other.getTicketVersionNo()); } if (other.hasCrcEncryptedticket()) { setCrcEncryptedticket(other.getCrcEncryptedticket()); } if (other.hasCbEncrypteduserdata()) { setCbEncrypteduserdata(other.getCbEncrypteduserdata()); } if (other.hasCbEncryptedAppownershipticket()) { setCbEncryptedAppownershipticket(other.getCbEncryptedAppownershipticket()); } if (other.hasEncryptedTicket()) { setEncryptedTicket(other.getEncryptedTicket()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { EncryptedAppTicketOuterClass.EncryptedAppTicket parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (EncryptedAppTicketOuterClass.EncryptedAppTicket) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private int ticketVersionNo_ ; /** * <code>optional uint32 ticket_version_no = 1;</code> */ public boolean hasTicketVersionNo() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional uint32 ticket_version_no = 1;</code> */ public int getTicketVersionNo() { return ticketVersionNo_; } /** * <code>optional uint32 ticket_version_no = 1;</code> */ public Builder setTicketVersionNo(int value) { bitField0_ |= 0x00000001; ticketVersionNo_ = value; onChanged(); return this; } /** * <code>optional uint32 ticket_version_no = 1;</code> */ public Builder clearTicketVersionNo() { bitField0_ = (bitField0_ & ~0x00000001); ticketVersionNo_ = 0; onChanged(); return this; } private int crcEncryptedticket_ ; /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ public boolean hasCrcEncryptedticket() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ public int getCrcEncryptedticket() { return crcEncryptedticket_; } /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ public Builder setCrcEncryptedticket(int value) { bitField0_ |= 0x00000002; crcEncryptedticket_ = value; onChanged(); return this; } /** * <code>optional uint32 crc_encryptedticket = 2;</code> */ public Builder clearCrcEncryptedticket() { bitField0_ = (bitField0_ & ~0x00000002); crcEncryptedticket_ = 0; onChanged(); return this; } private int cbEncrypteduserdata_ ; /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ public boolean hasCbEncrypteduserdata() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ public int getCbEncrypteduserdata() { return cbEncrypteduserdata_; } /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ public Builder setCbEncrypteduserdata(int value) { bitField0_ |= 0x00000004; cbEncrypteduserdata_ = value; onChanged(); return this; } /** * <code>optional uint32 cb_encrypteduserdata = 3;</code> */ public Builder clearCbEncrypteduserdata() { bitField0_ = (bitField0_ & ~0x00000004); cbEncrypteduserdata_ = 0; onChanged(); return this; } private int cbEncryptedAppownershipticket_ ; /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ public boolean hasCbEncryptedAppownershipticket() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ public int getCbEncryptedAppownershipticket() { return cbEncryptedAppownershipticket_; } /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ public Builder setCbEncryptedAppownershipticket(int value) { bitField0_ |= 0x00000008; cbEncryptedAppownershipticket_ = value; onChanged(); return this; } /** * <code>optional uint32 cb_encrypted_appownershipticket = 4;</code> */ public Builder clearCbEncryptedAppownershipticket() { bitField0_ = (bitField0_ & ~0x00000008); cbEncryptedAppownershipticket_ = 0; onChanged(); return this; } private com.google.protobuf.ByteString encryptedTicket_ = com.google.protobuf.ByteString.EMPTY; /** * <code>optional bytes encrypted_ticket = 5;</code> */ public boolean hasEncryptedTicket() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional bytes encrypted_ticket = 5;</code> */ public com.google.protobuf.ByteString getEncryptedTicket() { return encryptedTicket_; } /** * <code>optional bytes encrypted_ticket = 5;</code> */ public Builder setEncryptedTicket(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000010; encryptedTicket_ = value; onChanged(); return this; } /** * <code>optional bytes encrypted_ticket = 5;</code> */ public Builder clearEncryptedTicket() { bitField0_ = (bitField0_ & ~0x00000010); encryptedTicket_ = getDefaultInstance().getEncryptedTicket(); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:EncryptedAppTicket) } // @@protoc_insertion_point(class_scope:EncryptedAppTicket) private static final EncryptedAppTicketOuterClass.EncryptedAppTicket DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new EncryptedAppTicketOuterClass.EncryptedAppTicket(); } public static EncryptedAppTicketOuterClass.EncryptedAppTicket getDefaultInstance() { return DEFAULT_INSTANCE; } @java.lang.Deprecated public static final com.google.protobuf.Parser<EncryptedAppTicket> PARSER = new com.google.protobuf.AbstractParser<EncryptedAppTicket>() { public EncryptedAppTicket parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new EncryptedAppTicket(input, extensionRegistry); } }; public static com.google.protobuf.Parser<EncryptedAppTicket> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<EncryptedAppTicket> getParserForType() { return PARSER; } public EncryptedAppTicketOuterClass.EncryptedAppTicket getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_EncryptedAppTicket_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_EncryptedAppTicket_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\032encrypted_app_ticket.proto\"\255\001\n\022Encrypt" + "edAppTicket\022\031\n\021ticket_version_no\030\001 \001(\r\022\033" + "\n\023crc_encryptedticket\030\002 \001(\r\022\034\n\024cb_encryp" + "teduserdata\030\003 \001(\r\022\'\n\037cb_encrypted_appown" + "ershipticket\030\004 \001(\r\022\030\n\020encrypted_ticket\030\005" + " \001(\014B\005H\001\200\001\000" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_EncryptedAppTicket_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_EncryptedAppTicket_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_EncryptedAppTicket_descriptor, new java.lang.String[] { "TicketVersionNo", "CrcEncryptedticket", "CbEncrypteduserdata", "CbEncryptedAppownershipticket", "EncryptedTicket", }); } // @@protoc_insertion_point(outer_class_scope) }
/* * Autopsy Forensic Browser * * Copyright 2012 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.coreutils; /** * * @author dick */ class LnkEnums { private static final byte[] CDRIVES = new byte[]{(byte) 0xe0, 0x4f, (byte) 0xd0, 0x20, (byte) 0xea, 0x3a, 0x69, 0x10, (byte) 0xa2, (byte) 0xd8, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte) 0x9d}; private static final byte[] CMYDOCS = new byte[]{(byte) 0xba, (byte) 0x8a, 0x0d, 0x45, 0x25, (byte) 0xad, (byte) 0xd0, 0x11, (byte) 0x98, (byte) 0xa8, 0x08, 0x00, 0x36, 0x1b, 0x11, 0x03}; private static final byte[] IEFRAME = new byte[]{(byte) 0x80, 0x53, 0x1c, (byte) 0x87, (byte) 0xa0, 0x42, 0x69, 0x10, (byte) 0xa2, (byte) 0xea, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte) 0x9d}; public enum CommonCLSIDS { CDrivesFolder(CDRIVES), CMyDocsFolder(CMYDOCS), IEFrameDLL(IEFRAME), Unknown(new byte[16]); private byte[] flag; private CommonCLSIDS(byte[] flag) { this.flag = flag; } static CommonCLSIDS valueOf(byte[] type) { for (CommonCLSIDS value : CommonCLSIDS.values()) { if (java.util.Arrays.equals(value.flag, type)) { return value; } } return Unknown; } } public enum LinkFlags { HasLinkTargetIDList(0x00000001), HasLinkInfo(0x00000002), HasName(0x00000004), HasRelativePath(0x00000008), HasWorkingDir(0x00000010), HasArguments(0x00000020), HasIconLocation(0x00000040), IsUnicode(0x00000080), ForceNoLinkInfo(0x00000100), HasExpString(0x00000200), RunInSeparateProcess(0x00000400), Unused1(0x00000800), HasDarwinID(0x00001000), RunAsUser(0x00002000), HasExpIcon(0x00004000), NoPidlAlias(0x00008000), Unused2(0x00010000), RunWithShimLayer(0x00020000), ForceNoLinkTrack(0x00040000), EnableTargetMetaData(0x00080000), DisableLinkPathTracking(0x00100000), DisableKnownFolderTracking(0x00200000), DisableKnownFolderAlias(0x00400000), AllowLinkToLink(0x00800000), UnaliasOnSave(0x01000000), PreferEnvironmentPath(0x02000000), KeepLocalIDListForUNCTarget(0x04000000); private int flag; private LinkFlags(int flag) { this.flag = flag; } public int getFlag() { return flag; } } public enum DriveType { DRIVE_UNKNOWN(0x00000000), DRIVE_NO_ROOT_DIR(0x00000001), DRIVE_REMOVABLE(0x00000002), DRIVE_FIXED(0x00000003), DRIVE_REMOTE(0x00000004), DRIVE_CDROM(0x00000005), DRIVE_RAMDISK(0x00000006); private int flag; private DriveType(int flag) { this.flag = flag; } public int getFlag() { return flag; } static DriveType valueOf(int type) { for (DriveType value : DriveType.values()) { if (value.flag == type) { return value; } } return DRIVE_UNKNOWN; } } public enum FileAttributesFlags { READONLY(0x00000001), HIDDEN(0x00000002), SYSTEM(0x00000004), RESERVED1(0x00000008), DIRECTORY(0x00000010), ARCHIVE(0x00000020), RESERVED2(0x00000040), NORMAL(0x00000080), TEMPORARY(0x00000100), SPARSE_FILE(0x00000200), REPARSE_POINT(0x00000400), COMPRESSED(0x00000800), OFFLINE(0x00001000), NOT_CONTENT_INDEXED(0x00002000), ENCRYPTED(0x00004000); private int flag; private FileAttributesFlags(int flag) { this.flag = flag; } public int getFlag() { return flag; } } public enum LinkInfoFlags { VolumeIDAndLocalBasePath(0x00000001), CommonNetworkRelativeLinkAndPathSuffix(0x00000002); private int flag; private LinkInfoFlags(int flag) { this.flag = flag; } public int getFlag() { return flag; } } public enum CommonNetworkRelativeLinkFlags { ValidDevice(0x00000001), ValidNetType(0x00000002); private int flag; private CommonNetworkRelativeLinkFlags(int flag) { this.flag = flag; } public int getFlag() { return flag; } } public enum NetworkProviderType { WNNC_NET_AVID(0x001A0000), WNNC_NET_DOCUSPACE(0x001B0000), WNNC_NET_MANGOSOFT(0x001C0000), WNNC_NET_SERNET(0x001D0000), WNNC_NET_RIVERFRONT1(0x001E0000), WNNC_NET_RIVERFRONT2(0x001F0000), WNNC_NET_DECORB(0x00200000), WNNC_NET_PROTSTOR(0x00210000), WNNC_NET_FJ_REDIR(0x00220000), WNNC_NET_DISTINCT(0x00230000), WNNC_NET_TWINS(0x00240000), WNNC_NET_RDR2SAMPLE(0x00250000), WNNC_NET_CSC(0x00260000), WNNC_NET_3IN1(0x00270000), WNNC_NET_EXTENDNET(0x00290000), WNNC_NET_STAC(0x002A0000), WNNC_NET_FOXBAT(0x002B0000), WNNC_NET_YAHOO(0x002C0000), WNNC_NET_EXIFS(0x002D0000), WNNC_NET_DAV(0x002E0000), WNNC_NET_KNOWARE(0x002F0000), WNNC_NET_OBJECT_DIRE(0x00300000), WNNC_NET_MASFAX(0x00310000), WNNC_NET_HOB_NFS(0x00320000), WNNC_NET_SHIVA(0x00330000), WNNC_NET_IBMAL(0x00340000), WNNC_NET_LOCK(0x00350000), WNNC_NET_TERMSRV(0x00360000), WNNC_NET_SRT(0x00370000), WNNC_NET_QUINCY(0x00380000), WNNC_NET_OPENAFS(0x00390000), WNNC_NET_AVID1(0x003A0000), WNNC_NET_DFS(0x003B0000), WNNC_NET_KWNP(0x003C0000), WNNC_NET_ZENWORKS(0x003D0000), WNNC_NET_DRIVEONWEB(0x003E0000), WNNC_NET_VMWARE(0x003F0000), WNNC_NET_RSFX(0x00400000), WNNC_NET_MFILES(0x00410000), WNNC_NET_MS_NFS(0x00420000), WNNC_NET_GOOGLE(0x00430000), WNNC_NET_UNKNOWN(0x00000000); private int flag; private NetworkProviderType(int flag) { this.flag = flag; } static NetworkProviderType valueOf(int type) { for (NetworkProviderType value : NetworkProviderType.values()) { if (value.flag == type) { return value; } } return WNNC_NET_UNKNOWN; } public int getFlag() { return flag; } } }
package com.cube.storm; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.cube.storm.message.lib.listener.RegisterListener; import com.cube.storm.message.lib.receiver.MessageReceiver; import com.cube.storm.message.lib.resolver.DefaultMessageResolver; import com.cube.storm.message.lib.resolver.MessageResolver; import com.cube.storm.message.lib.service.TokenService; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.iid.FirebaseInstanceId; import lombok.Getter; import lombok.Setter; import java.util.HashMap; import java.util.Map; /** * This is the entry point class of the library. To enable the use of the library, you must instantiate * a new {@link com.cube.storm.MessageSettings.Builder} object in your {@link android.app.Application} singleton class. * * This class should not be directly instantiated. * * @author Callum Taylor * @project LightningMessage */ public class MessageSettings { /** * The singleton instance of the settings */ private static MessageSettings instance; /** * Gets the instance of the {@link com.cube.storm.MessageSettings} class * Throws a {@link IllegalAccessError} if the singleton has not been instantiated properly * * @return The instance */ public static MessageSettings getInstance() { if (instance == null) { throw new IllegalAccessError("You must build the Message settings object first using MessageSettings$Builder"); } return instance; } /** * Project number as defined in the Google console project page under "project number" */ @Getter @Setter private String projectNumber; /** * Callback used once the device has been registered for a push token */ @Getter @Setter private RegisterListener registerListener; /** * The gcm receiver class used to receive messages from Storm. */ @Getter @Setter private MessageReceiver receiver; /** * List of resolvers for different types of GCM messages received */ @Getter private Map<String, MessageResolver> messageResolvers = new HashMap<>(); /** * The broadcast receiver class for receiving new tokens. Should be the same as defined in the application manifest */ @Getter @Setter private Class<? extends TokenService> tokenService; /** * The builder class for {@link com.cube.storm.MessageSettings}. Use this to create a new {@link com.cube.storm.MessageSettings} instance * with the customised properties specific for your project. * * Call {@link #build()} to build the settings object. */ public static class Builder { /** * The temporary instance of the {@link com.cube.storm.MessageSettings} object. */ private MessageSettings construct; private Context context; /** * Default constructor */ public Builder(@NonNull Context context) { this.construct = new MessageSettings(); this.context = context.getApplicationContext(); registerMessageResolver(MessageReceiver.TYPE_DEFAULT, new DefaultMessageResolver()); messageReceiver(new MessageReceiver()); tokenService(TokenService.class); } /** * Sets the project number from the console * * @param projectNumber The project number * * @return The builder to allow for chaining */ public Builder projectNumber(@NonNull String projectNumber) { construct.projectNumber = projectNumber; return this; } /** * Sets the callback listener for when the device has been registered for a push token * * @param listener The listener to use * * @return The builder to allow for chaining */ public Builder registerListener(@Nullable RegisterListener listener) { construct.registerListener = listener; return this; } /** * Registers a resolver for a type of notification * * @param type The type of message received * @param resolver The handler for the receiver * * @return The builder to allow for chaining */ public Builder registerMessageResolver(String type, @NonNull MessageResolver resolver) { construct.messageResolvers.put(type, resolver); return this; } /** * Sets the receiver for the module. You must also set this in your manifest for the framework * to use correctly. * <p/> * <pre> * &lt;service * android:name="com.cube.storm.message.lib.receiver.MessageReceiver" * android:exported="false" * &gt; * &lt;intent-filter&gt; * &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; * &lt;/intent-filter&gt; * &lt;/service&gt; * </pre> * * @param receiver The receiver to use * * @return The builder to allow for chaining */ public Builder messageReceiver(@Nullable MessageReceiver receiver) { construct.receiver = receiver; return this; } /** * Sets the service for getting the GCM token for the module. You must also set this in your manifest for the framework * to use correctly. * <p/> * <pre> * &lt;service android:name="com.cube.storm.message.lib.service.TokenService" android:exported="false" /&gt; * </pre> * * @param tokenService The service to use * * @return The builder to allow for chaining */ public Builder tokenService(@NonNull Class<? extends TokenService> tokenService) { construct.tokenService = tokenService; return this; } /** * Builds the final settings object and sets its instance. Use {@link #getInstance()} to retrieve the settings * instance. * <p/> * This method will also register the receiver to the given context in {@link #Builder(android.content.Context)} if * the receiver is not null. * * @return The newly set {@link com.cube.storm.MessageSettings} instance * @throws RuntimeException if the GcmSenderId option for the {@link FirebaseApp} is empty */ public MessageSettings build() { MessageSettings.instance = construct; FirebaseApp firebaseApp = null; try { firebaseApp = FirebaseApp.getInstance(); } catch (Exception instanceException) { try { // Initialise Firebase firebaseApp = FirebaseApp.initializeApp(context, new FirebaseOptions.Builder() .setApplicationId(context.getPackageName()) .setGcmSenderId(MessageSettings.getInstance().getProjectNumber()) .build()); } catch (Exception initialiseException) { instanceException.printStackTrace(); initialiseException.printStackTrace(); } } if (firebaseApp == null) { throw new RuntimeException("Failed to initialise or reuse existing Firebase app"); } // Already has an instance of Firebase FirebaseOptions options = firebaseApp.getOptions(); if (options == null || TextUtils.isEmpty(options.getGcmSenderId())) { throw new RuntimeException("Missing GcmSenderId from Firebase instance!"); } if (construct.tokenService != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { context.startService(new Intent(context, construct.tokenService)); } } // check if token already is registered String token = FirebaseInstanceId.getInstance().getToken(); if (!TextUtils.isEmpty(token) && MessageSettings.getInstance().getRegisterListener() != null) { MessageSettings.getInstance().getRegisterListener().onDeviceRegistered(context, token); } return construct; } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * RegionSetType.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; /** * RegionSetType bean class */ public class RegionSetType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = RegionSetType 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 Item * This was an Array! */ protected com.amazon.ec2.RegionItemType[] localItem ; /* This tracker boolean wil be used to detect whether the user called the set method * for this attribute. It will be used to determine whether to include this field * in the serialized XML */ protected boolean localItemTracker = false ; /** * Auto generated getter method * @return com.amazon.ec2.RegionItemType[] */ public com.amazon.ec2.RegionItemType[] getItem(){ return localItem; } /** * validate the array for Item */ protected void validateItem(com.amazon.ec2.RegionItemType[] param){ } /** * Auto generated setter method * @param param Item */ public void setItem(com.amazon.ec2.RegionItemType[] param){ validateItem(param); if (param != null){ //update the setting tracker localItemTracker = true; } else { localItemTracker = false; } this.localItem=param; } /** * Auto generated add method for the array for convenience * @param param com.amazon.ec2.RegionItemType */ public void addItem(com.amazon.ec2.RegionItemType param){ if (localItem == null){ localItem = new com.amazon.ec2.RegionItemType[]{}; } //update the setting tracker localItemTracker = true; java.util.List list = org.apache.axis2.databinding.utils.ConverterUtil.toList(localItem); list.add(param); this.localItem = (com.amazon.ec2.RegionItemType[])list.toArray( new com.amazon.ec2.RegionItemType[list.size()]); } /** * 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 { RegionSetType.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+":RegionSetType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "RegionSetType", xmlWriter); } } if (localItemTracker){ if (localItem!=null){ for (int i = 0;i < localItem.length;i++){ if (localItem[i] != null){ localItem[i].serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","item"), factory,xmlWriter); } else { // we don't have to do any thing since minOccures is zero } } } else { throw new org.apache.axis2.databinding.ADBException("item cannot be null!!"); } } 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(); if (localItemTracker){ if (localItem!=null) { for (int i = 0;i < localItem.length;i++){ if (localItem[i] != null){ elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/", "item")); elementList.add(localItem[i]); } else { // nothing to do } } } else { throw new org.apache.axis2.databinding.ADBException("item 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 RegionSetType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ RegionSetType object = new RegionSetType(); 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 (!"RegionSetType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (RegionSetType)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(); java.util.ArrayList list1 = new java.util.ArrayList(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","item").equals(reader.getName())){ // Process the array and step past its final element's end. list1.add(com.amazon.ec2.RegionItemType.Factory.parse(reader)); //loop until we find a start element that is not part of this array boolean loopDone1 = false; while(!loopDone1){ // We should be at the end element, but make sure while (!reader.isEndElement()) reader.next(); // Step out of this element reader.next(); // Step to next element event. while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isEndElement()){ //two continuous end elements means we are exiting the xml structure loopDone1 = true; } else { if (new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","item").equals(reader.getName())){ list1.add(com.amazon.ec2.RegionItemType.Factory.parse(reader)); }else{ loopDone1 = true; } } } // call the converter utility to convert and set the array object.setItem((com.amazon.ec2.RegionItemType[]) org.apache.axis2.databinding.utils.ConverterUtil.convertToArray( com.amazon.ec2.RegionItemType.class, list1)); } // End of if for expected property start element else { } 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 }
/* * 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.indices.flush; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardNotFoundException; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.threadpool.ThreadPool; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; public class SyncedFlushSingleNodeTests extends ESSingleNodeTestCase { public void testModificationPreventsFlushing() throws InterruptedException { createIndex("test"); client().prepareIndex("test", "test", "1").setSource("{ \"foo\" : \"bar\" }", XContentType.JSON).get(); IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test")); IndexShard shard = test.getShardOrNull(0); SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class); final ShardId shardId = shard.shardId(); final ClusterState state = getInstanceFromNode(ClusterService.class).state(); final IndexShardRoutingTable shardRoutingTable = flushService.getShardRoutingTable(shardId, state); final List<ShardRouting> activeShards = shardRoutingTable.activeShards(); assertEquals("exactly one active shard", 1, activeShards.size()); Map<String, SyncedFlushService.PreSyncedFlushResponse> preSyncedResponses = SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId); assertEquals("exactly one commit id", 1, preSyncedResponses.size()); client().prepareIndex("test", "test", "2").setSource("{ \"foo\" : \"bar\" }", XContentType.JSON).get(); String syncId = UUIDs.randomBase64UUID(); SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>(); flushService.sendSyncRequests(syncId, activeShards, state, preSyncedResponses, shardId, shardRoutingTable.size(), listener); listener.latch.await(); assertNull(listener.error); ShardsSyncedFlushResult syncedFlushResult = listener.result; assertNotNull(syncedFlushResult); assertEquals(0, syncedFlushResult.successfulShards()); assertEquals(1, syncedFlushResult.totalShards()); assertEquals(syncId, syncedFlushResult.syncId()); assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0))); assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success()); assertEquals("pending operations", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason()); // pull another commit and make sure we can't sync-flush with the old one SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId); listener = new SyncedFlushUtil.LatchedListener<>(); flushService.sendSyncRequests(syncId, activeShards, state, preSyncedResponses, shardId, shardRoutingTable.size(), listener); listener.latch.await(); assertNull(listener.error); syncedFlushResult = listener.result; assertNotNull(syncedFlushResult); assertEquals(0, syncedFlushResult.successfulShards()); assertEquals(1, syncedFlushResult.totalShards()); assertEquals(syncId, syncedFlushResult.syncId()); assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0))); assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success()); assertEquals("commit has changed", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason()); } public void testSingleShardSuccess() throws InterruptedException { createIndex("test"); client().prepareIndex("test", "test", "1").setSource("{ \"foo\" : \"bar\" }", XContentType.JSON).get(); IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test")); IndexShard shard = test.getShardOrNull(0); SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class); final ShardId shardId = shard.shardId(); SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>(); flushService.attemptSyncedFlush(shardId, listener); listener.latch.await(); assertNull(listener.error); ShardsSyncedFlushResult syncedFlushResult = listener.result; assertNotNull(syncedFlushResult); assertEquals(1, syncedFlushResult.successfulShards()); assertEquals(1, syncedFlushResult.totalShards()); SyncedFlushService.ShardSyncedFlushResponse response = syncedFlushResult.shardResponses().values().iterator().next(); assertTrue(response.success()); } public void testSyncFailsIfOperationIsInFlight() throws InterruptedException, ExecutionException { createIndex("test"); client().prepareIndex("test", "test", "1").setSource("{ \"foo\" : \"bar\" }", XContentType.JSON).get(); IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test")); IndexShard shard = test.getShardOrNull(0); SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class); final ShardId shardId = shard.shardId(); PlainActionFuture<Releasable> fut = new PlainActionFuture<>(); shard.acquirePrimaryOperationPermit(fut, ThreadPool.Names.INDEX, ""); try (Releasable operationLock = fut.get()) { SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>(); flushService.attemptSyncedFlush(shardId, listener); listener.latch.await(); assertNull(listener.error); ShardsSyncedFlushResult syncedFlushResult = listener.result; assertNotNull(syncedFlushResult); assertEquals(0, syncedFlushResult.successfulShards()); assertNotEquals(0, syncedFlushResult.totalShards()); assertEquals("[1] ongoing operations on primary", syncedFlushResult.failureReason()); } } public void testSyncFailsOnIndexClosedOrMissing() throws InterruptedException { createIndex("test", Settings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) .build()); IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test")); final IndexShard shard = test.getShardOrNull(0); assertNotNull(shard); final ShardId shardId = shard.shardId(); final SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class); SyncedFlushUtil.LatchedListener listener = new SyncedFlushUtil.LatchedListener(); flushService.attemptSyncedFlush(new ShardId(shard.shardId().getIndex(), 1), listener); listener.latch.await(); assertNotNull(listener.error); assertNull(listener.result); assertEquals(ShardNotFoundException.class, listener.error.getClass()); assertEquals("no such shard", listener.error.getMessage()); assertAcked(client().admin().indices().prepareClose("test")); listener = new SyncedFlushUtil.LatchedListener(); flushService.attemptSyncedFlush(shardId, listener); listener.latch.await(); assertNotNull(listener.error); assertNull(listener.result); assertEquals("closed", listener.error.getMessage()); listener = new SyncedFlushUtil.LatchedListener(); flushService.attemptSyncedFlush(new ShardId("index not found", "_na_", 0), listener); listener.latch.await(); assertNotNull(listener.error); assertNull(listener.result); assertEquals("no such index", listener.error.getMessage()); } public void testFailAfterIntermediateCommit() throws InterruptedException { createIndex("test"); client().prepareIndex("test", "test", "1").setSource("{ \"foo\" : \"bar\" }", XContentType.JSON).get(); IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test")); IndexShard shard = test.getShardOrNull(0); SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class); final ShardId shardId = shard.shardId(); final ClusterState state = getInstanceFromNode(ClusterService.class).state(); final IndexShardRoutingTable shardRoutingTable = flushService.getShardRoutingTable(shardId, state); final List<ShardRouting> activeShards = shardRoutingTable.activeShards(); assertEquals("exactly one active shard", 1, activeShards.size()); Map<String, SyncedFlushService.PreSyncedFlushResponse> preSyncedResponses = SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId); assertEquals("exactly one commit id", 1, preSyncedResponses.size()); if (randomBoolean()) { client().prepareIndex("test", "test", "2").setSource("{}", XContentType.JSON).get(); } client().admin().indices().prepareFlush("test").setForce(true).get(); String syncId = UUIDs.randomBase64UUID(); final SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>(); flushService.sendSyncRequests(syncId, activeShards, state, preSyncedResponses, shardId, shardRoutingTable.size(), listener); listener.latch.await(); assertNull(listener.error); ShardsSyncedFlushResult syncedFlushResult = listener.result; assertNotNull(syncedFlushResult); assertEquals(0, syncedFlushResult.successfulShards()); assertEquals(1, syncedFlushResult.totalShards()); assertEquals(syncId, syncedFlushResult.syncId()); assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0))); assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success()); assertEquals("commit has changed", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason()); } public void testFailWhenCommitIsMissing() throws InterruptedException { createIndex("test"); client().prepareIndex("test", "test", "1").setSource("{ \"foo\" : \"bar\" }", XContentType.JSON).get(); IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test")); IndexShard shard = test.getShardOrNull(0); SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class); final ShardId shardId = shard.shardId(); final ClusterState state = getInstanceFromNode(ClusterService.class).state(); final IndexShardRoutingTable shardRoutingTable = flushService.getShardRoutingTable(shardId, state); final List<ShardRouting> activeShards = shardRoutingTable.activeShards(); assertEquals("exactly one active shard", 1, activeShards.size()); Map<String, SyncedFlushService.PreSyncedFlushResponse> preSyncedResponses = SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId); assertEquals("exactly one commit id", 1, preSyncedResponses.size()); preSyncedResponses.clear(); // wipe it... String syncId = UUIDs.randomBase64UUID(); SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>(); flushService.sendSyncRequests(syncId, activeShards, state, preSyncedResponses, shardId, shardRoutingTable.size(), listener); listener.latch.await(); assertNull(listener.error); ShardsSyncedFlushResult syncedFlushResult = listener.result; assertNotNull(syncedFlushResult); assertEquals(0, syncedFlushResult.successfulShards()); assertEquals(1, syncedFlushResult.totalShards()); assertEquals(syncId, syncedFlushResult.syncId()); assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0))); assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success()); assertEquals("no commit id from pre-sync flush", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES 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.io.hfile; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoder; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo; import org.apache.hadoop.hbase.regionserver.StoreFile; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import com.google.common.base.Preconditions; /** * Do different kinds of data block encoding according to column family * options. */ public class HFileDataBlockEncoderImpl implements HFileDataBlockEncoder { private final DataBlockEncoding onDisk; private final DataBlockEncoding inCache; public HFileDataBlockEncoderImpl(DataBlockEncoding encoding) { this(encoding, encoding); } /** * Do data block encoding with specified options. * @param onDisk What kind of data block encoding will be used before writing * HFileBlock to disk. This must be either the same as inCache or * {@link DataBlockEncoding#NONE}. * @param inCache What kind of data block encoding will be used in block * cache. */ public HFileDataBlockEncoderImpl(DataBlockEncoding onDisk, DataBlockEncoding inCache) { this.onDisk = onDisk != null ? onDisk : DataBlockEncoding.NONE; this.inCache = inCache != null ? inCache : DataBlockEncoding.NONE; Preconditions.checkArgument(onDisk == DataBlockEncoding.NONE || onDisk == inCache, "on-disk encoding (" + onDisk + ") must be " + "either the same as in-cache encoding (" + inCache + ") or " + DataBlockEncoding.NONE); } public static HFileDataBlockEncoder createFromFileInfo( FileInfo fileInfo, DataBlockEncoding preferredEncodingInCache) throws IOException { byte[] dataBlockEncodingType = fileInfo.get(StoreFile.DATA_BLOCK_ENCODING); if (dataBlockEncodingType == null) { return NoOpDataBlockEncoder.INSTANCE; } String dataBlockEncodingStr = Bytes.toString(dataBlockEncodingType); DataBlockEncoding onDisk; try { onDisk = DataBlockEncoding.valueOf(dataBlockEncodingStr); } catch (IllegalArgumentException ex) { throw new IOException("Invalid data block encoding type in file info: " + dataBlockEncodingStr, ex); } DataBlockEncoding inCache; if (onDisk == DataBlockEncoding.NONE) { // This is an "in-cache-only" encoding or fully-unencoded scenario. // Either way, we use the given encoding (possibly NONE) specified by // the column family in cache. inCache = preferredEncodingInCache; } else { // Leave blocks in cache encoded the same way as they are on disk. // If we switch encoding type for the CF or the in-cache-only encoding // flag, old files will keep their encoding both on disk and in cache, // but new files will be generated with the new encoding. inCache = onDisk; } return new HFileDataBlockEncoderImpl(onDisk, inCache); } @Override public void saveMetadata(StoreFile.Writer storeFileWriter) throws IOException { storeFileWriter.appendFileInfo(StoreFile.DATA_BLOCK_ENCODING, onDisk.getNameInBytes()); } @Override public DataBlockEncoding getEncodingOnDisk() { return onDisk; } @Override public DataBlockEncoding getEncodingInCache() { return inCache; } @Override public DataBlockEncoding getEffectiveEncodingInCache(boolean isCompaction) { if (!useEncodedScanner(isCompaction)) { return DataBlockEncoding.NONE; } return inCache; } @Override public HFileBlock diskToCacheFormat(HFileBlock block, boolean isCompaction) { if (block.getBlockType() == BlockType.DATA) { if (!useEncodedScanner(isCompaction)) { // Unencoded block, and we don't want to encode in cache. return block; } // Encode the unencoded block with the in-cache encoding. return encodeDataBlock(block, inCache, block.doesIncludeMemstoreTS()); } if (block.getBlockType() == BlockType.ENCODED_DATA) { if (block.getDataBlockEncodingId() == onDisk.getId()) { // The block is already in the desired in-cache encoding. return block; } // We don't want to re-encode a block in a different encoding. The HFile // reader should have been instantiated in such a way that we would not // have to do this. throw new AssertionError("Expected on-disk data block encoding " + onDisk + ", got " + block.getDataBlockEncoding()); } return block; } /** * Precondition: a non-encoded buffer. * Postcondition: on-disk encoding. */ @Override public Pair<ByteBuffer, BlockType> beforeWriteToDisk(ByteBuffer in, boolean includesMemstoreTS) { if (onDisk == DataBlockEncoding.NONE) { // there is no need to encode the block before writing it to disk return new Pair<ByteBuffer, BlockType>(in, BlockType.DATA); } ByteBuffer encodedBuffer = encodeBufferToHFileBlockBuffer(in, onDisk, includesMemstoreTS); return new Pair<ByteBuffer, BlockType>(encodedBuffer, BlockType.ENCODED_DATA); } @Override public boolean useEncodedScanner(boolean isCompaction) { if (isCompaction && onDisk == DataBlockEncoding.NONE) { return false; } return inCache != DataBlockEncoding.NONE; } private ByteBuffer encodeBufferToHFileBlockBuffer(ByteBuffer in, DataBlockEncoding algo, boolean includesMemstoreTS) { ByteArrayOutputStream encodedStream = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(encodedStream); DataBlockEncoder encoder = algo.getEncoder(); try { encodedStream.write(HFileBlock.DUMMY_HEADER); algo.writeIdInBytes(dataOut); encoder.compressKeyValues(dataOut, in, includesMemstoreTS); } catch (IOException e) { throw new RuntimeException(String.format("Bug in data block encoder " + "'%s', it probably requested too much data", algo.toString()), e); } return ByteBuffer.wrap(encodedStream.toByteArray()); } private HFileBlock encodeDataBlock(HFileBlock block, DataBlockEncoding algo, boolean includesMemstoreTS) { ByteBuffer compressedBuffer = encodeBufferToHFileBlockBuffer( block.getBufferWithoutHeader(), algo, includesMemstoreTS); int sizeWithoutHeader = compressedBuffer.limit() - HFileBlock.HEADER_SIZE; HFileBlock encodedBlock = new HFileBlock(BlockType.ENCODED_DATA, block.getOnDiskSizeWithoutHeader(), sizeWithoutHeader, block.getPrevBlockOffset(), compressedBuffer, HFileBlock.FILL_HEADER, block.getOffset(), includesMemstoreTS); block.passSchemaMetricsTo(encodedBlock); return encodedBlock; } @Override public String toString() { return getClass().getSimpleName() + "(onDisk=" + onDisk + ", inCache=" + inCache + ")"; } }
// Copyright 2021 The Bazel Authors. 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 com.google.devtools.build.lib.bazel.bzlmod; import com.google.auto.value.AutoValue; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Comparators; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Maps; import com.google.devtools.build.lib.server.FailureDetails.ExternalDeps.Code; import java.util.ArrayDeque; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Set; import javax.annotation.Nullable; /** * Runs module selection. This step of module resolution reads the output of {@link Discovery} and * applies the Minimal Version Selection algorithm to it, removing unselected modules from the * dependency graph and rewriting dependencies to point to the selected versions. * * <p>Essentially, what needs to happen is: * * <ul> * <li>In the most basic case, only one version of each module is selected (ie. remains in the dep * graph). The selected version is simply the highest among all existing versions in the dep * graph. In other words, each module name forms a "selection group". If foo@1.5 is selected, * then any other foo@X is removed from the dep graph, and any module depending on foo@X will * depend on foo@1.5 instead. * <li>As an extension of the above, we also remove any module that becomes unreachable from the * root module because of the removal of some other module. * <li>If, however, versions of the same module but with different compatibility levels exist in * the dep graph, then one version is selected for each compatibility level (ie. we split the * selection groups by compatibility level). In the end, though, still only one version can * remain in the dep graph after the removal of unselected and unreachable modules. * <li>Things get more complicated with multiple-version overrides. If module foo has a * multiple-version override which allows versions [1.3, 1.5, 2.0] (using the major version as * the compatibility level), then we further split the selection groups by the target allowed * version (keep in mind that versions are upgraded to the nearest higher-or-equal allowed * version at the same compatibility level). If, for example, some module depends on foo@1.0, * then it'll depend on foo@1.3 post-selection instead (and foo@1.0 will be removed). If any * of foo@1.7, foo@2.2, or foo@3.0 exist in the dependency graph before selection, they must * be removed before the end of selection (by becoming unreachable, for example), otherwise * it'll be an error since they're not allowed by the override (these versions are in * selection groups that have no valid target allowed version). * </ul> */ final class Selection { private Selection() {} /** During selection, a version is selected for each distinct "selection group". */ @AutoValue abstract static class SelectionGroup { static SelectionGroup create( String moduleName, int compatibilityLevel, Version targetAllowedVersion) { return new AutoValue_Selection_SelectionGroup( moduleName, compatibilityLevel, targetAllowedVersion); } abstract String getModuleName(); abstract int getCompatibilityLevel(); /** This is only used for modules with multiple-version overrides. */ abstract Version getTargetAllowedVersion(); } @AutoValue abstract static class ModuleNameAndCompatibilityLevel { static ModuleNameAndCompatibilityLevel create(String moduleName, int compatibilityLevel) { return new AutoValue_Selection_ModuleNameAndCompatibilityLevel( moduleName, compatibilityLevel); } abstract String getModuleName(); abstract int getCompatibilityLevel(); } /** * Computes a mapping from (moduleName, compatibilityLevel) to the set of allowed versions. This * is only performed for modules with multiple-version overrides. */ private static ImmutableMap<ModuleNameAndCompatibilityLevel, ImmutableSortedSet<Version>> computeAllowedVersionSets( ImmutableMap<String, ModuleOverride> overrides, ImmutableMap<ModuleKey, Module> depGraph) throws ExternalDepsException { Map<ModuleNameAndCompatibilityLevel, ImmutableSortedSet.Builder<Version>> allowedVersionSets = new HashMap<>(); for (Map.Entry<String, ModuleOverride> overrideEntry : overrides.entrySet()) { String moduleName = overrideEntry.getKey(); ModuleOverride override = overrideEntry.getValue(); if (!(override instanceof MultipleVersionOverride)) { continue; } ImmutableList<Version> allowedVersions = ((MultipleVersionOverride) override).getVersions(); for (Version allowedVersion : allowedVersions) { Module allowedVersionModule = depGraph.get(ModuleKey.create(moduleName, allowedVersion)); if (allowedVersionModule == null) { throw ExternalDepsException.withMessage( Code.VERSION_RESOLUTION_ERROR, "multiple_version_override for module %s contains version %s, but it doesn't" + " exist in the dependency graph", moduleName, allowedVersion); } ImmutableSortedSet.Builder<Version> allowedVersionSet = allowedVersionSets.computeIfAbsent( ModuleNameAndCompatibilityLevel.create( moduleName, allowedVersionModule.getCompatibilityLevel()), // Remember that the empty version compares greater than any other version, so we // can use it as a sentinel value. k -> ImmutableSortedSet.<Version>naturalOrder().add(Version.EMPTY)); allowedVersionSet.add(allowedVersion); } } return ImmutableMap.copyOf( Maps.transformValues(allowedVersionSets, ImmutableSortedSet.Builder::build)); } /** * Computes the {@link SelectionGroup} for the given module. If the module has a multiple-version * override (which would be reflected in the allowedVersionSets), information in there will be * used to compute its targetAllowedVersion. */ private static SelectionGroup computeSelectionGroup( Module module, ImmutableMap<ModuleNameAndCompatibilityLevel, ImmutableSortedSet<Version>> allowedVersionSets) { ImmutableSortedSet<Version> allowedVersionSet = allowedVersionSets.get( ModuleNameAndCompatibilityLevel.create( module.getName(), module.getCompatibilityLevel())); if (allowedVersionSet == null) { // This means that this module has no multiple-version override. return SelectionGroup.create(module.getName(), module.getCompatibilityLevel(), Version.EMPTY); } return SelectionGroup.create( module.getName(), module.getCompatibilityLevel(), // We use the `ceiling` method here to quickly locate the lowest allowed version that's // still no lower than this module's version. // If this module's version is higher than any allowed version (in which case EMPTY is // returned), it should result in an error. We don't immediately throw here because it might // still become unreferenced later. allowedVersionSet.ceiling(module.getVersion())); } /** * Runs module selection (aka version resolution). Returns a dep graph sorted in BFS iteration * order. */ public static ImmutableMap<ModuleKey, Module> run( ImmutableMap<ModuleKey, Module> depGraph, ImmutableMap<String, ModuleOverride> overrides) throws ExternalDepsException { // For any multiple-version overrides, build a mapping from (moduleName, compatibilityLevel) to // the set of allowed versions. ImmutableMap<ModuleNameAndCompatibilityLevel, ImmutableSortedSet<Version>> allowedVersionSets = computeAllowedVersionSets(overrides, depGraph); // For each module in the dep graph, pre-compute its selection group. For most modules this is // simply its (moduleName, compatibilityLevel) tuple; for modules with multiple-version // overrides, it additionally includes the targetAllowedVersion, which denotes the version to // "snap" to during selection. ImmutableMap<ModuleKey, SelectionGroup> selectionGroups = ImmutableMap.copyOf( Maps.transformValues( depGraph, module -> computeSelectionGroup(module, allowedVersionSets))); // Figure out the version to select for every selection group. Map<SelectionGroup, Version> selectedVersions = new HashMap<>(); for (Map.Entry<ModuleKey, SelectionGroup> entry : selectionGroups.entrySet()) { ModuleKey key = entry.getKey(); SelectionGroup selectionGroup = entry.getValue(); selectedVersions.merge(selectionGroup, key.getVersion(), Comparators::max); } // Build a new dep graph where deps with unselected versions are removed. ImmutableMap.Builder<ModuleKey, Module> newDepGraphBuilder = new ImmutableMap.Builder<>(); for (Module module : depGraph.values()) { // Remove any dep whose version isn't selected. Version selectedVersion = selectedVersions.get(selectionGroups.get(module.getKey())); if (!module.getKey().getVersion().equals(selectedVersion)) { continue; } // Rewrite deps to point to the selected version. newDepGraphBuilder.put( module.getKey(), module.withDepKeysTransformed( depKey -> ModuleKey.create( depKey.getName(), selectedVersions.get(selectionGroups.get(depKey))))); } ImmutableMap<ModuleKey, Module> newDepGraph = newDepGraphBuilder.buildOrThrow(); // Further remove unreferenced modules from the graph. We can find out which modules are // referenced by collecting deps transitively from the root. // We can also take this opportunity to check that none of the remaining modules conflict with // each other (e.g. same module name but different compatibility levels, or not satisfying // multiple_version_override). return new DepGraphWalker(newDepGraph, overrides, selectionGroups).walk(); } /** * Walks the dependency graph from the root node, collecting any reachable nodes through deps into * a new dep graph and checking that nothing conflicts. */ static class DepGraphWalker { private static final Joiner JOINER = Joiner.on(", "); private final ImmutableMap<ModuleKey, Module> oldDepGraph; private final ImmutableMap<String, ModuleOverride> overrides; private final ImmutableMap<ModuleKey, SelectionGroup> selectionGroups; private final HashMap<String, ExistingModule> moduleByName; DepGraphWalker( ImmutableMap<ModuleKey, Module> oldDepGraph, ImmutableMap<String, ModuleOverride> overrides, ImmutableMap<ModuleKey, SelectionGroup> selectionGroups) { this.oldDepGraph = oldDepGraph; this.overrides = overrides; this.selectionGroups = selectionGroups; this.moduleByName = new HashMap<>(); } /** * Walks the old dep graph and builds a new dep graph containing only deps reachable from the * root module. The returned map has a guaranteed breadth-first iteration order. */ ImmutableMap<ModuleKey, Module> walk() throws ExternalDepsException { ImmutableMap.Builder<ModuleKey, Module> newDepGraph = ImmutableMap.builder(); Set<ModuleKey> known = new HashSet<>(); Queue<ModuleKeyAndDependent> toVisit = new ArrayDeque<>(); toVisit.add(ModuleKeyAndDependent.create(ModuleKey.ROOT, null)); known.add(ModuleKey.ROOT); while (!toVisit.isEmpty()) { ModuleKeyAndDependent moduleKeyAndDependent = toVisit.remove(); ModuleKey key = moduleKeyAndDependent.getModuleKey(); Module module = oldDepGraph.get(key); visit(key, module, moduleKeyAndDependent.getDependent()); for (ModuleKey depKey : module.getDeps().values()) { if (known.add(depKey)) { toVisit.add(ModuleKeyAndDependent.create(depKey, key)); } } newDepGraph.put(key, module); } return newDepGraph.buildOrThrow(); } void visit(ModuleKey key, Module module, @Nullable ModuleKey from) throws ExternalDepsException { ModuleOverride override = overrides.get(key.getName()); if (override instanceof MultipleVersionOverride) { if (selectionGroups.get(key).getTargetAllowedVersion().isEmpty()) { // This module has no target allowed version, which means that there's no allowed version // higher than its version at the same compatibility level. Preconditions.checkState( from != null, "the root module cannot have a multiple version override"); throw ExternalDepsException.withMessage( Code.VERSION_RESOLUTION_ERROR, "%s depends on %s which is not allowed by the multiple_version_override on %s," + " which allows only [%s]", from, key, key.getName(), JOINER.join(((MultipleVersionOverride) override).getVersions())); } } else { ExistingModule existingModuleWithSameName = moduleByName.put( module.getName(), ExistingModule.create(key, module.getCompatibilityLevel(), from)); if (existingModuleWithSameName != null) { // This has to mean that a module with the same name but a different compatibility level // was also selected. Preconditions.checkState( from != null && existingModuleWithSameName.getDependent() != null, "the root module cannot possibly exist more than once in the dep graph"); throw ExternalDepsException.withMessage( Code.VERSION_RESOLUTION_ERROR, "%s depends on %s with compatibility level %d, but %s depends on %s with" + " compatibility level %d which is different", from, key, module.getCompatibilityLevel(), existingModuleWithSameName.getDependent(), existingModuleWithSameName.getModuleKey(), existingModuleWithSameName.getCompatibilityLevel()); } } // Make sure that we don't have `module` depending on the same dependency version twice. HashMap<ModuleKey, String> depKeyToRepoName = new HashMap<>(); for (Map.Entry<String, ModuleKey> depEntry : module.getDeps().entrySet()) { String repoName = depEntry.getKey(); ModuleKey depKey = depEntry.getValue(); String previousRepoName = depKeyToRepoName.put(depKey, repoName); if (previousRepoName != null) { throw ExternalDepsException.withMessage( Code.VERSION_RESOLUTION_ERROR, "%s depends on %s at least twice (with repo names %s and %s). Consider adding a" + " multiple_version_override if you want to depend on multiple versions of" + " %s simultaneously", key, depKey, repoName, previousRepoName, key.getName()); } } } @AutoValue abstract static class ModuleKeyAndDependent { abstract ModuleKey getModuleKey(); @Nullable abstract ModuleKey getDependent(); static ModuleKeyAndDependent create(ModuleKey moduleKey, @Nullable ModuleKey dependent) { return new AutoValue_Selection_DepGraphWalker_ModuleKeyAndDependent(moduleKey, dependent); } } @AutoValue abstract static class ExistingModule { abstract ModuleKey getModuleKey(); abstract int getCompatibilityLevel(); @Nullable abstract ModuleKey getDependent(); static ExistingModule create( ModuleKey moduleKey, int compatibilityLevel, ModuleKey dependent) { return new AutoValue_Selection_DepGraphWalker_ExistingModule( moduleKey, compatibilityLevel, dependent); } } } }
/** */ package gluemodel.CIM.IEC61970.Informative.InfAssets; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Pole Preservative Kind</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see gluemodel.CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getPolePreservativeKind() * @model * @generated */ public enum PolePreservativeKind implements Enumerator { /** * The '<em><b>Cellon</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CELLON_VALUE * @generated * @ordered */ CELLON(0, "cellon", "cellon"), /** * The '<em><b>Chemonite</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CHEMONITE_VALUE * @generated * @ordered */ CHEMONITE(1, "chemonite", "chemonite"), /** * The '<em><b>Unknown</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #UNKNOWN_VALUE * @generated * @ordered */ UNKNOWN(2, "unknown", "unknown"), /** * The '<em><b>Other</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OTHER_VALUE * @generated * @ordered */ OTHER(3, "other", "other"), /** * The '<em><b>Creosote</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CREOSOTE_VALUE * @generated * @ordered */ CREOSOTE(4, "creosote", "creosote"), /** * The '<em><b>Penta</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PENTA_VALUE * @generated * @ordered */ PENTA(5, "penta", "penta"), /** * The '<em><b>Naphthena</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NAPHTHENA_VALUE * @generated * @ordered */ NAPHTHENA(6, "naphthena", "naphthena"); /** * The '<em><b>Cellon</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Cellon</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CELLON * @model name="cellon" * @generated * @ordered */ public static final int CELLON_VALUE = 0; /** * The '<em><b>Chemonite</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Chemonite</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CHEMONITE * @model name="chemonite" * @generated * @ordered */ public static final int CHEMONITE_VALUE = 1; /** * The '<em><b>Unknown</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Unknown</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #UNKNOWN * @model name="unknown" * @generated * @ordered */ public static final int UNKNOWN_VALUE = 2; /** * The '<em><b>Other</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Other</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OTHER * @model name="other" * @generated * @ordered */ public static final int OTHER_VALUE = 3; /** * The '<em><b>Creosote</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Creosote</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CREOSOTE * @model name="creosote" * @generated * @ordered */ public static final int CREOSOTE_VALUE = 4; /** * The '<em><b>Penta</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Penta</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PENTA * @model name="penta" * @generated * @ordered */ public static final int PENTA_VALUE = 5; /** * The '<em><b>Naphthena</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Naphthena</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NAPHTHENA * @model name="naphthena" * @generated * @ordered */ public static final int NAPHTHENA_VALUE = 6; /** * An array of all the '<em><b>Pole Preservative Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final PolePreservativeKind[] VALUES_ARRAY = new PolePreservativeKind[] { CELLON, CHEMONITE, UNKNOWN, OTHER, CREOSOTE, PENTA, NAPHTHENA, }; /** * A public read-only list of all the '<em><b>Pole Preservative Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<PolePreservativeKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Pole Preservative Kind</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static PolePreservativeKind get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { PolePreservativeKind result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Pole Preservative Kind</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static PolePreservativeKind getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { PolePreservativeKind result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Pole Preservative Kind</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static PolePreservativeKind get(int value) { switch (value) { case CELLON_VALUE: return CELLON; case CHEMONITE_VALUE: return CHEMONITE; case UNKNOWN_VALUE: return UNKNOWN; case OTHER_VALUE: return OTHER; case CREOSOTE_VALUE: return CREOSOTE; case PENTA_VALUE: return PENTA; case NAPHTHENA_VALUE: return NAPHTHENA; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private PolePreservativeKind(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //PolePreservativeKind
/* * 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.iot.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Parameters used when defining a mitigation action that move a set of things to a thing group. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AddThingsToThingGroupParams implements Serializable, Cloneable, StructuredPojo { /** * <p> * The list of groups to which you want to add the things that triggered the mitigation action. You can add a thing * to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * </p> */ private java.util.List<String> thingGroupNames; /** * <p> * Specifies if this mitigation action can move the things that triggered the mitigation action even if they are * part of one or more dynamic thing groups. * </p> */ private Boolean overrideDynamicGroups; /** * <p> * The list of groups to which you want to add the things that triggered the mitigation action. You can add a thing * to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * </p> * * @return The list of groups to which you want to add the things that triggered the mitigation action. You can add * a thing to a maximum of 10 groups, but you can't add a thing to more than one group in the same * hierarchy. */ public java.util.List<String> getThingGroupNames() { return thingGroupNames; } /** * <p> * The list of groups to which you want to add the things that triggered the mitigation action. You can add a thing * to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * </p> * * @param thingGroupNames * The list of groups to which you want to add the things that triggered the mitigation action. You can add a * thing to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. */ public void setThingGroupNames(java.util.Collection<String> thingGroupNames) { if (thingGroupNames == null) { this.thingGroupNames = null; return; } this.thingGroupNames = new java.util.ArrayList<String>(thingGroupNames); } /** * <p> * The list of groups to which you want to add the things that triggered the mitigation action. You can add a thing * to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setThingGroupNames(java.util.Collection)} or {@link #withThingGroupNames(java.util.Collection)} if you * want to override the existing values. * </p> * * @param thingGroupNames * The list of groups to which you want to add the things that triggered the mitigation action. You can add a * thing to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * @return Returns a reference to this object so that method calls can be chained together. */ public AddThingsToThingGroupParams withThingGroupNames(String... thingGroupNames) { if (this.thingGroupNames == null) { setThingGroupNames(new java.util.ArrayList<String>(thingGroupNames.length)); } for (String ele : thingGroupNames) { this.thingGroupNames.add(ele); } return this; } /** * <p> * The list of groups to which you want to add the things that triggered the mitigation action. You can add a thing * to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * </p> * * @param thingGroupNames * The list of groups to which you want to add the things that triggered the mitigation action. You can add a * thing to a maximum of 10 groups, but you can't add a thing to more than one group in the same hierarchy. * @return Returns a reference to this object so that method calls can be chained together. */ public AddThingsToThingGroupParams withThingGroupNames(java.util.Collection<String> thingGroupNames) { setThingGroupNames(thingGroupNames); return this; } /** * <p> * Specifies if this mitigation action can move the things that triggered the mitigation action even if they are * part of one or more dynamic thing groups. * </p> * * @param overrideDynamicGroups * Specifies if this mitigation action can move the things that triggered the mitigation action even if they * are part of one or more dynamic thing groups. */ public void setOverrideDynamicGroups(Boolean overrideDynamicGroups) { this.overrideDynamicGroups = overrideDynamicGroups; } /** * <p> * Specifies if this mitigation action can move the things that triggered the mitigation action even if they are * part of one or more dynamic thing groups. * </p> * * @return Specifies if this mitigation action can move the things that triggered the mitigation action even if they * are part of one or more dynamic thing groups. */ public Boolean getOverrideDynamicGroups() { return this.overrideDynamicGroups; } /** * <p> * Specifies if this mitigation action can move the things that triggered the mitigation action even if they are * part of one or more dynamic thing groups. * </p> * * @param overrideDynamicGroups * Specifies if this mitigation action can move the things that triggered the mitigation action even if they * are part of one or more dynamic thing groups. * @return Returns a reference to this object so that method calls can be chained together. */ public AddThingsToThingGroupParams withOverrideDynamicGroups(Boolean overrideDynamicGroups) { setOverrideDynamicGroups(overrideDynamicGroups); return this; } /** * <p> * Specifies if this mitigation action can move the things that triggered the mitigation action even if they are * part of one or more dynamic thing groups. * </p> * * @return Specifies if this mitigation action can move the things that triggered the mitigation action even if they * are part of one or more dynamic thing groups. */ public Boolean isOverrideDynamicGroups() { return this.overrideDynamicGroups; } /** * 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 (getThingGroupNames() != null) sb.append("ThingGroupNames: ").append(getThingGroupNames()).append(","); if (getOverrideDynamicGroups() != null) sb.append("OverrideDynamicGroups: ").append(getOverrideDynamicGroups()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AddThingsToThingGroupParams == false) return false; AddThingsToThingGroupParams other = (AddThingsToThingGroupParams) obj; if (other.getThingGroupNames() == null ^ this.getThingGroupNames() == null) return false; if (other.getThingGroupNames() != null && other.getThingGroupNames().equals(this.getThingGroupNames()) == false) return false; if (other.getOverrideDynamicGroups() == null ^ this.getOverrideDynamicGroups() == null) return false; if (other.getOverrideDynamicGroups() != null && other.getOverrideDynamicGroups().equals(this.getOverrideDynamicGroups()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getThingGroupNames() == null) ? 0 : getThingGroupNames().hashCode()); hashCode = prime * hashCode + ((getOverrideDynamicGroups() == null) ? 0 : getOverrideDynamicGroups().hashCode()); return hashCode; } @Override public AddThingsToThingGroupParams clone() { try { return (AddThingsToThingGroupParams) 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.iot.model.transform.AddThingsToThingGroupParamsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright (C) 2011 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 cn.droidlover.xdroid.cache; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * ***************************************************************************** * Taken from the JB source code, can be found in: * libcore/luni/src/main/java/libcore/io/DiskLruCache.java * or direct link: * https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java * ***************************************************************************** * <p/> * A cache that uses a bounded amount of space on a filesystem. Each cache * entry has a string key and a fixed number of values. Values are byte * sequences, accessible as streams or files. Each value must be between {@code * 0} and {@code Integer.MAX_VALUE} bytes in length. * <p/> * <p>The cache stores its data in a directory on the filesystem. This * directory must be exclusive to the cache; the cache may delete or overwrite * files from its directory. It is an error for multiple processes to use the * same cache directory at the same time. * <p/> * <p>This cache limits the number of bytes that it will store on the * filesystem. When the number of stored bytes exceeds the limit, the cache will * remove entries in the background until the limit is satisfied. The limit is * not strict: the cache may temporarily exceed it while waiting for files to be * deleted. The limit does not include filesystem overhead or the cache * journal so space-sensitive applications should set a conservative limit. * <p/> * <p>Clients call {@link #edit} to create or update the values of an entry. An * entry may have only one editor at one time; if a value is not available to be * edited then {@link #edit} will return null. * <ul> * <li>When an entry is being <strong>created</strong> it is necessary to * supply a full set of values; the empty value should be used as a * placeholder if necessary. * <li>When an entry is being <strong>edited</strong>, it is not necessary * to supply data for every value; values default to their previous * value. * </ul> * Every {@link #edit} call must be matched by a call to {@link Editor#commit} * or {@link Editor#abort}. Committing is atomic: a read observes the full set * of values as they were before or after the commit, but never a mix of values. * <p/> * <p>Clients call {@link #get} to read a snapshot of an entry. The read will * observe the value at the time that {@link #get} was called. Updates and * removals after the call do not impact ongoing reads. * <p/> * <p>This class is tolerant of some I/O errors. If files are missing with the * filesystem, the corresponding entries will be dropped from the cache. If * an error occurs while writing a cache value, the edit will fail silently. * Callers should handle other problems by catching {@code IOException} and * responding appropriately. */ public final class DiskLruCache implements Closeable { static final String JOURNAL_FILE = "journal"; static final String JOURNAL_FILE_TMP = "journal.tmp"; static final String MAGIC = "libcore.io.DiskLruCache"; static final String VERSION_1 = "1"; static final long ANY_SEQUENCE_NUMBER = -1; private static final String CLEAN = "CLEAN"; private static final String DIRTY = "DIRTY"; private static final String REMOVE = "REMOVE"; private static final String READ = "READ"; private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final int IO_BUFFER_SIZE = 8 * 1024; /* * This cache uses a journal file named "journal". A typical journal file * looks like this: * libcore.io.DiskLruCache * 1 * 100 * 2 * * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 * DIRTY 335c4c6028171cfddfbaae1a9c313c52 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 * REMOVE 335c4c6028171cfddfbaae1a9c313c52 * DIRTY 1ab96a171faeeee38496d8b330771a7a * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 * READ 335c4c6028171cfddfbaae1a9c313c52 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 * * The first five lines of the journal form its header. They are the * constant string "libcore.io.DiskLruCache", the disk cache's version, * the application's version, the value count, and a blank line. * * Each of the subsequent lines in the file is a record of the state of a * cache entry. Each line contains space-separated values: a state, a key, * and optional state-specific values. * o DIRTY lines track that an entry is actively being created or updated. * Every successful DIRTY action should be followed by a CLEAN or REMOVE * action. DIRTY lines without a matching CLEAN or REMOVE indicate that * temporary files may need to be deleted. * o CLEAN lines track a cache entry that has been successfully published * and may be read. A publish line is followed by the lengths of each of * its values. * o READ lines track accesses for LRU. * o REMOVE lines track entries that have been deleted. * * The journal file is appended to as cache operations occur. The journal may * occasionally be compacted by dropping redundant lines. A temporary file named * "journal.tmp" will be used during compaction; that file should be deleted if * it exists when the cache is opened. */ private final File directory; private final File journalFile; private final File journalFileTmp; private final int appVersion; private final long maxSize; private final int valueCount; private long size = 0; private Writer journalWriter; private final LinkedHashMap<String, Entry> lruEntries = new LinkedHashMap<String, Entry>(0, 0.75f, true); private int redundantOpCount; /** * To differentiate between old and current snapshots, each entry is given * a sequence number each time an edit is committed. A snapshot is stale if * its sequence number is not equal to its entry's sequence number. */ private long nextSequenceNumber = 0; /* From java.util.Arrays */ @SuppressWarnings("unchecked") private static <T> T[] copyOfRange(T[] original, int start, int end) { final int originalLength = original.length; // For exception priority compatibility. if (start > end) { throw new IllegalArgumentException(); } if (start < 0 || start > originalLength) { throw new ArrayIndexOutOfBoundsException(); } final int resultLength = end - start; final int copyLength = Math.min(resultLength, originalLength - start); final T[] result = (T[]) Array .newInstance(original.getClass().getComponentType(), resultLength); System.arraycopy(original, start, result, 0, copyLength); return result; } /** * Returns the remainder of 'reader' as a string, closing it when done. */ public static String readFully(Reader reader) throws IOException { try { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; int count; while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } return writer.toString(); } finally { reader.close(); } } /** * Returns the ASCII characters up to but not including the next "\r\n", or * "\n". * * @throws EOFException if the stream is exhausted before the next newline * character. */ public static String readAsciiLine(InputStream in) throws IOException { // TODO: support UTF-8 here instead StringBuilder result = new StringBuilder(80); while (true) { int c = in.read(); if (c == -1) { throw new EOFException(); } else if (c == '\n') { break; } result.append((char) c); } int length = result.length(); if (length > 0 && result.charAt(length - 1) == '\r') { result.setLength(length - 1); } return result.toString(); } /** * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null. */ public static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } /** * Recursively delete everything in {@code dir}. */ // TODO: this should specify paths as Strings rather than as Files public static void deleteContents(File dir) throws IOException { File[] files = dir.listFiles(); if (files == null) { throw new IllegalArgumentException("not a directory: " + dir); } for (File file : files) { if (file.isDirectory()) { deleteContents(file); } if (!file.delete()) { throw new IOException("failed to delete file: " + file); } } } /** * This cache uses a single background thread to evict entries. */ private final ExecutorService executorService = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); private final Callable<Void> cleanupCallable = new Callable<Void>() { @Override public Void call() throws Exception { synchronized (DiskLruCache.this) { if (journalWriter == null) { return null; // closed } trimToSize(); if (journalRebuildRequired()) { rebuildJournal(); redundantOpCount = 0; } } return null; } }; private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) { this.directory = directory; this.appVersion = appVersion; this.journalFile = new File(directory, JOURNAL_FILE); this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP); this.valueCount = valueCount; this.maxSize = maxSize; } /** * Opens the cache in {@code directory}, creating a cache if none exists * there. * * @param directory a writable directory * @param appVersion * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store * @throws IOException if reading or writing the cache directory fails */ public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize) throws IOException { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } if (valueCount <= 0) { throw new IllegalArgumentException("valueCount <= 0"); } // prefer to pick up where we left off DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); if (cache.journalFile.exists()) { try { cache.readJournal(); cache.processJournal(); cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true), IO_BUFFER_SIZE); return cache; } catch (IOException journalIsCorrupt) { // System.logW("DiskLruCache " + directory + " is corrupt: " // + journalIsCorrupt.getMessage() + ", removing"); cache.delete(); } } // create a new empty cache directory.mkdirs(); cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); cache.rebuildJournal(); return cache; } private void readJournal() throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE); try { String magic = readAsciiLine(in); String version = readAsciiLine(in); String appVersionString = readAsciiLine(in); String valueCountString = readAsciiLine(in); String blank = readAsciiLine(in); if (!MAGIC.equals(magic) || !VERSION_1.equals(version) || !Integer.toString(appVersion).equals(appVersionString) || !Integer.toString(valueCount).equals(valueCountString) || !"".equals(blank)) { throw new IOException("unexpected journal header: [" + magic + ", " + version + ", " + valueCountString + ", " + blank + "]"); } while (true) { try { readJournalLine(readAsciiLine(in)); } catch (EOFException endOfJournal) { break; } } } finally { closeQuietly(in); } } private void readJournalLine(String line) throws IOException { String[] parts = line.split(" "); if (parts.length < 2) { throw new IOException("unexpected journal line: " + line); } String key = parts[1]; if (parts[0].equals(REMOVE) && parts.length == 2) { lruEntries.remove(key); return; } Entry entry = lruEntries.get(key); if (entry == null) { entry = new Entry(key); lruEntries.put(key, entry); } if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) { entry.readable = true; entry.currentEditor = null; entry.setLengths(copyOfRange(parts, 2, parts.length)); } else if (parts[0].equals(DIRTY) && parts.length == 2) { entry.currentEditor = new Editor(entry); } else if (parts[0].equals(READ) && parts.length == 2) { // this work was already done by calling lruEntries.get() } else { throw new IOException("unexpected journal line: " + line); } } /** * Computes the initial size and collects garbage as a part of opening the * cache. Dirty entries are assumed to be inconsistent and will be deleted. */ private void processJournal() throws IOException { deleteIfExists(journalFileTmp); for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) { Entry entry = i.next(); if (entry.currentEditor == null) { for (int t = 0; t < valueCount; t++) { size += entry.lengths[t]; } } else { entry.currentEditor = null; for (int t = 0; t < valueCount; t++) { deleteIfExists(entry.getCleanFile(t)); deleteIfExists(entry.getDirtyFile(t)); } i.remove(); } } } /** * Creates a new journal that omits redundant information. This replaces the * current journal if it exists. */ private synchronized void rebuildJournal() throws IOException { if (journalWriter != null) { journalWriter.close(); } Writer writer = new BufferedWriter(new FileWriter(journalFileTmp), IO_BUFFER_SIZE); writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); writer.write("\n"); writer.write(Integer.toString(appVersion)); writer.write("\n"); writer.write(Integer.toString(valueCount)); writer.write("\n"); writer.write("\n"); for (Entry entry : lruEntries.values()) { if (entry.currentEditor != null) { writer.write(DIRTY + ' ' + entry.key + '\n'); } else { writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); } } writer.close(); journalFileTmp.renameTo(journalFile); journalWriter = new BufferedWriter(new FileWriter(journalFile, true), IO_BUFFER_SIZE); } private static void deleteIfExists(File file) throws IOException { // try { // Libcore.os.remove(file.getPath()); // } catch (ErrnoException errnoException) { // if (errnoException.errno != OsConstants.ENOENT) { // throw errnoException.rethrowAsIOException(); // } // } if (file.exists() && !file.delete()) { throw new IOException(); } } /** * Returns a snapshot of the entry named {@code key}, or null if it doesn't * exist is not currently readable. If a value is returned, it is moved to * the head of the LRU queue. */ public synchronized Snapshot get(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null) { return null; } if (!entry.readable) { return null; } /* * Open all streams eagerly to guarantee that we see a single published * snapshot. If we opened streams lazily then the streams could come * with different edits. */ InputStream[] ins = new InputStream[valueCount]; try { for (int i = 0; i < valueCount; i++) { ins[i] = new FileInputStream(entry.getCleanFile(i)); } } catch (FileNotFoundException e) { // a file must have been deleted manually! return null; } redundantOpCount++; journalWriter.append(READ + ' ' + key + '\n'); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return new Snapshot(key, entry.sequenceNumber, ins); } /** * Returns an editor for the entry named {@code key}, or null if another * edit is in progress. */ public Editor edit(String key) throws IOException { return edit(key, ANY_SEQUENCE_NUMBER); } private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null || entry.sequenceNumber != expectedSequenceNumber)) { return null; // snapshot is stale } if (entry == null) { entry = new Entry(key); lruEntries.put(key, entry); } else if (entry.currentEditor != null) { return null; // another edit is in progress } Editor editor = new Editor(entry); entry.currentEditor = editor; // flush the journal before creating files to prevent file leaks journalWriter.write(DIRTY + ' ' + key + '\n'); journalWriter.flush(); return editor; } /** * Returns the directory where this cache stores its data. */ public File getDirectory() { return directory; } /** * Returns the maximum number of bytes that this cache should use to store * its data. */ public long maxSize() { return maxSize; } /** * Returns the number of bytes currently being used to store the values in * this cache. This may be greater than the max size if a background * deletion is pending. */ public synchronized long size() { return size; } private synchronized void completeEdit(Editor editor, boolean success) throws IOException { Entry entry = editor.entry; if (entry.currentEditor != editor) { throw new IllegalStateException(); } // if this edit is creating the entry for the first time, every index must have a value if (success && !entry.readable) { for (int i = 0; i < valueCount; i++) { if (!entry.getDirtyFile(i).exists()) { editor.abort(); throw new IllegalStateException("edit didn't create file " + i); } } } for (int i = 0; i < valueCount; i++) { File dirty = entry.getDirtyFile(i); if (success) { if (dirty.exists()) { File clean = entry.getCleanFile(i); dirty.renameTo(clean); long oldLength = entry.lengths[i]; long newLength = clean.length(); entry.lengths[i] = newLength; size = size - oldLength + newLength; } } else { deleteIfExists(dirty); } } redundantOpCount++; entry.currentEditor = null; if (entry.readable | success) { entry.readable = true; journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); if (success) { entry.sequenceNumber = nextSequenceNumber++; } } else { lruEntries.remove(entry.key); journalWriter.write(REMOVE + ' ' + entry.key + '\n'); } if (size > maxSize || journalRebuildRequired()) { executorService.submit(cleanupCallable); } } /** * We only rebuild the journal when it will halve the size of the journal * and eliminate at least 2000 ops. */ private boolean journalRebuildRequired() { final int REDUNDANT_OP_COMPACT_THRESHOLD = 2000; return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD && redundantOpCount >= lruEntries.size(); } /** * Drops the entry for {@code key} if it exists and can be removed. Entries * actively being edited cannot be removed. * * @return true if an entry was removed. */ public synchronized boolean remove(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null || entry.currentEditor != null) { return false; } for (int i = 0; i < valueCount; i++) { File file = entry.getCleanFile(i); if (!file.delete()) { throw new IOException("failed to delete " + file); } size -= entry.lengths[i]; entry.lengths[i] = 0; } redundantOpCount++; journalWriter.append(REMOVE + ' ' + key + '\n'); lruEntries.remove(key); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return true; } /** * Returns true if this cache has been closed. */ public boolean isClosed() { return journalWriter == null; } private void checkNotClosed() { if (journalWriter == null) { throw new IllegalStateException("cache is closed"); } } /** * Force buffered operations to the filesystem. */ public synchronized void flush() throws IOException { checkNotClosed(); trimToSize(); journalWriter.flush(); } /** * Closes this cache. Stored values will remain on the filesystem. */ public synchronized void close() throws IOException { if (journalWriter == null) { return; // already closed } for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } } trimToSize(); journalWriter.close(); journalWriter = null; } private void trimToSize() throws IOException { while (size > maxSize) { // Map.Entry<String, Entry> toEvict = lruEntries.eldest(); final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next(); remove(toEvict.getKey()); } } /** * Closes the cache and deletes all of its stored values. This will delete * all files in the cache directory including files that weren't created by * the cache. */ public void delete() throws IOException { close(); deleteContents(directory); } private void validateKey(String key) { if (key.contains(" ") || key.contains("\n") || key.contains("\r")) { throw new IllegalArgumentException( "keys must not contain spaces or newlines: \"" + key + "\""); } } private static String inputStreamToString(InputStream in) throws IOException { return readFully(new InputStreamReader(in, UTF_8)); } /** * A snapshot of the values for an entry. */ public final class Snapshot implements Closeable { private final String key; private final long sequenceNumber; private final InputStream[] ins; private Snapshot(String key, long sequenceNumber, InputStream[] ins) { this.key = key; this.sequenceNumber = sequenceNumber; this.ins = ins; } /** * Returns an editor for this snapshot's entry, or null if either the * entry has changed since this snapshot was created or if another edit * is in progress. */ public Editor edit() throws IOException { return DiskLruCache.this.edit(key, sequenceNumber); } /** * Returns the unbuffered stream with the value for {@code index}. */ public InputStream getInputStream(int index) { return ins[index]; } /** * Returns the string value for {@code index}. */ public String getString(int index) throws IOException { return inputStreamToString(getInputStream(index)); } @Override public void close() { for (InputStream in : ins) { closeQuietly(in); } } } /** * Edits the values for an entry. */ public final class Editor { private final Entry entry; private boolean hasErrors; private Editor(Entry entry) { this.entry = entry; } /** * Returns an unbuffered input stream to read the last committed value, * or null if no value has been committed. */ public InputStream newInputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { return null; } return new FileInputStream(entry.getCleanFile(index)); } } /** * Returns the last committed value as a string, or null if no value * has been committed. */ public String getString(int index) throws IOException { InputStream in = newInputStream(index); return in != null ? inputStreamToString(in) : null; } /** * Returns a new unbuffered output stream to write the value at * {@code index}. If the underlying output stream encounters errors * when writing to the filesystem, this edit will be aborted when * {@link #commit} is called. The returned output stream does not throw * IOExceptions. */ public OutputStream newOutputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index))); } } /** * Sets the value at {@code index} to {@code value}. */ public void set(int index, String value) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(newOutputStream(index), UTF_8); writer.write(value); } finally { closeQuietly(writer); } } /** * Commits this edit so it is visible to readers. This releases the * edit lock so another edit may be started on the same key. */ public void commit() throws IOException { if (hasErrors) { completeEdit(this, false); remove(entry.key); // the previous entry is stale } else { completeEdit(this, true); } } /** * Aborts this edit. This releases the edit lock so another edit may be * started on the same key. */ public void abort() throws IOException { completeEdit(this, false); } private class FaultHidingOutputStream extends FilterOutputStream { private FaultHidingOutputStream(OutputStream out) { super(out); } @Override public void write(int oneByte) { try { out.write(oneByte); } catch (IOException e) { hasErrors = true; } } @Override public void write(byte[] buffer, int offset, int length) { try { out.write(buffer, offset, length); } catch (IOException e) { hasErrors = true; } } @Override public void close() { try { out.close(); } catch (IOException e) { hasErrors = true; } } @Override public void flush() { try { out.flush(); } catch (IOException e) { hasErrors = true; } } } } private final class Entry { private final String key; /** * Lengths of this entry's files. */ private final long[] lengths; /** * True if this entry has ever been published */ private boolean readable; /** * The ongoing edit or null if this entry is not being edited. */ private Editor currentEditor; /** * The sequence number of the most recently committed edit to this entry. */ private long sequenceNumber; private Entry(String key) { this.key = key; this.lengths = new long[valueCount]; } public String getLengths() throws IOException { StringBuilder result = new StringBuilder(); for (long size : lengths) { result.append(' ').append(size); } return result.toString(); } /** * Set lengths using decimal numbers like "10123". */ private void setLengths(String[] strings) throws IOException { if (strings.length != valueCount) { throw invalidLengths(strings); } try { for (int i = 0; i < strings.length; i++) { lengths[i] = Long.parseLong(strings[i]); } } catch (NumberFormatException e) { throw invalidLengths(strings); } } private IOException invalidLengths(String[] strings) throws IOException { throw new IOException("unexpected journal line: " + Arrays.toString(strings)); } public File getCleanFile(int i) { return new File(directory, key + "." + i); } public File getDirtyFile(int i) { return new File(directory, key + "." + i + ".tmp"); } } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.java19api; import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil; import com.intellij.codeInspection.AbstractDependencyVisitor; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.lang.java.JavaLanguage; import com.intellij.lang.java.lexer.JavaLexer; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.compiler.CompilerPaths; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.EffectiveLanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.impl.java.stubs.index.JavaModuleNameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.ProjectScope; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.text.UniqueNameGenerator; import gnu.trove.THashMap; import gnu.trove.THashSet; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; import java.util.regex.Pattern; import static com.intellij.ide.fileTemplates.JavaTemplateUtil.INTERNAL_MODULE_INFO_TEMPLATE_NAME; import static com.intellij.psi.PsiJavaModule.*; /** * @author Pavel.Dolgov */ public class Java9GenerateModuleDescriptorsAction extends AnAction { private static final Logger LOG = Logger.getInstance(Java9GenerateModuleDescriptorsAction.class); @Override public void update(@NotNull AnActionEvent e) { Project project = e.getProject(); e.getPresentation().setEnabled(project != null && !DumbService.isDumb(project) && isModularJdkAvailable()); } private static boolean isModularJdkAvailable() { return Arrays.stream(ProjectJdkTable.getInstance().getAllJdks()) .anyMatch(sdk -> JavaSdkUtil.isJdkAtLeast(sdk, JavaSdkVersion.JDK_1_9)); } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getProject(); if (project == null) return; CompilerManager compilerManager = CompilerManager.getInstance(project); CompileScope scope = compilerManager.createProjectCompileScope(project); if (!compilerManager.isUpToDate(scope)) { int result = Messages.showYesNoCancelDialog( project, RefactoringBundle.message("generate.module.descriptors.rebuild.message"), getTitle(), null); if (result == Messages.CANCEL) { return; } if (result == Messages.YES) { compilerManager.compile(scope, (aborted, errors, warnings, compileContext) -> { if (!aborted && errors == 0) { generate(project); } }); return; } } generate(project); } private static void generate(@NotNull Project project) { DumbService.getInstance(project).smartInvokeLater( () -> generateWhenSmart(project, new UniqueModuleNames(project))); } private static void generateWhenSmart(@NotNull Project project, @NotNull UniqueModuleNames uniqueModuleNames) { ProgressManager.getInstance().run( new Task.Backgroundable(project, getTitle(), true) { @Override public void run(@NotNull ProgressIndicator indicator) { THashMap<Module, List<File>> classFiles = new THashMap<>(); int totalFiles = collectClassFiles(project, classFiles); if (totalFiles != 0) { new DescriptorsGenerator(project, uniqueModuleNames).generate(classFiles, indicator, totalFiles); } } }); } private static int collectClassFiles(@NotNull Project project, @NotNull Map<Module, List<File>> classFiles) { ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); indicator.setIndeterminate(true); indicator.setText(RefactoringBundle.message("generate.module.descriptors.scanning.message")); Module[] modules = StreamEx.of(ModuleManager.getInstance(project).getModules()) .filter(module -> mayContainModuleInfo(module)) .toArray(Module.EMPTY_ARRAY); if (modules.length == 0) { CommonRefactoringUtil.showErrorHint( project, null, RefactoringBundle.message("generate.module.descriptors.no.suitable.modules.message"), getTitle(), null); return 0; } int totalFiles = 0; for (Module module : modules) { List<File> moduleClasses = new ArrayList<>(); classFiles.put(module, moduleClasses); String production = CompilerPaths.getModuleOutputPath(module, false); File productionRoot = production != null ? new File(production) : null; if (productionRoot != null) { collectClassFiles(productionRoot, moduleClasses); } totalFiles += moduleClasses.size(); } if (totalFiles == 0) { CommonRefactoringUtil.showErrorHint( project, null, RefactoringBundle.message("generate.module.descriptors.build.required.message"), getTitle(), null); } return totalFiles; } private static boolean mayContainModuleInfo(Module module) { return ReadAction.compute(() -> EffectiveLanguageLevelUtil.getEffectiveLanguageLevel(module).isAtLeast(LanguageLevel.JDK_1_9) ); } private static void collectClassFiles(@NotNull File file, @NotNull List<? super File> files) { final File[] children = file.listFiles(); if (children != null) { // is Directory for (File child : children) { collectClassFiles(child, files); } } else if (file.getName().endsWith(CommonClassNames.CLASS_FILE_EXTENSION)) { files.add(file); } } private static String getTitle() { return RefactoringBundle.message("generate.module.descriptors.title"); } private static String getCommandTitle() { return RefactoringBundle.message("generate.module.descriptors.command.title"); } private static class ProgressTracker { ProgressIndicator myIndicator; int myCount; int mySize; int myPhase; double myUpToNow; private final double[] myPhases; ProgressTracker(double... phases) { myPhases = phases; } void startPhase(String text, int size) { myIndicator.setText(text); myCount = 0; mySize = Math.min(size, 1); } public void nextPhase() { myUpToNow += myPhases[myPhase++]; } public void increment() { myIndicator.setFraction(myUpToNow + myPhases[myPhase] * ++myCount / (double)mySize); } public void init(ProgressIndicator indicator) { myIndicator = indicator; myIndicator.setFraction(0); myIndicator.setIndeterminate(false); } public void dispose() { myIndicator = null; } } private static class DescriptorsGenerator { private final Project myProject; private final UniqueModuleNames myUniqueModuleNames; private final List<ModuleNode> myModuleNodes = new ArrayList<>(); private final Set<String> myUsedExternallyPackages = new THashSet<>(); private final ProgressTracker myProgressTracker = new ProgressTracker(0.5, 0.3, 0.2); DescriptorsGenerator(@NotNull Project project, @NotNull UniqueModuleNames uniqueModuleNames) { myProject = project; myUniqueModuleNames = uniqueModuleNames; } void generate(THashMap<Module, List<File>> classFiles, ProgressIndicator indicator, int totalFiles) { myProgressTracker.init(indicator); List<ModuleInfo> moduleInfos; try { myProgressTracker.startPhase(RefactoringBundle.message("generate.module.descriptors.collecting.message"), totalFiles); Map<String, Set<ModuleNode>> packagesDeclaredInModules = collectDependencies(classFiles); myProgressTracker.nextPhase(); myProgressTracker.startPhase(RefactoringBundle.message("generate.module.descriptors.analysing.message"), myModuleNodes.size()); analyseDependencies(packagesDeclaredInModules); myProgressTracker.nextPhase(); myProgressTracker.startPhase(RefactoringBundle.message("generate.module.descriptors.preparing.message"), myModuleNodes.size()); moduleInfos = prepareModuleInfos(); myProgressTracker.nextPhase(); } finally { myProgressTracker.dispose(); } createFilesLater(moduleInfos); } private void createFilesLater(List<? extends ModuleInfo> moduleInfos) { ApplicationManager.getApplication().invokeLater(() -> { if (!myProject.isDisposed()) { CommandProcessor.getInstance().executeCommand(myProject, () -> ((ApplicationEx)ApplicationManager.getApplication()).runWriteActionWithCancellableProgressInDispatchThread( getCommandTitle(), myProject, null, indicator -> createFiles(myProject, moduleInfos, indicator)), getCommandTitle(), null); } }); } private Map<String, Set<ModuleNode>> collectDependencies(THashMap<Module, List<File>> classFiles) { PackageNamesCache packageNamesCache = new PackageNamesCache(myProject); Map<String, Set<ModuleNode>> packagesDeclaredInModules = new THashMap<>(); for (Map.Entry<Module, List<File>> entry : classFiles.entrySet()) { Module module = entry.getKey(); ModuleVisitor visitor = new ModuleVisitor(packageNamesCache); List<File> files = entry.getValue(); if (files.isEmpty()) { LOG.info("Output directory for module " + module.getName() + " doesn't contain .class files"); continue; } for (File file : files) { visitor.processFile(file); myProgressTracker.increment(); } Set<String> declaredPackages = visitor.getDeclaredPackages(); Set<String> requiredPackages = visitor.getRequiredPackages(); requiredPackages.removeAll(declaredPackages); myUsedExternallyPackages.addAll(requiredPackages); ModuleNode moduleNode = new ModuleNode(module, declaredPackages, requiredPackages, myUniqueModuleNames); myModuleNodes.add(moduleNode); for (String declaredPackage : declaredPackages) { packagesDeclaredInModules.computeIfAbsent(declaredPackage, __ -> new THashSet<>()).add(moduleNode); } } return packagesDeclaredInModules; } private void analyseDependencies(Map<String, Set<ModuleNode>> packagesDeclaredInModules) { Map<PsiJavaModule, ModuleNode> nodesByDescriptor = new THashMap<>(); for (ModuleNode moduleNode : myModuleNodes) { if (moduleNode.getDescriptor() != null) { nodesByDescriptor.put(moduleNode.getDescriptor(), moduleNode); } for (String packageName : moduleNode.getRequiredPackages()) { Set<ModuleNode> set = packagesDeclaredInModules.get(packageName); if (set == null) { PsiPackage psiPackage = JavaPsiFacade.getInstance(myProject).findPackage(packageName); if (psiPackage != null) { PsiJavaModule descriptor = ReadAction.compute(() -> findDescriptor(psiPackage)); if (descriptor != null) { ModuleNode dependencyNode = nodesByDescriptor.computeIfAbsent(descriptor, ModuleNode::new); moduleNode.getDependencies().add(dependencyNode); } } } else { if (set.size() != 1) { LOG.info("Split package " + packageName + " found in " + set); } moduleNode.getDependencies().addAll(set); } } myProgressTracker.increment(); } } private List<ModuleInfo> prepareModuleInfos() { List<ModuleInfo> moduleInfo = new ArrayList<>(); for (ModuleNode moduleNode : myModuleNodes) { if (moduleNode.getDescriptor() != null) { LOG.info("Module descriptor already exists in " + moduleNode); continue; } for (String packageName : moduleNode.getDeclaredPackages()) { if (myUsedExternallyPackages.contains(packageName)) { moduleNode.getExports().add(packageName); } } PsiDirectory rootDir = moduleNode.getRootDir(); if (rootDir != null) { List<String> dependencies = StreamEx.of(moduleNode.getSortedDependencies()) .map(ModuleNode::getName) .filter(name -> !JAVA_BASE.equals(name)) .toList(); List<String> exports = moduleNode.getSortedExports(); moduleInfo.add(new ModuleInfo(rootDir, moduleNode.getName(), dependencies, exports)); } else { LOG.info("Skipped module " + moduleNode + " because it doesn't have production source root"); } myProgressTracker.increment(); } return moduleInfo; } private static void createFiles(Project project, List<? extends ModuleInfo> moduleInfos, ProgressIndicator indicator) { indicator.setIndeterminate(false); int count = 0; double total = moduleInfos.size(); FileTemplate template = FileTemplateManager.getInstance(project).getInternalTemplate(INTERNAL_MODULE_INFO_TEMPLATE_NAME); for (ModuleInfo moduleInfo : moduleInfos) { ProgressManager.getInstance().executeNonCancelableSection(() -> createFile(template, moduleInfo)); indicator.setFraction(++count / total); } } private static void createFile(FileTemplate template, ModuleInfo moduleInfo) { if (moduleInfo.fileAlreadyExists()) { return; } Project project = moduleInfo.myRootDir.getProject(); Properties properties = FileTemplateManager.getInstance(project).getDefaultProperties(); FileTemplateUtil.fillDefaultProperties(properties, moduleInfo.myRootDir); properties.setProperty(FileTemplate.ATTRIBUTE_NAME, MODULE_INFO_CLASS); try { PsiJavaFile moduleInfoFile = // this is done to copy the file header to the output (PsiJavaFile)FileTemplateUtil.createFromTemplate(template, MODULE_INFO_FILE, properties, moduleInfo.myRootDir); PsiJavaModule javaModule = moduleInfoFile.getModuleDeclaration(); LOG.assertTrue(javaModule != null, "module-info file should contain module declaration"); CharSequence moduleText = moduleInfo.createModuleText(); PsiJavaFile dummyFile = (PsiJavaFile)PsiFileFactory.getInstance(project) .createFileFromText(MODULE_INFO_FILE, JavaLanguage.INSTANCE, moduleText); PsiJavaModule actualModule = dummyFile.getModuleDeclaration(); LOG.assertTrue(actualModule != null, "module declaration wasn't created"); javaModule.replace(actualModule); CodeStyleManager.getInstance(project).reformat(moduleInfoFile); } catch (Exception e) { LOG.error("Failed to create module-info.java in " + moduleInfo.myRootDir.getVirtualFile().getPath() + ": " + e.getMessage()); } } @Nullable private static PsiJavaModule findDescriptor(PsiPackage psiPackage) { PsiManager psiManager = psiPackage.getManager(); return StreamEx.of(psiPackage.getDirectories()) .map(PsiDirectory::getVirtualFile) .nonNull() .map(psiManager::findDirectory) .nonNull() .findAny() .map(JavaModuleGraphUtil::findDescriptorByElement) .orElse(null); } } private static class ModuleNode implements Comparable<ModuleNode> { private final Module myModule; private final Set<String> myDeclaredPackages; private final Set<String> myRequiredPackages; private final Set<ModuleNode> myDependencies = new THashSet<>(); private final Set<String> myExports = new THashSet<>(); private final PsiJavaModule myDescriptor; private final String myName; ModuleNode(@NotNull Module module, @NotNull Set<String> declaredPackages, @NotNull Set<String> requiredPackages, @NotNull UniqueModuleNames uniqueModuleNames) { myModule = module; myDeclaredPackages = declaredPackages; myRequiredPackages = requiredPackages; myDescriptor = ReadAction.compute(() -> { VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(false); return sourceRoots.length != 0 ? findDescriptor(module, sourceRoots[0]) : null; }); myName = myDescriptor != null ? myDescriptor.getName() : uniqueModuleNames.getUniqueName(myModule); } @Nullable private static PsiJavaModule findDescriptor(@NotNull Module module, VirtualFile root) { return JavaModuleGraphUtil.findDescriptorByFile(root, module.getProject()); } ModuleNode(@NotNull PsiJavaModule descriptor) { myModule = ReadAction.compute(() -> ModuleUtilCore.findModuleForPsiElement(descriptor)); myDeclaredPackages = Collections.emptySet(); myRequiredPackages = Collections.emptySet(); myDescriptor = descriptor; myName = myDescriptor.getName(); } public Set<String> getDeclaredPackages() { return myDeclaredPackages; } public Set<String> getRequiredPackages() { return myRequiredPackages; } public Set<ModuleNode> getDependencies() { return myDependencies; } public List<ModuleNode> getSortedDependencies() { ArrayList<ModuleNode> list = new ArrayList<>(myDependencies); list.sort(ModuleNode::compareTo); return list; } public Set<String> getExports() { return myExports; } public List<String> getSortedExports() { ArrayList<String> list = new ArrayList<>(myExports); list.sort(String::compareTo); return list; } public PsiJavaModule getDescriptor() { return myDescriptor; } @NotNull public String getName() { return myName; } @Override public String toString() { return myName; } @Override public boolean equals(Object o) { return this == o || o instanceof ModuleNode && myName.equals(((ModuleNode)o).myName); } @Override public int hashCode() { return myName.hashCode(); } @Override public int compareTo(@NotNull ModuleNode o) { int m1 = myModule == null ? 0 : 1, m2 = o.myModule == null ? 0 : 1; if (m1 != m2) return m1 - m2; int j1 = myName.startsWith("java.") || myName.startsWith("javax.") ? 0 : 1; int j2 = o.myName.startsWith("java.") || o.myName.startsWith("javax.") ? 0 : 1; if (j1 != j2) return j1 - j2; return StringUtil.compare(myName, o.myName, false); } public PsiDirectory getRootDir() { if (myModule == null) return null; return ReadAction.compute(() -> { ModuleRootManager moduleManager = ModuleRootManager.getInstance(myModule); PsiManager psiManager = PsiManager.getInstance(myModule.getProject()); return findJavaDirectory(psiManager, moduleManager.getSourceRoots(false)); }); } @Nullable private static PsiDirectory findJavaDirectory(PsiManager psiManager, VirtualFile[] roots) { return StreamEx.of(roots) .sorted(Comparator.comparingInt((VirtualFile vFile) -> "java".equals(vFile.getName()) ? 0 : 1) .thenComparing(VirtualFile::getName)) .map(psiManager::findDirectory) .nonNull() .findFirst() .orElse(null); } } public static class NameConverter { // "public" is for tests private static final Pattern NON_NAME = Pattern.compile("[^A-Za-z0-9]"); private static final Pattern DOT_SEQUENCE = Pattern.compile("\\.{2,}"); private static final Pattern SINGLE_DOT = Pattern.compile("\\."); @NotNull public static String convertModuleName(@NotNull String name) { // All non-alphanumeric characters ([^A-Za-z0-9]) are replaced with a dot (".") ... name = NON_NAME.matcher(name).replaceAll("."); // ... all repeating dots are replaced with one dot ... name = DOT_SEQUENCE.matcher(name).replaceAll("."); // ... and all leading and trailing dots are removed. name = StringUtil.trimLeading(StringUtil.trimTrailing(name, '.'), '.'); // sanitize keywords and leading digits String[] parts = splitByDots(name); StringBuilder builder = new StringBuilder(); boolean first = true; for (String part : parts) { if (part.length() == 0) { continue; } if (Character.isJavaIdentifierStart(part.charAt(0))) { if (!first) { builder.append('.'); } builder.append(part); if (JavaLexer.isKeyword(part, LanguageLevel.JDK_1_9)) { builder.append('x'); } } else { // it's a leading digit if (first) { builder.append("module"); } builder.append(part); } first = false; } return builder.toString(); } static String @NotNull [] splitByDots(@NotNull String text) { return SINGLE_DOT.split(text); } } private static class UniqueModuleNames { private final UniqueNameGenerator myNameGenerator; UniqueModuleNames(@NotNull Project project) { LOG.assertTrue(!DumbService.isDumb(project), "Module name index should be ready"); JavaModuleNameIndex index = JavaModuleNameIndex.getInstance(); GlobalSearchScope scope = ProjectScope.getAllScope(project); List<PsiJavaModule> modules = new ArrayList<>(); for (String key : index.getAllKeys(project)) { modules.addAll(index.get(key, project, scope)); } myNameGenerator = new UniqueNameGenerator(modules, module -> ReadAction.compute(() -> module.getName())); } @NotNull public String getUniqueName(@NotNull Module module) { String name = NameConverter.convertModuleName(module.getName()); return myNameGenerator.generateUniqueName(name); } } private static class PackageNamesCache { private final Map<String, Boolean> myPackages = new THashMap<>(); private final JavaPsiFacade myPsiFacade; PackageNamesCache(Project project) { myPsiFacade = JavaPsiFacade.getInstance(project); } private String getPackageName(String className) { for (int dotPos = className.lastIndexOf('.'); dotPos > 0; dotPos = className.lastIndexOf('.', dotPos - 1)) { String packageName = className.substring(0, dotPos); Boolean isPackage = myPackages.computeIfAbsent(packageName, this::isExistingPackage); if (isPackage) { return packageName; } } return null; } @NotNull private Boolean isExistingPackage(String packageName) { return ReadAction.compute(() -> myPsiFacade.findPackage(packageName) != null); } } private static class ModuleVisitor extends AbstractDependencyVisitor { private final Set<String> myRequiredPackages = new THashSet<>(); private final Set<String> myDeclaredPackages = new THashSet<>(); private final PackageNamesCache myPackageNamesCache; ModuleVisitor(PackageNamesCache packageNamesCache) { myPackageNamesCache = packageNamesCache; } @Override protected void addClassName(String className) { String packageName = myPackageNamesCache.getPackageName(className); if (packageName != null) { myRequiredPackages.add(packageName); } } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); String packageName = myPackageNamesCache.getPackageName(getCurrentClassName()); if (packageName != null) { myDeclaredPackages.add(packageName); } } public Set<String> getRequiredPackages() { return myRequiredPackages; } public Set<String> getDeclaredPackages() { return myDeclaredPackages; } } private static class ModuleInfo { final PsiDirectory myRootDir; final String myName; final List<String> myRequires; final List<String> myExports; private ModuleInfo(@NotNull PsiDirectory rootDir, @NotNull String name, @NotNull List<String> requires, @NotNull List<String> exports) { myRootDir = rootDir; myName = name; myRequires = requires; myExports = exports; } boolean fileAlreadyExists() { return StreamEx.of(myRootDir.getChildren()) .select(PsiFile.class) .map(PsiFileSystemItem::getName) .anyMatch(MODULE_INFO_FILE::equals); } @NotNull CharSequence createModuleText() { StringBuilder text = new StringBuilder(); text.append("module ").append(myName).append(" {"); for (String dependency : myRequires) { if ("java.base".equals(dependency)) { continue; } boolean isBadSyntax = StreamEx.of(NameConverter.splitByDots(dependency)) .anyMatch(part -> JavaLexer.isKeyword(part, LanguageLevel.JDK_1_9)); text.append('\n').append(isBadSyntax ? "// " : " ").append(PsiKeyword.REQUIRES).append(' ').append(dependency).append(";"); } if (!myRequires.isEmpty() && !myExports.isEmpty()) { text.append('\n'); } for (String packageName : myExports) { text.append("\n ").append(PsiKeyword.EXPORTS).append(' ').append(packageName).append(";"); } text.append("\n}"); return text; } } }
package ac.uk.abdn.fits.demo.query.operator; import java.util.Calendar; import java.util.HashMap; import math.geom2d.polygon.SimplePolygon2D; import ac.uk.abdn.fits.demo.gmap.model.polygon.Point; import ac.uk.abdn.fits.demo.gmap.model.polygon.Polygon; import ac.uk.abdn.fits.demo.query.operator.area.OperatingAreaRelaxation; import ac.uk.abdn.fits.demo.query.operator.area.OperatingAreaRelaxation.Direction; public class BanffshirePartnershipDialABus extends Operator{ public static final String POLYGON_STR= "-2.7685546875,57.69240553526457,0.0 -2.775421142578125,57.629963916724314,0.0 -2.7472686767578125,57.602014062545535,0.0 -2.6992034912109375,57.57514724603766,0.0 -2.65045166015625,57.54826058225397,0.0 -2.618865966796875,57.544207445951805,0.0 -2.5872802734375,57.56492896950416,0.0 -2.52685546875,57.57873677041636,0.0 -2.4616241455078125,57.58278606520832,0.0 -2.39501953125,57.59456326992429,0.0 -2.300262451171875,57.59612714310655,0.0 -2.2913360595703125,57.694974357167204,0.0 -2.7685546875,57.69240553526457,0.0"; private Polygon ploygon; // private PassengerType[] eligiblePassengers; // Unable to use regular PT private HashMap<PassengerAge, Double> age_group = new HashMap<PassengerAge, Double>(); private HashMap<PassengerMobilityStatus, Double> mobility_status = new HashMap<PassengerMobilityStatus, Double>(); private HashMap<PassengerJourneyPurpose, Double> journey_purpose = new HashMap<PassengerJourneyPurpose, Double>(); private EligibilityCalculator eligibility_cal; public static final String operatingTime = "0900-1600; Mon to Fri"; private String fare = "Equivalent to standard bus fares. Concession passes valid"; //"Equivalent to standard bus fares. Concession passes valid"; public BanffshirePartnershipDialABus(String name, String description, String elig, String preferences, String tel, String website, String address, String email, String contactUs, String layer) { super(name, description, elig, preferences, tel, website, address, email, contactUs, layer); } public BanffshirePartnershipDialABus() { super("Banffshire Partnership Dial a Bus" , "Wheelchair accessible door to door service" , "Unable to use regular PT" , "Social and shopping" , "" , "http://www.banffshirepartners.co.uk/comtrans.htm" , "The Old School, Boyndie, Banff. AB45 2JT" , "bpl.transport@banffdab.org.uk" , "The Old School, Boyndie, Banff. AB45 2JT\nTel: 01261 843598 FFFax: 01261 843598\nE-mail: bpl.transport@banffdab.org.uk" , "North Aberdeenshire on-demand bus services"); ploygon = new Polygon(Operator.getPoints(POLYGON_STR)); eligibility(); } private void eligibility(){ age_group.put(PassengerAge.under_16, 1.0); age_group.put(PassengerAge.from_16_to_21, 1.0); age_group.put(PassengerAge.from_22_to_54, 1.0); age_group.put(PassengerAge.from_55_to_59, 1.0); age_group.put(PassengerAge.over_60, 1.0); mobility_status.put(PassengerMobilityStatus.Able_bodied, 1.2); // mobility_status.put(PassengerMobilityStatus.Disabled_wheelchair_user, 1.2); mobility_status.put(PassengerMobilityStatus.Disabled_wheelchair_user, 1.0); // change from 1.2 to 1.0; discussed with David. mobility_status.put(PassengerMobilityStatus.Disable_other, 1.2); mobility_status.put(PassengerMobilityStatus.Mobility_impaired_unable_to_use_regular_PT, 1.0); journey_purpose.put(PassengerJourneyPurpose.Health_appointment, 1.4); journey_purpose.put(PassengerJourneyPurpose.Shopping, 1.0); journey_purpose.put(PassengerJourneyPurpose.Social_or_leisure, 1.0); journey_purpose.put(PassengerJourneyPurpose.School_or_education, 1.4); journey_purpose.put(PassengerJourneyPurpose.Work_commuting, 1.4); journey_purpose.put(PassengerJourneyPurpose.Other, 1.4); this.eligibility_cal = new EligibilityCalculator(age_group, mobility_status, journey_purpose); } @Override public boolean isCovered(Point point) { return ploygon.contains(point); } @Override public boolean checkOperatingTime(Calendar c) { if(c.get(Calendar.DAY_OF_WEEK)>= Calendar.MONDAY && c.get(Calendar.DAY_OF_WEEK)<= Calendar.FRIDAY){ if(c.get(Calendar.HOUR_OF_DAY)>= 9 && c.get(Calendar.HOUR_OF_DAY)< 16){ return true; } } return false; } @Override public String getDepartureTime() { return operatingTime; } @Override public String getArrivalTime() { return operatingTime; } @Override public String getFare() { // TODO Auto-generated method stub return fare; } @Override public String getOperatingTime() { return operatingTime; } @Override public boolean relaxOpeningTime(Calendar c, int hour) { if(c.get(Calendar.DAY_OF_WEEK)>= Calendar.MONDAY && c.get(Calendar.DAY_OF_WEEK)<= Calendar.FRIDAY){ if(c.get(Calendar.HOUR_OF_DAY)>= (9 - hour) && c.get(Calendar.HOUR_OF_DAY)< 16){ return true; } } return false; } @Override public boolean relaxClosingTime(Calendar c, int hour) { if(c.get(Calendar.DAY_OF_WEEK)>= Calendar.MONDAY && c.get(Calendar.DAY_OF_WEEK)<= Calendar.FRIDAY){ if(c.get(Calendar.HOUR_OF_DAY)>= 9 && c.get(Calendar.HOUR_OF_DAY)< (16 + hour)){ return true; } } return false; } @Override public boolean checkEligibility(PassengerAge age, PassengerMobilityStatus mobility, PassengerJourneyPurpose purpose) { if(eligibility_cal.get_disutil(age, mobility, purpose) == 1.0){ return true; } return false; } @Override public double relaxPassengerType(PassengerAge age, PassengerMobilityStatus mobility_status, PassengerJourneyPurpose purpose) { return eligibility_cal.get_disutil(age, mobility_status, purpose); } @Override public boolean relaxOperatingArea(Point point, Direction direction, int miles) { OperatingAreaRelaxation relaxation = OperatingAreaRelaxation.getInstance(); Polygon p = relaxation.relax(this.ploygon, direction, miles); if(p.contains(point)){ return true; } return false; } @Override public String getOpeningTime() { return "9:00"; } @Override public String getClosingTime() { return "16:00"; } @Override public String relaxiPassengerTypeInfo(PassengerAge age, PassengerMobilityStatus mobility_status, PassengerJourneyPurpose purpose) { StringBuilder sb = new StringBuilder(""); if(age_group.get(age) > 1.0){ sb.append("age group is relaxed to include " + age.toString(age)); } if(this.mobility_status.get(mobility_status) > 1.0){ if(sb.length() > 0){ sb.append("; "); } sb.append("passenger mobility status is relaxed to include " + mobility_status.toString(mobility_status)); } if(journey_purpose.get(purpose) > 1.0){ if(sb.length() > 0){ sb.append("; "); } sb.append("journey purpose is relaxed to include " + purpose.toString(purpose)); } return sb.toString(); } @Override public double getShortestDistanceToBoundary(Point point) { Point[] points = ploygon.getPoints(); double[] x_coord = new double[points.length]; double[] y_coord = new double[points.length]; for(int i=0; i< points.length; i++){ x_coord[i] = points[i].x(); y_coord[i] = points[i].y(); } SimplePolygon2D polygon2D = new SimplePolygon2D(x_coord, y_coord); return polygon2D.distance(point.x(), point.y()); } }
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.background.stationary; import boofcv.alg.InputSanityCheck; import boofcv.alg.misc.ImageMiscOps; import boofcv.core.image.FactoryGImageMultiBand; import boofcv.core.image.GImageMultiBand; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageInterleaved; import boofcv.struct.image.ImageType; import boofcv.struct.image.InterleavedF32; import pabeles.concurrency.GrowArray; //CONCURRENT_INLINE import boofcv.concurrency.BoofConcurrency; /** * Implementation of {@link BackgroundStationaryGaussian} for {@link ImageInterleaved}. * * @author Peter Abeles */ public class BackgroundStationaryGaussian_IL<T extends ImageInterleaved<T>> extends BackgroundStationaryGaussian<T> { // wrappers which provide abstraction across image types protected GImageMultiBand inputWrapper; protected GImageMultiBand bgWrapper; // storage for multi-band pixel values Work work; GrowArray<Work> workspace; // background is composed of bands*2 channels. even = mean, odd = variance InterleavedF32 background; /** * Configurations background removal. * * @param learnRate Specifies how quickly the background is updated. 0 = static 1.0 = instant. Try 0.05 * @param threshold Threshold for background. Consult a chi-square table for reasonably values. * 10 to 16 for 1 to 3 bands. * @param imageType Type of input image. */ public BackgroundStationaryGaussian_IL( float learnRate, float threshold, ImageType<T> imageType ) { super(learnRate, threshold, imageType); int numBands = imageType.getNumBands(); background = new InterleavedF32(0, 0, 2*numBands); bgWrapper = FactoryGImageMultiBand.create(background.getImageType()); bgWrapper.wrap(background); inputWrapper = FactoryGImageMultiBand.create(imageType); workspace = new GrowArray<>(() -> new Work(numBands)); work = workspace.grow(); } @Override public void reset() { background.reshape(0, 0); } @Override public void updateBackground( T frame ) { inputWrapper.wrap(frame); // Fill in background model with the mean and initial variance of each pixel if (background.width != frame.width || background.height != frame.height) { background.reshape(frame.width, frame.height); //CONCURRENT_BELOW BoofConcurrency.loopBlocks(0, frame.height, 20, workspace, (work, idx0, idx1) -> { final int idx0 = 0, idx1 = frame.height; float[] inputPixel = work.inputPixel; float[] bgPixel = work.bgPixel; for (int y = idx0; y < idx1; y++) { for (int x = 0; x < frame.width; x++) { inputWrapper.get(x, y, inputPixel); for (int i = 0; i < frame.numBands; i++) { bgPixel[i*2] = inputPixel[i]; bgPixel[i*2 + 1] = initialVariance; } bgWrapper.set(x, y, bgPixel); } } //CONCURRENT_ABOVE }}); return; } InputSanityCheck.checkSameShape(background, frame); final int numBands = background.getNumBands()/2; final float minusLearn = 1.0f - learnRate; //CONCURRENT_BELOW BoofConcurrency.loopBlocks(0, frame.height, 20, workspace, (work, idx0, idx1) -> { final int idx0 = 0, idx1 = frame.height; float[] inputPixel = work.inputPixel; for (int y = idx0; y < idx1; y++) { int indexBG = y*background.stride; int indexInput = frame.startIndex + y*frame.stride; int end = indexInput + frame.width*numBands; while (indexInput < end) { inputWrapper.getF(indexInput, inputPixel); for (int band = 0; band < numBands; band++) { float inputValue = inputPixel[band]; float meanBG = background.data[indexBG]; float varianceBG = background.data[indexBG + 1]; float diff = meanBG - inputValue; background.data[indexBG++] = minusLearn*meanBG + learnRate*inputValue; background.data[indexBG++] = minusLearn*varianceBG + learnRate*diff*diff; } indexInput += frame.numBands; } } //CONCURRENT_ABOVE }}); } @Override public void segment( T frame, GrayU8 segmented ) { segmented.reshape(frame.width, frame.height); if (background.width != frame.width || background.height != frame.height) { ImageMiscOps.fill(segmented, unknownValue); return; } inputWrapper.wrap(frame); final int numBands = background.getNumBands()/2; float adjustedMinimumDifference = minimumDifference*numBands; //CONCURRENT_BELOW BoofConcurrency.loopBlocks(0, frame.height, 20, workspace, (work, idx0, idx1) -> { final int idx0 = 0, idx1 = frame.height; float[] inputPixel = work.inputPixel; for (int y = idx0; y < idx1; y++) { int indexBG = y*background.stride; int indexInput = frame.startIndex + y*frame.stride; int indexSegmented = segmented.startIndex + y*segmented.stride; int end = indexInput + frame.width*frame.numBands; while (indexInput < end) { inputWrapper.getF(indexInput, inputPixel); float mahalanobis = 0; for (int band = 0; band < numBands; band++) { int indexBG_band = indexBG + band*2; float meanBG = background.data[indexBG_band]; float varBG = background.data[indexBG_band + 1]; float diff = meanBG - inputPixel[band]; mahalanobis += diff*diff/varBG; } if (mahalanobis <= threshold) { segmented.data[indexSegmented] = 0; } else { if (minimumDifference == 0) { segmented.data[indexSegmented] = 1; } else { float sumAbsDiff = 0; for (int band = 0; band < numBands; band++) { int indexBG_band = indexBG + band*2; sumAbsDiff += Math.abs(background.data[indexBG_band] - inputPixel[band]); } if (sumAbsDiff >= adjustedMinimumDifference) segmented.data[indexSegmented] = 1; else segmented.data[indexSegmented] = 0; } } indexInput += frame.numBands; indexSegmented += 1; indexBG += background.numBands; } } //CONCURRENT_ABOVE }}); } private static class Work { final float[] inputPixel; final float[] bgPixel; public Work( int numBands ) { inputPixel = new float[numBands]; bgPixel = new float[numBands*2]; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.nutch.indexer; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.crawl.CrawlDb; import org.apache.nutch.crawl.Inlinks; import org.apache.nutch.crawl.LinkDb; import org.apache.nutch.crawl.NutchWritable; import org.apache.nutch.metadata.Metadata; import org.apache.nutch.metadata.Nutch; import org.apache.nutch.net.URLFilters; import org.apache.nutch.net.URLNormalizers; import org.apache.nutch.parse.Parse; import org.apache.nutch.parse.ParseData; import org.apache.nutch.parse.ParseImpl; import org.apache.nutch.parse.ParseText; import org.apache.nutch.scoring.ScoringFilterException; import org.apache.nutch.scoring.ScoringFilters; public class IndexerMapReduce extends Configured implements Mapper<Text, Writable, Text, NutchWritable>, Reducer<Text, NutchWritable, Text, NutchIndexAction> { public static final Logger LOG = LoggerFactory.getLogger(IndexerMapReduce.class); public static final String INDEXER_DELETE = "indexer.delete"; public static final String INDEXER_DELETE_ROBOTS_NOINDEX = "indexer.delete.robots.noindex"; public static final String INDEXER_SKIP_NOTMODIFIED = "indexer.skip.notmodified"; public static final String URL_FILTERING = "indexer.url.filters"; public static final String URL_NORMALIZING = "indexer.url.normalizers"; private boolean skip = false; private boolean delete = false; private boolean deleteRobotsNoIndex = false; private IndexingFilters filters; private ScoringFilters scfilters; // using normalizers and/or filters private boolean normalize = false; private boolean filter = false; // url normalizers, filters and job configuration private URLNormalizers urlNormalizers; private URLFilters urlFilters; public void configure(JobConf job) { setConf(job); this.filters = new IndexingFilters(getConf()); this.scfilters = new ScoringFilters(getConf()); this.delete = job.getBoolean(INDEXER_DELETE, false); this.deleteRobotsNoIndex = job.getBoolean(INDEXER_DELETE_ROBOTS_NOINDEX, false); this.skip = job.getBoolean(INDEXER_SKIP_NOTMODIFIED, false); normalize = job.getBoolean(URL_NORMALIZING, false); filter = job.getBoolean(URL_FILTERING, false); if (normalize) { urlNormalizers = new URLNormalizers(getConf(), URLNormalizers.SCOPE_DEFAULT); } if (filter) { urlFilters = new URLFilters(getConf()); } } /** * Normalizes and trims extra whitespace from the given url. * * @param url The url to normalize. * * @return The normalized url. */ private String normalizeUrl(String url) { if (!normalize) { return url; } String normalized = null; if (urlNormalizers != null) { try { // normalize and trim the url normalized = urlNormalizers.normalize(url, URLNormalizers.SCOPE_INDEXER); normalized = normalized.trim(); } catch (Exception e) { LOG.warn("Skipping " + url + ":" + e); normalized = null; } } return normalized; } /** * Filters the given url. * * @param url The url to filter. * * @return The filtered url or null. */ private String filterUrl(String url) { if (!filter) { return url; } try { url = urlFilters.filter(url); } catch (Exception e) { url = null; } return url; } public void map(Text key, Writable value, OutputCollector<Text, NutchWritable> output, Reporter reporter) throws IOException { String urlString = filterUrl(normalizeUrl(key.toString())); if (urlString == null) { return; } else { key.set(urlString); } output.collect(key, new NutchWritable(value)); } public void reduce(Text key, Iterator<NutchWritable> values, OutputCollector<Text, NutchIndexAction> output, Reporter reporter) throws IOException { Inlinks inlinks = null; CrawlDatum dbDatum = null; CrawlDatum fetchDatum = null; ParseData parseData = null; ParseText parseText = null; while (values.hasNext()) { final Writable value = values.next().get(); // unwrap if (value instanceof Inlinks) { inlinks = (Inlinks)value; } else if (value instanceof CrawlDatum) { final CrawlDatum datum = (CrawlDatum)value; if (CrawlDatum.hasDbStatus(datum)) { dbDatum = datum; } else if (CrawlDatum.hasFetchStatus(datum)) { // don't index unmodified (empty) pages if (datum.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) { fetchDatum = datum; /** * Check if we need to delete 404 NOT FOUND and 301 PERMANENT REDIRECT. */ if (delete) { if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_GONE) { reporter.incrCounter("IndexerStatus", "Documents deleted", 1); NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE); output.collect(key, action); return; } if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM) { reporter.incrCounter("IndexerStatus", "Perm redirects deleted", 1); NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE); output.collect(key, action); return; } } } } else if (CrawlDatum.STATUS_LINKED == datum.getStatus() || CrawlDatum.STATUS_SIGNATURE == datum.getStatus() || CrawlDatum.STATUS_PARSE_META == datum.getStatus()) { continue; } else { throw new RuntimeException("Unexpected status: "+datum.getStatus()); } } else if (value instanceof ParseData) { parseData = (ParseData)value; // Handle robots meta? https://issues.apache.org/jira/browse/NUTCH-1434 if (deleteRobotsNoIndex) { // Get the robots meta data String robotsMeta = parseData.getMeta("robots"); // Has it a noindex for this url? if (robotsMeta != null && robotsMeta.toLowerCase().indexOf("noindex") != -1) { // Delete it! NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE); output.collect(key, action); return; } } } else if (value instanceof ParseText) { parseText = (ParseText)value; } else if (LOG.isWarnEnabled()) { LOG.warn("Unrecognized type: "+value.getClass()); } } if (fetchDatum == null || dbDatum == null || parseText == null || parseData == null) { return; // only have inlinks } // Whether to skip DB_NOTMODIFIED pages if (skip && dbDatum.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) { reporter.incrCounter("IndexerStatus", "Skipped", 1); return; } if (!parseData.getStatus().isSuccess() || fetchDatum.getStatus() != CrawlDatum.STATUS_FETCH_SUCCESS) { return; } NutchDocument doc = new NutchDocument(); final Metadata metadata = parseData.getContentMeta(); // add segment, used to map from merged index back to segment files doc.add("segment", metadata.get(Nutch.SEGMENT_NAME_KEY)); // add digest, used by dedup doc.add("digest", metadata.get(Nutch.SIGNATURE_KEY)); final Parse parse = new ParseImpl(parseText, parseData); try { // extract information from dbDatum and pass it to // fetchDatum so that indexing filters can use it final Text url = (Text) dbDatum.getMetaData().get(Nutch.WRITABLE_REPR_URL_KEY); if (url != null) { fetchDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY, url); } // run indexing filters doc = this.filters.filter(doc, parse, key, fetchDatum, inlinks); } catch (final IndexingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Error indexing "+key+": "+e); } reporter.incrCounter("IndexerStatus", "Errors", 1); return; } // skip documents discarded by indexing filters if (doc == null) { reporter.incrCounter("IndexerStatus", "Skipped by filters", 1); return; } float boost = 1.0f; // run scoring filters try { boost = this.scfilters.indexerScore(key, doc, dbDatum, fetchDatum, parse, inlinks, boost); } catch (final ScoringFilterException e) { if (LOG.isWarnEnabled()) { LOG.warn("Error calculating score " + key + ": " + e); } return; } // apply boost to all indexed fields. doc.setWeight(boost); // store boost for use by explain and dedup doc.add("boost", Float.toString(boost)); reporter.incrCounter("IndexerStatus", "Documents added", 1); NutchIndexAction action = new NutchIndexAction(doc, NutchIndexAction.ADD); output.collect(key, action); } public void close() throws IOException { } public static void initMRJob(Path crawlDb, Path linkDb, Collection<Path> segments, JobConf job) { LOG.info("IndexerMapReduce: crawldb: " + crawlDb); if (linkDb!=null) LOG.info("IndexerMapReduce: linkdb: " + linkDb); for (final Path segment : segments) { LOG.info("IndexerMapReduces: adding segment: " + segment); FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.FETCH_DIR_NAME)); FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.PARSE_DIR_NAME)); FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME)); FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME)); } FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME)); if (linkDb!=null) FileInputFormat.addInputPath(job, new Path(linkDb, LinkDb.CURRENT_NAME)); job.setInputFormat(SequenceFileInputFormat.class); job.setMapperClass(IndexerMapReduce.class); job.setReducerClass(IndexerMapReduce.class); job.setOutputFormat(IndexerOutputFormat.class); job.setOutputKeyClass(Text.class); job.setMapOutputValueClass(NutchWritable.class); job.setOutputValueClass(NutchWritable.class); } }
/** * Copyright (c) 2014 Samsung Electronics, 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. * * 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 HOLDER 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 com.samsung.sec.dexter.util; import com.google.common.base.Charsets; import com.samsung.sec.dexter.core.exception.DexterRuntimeException; import java.nio.charset.Charset; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.parser.ParserLanguage; public class CppUtil { static Charset sourceEncoding = Charsets.UTF_8; static Logger logger = Logger.getLogger(CppUtil.class); private CppUtil() {} /** * ExtractModuleName(String sourceFilePath, final int lineNumber) method is * responsible for getting ModuleInformation * * @param [in] * String sourceFilePath, final int lineNumber * @return [out] Map<String, String> * @warning [None] * @exception IO * exception */ public static synchronized Map<String, String> extractModuleName(String sourceFilePath, final int lineNumber) { Map<String, String> mapModuleName = null; String code = DexterUtilHelper.getContentsFromFile(sourceFilePath, sourceEncoding); IASTTranslationUnit translationUnit = TranslationUnitFactory.getASTTranslationUnit(code, ParserLanguage.CPP, sourceFilePath); final String fileExtension = sourceFilePath.substring(sourceFilePath.indexOf('.')); ASTVisitor visitor = new ASTVisitor() { public int visit(IASTDeclaration declaration) { boolean visitStatus = DexterUtilHelper.visitFunction(declaration, lineNumber, fileExtension); if (visitStatus) { return ASTVisitor.PROCESS_ABORT; } return ASTVisitor.PROCESS_CONTINUE; } }; visitor.shouldVisitDeclarations = true; translationUnit.accept(visitor); mapModuleName = DexterUtilHelper.getMapData(); return mapModuleName; } public static synchronized Map<String, String> extractModuleName(final IASTTranslationUnit translationUnit, final String fileExtension, final int lineNumber) { Map<String, String> mapModuleName = null; ASTVisitor visitor = new ASTVisitor() { public int visit(IASTDeclaration declaration) { boolean visitStatus = DexterUtilHelper.visitFunction(declaration, lineNumber, fileExtension); if (visitStatus) { return ASTVisitor.PROCESS_ABORT; } return ASTVisitor.PROCESS_CONTINUE; } }; visitor.shouldVisitDeclarations = true; translationUnit.accept(visitor); mapModuleName = DexterUtilHelper.getMapData(); return mapModuleName; } /** * GeneratorCodeMetrics(String sourceFilePath) method is responsible for * generating code Metrices * * @param [in] * String sourceFilePath * @return [out] Map<String, String> * @warning [None] * @exception IO * exception */ public static synchronized Map<String, Object> generatorCodeMetrics(String sourceFilePath) { Map<String, Object> mapCodeMetrics = new HashMap<String, Object>(); DexterUtilHelper.mapSourceMatrices.clear(); DexterUtilHelper.count = 0; DexterUtilHelper.methodCount = 0; DexterUtilHelper.classCount = 0; IASTTranslationUnit translationUnit = null; try { String code = DexterUtilHelper.getContentsFromFile(sourceFilePath, sourceEncoding); translationUnit = TranslationUnitFactory.getASTTranslationUnit(code, ParserLanguage.CPP, sourceFilePath); } catch (DexterRuntimeException e) { logger.error("can't make a code metrics : " + sourceFilePath, e); return new HashMap<String, Object>(0); } ASTVisitor visitor = new ASTVisitor() { public int visit(IASTDeclaration declaration) { boolean visitStatus = DexterUtilHelper.visitSourceCodeforCalMethodAndClassCount(declaration); if (visitStatus) { return ASTVisitor.PROCESS_ABORT; } return ASTVisitor.PROCESS_CONTINUE; } }; visitor.shouldVisitDeclarations = true; translationUnit.accept(visitor); ASTVisitor visitor1 = new ASTVisitor() { public int visit(IASTDeclaration declaration) { boolean visitStatus1 = DexterUtilHelper.visitSourceCodeforCalFileComplexity(declaration); if (visitStatus1) { return ASTVisitor.PROCESS_ABORT; } return ASTVisitor.PROCESS_CONTINUE; } }; visitor1.shouldVisitDeclarations = true; translationUnit.accept(visitor1); Map<String, Integer> mapSourceMatrices = DexterUtilHelper.mapSourceMatrices; Collection<Integer> values = mapSourceMatrices.values(); Object[] arrayValues = values.toArray(); int MaxComplexity = 0; int MinComplexity = 0; int SumOfComplexity = 0; int AverageComplexity = 0; if (arrayValues.length > 0) { int ArrayFirstValue = (int) arrayValues[0]; MaxComplexity = ArrayFirstValue; MinComplexity = ArrayFirstValue; SumOfComplexity = 0; for (Object object : arrayValues) { int value = (int) object; SumOfComplexity += value; if (value > MaxComplexity) { MaxComplexity = value; } if (value < MinComplexity) { MinComplexity = value; } } AverageComplexity = (int) SumOfComplexity / arrayValues.length; } int methodCount = DexterUtilHelper.methodCount; int classCount = DexterUtilHelper.classCount; int[] locArray = SourceCodeMatricsHelper.getSourceLOCArray(sourceFilePath); int SLOC = locArray[0]; int FileLOC = locArray[1]; int CodeCommentLOC = locArray[3]; // int EmptyLineLOC =locArray[2]; float commentRatio = 0.0f; int baseTotalLoc = CodeCommentLOC + SLOC; if (baseTotalLoc != 0) { commentRatio = CodeCommentLOC / (float) baseTotalLoc; } mapCodeMetrics.put("loc", FileLOC); mapCodeMetrics.put("sloc", SLOC); mapCodeMetrics.put("cloc", CodeCommentLOC); mapCodeMetrics.put("commentRatio", commentRatio); mapCodeMetrics.put("maxComplexity", MaxComplexity); mapCodeMetrics.put("minComplexity", MinComplexity); mapCodeMetrics.put("avgComplexity", AverageComplexity); mapCodeMetrics.put("classCount", classCount); mapCodeMetrics.put("methodCount", methodCount); return mapCodeMetrics; } }
package org.apache.lucene.search.exposed; import org.apache.lucene.search.exposed.compare.NamedComparator; import java.util.ArrayList; import java.util.List; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A request defines how a TermProvider is to behave with regard to fields * and sorting. * </p><p> * A FacetGroup is the primary access point for sorting. A FacetGroup contains one or * more Fields from one or more segments. * </p><p> * Field is single field and single segment oriented. It is used internally by * FacetGroup but can be used externally if the index is fully optimized and sorting * is requested for a single field. */ public class ExposedRequest { /** * A group is a collections of fields that are to be treated as one. * An example could be a group named "title" with the fields "lti", * "sort_title" and "subtitle" as fields. The same comparator must be used * for all fields in order for term ordering to be consistent for the group. */ public static class Group { private final String name; private final List<Field> fields; private final NamedComparator comparator; private final boolean concat; private final String collatorID; public Group(String name, List<Field> fields, NamedComparator comparator) { this(name, fields, comparator, null); } public Group(String name, List<Field> fields, NamedComparator comparator, String concatCollatorID) { this.name = name; this.fields = fields; this.comparator = comparator; concat = concatCollatorID != null; collatorID = concatCollatorID; } /** * Checks whether the given FacetGroup is equal to. The order of the * contained fields is irrelevant, but the set of fields must be equal. * </p><p> * The name of the group is not used while comparing. * @param other the group to compare to. * @return true if the two groups are equivalent.. */ // TODO: Fix hashcode to fulfill the equals vs. hashcode contract public boolean equals(Group other) { if (other.getFields().size() != getFields().size() || !getComparator().getID().equals(other.getComparator().getID())) { return false; } fieldLoop: for (Field otherField: other.getFields()) { for (Field thisField: getFields()) { if (thisField.equals(otherField)) { continue fieldLoop; } } return false; } return concat == other.concat; } /** * Similar to {@link #equals(org.apache.lucene.search.exposed.ExposedRequest.Group)} but if the comparatorID for * the other group is FREE_ORDER, it matches any comparatorID this group has. * @param other the group to check with. * @return true if this group can deliver data for the other group. */ // TODO: Re-introduce re-use of structures when count order is requested public boolean worksfor(Group other) { if (other.getFields().size() != getFields().size()) { return false; } if (!getComparator().getID().equals(other.getComparator().getID())) { return false; } fieldLoop: for (Field otherField: other.getFields()) { for (Field thisField: getFields()) { if (thisField.worksfor(otherField)) { continue fieldLoop; } } return false; } // concat inequality is acceptable here as it only affects display return true; } public String getName() { return name; } public List<Field> getFields() { return fields; } public NamedComparator getComparator() { return comparator; } public boolean isConcat() { return concat; } public List<String> getFieldNames() { List<String> fieldNames = new ArrayList<String>(fields.size()); for (Field field: fields) { fieldNames.add(field.getField()); } return fieldNames; } public String getConcatCollatorID() { return collatorID; } /** * If the comparatorID is {@link #FREE_ORDER} we set it to * {@link #LUCENE_ORDER}; */ /* void normalizeComparatorIDs() { if (!FREE_ORDER.equals(getComparatorID())) { return; } comparatorID = FREE_ORDER; for (Field field: fields) { field.comparatorID = FREE_ORDER; } } */ } public static class Field { private final String field; private final NamedComparator comparator; private final boolean concat; private final String collatorID; public Field(String field, NamedComparator comparator) { this(field, comparator, null); } public Field(String field, NamedComparator comparator, String concatCollatorID) { this.field = field; this.comparator = comparator; concat = concatCollatorID != null; collatorID = concatCollatorID; } /** * Checks whether the given object is also a Field and if so whether the * field and comparatorIDs are equal. * @param obj candidate for equality. * @return true if the given object is equivalent to this. */ public boolean equals(Object obj) { if (!(obj instanceof Field)) { return false; } Field other = (Field)obj; return field.equals(other.field) && comparator.getID().equals(other.comparator.getID()); } /** * Similar to {@link #equals} but if the comparatorID for the other * field is FREE_ORDER, it matches any comparatorID this field has. * @param other the field to check with. * @return true if this group can deliver data for the other field. **/ // TODO: All structures works when count order is requested public boolean worksfor(Field other) { return field.equals(other.field) && comparator.getID().equals(other.comparator.getID()); } public String getField() { return field; } public boolean isConcat() { return concat; } public NamedComparator getComparator() { return comparator; } public boolean equals(Field otherField) { return getField().equals(otherField.getField()) && getComparator().getID().equals(otherField.getComparator().getID()); } public String getConcatCollatorID() { return collatorID; } } }
/* * Copyright 2012-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.boot.actuate.autoconfigure.health; import java.security.Principal; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.springframework.boot.actuate.endpoint.SecurityContext; import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse; import org.springframework.boot.actuate.health.CompositeHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthEndpointWebExtension; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.HealthWebEndpointResponseMapper; import org.springframework.boot.actuate.health.OrderedHealthAggregator; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link HealthEndpointAutoConfiguration} in a servlet environment. * * @author Andy Wilkinson * @author Stephane Nicoll * @author Phillip Webb */ public class HealthEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration( AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); @Test public void runShouldCreateExtensionBeans() { this.contextRunner.run((context) -> assertThat(context) .hasSingleBean(HealthEndpointWebExtension.class)); } @Test public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") .run((context) -> assertThat(context) .doesNotHaveBean(HealthEndpointWebExtension.class)); } @Test public void runWithCustomHealthMappingShouldMapStatusCode() { this.contextRunner .withPropertyValues("management.health.status.http-mapping.CUSTOM=500") .run((context) -> { Object extension = context.getBean(HealthEndpointWebExtension.class); HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils .getField(extension, "responseMapper"); Class<SecurityContext> securityContext = SecurityContext.class; assertThat(responseMapper .map(Health.down().build(), mock(securityContext)) .getStatus()).isEqualTo(503); assertThat(responseMapper.map(Health.status("OUT_OF_SERVICE").build(), mock(securityContext)).getStatus()).isEqualTo(503); assertThat(responseMapper .map(Health.status("CUSTOM").build(), mock(securityContext)) .getStatus()).isEqualTo(500); }); } @Test public void unauthenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertThat( extension.health(mock(SecurityContext.class)).getBody().getDetails()) .isEmpty(); }); } @Test public void authenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); assertThat(extension.health(securityContext).getBody().getDetails()) .isEmpty(); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { this.contextRunner .withPropertyValues( "management.endpoint.health.show-details=when-authorized") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); assertThat(extension.health(securityContext).getBody().getDetails()) .isNotEmpty(); }); } @Test public void unauthenticatedUsersCanBeShownDetails() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=always") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertThat(extension.health(null).getBody().getDetails()) .isNotEmpty(); }); } @Test public void detailsCanBeHiddenFromAuthenticatedUsers() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=never") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertThat(extension.health(mock(SecurityContext.class)).getBody() .getDetails()).isEmpty(); }); } @Test public void detailsCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); assertThat(extension.health(securityContext).getBody().getDetails()) .isEmpty(); }); } @Test public void detailsCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); assertThat(extension.health(securityContext).getBody().getDetails()) .isNotEmpty(); }); } @Test public void unauthenticatedUsersAreNotShownComponentByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertDetailsNotFound( extension.healthForComponent(mock(SecurityContext.class), "simple")); }); } @Test public void authenticatedUsersAreNotShownComponentByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); assertDetailsNotFound( extension.healthForComponent(securityContext, "simple")); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownComponent() { this.contextRunner .withPropertyValues( "management.endpoint.health.show-details=when-authorized") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); assertSimpleComponent( extension.healthForComponent(securityContext, "simple")); }); } @Test public void unauthenticatedUsersCanBeShownComponent() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=always") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertSimpleComponent(extension.healthForComponent(null, "simple")); }); } @Test public void componentCanBeHiddenFromAuthenticatedUsers() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=never") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension .healthForComponent(mock(SecurityContext.class), "simple")); }); } @Test public void componentCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); assertDetailsNotFound( extension.healthForComponent(securityContext, "simple")); }); } @Test public void componentCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); assertSimpleComponent( extension.healthForComponent(securityContext, "simple")); }); } @Test public void componentThatDoesNotExistMapTo404() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=always") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertDetailsNotFound( extension.healthForComponent(null, "does-not-exist")); }); } @Test public void unauthenticatedUsersAreNotShownComponentInstanceByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponentInstance( mock(SecurityContext.class), "composite", "one")); }); } @Test public void authenticatedUsersAreNotShownComponentInstanceByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); assertDetailsNotFound(extension.healthForComponentInstance(securityContext, "composite", "one")); }); } @Test public void authenticatedUsersWhenAuthorizedCanBeShownComponentInstance() { this.contextRunner .withPropertyValues( "management.endpoint.health.show-details=when-authorized") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); assertSimpleComponent(extension.healthForComponentInstance( securityContext, "composite", "one")); }); } @Test public void unauthenticatedUsersCanBeShownComponentInstance() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=always") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertSimpleComponent(extension.healthForComponentInstance(null, "composite", "one")); }); } @Test public void componentInstanceCanBeHiddenFromAuthenticatedUsers() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=never") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponentInstance( mock(SecurityContext.class), "composite", "one")); }); } @Test public void componentInstanceCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(false); assertDetailsNotFound(extension.healthForComponentInstance( securityContext, "composite", "one")); }); } @Test public void componentInstanceCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ACTUATOR")).willReturn(true); assertSimpleComponent(extension.healthForComponentInstance( securityContext, "composite", "one")); }); } @Test public void componentInstanceThatDoesNotExistMapTo404() { this.contextRunner .withPropertyValues("management.endpoint.health.show-details=always") .run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponentInstance(null, "composite", "does-not-exist")); }); } private void assertDetailsNotFound(WebEndpointResponse<?> response) { assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); assertThat(response.getBody()).isNull(); } private void assertSimpleComponent(WebEndpointResponse<Health> response) { assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(response.getBody().getDetails()).containsOnly(entry("counter", 42)); } @Test public void roleCanBeCustomized() { this.contextRunner.withPropertyValues( "management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ADMIN").run((context) -> { HealthEndpointWebExtension extension = context .getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); given(securityContext.getPrincipal()) .willReturn(mock(Principal.class)); given(securityContext.isUserInRole("ADMIN")).willReturn(true); assertThat(extension.health(securityContext).getBody().getDetails()) .isNotEmpty(); }); } @Configuration static class HealthIndicatorsConfiguration { @Bean public HealthIndicator simpleHealthIndicator() { return () -> Health.up().withDetail("counter", 42).build(); } @Bean public HealthIndicator compositeHealthIndicator() { Map<String, HealthIndicator> nestedIndicators = new HashMap<>(); nestedIndicators.put("one", simpleHealthIndicator()); nestedIndicators.put("two", () -> Health.up().build()); return new CompositeHealthIndicator(new OrderedHealthAggregator(), nestedIndicators); } } }
package hex.tree; import hex.*; import static hex.ModelCategory.Binomial; import static hex.genmodel.GenModel.createAuxKey; import hex.genmodel.algos.tree.SharedTreeMojoModel; import hex.genmodel.algos.tree.SharedTreeSubgraph; import hex.glm.GLMModel; import hex.util.LinearAlgebraUtils; import water.*; import water.codegen.CodeGenerator; import water.codegen.CodeGeneratorPipeline; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.JCodeSB; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.parser.BufferedString; import water.util.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; public abstract class SharedTreeModel< M extends SharedTreeModel<M, P, O>, P extends SharedTreeModel.SharedTreeParameters, O extends SharedTreeModel.SharedTreeOutput > extends Model<M, P, O> implements Model.LeafNodeAssignment, Model.GetMostImportantFeatures { @Override public String[] getMostImportantFeatures(int n) { if (_output == null) return null; TwoDimTable vi = _output._variable_importances; if (vi==null) return null; n = Math.min(n, vi.getRowHeaders().length); String[] res = new String[n]; System.arraycopy(vi.getRowHeaders(), 0, res, 0, n); return res; } @Override public ToEigenVec getToEigenVec() { return LinearAlgebraUtils.toEigen; } public abstract static class SharedTreeParameters extends Model.Parameters { public int _ntrees=50; // Number of trees in the final model. Grid Search, comma sep values:50,100,150,200 public int _max_depth = 5; // Maximum tree depth. Grid Search, comma sep values:5,7 public double _min_rows = 10; // Fewest allowed observations in a leaf (in R called 'nodesize'). Grid Search, comma sep values public int _nbins = 20; // Numerical (real/int) cols: Build a histogram of this many bins, then split at the best point public int _nbins_cats = 1024; // Categorical (factor) cols: Build a histogram of this many bins, then split at the best point public double _min_split_improvement = 1e-5; // Minimum relative improvement in squared error reduction for a split to happen public enum HistogramType { AUTO, UniformAdaptive, Random, QuantilesGlobal, RoundRobin } public HistogramType _histogram_type = HistogramType.AUTO; // What type of histogram to use for finding optimal split points public double _r2_stopping = Double.MAX_VALUE; // Stop when the r^2 metric equals or exceeds this value public int _nbins_top_level = 1<<10; //hardcoded maximum top-level number of bins for real-valued columns public boolean _build_tree_one_node = false; public int _score_tree_interval = 0; // score every so many trees (no matter what) public int _initial_score_interval = 4000; //Adding this parameter to take away the hard coded value of 4000 for scoring the first 4 secs public int _score_interval = 4000; //Adding this parameter to take away the hard coded value of 4000 for scoring each iteration every 4 secs public double _sample_rate = 0.632; //fraction of rows to sample for each tree public double[] _sample_rate_per_class; //fraction of rows to sample for each tree, per class public boolean _calibrate_model = false; // Use Platt Scaling public Key<Frame> _calibration_frame; public Frame calib() { return _calibration_frame == null ? null : _calibration_frame.get(); } @Override public long progressUnits() { return _ntrees + (_histogram_type==HistogramType.QuantilesGlobal || _histogram_type==HistogramType.RoundRobin ? 1 : 0); } public double _col_sample_rate_change_per_level = 1.0f; //relative change of the column sampling rate for every level public double _col_sample_rate_per_tree = 1.0f; //fraction of columns to sample for each tree /** Fields which can NOT be modified if checkpoint is specified. * FIXME: should be defined in Schema API annotation */ private static String[] CHECKPOINT_NON_MODIFIABLE_FIELDS = { "_build_tree_one_node", "_sample_rate", "_max_depth", "_min_rows", "_nbins", "_nbins_cats", "_nbins_top_level"}; protected String[] getCheckpointNonModifiableFields() { return CHECKPOINT_NON_MODIFIABLE_FIELDS; } /** This method will take actual parameters and validate them with parameters of * requested checkpoint. In case of problem, it throws an API exception. * * @param checkpointParameters checkpoint parameters */ public void validateWithCheckpoint(SharedTreeParameters checkpointParameters) { for (Field fAfter : this.getClass().getFields()) { // only look at non-modifiable fields if (ArrayUtils.contains(getCheckpointNonModifiableFields(),fAfter.getName())) { for (Field fBefore : checkpointParameters.getClass().getFields()) { if (fBefore.equals(fAfter)) { try { if (!PojoUtils.equals(this, fAfter, checkpointParameters, checkpointParameters.getClass().getField(fAfter.getName()))) { throw new H2OIllegalArgumentException(fAfter.getName(), "TreeBuilder", "Field " + fAfter.getName() + " cannot be modified if checkpoint is specified!"); } } catch (NoSuchFieldException e) { throw new H2OIllegalArgumentException(fAfter.getName(), "TreeBuilder", "Field " + fAfter.getName() + " is not supported by checkpoint!"); } } } } } } } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { switch(_output.getModelCategory()) { case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain); case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain); case Regression: return new ModelMetricsRegression.MetricBuilderRegression(); default: throw H2O.unimpl(); } } public abstract static class SharedTreeOutput extends Model.Output { /** InitF value (for zero trees) * f0 = mean(yi) for gaussian * f0 = log(yi/1-yi) for bernoulli * * For GBM bernoulli, the initial prediction for 0 trees is * p = 1/(1+exp(-f0)) * * From this, the mse for 0 trees (null model) can be computed as follows: * mean((yi-p)^2) * */ public double _init_f; /** Number of trees actually in the model (as opposed to requested) */ public int _ntrees; /** More indepth tree stats */ public final TreeStats _treeStats; /** Trees get big, so store each one separately in the DKV. */ public Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeys; public Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeysAux; public ScoreKeeper[/*ntrees+1*/] _scored_train; public ScoreKeeper[/*ntrees+1*/] _scored_valid; public ScoreKeeper[] scoreKeepers() { ArrayList<ScoreKeeper> skl = new ArrayList<>(); ScoreKeeper[] ska = _validation_metrics != null ? _scored_valid : _scored_train; for( ScoreKeeper sk : ska ) if (!sk.isEmpty()) skl.add(sk); return skl.toArray(new ScoreKeeper[skl.size()]); } /** Training time */ public long[/*ntrees+1*/] _training_time_ms = {System.currentTimeMillis()}; /** * Variable importances computed during training */ public TwoDimTable _variable_importances; public VarImp _varimp; public GLMModel _calib_model; public SharedTreeOutput( SharedTree b) { super(b); _ntrees = 0; // No trees yet _treeKeys = new Key[_ntrees][]; // No tree keys yet _treeKeysAux = new Key[_ntrees][]; // No tree keys yet _treeStats = new TreeStats(); _scored_train = new ScoreKeeper[]{new ScoreKeeper(Double.NaN)}; _scored_valid = new ScoreKeeper[]{new ScoreKeeper(Double.NaN)}; _modelClassDist = _priorClassDist; } // Append next set of K trees public void addKTrees( DTree[] trees) { // DEBUG: Print the generated K trees //SharedTree.printGenerateTrees(trees); assert nclasses()==trees.length; // Compress trees and record tree-keys _treeKeys = Arrays.copyOf(_treeKeys ,_ntrees+1); _treeKeysAux = Arrays.copyOf(_treeKeysAux ,_ntrees+1); Key[] keys = _treeKeys[_ntrees] = new Key[trees.length]; Key[] keysAux = _treeKeysAux[_ntrees] = new Key[trees.length]; Futures fs = new Futures(); for( int i=0; i<nclasses(); i++ ) if( trees[i] != null ) { CompressedTree ct = trees[i].compress(_ntrees,i,_domains); DKV.put(keys[i]=ct._key,ct,fs); _treeStats.updateBy(trees[i]); // Update tree shape stats CompressedTree ctAux = new CompressedTree(trees[i]._abAux.buf(),-1,-1,-1); keysAux[i] = ctAux._key = Key.make(createAuxKey(ct._key.toString())); DKV.put(ctAux,fs); } _ntrees++; // 1-based for errors; _scored_train[0] is for zero trees, not 1 tree _scored_train = ArrayUtils.copyAndFillOf(_scored_train, _ntrees+1, new ScoreKeeper()); _scored_valid = _scored_valid != null ? ArrayUtils.copyAndFillOf(_scored_valid, _ntrees+1, new ScoreKeeper()) : null; _training_time_ms = ArrayUtils.copyAndFillOf(_training_time_ms, _ntrees+1, System.currentTimeMillis()); fs.blockForPending(); } public CompressedTree ctree( int tnum, int knum ) { return _treeKeys[tnum][knum].get(); } public String toStringTree ( int tnum, int knum ) { return ctree(tnum,knum).toString(this); } } public SharedTreeModel(Key<M> selfKey, P parms, O output) { super(selfKey, parms, output); } protected String[] makeAllTreeColumnNames() { int classTrees = 0; for (int i = 0; i < _output._treeKeys[0].length; ++i) { if (_output._treeKeys[0][i] != null) classTrees++; } final int outputcols = _output._treeKeys.length * classTrees; final String[] names = new String[outputcols]; int col = 0; for (int tidx = 0; tidx < _output._treeKeys.length; tidx++) { Key[] keys = _output._treeKeys[tidx]; for (int c = 0; c < keys.length; c++) { if (keys[c] != null) { names[col++] = "T" + (tidx + 1) + (keys.length == 1 ? "" : (".C" + (c + 1))); } } } return names; } @Override public Frame scoreLeafNodeAssignment(Frame frame, LeafNodeAssignmentType type, Key<Frame> destination_key) { Frame adaptFrm = new Frame(frame); adaptTestForTrain(adaptFrm, true, false); final String[] names = makeAllTreeColumnNames(); AssignLeafNodeTaskBase task = AssignLeafNodeTaskBase.make(_output, type); return task.execute(adaptFrm, names, destination_key); } public static class BufStringDecisionPathTracker implements SharedTreeMojoModel.DecisionPathTracker<BufferedString> { private final byte[] _buf = new byte[64]; private final BufferedString _bs = new BufferedString(_buf, 0, 0); private int _pos = 0; @Override public boolean go(int depth, boolean right) { _buf[depth] = right ? (byte) 'R' : (byte) 'L'; if (right) _pos = depth; return true; } @Override public BufferedString terminate() { _bs.setLen(_pos); _pos = 0; return _bs; } } private static abstract class AssignLeafNodeTaskBase extends MRTask<AssignLeafNodeTaskBase> { final Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeys; final String _domains[][]; AssignLeafNodeTaskBase(SharedTreeOutput output) { _treeKeys = output._treeKeys; _domains = output._domains; } protected abstract void initMap(); protected abstract void assignNode(final int tidx, final int cls, final CompressedTree tree, final double[] input, final NewChunk out); @Override public void map(Chunk chks[], NewChunk[] idx) { double[] input = new double[chks.length]; initMap(); for (int row = 0; row < chks[0]._len; row++) { for (int i = 0; i < chks.length; i++) input[i] = chks[i].atd(row); int col = 0; for (int tidx = 0; tidx < _treeKeys.length; tidx++) { Key[] keys = _treeKeys[tidx]; for (int cls = 0; cls < keys.length; cls++) { Key key = keys[cls]; if (key != null) { CompressedTree tree = DKV.get(key).get(); assignNode(tidx, cls, tree, input, idx[col++]); } } } assert (col == idx.length); } } protected abstract Frame execute(Frame adaptFrm, String[] names, Key<Frame> destKey); private static AssignLeafNodeTaskBase make(SharedTreeOutput modelOutput, LeafNodeAssignmentType type) { switch (type) { case Path: return new AssignTreePathTask(modelOutput); case Node_ID: return new AssignLeafNodeIdTask(modelOutput); default: throw new UnsupportedOperationException("Unknown leaf node assignment type: " + type); } } } private static class AssignTreePathTask extends AssignLeafNodeTaskBase { private transient BufStringDecisionPathTracker _tr; private AssignTreePathTask(SharedTreeOutput output) { super(output); } @Override protected void initMap() { _tr = new BufStringDecisionPathTracker(); } @Override protected void assignNode(int tidx, int cls, CompressedTree tree, double[] input, NewChunk out) { BufferedString pred = tree.getDecisionPath(input, _domains, _tr); out.addStr(pred); } @Override protected Frame execute(Frame adaptFrm, String[] names, Key<Frame> destKey) { Frame res = doAll(names.length, Vec.T_STR, adaptFrm).outputFrame(destKey, names, null); // convert to categorical Vec vv; Vec[] nvecs = new Vec[res.vecs().length]; for(int c=0;c<res.vecs().length;++c) { vv = res.vec(c); try { nvecs[c] = vv.toCategoricalVec(); } catch (Exception e) { VecUtils.deleteVecs(nvecs, c); throw e; } } res.delete(); res = new Frame(destKey, names, nvecs); DKV.put(res); return res; } } private static class AssignLeafNodeIdTask extends AssignLeafNodeTaskBase { private final Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _auxTreeKeys; private final int _nclasses; private transient BufStringDecisionPathTracker _tr; private AssignLeafNodeIdTask(SharedTreeOutput output) { super(output); _auxTreeKeys = output._treeKeysAux; _nclasses = output.nclasses(); } @Override protected void initMap() { _tr = new BufStringDecisionPathTracker(); } @Override protected void assignNode(int tidx, int cls, CompressedTree tree, double[] input, NewChunk out) { CompressedTree auxTree = _auxTreeKeys[tidx][cls].get(); assert auxTree != null; final double d = SharedTreeMojoModel.scoreTree(tree._bits, input, true, _domains); final int nodeId = SharedTreeMojoModel.getLeafNodeId(d, auxTree._bits); out.addNum(nodeId, 0); } @Override protected Frame execute(Frame adaptFrm, String[] names, Key<Frame> destKey) { return doAll(names.length, Vec.T_NUM, adaptFrm).outputFrame(destKey, names, null); } } @Override protected Frame postProcessPredictions(Frame adaptedFrame, Frame predictFr, Job j) { if (_output._calib_model == null) return predictFr; if (_output.getModelCategory() == Binomial) { Key<Job> jobKey = j != null ? j._key : null; Key<Frame> calibInputKey = Key.make(); Frame calibOutput = null; try { Frame calibInput = new Frame(calibInputKey, new String[]{"p"}, new Vec[]{predictFr.vec(1)}); calibOutput = _output._calib_model.score(calibInput); assert calibOutput._names.length == 3; Vec[] calPredictions = calibOutput.remove(new int[]{1, 2}); // append calibrated probabilities to the prediction frame predictFr.write_lock(jobKey); for (int i = 0; i < calPredictions.length; i++) predictFr.add("cal_" + predictFr.name(1 + i), calPredictions[i]); return predictFr.update(jobKey); } finally { predictFr.unlock(jobKey); DKV.remove(calibInputKey); if (calibOutput != null) calibOutput.remove(); } } else throw H2O.unimpl("Calibration is only supported for binomial models"); } protected double[] score0Incremental(Score.ScoreIncInfo sii, Chunk chks[], double offset, int row_in_chunk, double[] tmp, double[] preds) { return score0(chks, offset, row_in_chunk, tmp, preds); // by default delegate to non-incremental implementation } @Override protected double[] score0(double[] data, double[] preds, double offset) { return score0(data, preds, offset, _output._treeKeys.length); } @Override protected double[] score0(double[/*ncols*/] data, double[/*nclasses+1*/] preds) { return score0(data, preds, 0.0); } protected double[] score0(double[] data, double[] preds, double offset, int ntrees) { Arrays.fill(preds,0); return score0(data, preds, offset, 0, ntrees); } protected double[] score0(double[] data, double[] preds, double offset, int startTree, int ntrees) { // Prefetch trees into the local cache if it is necessary // Invoke scoring for( int tidx=startTree; tidx<ntrees; tidx++ ) score0(data, preds, tidx); return preds; } // Score per line per tree private void score0(double[] data, double[] preds, int treeIdx) { Key[] keys = _output._treeKeys[treeIdx]; for( int c=0; c<keys.length; c++ ) { if (keys[c] != null) { double pred = DKV.get(keys[c]).<CompressedTree>get().score(data,_output._domains); assert (!Double.isInfinite(pred)); preds[keys.length == 1 ? 0 : c + 1] += pred; } } } /** Performs deep clone of given model. */ protected M deepClone(Key<M> result) { M newModel = IcedUtils.deepCopy(self()); newModel._key = result; // Do not clone model metrics newModel._output.clearModelMetrics(); newModel._output._training_metrics = null; newModel._output._validation_metrics = null; // Clone trees Key[][] treeKeys = newModel._output._treeKeys; for (int i = 0; i < treeKeys.length; i++) { for (int j = 0; j < treeKeys[i].length; j++) { if (treeKeys[i][j] == null) continue; CompressedTree ct = DKV.get(treeKeys[i][j]).get(); CompressedTree newCt = IcedUtils.deepCopy(ct); newCt._key = CompressedTree.makeTreeKey(i, j); DKV.put(treeKeys[i][j] = newCt._key,newCt); } } // Clone Aux info Key[][] treeKeysAux = newModel._output._treeKeysAux; if (treeKeysAux!=null) { for (int i = 0; i < treeKeysAux.length; i++) { for (int j = 0; j < treeKeysAux[i].length; j++) { if (treeKeysAux[i][j] == null) continue; CompressedTree ct = DKV.get(treeKeysAux[i][j]).get(); CompressedTree newCt = IcedUtils.deepCopy(ct); newCt._key = Key.make(createAuxKey(treeKeys[i][j].toString())); DKV.put(treeKeysAux[i][j] = newCt._key,newCt); } } } return newModel; } @Override protected Futures remove_impl( Futures fs ) { for (Key[] ks : _output._treeKeys) for (Key k : ks) if( k != null ) k.remove(fs); for (Key[] ks : _output._treeKeysAux) for (Key k : ks) if( k != null ) k.remove(fs); if (_output._calib_model != null) _output._calib_model.remove(fs); return super.remove_impl(fs); } /** Write out K/V pairs */ @Override protected AutoBuffer writeAll_impl(AutoBuffer ab) { for (Key<CompressedTree>[] ks : _output._treeKeys) for (Key<CompressedTree> k : ks) ab.putKey(k); for (Key<CompressedTree>[] ks : _output._treeKeysAux) for (Key<CompressedTree> k : ks) ab.putKey(k); return super.writeAll_impl(ab); } @Override protected Keyed readAll_impl(AutoBuffer ab, Futures fs) { for (Key<CompressedTree>[] ks : _output._treeKeys) for (Key<CompressedTree> k : ks) ab.getKey(k,fs); for (Key<CompressedTree>[] ks : _output._treeKeysAux) for (Key<CompressedTree> k : ks) ab.getKey(k,fs); return super.readAll_impl(ab,fs); } @SuppressWarnings("unchecked") // `M` is really the type of `this` private M self() { return (M)this; } /** * Converts a given tree of the ensemble to a user-understandable representation. * @param tidx tree index * @param cls tree class * @return instance of SharedTreeSubgraph */ public SharedTreeSubgraph getSharedTreeSubgraph(final int tidx, final int cls) { if (tidx < 0 || tidx >= _output._ntrees) { throw new IllegalArgumentException("Invalid tree index: " + tidx + ". Tree index must be in range [0, " + (_output._ntrees -1) + "]."); } final CompressedTree auxCompressedTree = _output._treeKeysAux[tidx][cls].get(); return _output._treeKeys[tidx][cls].get().toSharedTreeSubgraph(auxCompressedTree, _output._names, _output._domains); } //-------------------------------------------------------------------------------------------------------------------- // Serialization into a POJO //-------------------------------------------------------------------------------------------------------------------- // Override in subclasses to provide some top-level model-specific goodness @Override protected boolean toJavaCheckTooBig() { // If the number of leaves in a forest is more than N, don't try to render it in the browser as POJO code. return _output==null || _output._treeStats._num_trees * _output._treeStats._mean_leaves > 1000000; } protected boolean binomialOpt() { return true; } @Override protected SBPrintStream toJavaInit(SBPrintStream sb, CodeGeneratorPipeline fileCtx) { if (_parms._categorical_encoding != Parameters.CategoricalEncodingScheme.AUTO && _parms._categorical_encoding != Parameters.CategoricalEncodingScheme.Enum) { throw new IllegalArgumentException("Only default categorical_encoding scheme is supported for POJO/MOJO"); } sb.nl(); sb.ip("public boolean isSupervised() { return true; }").nl(); sb.ip("public int nfeatures() { return " + _output.nfeatures() + "; }").nl(); sb.ip("public int nclasses() { return " + _output.nclasses() + "; }").nl(); return sb; } @Override protected void toJavaPredictBody(SBPrintStream body, CodeGeneratorPipeline classCtx, CodeGeneratorPipeline fileCtx, final boolean verboseCode) { final int nclass = _output.nclasses(); body.ip("java.util.Arrays.fill(preds,0);").nl(); final String mname = JCodeGen.toJavaId(_key.toString()); // One forest-per-GBM-tree, with a real-tree-per-class for (int t=0; t < _output._treeKeys.length; t++) { // Generate score method for given tree toJavaForestName(body.i(),mname,t).p(".score0(data,preds);").nl(); final int treeIdx = t; fileCtx.add(new CodeGenerator() { @Override public void generate(JCodeSB out) { try { // Generate a class implementing a tree out.nl(); toJavaForestName(out.ip("class "), mname, treeIdx).p(" {").nl().ii(1); out.ip("public static void score0(double[] fdata, double[] preds) {").nl().ii(1); for (int c = 0; c < nclass; c++) { if (_output._treeKeys[treeIdx][c] == null) continue; if (!(binomialOpt() && c == 1 && nclass == 2)) // Binomial optimization toJavaTreeName(out.ip("preds[").p(nclass == 1 ? 0 : c + 1).p("] += "), mname, treeIdx, c).p(".score0(fdata);").nl(); } out.di(1).ip("}").nl(); // end of function out.di(1).ip("}").nl(); // end of forest class // Generate the pre-tree classes afterwards for (int c = 0; c < nclass; c++) { if (_output._treeKeys[treeIdx][c] == null) continue; if (!(binomialOpt() && c == 1 && nclass == 2)) { // Binomial optimization String javaClassName = toJavaTreeName(new SB(), mname, treeIdx, c).toString(); CompressedTree ct = _output.ctree(treeIdx, c); SB sb = new SB(); new TreeJCodeGen(SharedTreeModel.this, ct, sb, javaClassName, verboseCode).generate(); out.p(sb); } } } catch (Throwable t) { t.printStackTrace(); throw new IllegalArgumentException("Internal error creating the POJO.", t); } } }); } toJavaUnifyPreds(body); } protected abstract void toJavaUnifyPreds(SBPrintStream body); protected <T extends JCodeSB> T toJavaTreeName(T sb, String mname, int t, int c ) { return (T) sb.p(mname).p("_Tree_").p(t).p("_class_").p(c); } protected <T extends JCodeSB> T toJavaForestName(T sb, String mname, int t ) { return (T) sb.p(mname).p("_Forest_").p(t); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.carbondata.core.scan.filter.executer; import java.io.IOException; import java.util.BitSet; import java.util.List; import org.apache.carbondata.core.datastore.block.SegmentProperties; import org.apache.carbondata.core.datastore.chunk.DimensionColumnDataChunk; import org.apache.carbondata.core.datastore.chunk.impl.DimensionRawColumnChunk; import org.apache.carbondata.core.datastore.chunk.impl.FixedLengthDimensionDataChunk; import org.apache.carbondata.core.keygenerator.directdictionary.DirectDictionaryGenerator; import org.apache.carbondata.core.keygenerator.directdictionary.DirectDictionaryKeyGeneratorFactory; import org.apache.carbondata.core.metadata.AbsoluteTableIdentifier; import org.apache.carbondata.core.metadata.encoder.Encoding; import org.apache.carbondata.core.scan.expression.Expression; import org.apache.carbondata.core.scan.expression.exception.FilterUnsupportedException; import org.apache.carbondata.core.scan.filter.FilterUtil; import org.apache.carbondata.core.scan.filter.resolver.resolverinfo.DimColumnResolvedFilterInfo; import org.apache.carbondata.core.scan.filter.resolver.resolverinfo.MeasureColumnResolvedFilterInfo; import org.apache.carbondata.core.scan.processor.BlocksChunkHolder; import org.apache.carbondata.core.util.BitSetGroup; import org.apache.carbondata.core.util.ByteUtil; import org.apache.carbondata.core.util.CarbonUtil; public class RowLevelRangeLessThanFiterExecuterImpl extends RowLevelFilterExecuterImpl { private byte[][] filterRangeValues; public RowLevelRangeLessThanFiterExecuterImpl( List<DimColumnResolvedFilterInfo> dimColEvaluatorInfoList, List<MeasureColumnResolvedFilterInfo> msrColEvalutorInfoList, Expression exp, AbsoluteTableIdentifier tableIdentifier, byte[][] filterRangeValues, SegmentProperties segmentProperties) { super(dimColEvaluatorInfoList, msrColEvalutorInfoList, exp, tableIdentifier, segmentProperties, null); this.filterRangeValues = filterRangeValues; } @Override public BitSet isScanRequired(byte[][] blockMaxValue, byte[][] blockMinValue) { BitSet bitSet = new BitSet(1); byte[][] filterValues = this.filterRangeValues; int columnIndex = this.dimColEvaluatorInfoList.get(0).getColumnIndex(); boolean isScanRequired = isScanRequired(blockMinValue[columnIndex], filterValues); if (isScanRequired) { bitSet.set(0); } return bitSet; } private boolean isScanRequired(byte[] blockMinValue, byte[][] filterValues) { boolean isScanRequired = false; for (int k = 0; k < filterValues.length; k++) { // and filter-min should be positive int minCompare = ByteUtil.UnsafeComparer.INSTANCE.compareTo(filterValues[k], blockMinValue); // if any filter applied is not in range of min and max of block // then since its a less than fiter validate whether the block // min range is less than applied filter member if (minCompare > 0) { isScanRequired = true; break; } } return isScanRequired; } @Override public BitSetGroup applyFilter(BlocksChunkHolder blockChunkHolder) throws FilterUnsupportedException, IOException { if (!dimColEvaluatorInfoList.get(0).getDimension().hasEncoding(Encoding.DICTIONARY)) { return super.applyFilter(blockChunkHolder); } int blockIndex = segmentProperties.getDimensionOrdinalToBlockMapping() .get(dimColEvaluatorInfoList.get(0).getColumnIndex()); if (null == blockChunkHolder.getDimensionRawDataChunk()[blockIndex]) { blockChunkHolder.getDimensionRawDataChunk()[blockIndex] = blockChunkHolder.getDataBlock() .getDimensionChunk(blockChunkHolder.getFileReader(), blockIndex); } DimensionRawColumnChunk rawColumnChunk = blockChunkHolder.getDimensionRawDataChunk()[blockIndex]; BitSetGroup bitSetGroup = new BitSetGroup(rawColumnChunk.getPagesCount()); for (int i = 0; i < rawColumnChunk.getPagesCount(); i++) { if (rawColumnChunk.getMinValues() != null) { if (isScanRequired(rawColumnChunk.getMinValues()[i], this.filterRangeValues)) { int compare = ByteUtil.UnsafeComparer.INSTANCE .compareTo(filterRangeValues[0], rawColumnChunk.getMaxValues()[i]); if (compare > 0) { BitSet bitSet = new BitSet(rawColumnChunk.getRowCount()[i]); bitSet.flip(0, rawColumnChunk.getRowCount()[i]); bitSetGroup.setBitSet(bitSet, i); } else { BitSet bitSet = getFilteredIndexes(rawColumnChunk.convertToDimColDataChunk(i), rawColumnChunk.getRowCount()[i]); bitSetGroup.setBitSet(bitSet, i); } } } else { BitSet bitSet = getFilteredIndexes(rawColumnChunk.convertToDimColDataChunk(i), rawColumnChunk.getRowCount()[i]); bitSetGroup.setBitSet(bitSet, i); } } return bitSetGroup; } private BitSet getFilteredIndexes(DimensionColumnDataChunk dimensionColumnDataChunk, int numerOfRows) { byte[] defaultValue = null; if (dimColEvaluatorInfoList.get(0).getDimension().hasEncoding(Encoding.DIRECT_DICTIONARY)) { DirectDictionaryGenerator directDictionaryGenerator = DirectDictionaryKeyGeneratorFactory .getDirectDictionaryGenerator( dimColEvaluatorInfoList.get(0).getDimension().getDataType()); int key = directDictionaryGenerator.generateDirectSurrogateKey(null) + 1; defaultValue = FilterUtil.getMaskKey(key, dimColEvaluatorInfoList.get(0).getDimension(), this.segmentProperties.getDimensionKeyGenerator()); } if (dimensionColumnDataChunk.isExplicitSorted() && dimensionColumnDataChunk instanceof FixedLengthDimensionDataChunk) { return setFilterdIndexToBitSetWithColumnIndex( (FixedLengthDimensionDataChunk) dimensionColumnDataChunk, numerOfRows, defaultValue); } return setFilterdIndexToBitSet(dimensionColumnDataChunk, numerOfRows, defaultValue); } /** * Method will scan the block and finds the range start index from which all members * will be considered for applying range filters. this method will be called if the * column is not supported by default so column index mapping will be present for * accesing the members from the block. * * @param dimensionColumnDataChunk * @param numerOfRows * @return BitSet. */ private BitSet setFilterdIndexToBitSetWithColumnIndex( FixedLengthDimensionDataChunk dimensionColumnDataChunk, int numerOfRows, byte[] defaultValue) { BitSet bitSet = new BitSet(numerOfRows); int start = 0; int last = 0; int startIndex = 0; int skip = 0; byte[][] filterValues = this.filterRangeValues; //find the number of default values to skip the null value in case of direct dictionary if (null != defaultValue) { start = CarbonUtil .getFirstIndexUsingBinarySearch(dimensionColumnDataChunk, startIndex, numerOfRows - 1, defaultValue, false); if (start < 0) { skip = -(start + 1); // end of block if (skip == numerOfRows) { return bitSet; } } else { skip = start; } startIndex = skip; } for (int i = 0; i < filterValues.length; i++) { start = CarbonUtil .getFirstIndexUsingBinarySearch(dimensionColumnDataChunk, startIndex, numerOfRows - 1, filterValues[i], false); // Logic will handle the case where the range filter member is not present in block // in this case the binary search will return the index from where the bit sets will be // set inorder to apply filters. this is Lesser than filter so the range will be taken // from the prev element which is Lesser than filter member. start = CarbonUtil.nextLesserValueToTarget(start, dimensionColumnDataChunk, filterValues[i]); if (start < 0) { start = -(start + 1); if (start >= numerOfRows) { start = start - 1; } // Method will compare the tentative index value after binary search, this tentative // index needs to be compared by the filter member if its < filter then from that // index the bitset will be considered for filtering process. if (ByteUtil.compare(filterValues[i], dimensionColumnDataChunk.getChunkData(dimensionColumnDataChunk.getInvertedIndex(start))) < 0) { start = start - 1; } } last = start; for (int j = start; j >= skip; j--) { bitSet.set(dimensionColumnDataChunk.getInvertedIndex(j)); last--; } startIndex = last; if (startIndex >= 0) { break; } } return bitSet; } /** * Method will scan the block and finds the range start index from which all * members will be considered for applying range filters. this method will * be called if the column is sorted default so column index * mapping will be present for accesing the members from the block. * * @param dimensionColumnDataChunk * @param numerOfRows * @return BitSet. */ private BitSet setFilterdIndexToBitSet(DimensionColumnDataChunk dimensionColumnDataChunk, int numerOfRows, byte[] defaultValue) { BitSet bitSet = new BitSet(numerOfRows); if (dimensionColumnDataChunk instanceof FixedLengthDimensionDataChunk) { int start = 0; int last = 0; int startIndex = 0; int skip = 0; byte[][] filterValues = this.filterRangeValues; //find the number of default values to skip the null value in case of direct dictionary if (null != defaultValue) { start = CarbonUtil.getFirstIndexUsingBinarySearch( (FixedLengthDimensionDataChunk) dimensionColumnDataChunk, startIndex, numerOfRows - 1, defaultValue, false); if (start < 0) { skip = -(start + 1); // end of block if (skip == numerOfRows) { return bitSet; } } else { skip = start; } startIndex = skip; } for (int k = 0; k < filterValues.length; k++) { start = CarbonUtil.getFirstIndexUsingBinarySearch( (FixedLengthDimensionDataChunk) dimensionColumnDataChunk, startIndex, numerOfRows - 1, filterValues[k], false); if (start >= 0) { start = CarbonUtil.nextLesserValueToTarget(start, (FixedLengthDimensionDataChunk) dimensionColumnDataChunk, filterValues[k]); } if (start < 0) { start = -(start + 1); if (start >= numerOfRows) { start = numerOfRows - 1; } // Method will compare the tentative index value after binary search, this tentative // index needs to be compared by the filter member if its < filter then from that // index the bitset will be considered for filtering process. if (ByteUtil.compare(filterValues[k], dimensionColumnDataChunk.getChunkData(start)) < 0) { start = start - 1; } } last = start; for (int j = start; j >= skip; j--) { bitSet.set(j); last--; } startIndex = last; if (startIndex <= 0) { break; } } } return bitSet; } @Override public void readBlocks(BlocksChunkHolder blockChunkHolder) throws IOException { if (!dimColEvaluatorInfoList.get(0).getDimension().hasEncoding(Encoding.DICTIONARY)) { super.readBlocks(blockChunkHolder); } int blockIndex = segmentProperties.getDimensionOrdinalToBlockMapping() .get(dimColEvaluatorInfoList.get(0).getColumnIndex()); if (null == blockChunkHolder.getDimensionRawDataChunk()[blockIndex]) { blockChunkHolder.getDimensionRawDataChunk()[blockIndex] = blockChunkHolder.getDataBlock() .getDimensionChunk(blockChunkHolder.getFileReader(), blockIndex); } } }
package com.comcast.oscar.configurationfile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.snmp4j.asn1.BER; import com.comcast.oscar.ber.BERService; import com.comcast.oscar.compiler.DocsisConstants; import com.comcast.oscar.compiler.PacketCableCompiler; import com.comcast.oscar.compiler.PacketCableConstants; import com.comcast.oscar.constants.Constants; import com.comcast.oscar.datatype.DataTypeDictionaryReference; import com.comcast.oscar.datatype.DataTypeFormatConversion; import com.comcast.oscar.dictionary.Dictionary; import com.comcast.oscar.dictionary.DictionarySQLConstants; import com.comcast.oscar.dictionary.DictionarySQLQueries; import com.comcast.oscar.netsnmp.NetSNMP; import com.comcast.oscar.tlv.TlvBuilder; import com.comcast.oscar.tlv.TlvDisassemble; import com.comcast.oscar.tlv.TlvException; import com.comcast.oscar.tlv.TlvVariableBinding; import com.comcast.oscar.utilities.BinaryConversion; import com.comcast.oscar.utilities.HexString; import com.comcast.oscar.utilities.JSONTools; import com.comcast.oscar.utilities.PrettyPrint; /** * @bannerLicense Copyright 2015 Comcast Cable Communications Management, LLC<br> ___________________________________________________________________<br> Licensed under the Apache License, Version 2.0 (the "License")<br> you may not use this file except in compliance with the License.<br> You may obtain a copy of the License at<br> http://www.apache.org/licenses/LICENSE-2.0<br> Unless required by applicable law or agreed to in writing, software<br> distributed under the License is distributed on an "AS IS" BASIS,<br> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br> See the License for the specific language governing permissions and<br> limitations under the License.<br> * @author Maurice Garcia (maurice.garcia.2015@gmail.com) */ public class ConfigurationFileExport { //Log4J2 logging private static final Logger logger = LogManager.getLogger(ConfigurationFileExport.class); /*House the Configuration Byte Array */ private byte[] bTLV; private final boolean debug = Boolean.FALSE; private ArrayList<JSONObject> aljoTopLevelTlvDictionary; private final Integer RESET_DATA_TYPE_MULTI_TLV_BYTE_ARRAY_SEARCH = -1; private Map<Integer,String> BER_DATA_TYPE = new HashMap<Integer,String>(); private DictionarySQLQueries dsqDictionarySQLQueries = null; private String sConfigurationFileStart; private int iConfigurationFileType = -1; private boolean boolVerboseExport = true; private boolean boolDottextOutputFormat = true; private boolean boolTlvCommentSuppress = false; public final String END_OF_CODE_BLOCK = "\\*EOCB*\\"; public static final Integer DOCSIS_PKTCBL = -1; public static final Integer DOCSIS_VER_10 = ConfigurationFileTypeConstants.DOCSIS_10_CONFIGURATION_TYPE; public static final Integer DOCSIS_VER_11 = ConfigurationFileTypeConstants.DOCSIS_11_CONFIGURATION_TYPE; public static final Integer DOCSIS_VER_20 = ConfigurationFileTypeConstants.DOCSIS_20_CONFIGURATION_TYPE; public static final Integer DOCSIS_VER_30 = ConfigurationFileTypeConstants.DOCSIS_30_CONFIGURATION_TYPE; public static final Integer DOCSIS_VER_31 = ConfigurationFileTypeConstants.DOCSIS_31_CONFIGURATION_TYPE; public static final Integer PKT_CBL_VER_10 = ConfigurationFileTypeConstants.PKT_CABLE_10_CONFIGURATION_TYPE; public static final Integer PKT_CBL_VER_15 = ConfigurationFileTypeConstants.PKT_CABLE_15_CONFIGURATION_TYPE; public static final Integer PKT_CBL_VER_20 = ConfigurationFileTypeConstants.PKT_CABLE_20_CONFIGURATION_TYPE; public static final Integer DPOE_VER_10 = ConfigurationFileTypeConstants.DPOE_10_CONFIGURATION_TYPE; public static final Integer DPOE_VER_20 = ConfigurationFileTypeConstants.DPOE_20_CONFIGURATION_TYPE; public static final Boolean EXPORT_DEFAULT_TLV = true; public static final Boolean EXPORT_FOUND_TLV = false; public static final Boolean TEXTUAL_OID_FORMAT = true; public static final Boolean DOTTED_OID_FORMAT = false; public static final Boolean SUPPRESS_TLV_COMMENT = true; /** * @deprecated - This is no longer supported but will work Only support DOCSIS and PacketCable * @param fTLV - Configuration File - Only support DOCSIS and PacketCable */ public ConfigurationFileExport (File fTLV) { //Convert to Byte Array this.bTLV = HexString.fileToByteArray(fTLV); if (debug) logger.debug("ConfigrationFileExport() -> FileByteLength: " + this.bTLV.length); if (bTLV[0] == PacketCableConstants.FILE_MARKER) { dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); } else { dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); } init(); //Build Dictionary tlvToDictionary (); } /** * * @param fTLV - Will Support all Configuration file Types: DOCSIS, PacketCable and DPoE * @param iConfigurationFileType - Set Configuration Type via Static FIELDS*/ public ConfigurationFileExport (File fTLV, int iConfigurationFileType) { boolean localDebug = Boolean.FALSE; this.bTLV = HexString.fileToByteArray(fTLV); //DumpTLV to STDOUT if (localDebug) { logger.debug(TlvBuilder.tlvDump(this.bTLV)); } this.iConfigurationFileType = iConfigurationFileType; /* This is to support the deprecated method public ConfigurationFileExport (File fTLV) */ if ((iConfigurationFileType <= DOCSIS_PKTCBL)) { //Convert to Byte Array this.bTLV = HexString.fileToByteArray(fTLV); if (debug) logger.debug("ConfigrationFileExport(f,i) -> FileByteLength: " + this.bTLV.length); if (bTLV[0] == PacketCableConstants.FILE_MARKER) { if (localDebug) logger.debug("Packet Cable Configuration File - Anonomous - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); } else { if (localDebug) logger.debug("DOCSIS Configuration File - Anonomous - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); } init(); } else if ((iConfigurationFileType >= DOCSIS_VER_10) && (iConfigurationFileType <= DOCSIS_VER_31)) { if (localDebug) logger.debug("DOCSIS Configuration File - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); init(); } else if ((iConfigurationFileType >= PKT_CBL_VER_10) && (iConfigurationFileType <= PKT_CBL_VER_20)) { if (localDebug) logger.debug("PacketCable Configuration File - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); init(); } else if ((iConfigurationFileType >= DPOE_VER_20) && (iConfigurationFileType <= DPOE_VER_20)) { if (localDebug) logger.debug("DPoE Configuration File - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DPOE_DICTIONARY_TABLE_NAME); init(iConfigurationFileType); } //Build Dictionary tlvToDictionary (); } /** * This constructor checks the first Byte to determine if it is a Packet Cable File or DOCSIS File * Byte = 0xFE = Packet Cable * @deprecated - This is no longer supported but will work Only support DOCSIS and PacketCable * @param tbTLV - Will ONLY Support Configuration file Types: DOCSIS and PacketCable */ public ConfigurationFileExport (TlvBuilder tbTLV) { boolean localDebug = Boolean.FALSE; //Convert to Byte Array this.bTLV = tbTLV.toByteArray(); if (bTLV[0] == PacketCableConstants.FILE_MARKER) { if (localDebug|debug) { logger.debug("ConfigrationFileExport(tb) - PacketCable File"); } dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); } else { if (localDebug|debug) { logger.debug("ConfigrationFileExport(tb) - DOCSIS File"); } dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); } init(); //Build Dictionary tlvToDictionary (); } /** * * @param tbTLV * @param iConfigurationFileType */ public ConfigurationFileExport (TlvBuilder tbTLV, int iConfigurationFileType) { boolean localDebug = Boolean.FALSE; //Convert to Byte Array this.bTLV = tbTLV.toByteArray(); this.iConfigurationFileType = iConfigurationFileType; if ((iConfigurationFileType >= DOCSIS_VER_10) && (iConfigurationFileType <= DOCSIS_VER_31)) { if (localDebug) logger.debug("DOCSIS Configuration File"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); init(); } else if ((iConfigurationFileType >= PKT_CBL_VER_10) && (iConfigurationFileType <= PKT_CBL_VER_20)) { if (localDebug) logger.debug("PacketCable Configuration File"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); init(); } else if ((iConfigurationFileType >= DPOE_VER_20) && (iConfigurationFileType <= DPOE_VER_20)) { if (localDebug) logger.debug("DPoE Configuration File"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DPOE_DICTIONARY_TABLE_NAME); init(iConfigurationFileType); } //Build Dictionary tlvToDictionary (); } /** * @deprecated - This is no longer supported but will work Only support DOCSIS and PacketCable * @param tbTLV * @param boolStripFinalize boolean */ public ConfigurationFileExport (TlvBuilder tbTLV, boolean boolStripFinalize) { boolean localDebug = Boolean.FALSE; if (boolStripFinalize) { if (debug|localDebug) logger.debug("ConfigrationFileExport(tb,bool) - StripFinalize"); //Check for PacketCable Marker if (tbTLV.toByteArray()[0] == PacketCableConstants.FILE_MARKER) { if (debug|localDebug) logger.debug("ConfigrationFileExport(tb,bool) - StripFinalize - PacketCable File"); try { this.bTLV = ConfigurationFile.stripFinalize(tbTLV, ConfigurationFile.PKT_CBL_VER_20).toByteArray(); } catch (TlvException e) { e.printStackTrace(); } } else { if (debug|localDebug) { logger.debug("ConfigrationFileExport(tb,bool) - StripFinalize - DOCSIS File");} try { this.bTLV = ConfigurationFile.stripFinalize(tbTLV, ConfigurationFile.DOCSIS_VER_31).toByteArray(); } catch (TlvException e) { e.printStackTrace(); } } } else { //Convert to Byte Array this.bTLV = tbTLV.toByteArray(); } if (bTLV[0] == PacketCableConstants.FILE_MARKER) { dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); } else { dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); } init(); //Build Dictionary tlvToDictionary (); } /** * @param cfConfigurationFile - Will Support all Configuration file Types: DOCSIS, PacketCable and DPoE */ public ConfigurationFileExport (ConfigurationFile cfConfigurationFile) { boolean localDebug = Boolean.FALSE; //Convert to Byte Array this.bTLV = cfConfigurationFile.toByteArray(); //DumpTLV to STDOUT if (localDebug) { logger.debug(TlvBuilder.tlvDump(this.bTLV)); } //Update to determine what type of configuration is selected this.iConfigurationFileType = cfConfigurationFile.getConfigurationFileType(); //Check for DPoE Type Configuration File if ((this.iConfigurationFileType >= DPOE_VER_20) && (this.iConfigurationFileType <= DPOE_VER_20)) { if (localDebug) logger.debug("ConfigurationFileExport(cf) -> DPoE Configuration File - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DPOE_DICTIONARY_TABLE_NAME); init(this.iConfigurationFileType); } else { if (bTLV[0] == PacketCableConstants.FILE_MARKER) { if (localDebug) logger.debug("ConfigurationFileExport(cf) -> PacketCable Configuration File - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); init(); } else { if (localDebug) logger.debug("ConfigurationFileExport(cf) -> DOCSIS Configuration File - ConfigType -> (" + iConfigurationFileType + ")"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); init(); } } //Build Dictionary tlvToDictionary (); } /** * This will only produce the Full Default Configuration Options * @param iConfigurationFileType - Will Support all Configuration file Types: DOCSIS, PacketCable and DPoE - Set Configuration Type via Static FIELD */ public ConfigurationFileExport (int iConfigurationFileType) { Boolean localDebug = Boolean.FALSE; JSONArray jaTlvDictionary = null; this.iConfigurationFileType = iConfigurationFileType; if (localDebug) logger.debug("ConfigurationFileExport(i): ConfigurationFileType: " + iConfigurationFileType); if ((this.iConfigurationFileType >= DOCSIS_VER_10) && (this.iConfigurationFileType <= DOCSIS_VER_31)) { if (localDebug) logger.debug("ConfigurationFileExport(i): DOCSIS -> CONFIGURATION-TYPE"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DOCSIS_DICTIONARY_TABLE_NAME); jaTlvDictionary = dsqDictionarySQLQueries.getAllTlvDefinition(DictionarySQLQueries.CONFIGURATION_FILE_TYPE_DOCSIS); bTLV = docsisPsuedoTLVArray(); init(); } else if ((this.iConfigurationFileType >= PKT_CBL_VER_10) && (this.iConfigurationFileType <= PKT_CBL_VER_20)) { if (localDebug) logger.debug("ConfigurationFileExport(i): PACKET-CABLE -> CONFIGURATION-TYPE"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); jaTlvDictionary = dsqDictionarySQLQueries.getAllTlvDefinition(DictionarySQLQueries.CONFIGURATION_FILE_TYPE_PACKET_CABLE); bTLV = packetCablePsuedoTLVArray(); init(); } else if ((this.iConfigurationFileType >= DPOE_VER_10) && (this.iConfigurationFileType <= DPOE_VER_20)) { if (localDebug) logger.debug("ConfigurationFileExport(i): DPoE -> CONFIGURATION-TYPE"); dsqDictionarySQLQueries = new DictionarySQLQueries(DictionarySQLQueries.DPOE_DICTIONARY_TABLE_NAME); jaTlvDictionary = dsqDictionarySQLQueries.getAllTlvDefinition(DictionarySQLQueries.CONFIGURATION_FILE_TYPE_DPOE); bTLV = packetCablePsuedoTLVArray(); init(iConfigurationFileType); } convertJSONArrayDictToJSONObjectArrayList(jaTlvDictionary); } /** * @deprecated * @since v1.0.1 * @param iIndentation * @return String*/ public String toPrettyPrint (int iIndentation) { boolean localDebug = Boolean.FALSE; StringBuilder sbTlvPrettyPrint = new StringBuilder(banner()); if (debug|localDebug) logger.debug("ConfigrationFileExport().toPrettyPrint() -> aljoTopLevelTlvDictionaryLength: " + aljoTopLevelTlvDictionary.size()); sbTlvPrettyPrint.append( sConfigurationFileStart + " {\n"); for (JSONObject joTLV : aljoTopLevelTlvDictionary) { //Added for Default Configuration file option if (joTLV.length() == 0) {continue;} try { if (joTLV.getBoolean(Dictionary.ARE_SUBTYPES)) { sbTlvPrettyPrint .append("\n\t") .append(joTLV.get(Dictionary.TLV_NAME)) .append(" {\n"); sbTlvPrettyPrint.append(topLevelTLVCodeBlock(joTLV.getJSONArray(Dictionary.SUBTYPE_ARRAY),2)); } else { sbTlvPrettyPrint.append(topLevelTLVCodeBlock(joTLV,2)); } } catch (JSONException e) { e.printStackTrace(); } } sbTlvPrettyPrint.append("}\n\n"); return sbTlvPrettyPrint.toString(); } /** * * @param boolIncludeDefaultTLV = True == will include default TLV if no value is found * @return String of the Compiled Configuration File*/ public String toPrettyPrint(boolean boolIncludeDefaultTLV) { //Deprecated setExportVerbose() this.boolVerboseExport = boolIncludeDefaultTLV; //Set ConfigurationFile Type String sConfigurationFile = ""; for (JSONObject joTLV : aljoTopLevelTlvDictionary) { //Added for Default Configuration file option if (joTLV.length() == 0) {continue;} try { if (joTLV.getBoolean(Dictionary.ARE_SUBTYPES)) { sConfigurationFile += ("\n\t") + (joTLV.get(Dictionary.TLV_NAME)) + (" {\n"); sConfigurationFile += (topLevelTLVCodeBlock(joTLV.getJSONArray(Dictionary.SUBTYPE_ARRAY),2)); } else { sConfigurationFile += (topLevelTLVCodeBlock(joTLV,2)); } } catch (JSONException e) { e.printStackTrace(); } } com.comcast.oscar.utilities.PrettyPrint ppConfigurationFile = new com.comcast.oscar.utilities.PrettyPrint((sConfigurationFileStart + " {\n") + (sConfigurationFile) + ("}\n")); String sConfigurationOuput = ""; if (boolTlvCommentSuppress) { sConfigurationOuput = ppConfigurationFile.toString().replaceAll("/\\*.*?\\*/",""); } else { sConfigurationOuput = ppConfigurationFile.toString(); } return (banner().toString()) + sConfigurationOuput; } /** * * @param boolIncludeDefaultTLV True == will include default TLV if no value is found * @param boolTlvCommentSuppress True == will NOT include TLV Comment * @return */ public String toPrettyPrint(boolean boolIncludeDefaultTLV,boolean boolTlvCommentSuppress) { this.boolTlvCommentSuppress = boolTlvCommentSuppress; return toPrettyPrint(boolIncludeDefaultTLV); } /** * * @return Map<Integer,String>*/ public Map<Integer,String> toHex () { return null; } /** * * @return TlvBuilder * @throws TlvException */ public TlvBuilder getTlvBuilder() throws TlvException { TlvBuilder tb = new TlvBuilder(); tb.add(new HexString(this.bTLV)); return tb; } /** * * Example: TLV Dot Notation: 25.1.2 * * @param sTlvDotNotation * @return String*/ public String getTlvDefintion (String sTlvDotNotation) { boolean localDebug = Boolean.FALSE; String sTlvDescription = ""; String sTlvName = ""; String sDisplayHint = ""; List<String> lsTlvDotNotation = new ArrayList<String>(); lsTlvDotNotation = Arrays.asList(sTlvDotNotation.split("\\.")); if (debug|localDebug) logger.debug("ConfigrationFileExport.getTlvDefintion(): " + lsTlvDotNotation.toString()); //Get TLV Dictionary for the Top Level JSONObject joTlvDictionary = dsqDictionarySQLQueries.getTlvDefinition(Integer.decode(lsTlvDotNotation.get(0))); //Search for TLV Definition if (lsTlvDotNotation.size() == 1) { try { sTlvName = joTlvDictionary.getString(Dictionary.TLV_NAME); sTlvDescription = joTlvDictionary.getString(Dictionary.TLV_DESCRIPTION); } catch (JSONException e) { e.printStackTrace(); } sDisplayHint = getDisplayHint(joTlvDictionary); } else if (lsTlvDotNotation.size() >= 1) { int iRecursiveSearch = 0; while (iRecursiveSearch < lsTlvDotNotation.size()) { if (debug|localDebug) logger.debug("ConfigrationFileExport.getTlvDefintion(): WHILE-LOOP"); try { if (joTlvDictionary.getString(Dictionary.TYPE).equals(lsTlvDotNotation.get(iRecursiveSearch))) { if (joTlvDictionary.getBoolean(Dictionary.ARE_SUBTYPES)) { try { JSONArray jaTlvDictionary = joTlvDictionary.getJSONArray(Dictionary.SUBTYPE_ARRAY); for (int iIndex = 0 ; iIndex < jaTlvDictionary.length() ; iIndex++) { if (debug|localDebug) logger.debug("ConfigrationFileExport.getTlvDefintion(): FOR-LOOP"); JSONObject joTlvDictionaryTemp = jaTlvDictionary.getJSONObject(iIndex); if (joTlvDictionaryTemp.getString(Dictionary.TYPE).equals(lsTlvDotNotation.get(iRecursiveSearch+1))) { joTlvDictionary = joTlvDictionaryTemp; iRecursiveSearch++; break; } } } catch (JSONException e) { e.printStackTrace(); } } else { sTlvName = joTlvDictionary.getString(Dictionary.TLV_NAME); sTlvDescription = joTlvDictionary.getString(Dictionary.TLV_DESCRIPTION); sDisplayHint = getDisplayHint(joTlvDictionary); iRecursiveSearch++; } } } catch (JSONException e1) { e1.printStackTrace(); } } } return "\n\n" + sTlvName + ":\n\n" + PrettyPrint.ToParagraphForm(sTlvDescription) + "\n\n" + "String Format:\n" + sDisplayHint; } /** * * @param iTlvType * @return JSONArray */ public JSONArray getTopLevelTLVJSON(int iTlvType) { JSONArray jaTopLevelTLV = new JSONArray(); for (JSONObject joTopLevelTLV : aljoTopLevelTlvDictionary) { try { if (joTopLevelTLV.getInt(Dictionary.TYPE) == iTlvType) { jaTopLevelTLV.put(joTopLevelTLV); } } catch (JSONException e) { e.printStackTrace(); } } return jaTopLevelTLV; } /** * Method will default to no Verbose * @param fOutput * @return true is write, false is it did not write */ public boolean writeToDisk(File fOutput) { return writeToDisk(fOutput,ConfigurationFileExport.EXPORT_FOUND_TLV); } /** * * @param fOutput * @param boolVerbose * @return true is write, false is it did not write */ public boolean writeToDisk(File fOutput,boolean boolVerbose) { boolean localDebug = Boolean.FALSE; byte[] bConfiguration = HexString.toByteArray(HexString.asciiToHex(toPrettyPrint(boolVerbose))); if (bConfiguration == null) { if (debug|localDebug) { logger.debug("ConfigurationFile.writeToDisk() - NULL ByteArray"); } return false; } if (debug|localDebug) { logger.debug("ConfigurationFile.writeToDisk() " + " - Total Byte Count: " + bConfiguration.length + " - FileName: " + fOutput.getName()); } OutputStream out = null; if (fOutput.getName() != null) { try { out = new FileOutputStream(fOutput); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (fOutput.getName().length() != 0) { try { out = new FileOutputStream(fOutput.getName()); } catch (IOException e) { e.printStackTrace(); } } else { File fCf = null; fCf = fOutput; try { out = new FileOutputStream(fCf); } catch (FileNotFoundException e) { e.printStackTrace(); } } try { out.write(bConfiguration); } catch (IOException e) { e.printStackTrace(); } try { out.flush(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } return true; } /** * * @return the ConfigurationFile Type per the ConfigurationFile() field statics */ public int getConfigurationFileType () { if (bTLV[0] == PacketCableConstants.FILE_MARKER) { return ConfigurationFile.PKT_CBL_VER_20; } else { return ConfigurationFile.DOCSIS_VER_31; } } /** * * @param boolDottextOutputFormat TRUE = Textual OID Output , FALSE = Dotted OID Output */ public void setDotTextOIDOutputFormat(boolean boolDottextOutputFormat) { this.boolDottextOutputFormat = boolDottextOutputFormat; } /** * DEFAULT = true; * @deprecated * @param boolVerboseExport*/ public void setExportVerbose(boolean boolVerboseExport) { this.boolVerboseExport = boolVerboseExport; } /* ******************************************************************************* * Private Methods ********************************************************************************/ /** * */ private void tlvToDictionary () { boolean localDebug = Boolean.FALSE; String sDictionaryTableName; //Starting Container for holding a DATA_TYPE_MULTI_TLV_BYTE_ARRAY TlvBuilder tbTopLevelTLV = new TlvBuilder(); //Container for holding a DATA_TYPE_MULTI_TLV_BYTE_ARRAY TlvBuilder tbMultiTlvByteArray = new TlvBuilder(); //Container for holding MultiTlvByteArray TlvVariableBinding tvbMultiTlvByteArray = null; //List to start JSON Array Objects aljoTopLevelTlvDictionary = new ArrayList<JSONObject>(); //Create a TLV Builder TlvBuilder tbTLV = new TlvBuilder(); if (iConfigurationFileType == DOCSIS_PKTCBL) { //Determine what kind of file: DOCSIS or PACKET CABLE if (bTLV[0] == PacketCableConstants.FILE_MARKER) { if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary() -> PACKET-CABLE-FILE-FOUND"); sDictionaryTableName = DictionarySQLConstants.PACKET_CABLE_DICTIONARY_TABLE_NAME; } else { if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary() -> DOCSIS-CABLE-FILE-FOUND"); sDictionaryTableName = DictionarySQLConstants.DOCSIS_DICTIONARY_TABLE_NAME; } //Get Top Level TLV Dictionary dsqDictionarySQLQueries = new DictionarySQLQueries(sDictionaryTableName); } else { sDictionaryTableName = dsqDictionarySQLQueries.getDictionaryTableName(); } //Build Map to determine the Type to ByteLength Mapping Map<Integer,Integer> miiTopLevelTLV = dsqDictionarySQLQueries.getTopLevelByteLength(); //Add TLV Byte Array from Constructor for later processing tbTLV.add(new TlvVariableBinding(bTLV,miiTopLevelTLV)); if (debug|localDebug) logger.debug( "ConfigrationFileExport.tlvToDictionary() -> " + "miiTopLevelTLV.size(): " + miiTopLevelTLV.size() + " -> " + "tbTLV.length(): " + tbTLV.length() + " -> " + "bTLV.length: " + bTLV.length); int iTlvType = 0 , iMultiTlvByteArrayType = RESET_DATA_TYPE_MULTI_TLV_BYTE_ARRAY_SEARCH; if (debug|localDebug) { logger.debug("ConfigrationFileExport.tlvToDictionary() -> miiTopLevelTLV: " + miiTopLevelTLV); if (tbTLV.toByteArray()[0] == PacketCableConstants.FILE_MARKER) { try { for (HexString hs : PacketCableCompiler.getTopLevelTlvToHexStringList(tbTLV.toByteArray())) { logger.debug("TLV-HEX: " + hs.toString(":")); } } catch (TlvException e) { e.printStackTrace(); } } } /*************************************************************************** * Sort by TopLevel TLVs via List<byte[]> ***************************************************************************/ for (byte[] bTopLevelTLV : tbTLV.sortByTopLevelTlv(miiTopLevelTLV)) { //Search TLV List if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary() -> Sort by TopLevel" + miiTopLevelTLV); //Get TLV Type iTlvType = BinaryConversion.byteToUnsignedInteger(bTopLevelTLV[0]); if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary() -> TLV-TYPE: " + iTlvType); //Check for DOCSIS EOF - Reached end of file (EOF) if (iTlvType == BinaryConversion.byteToUnsignedInteger(DocsisConstants.EOF)) {break;} //Get TLV Dictionary for iTlvType JSONObject joDictionaryTemp = dsqDictionarySQLQueries.getTlvDefinition(iTlvType); //Check for TLV's that are DATA_TYPE_MULTI_TLV_BYTE_ARRAY try { //Check for TLV's that are DATA_TYPE_MULTI_TLV_BYTE_ARRAY and make sure that we are not combining different TLV Types if (joDictionaryTemp.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_MULTI_TLV_BYTE_ARRAY) && (joDictionaryTemp.getInt(Dictionary.TYPE) == iTlvType)) { // If this is a -1, that means that this is the first time it saw a DATA_TYPE_MULTI_TLV_BYTE_ARRAY if ((iMultiTlvByteArrayType == RESET_DATA_TYPE_MULTI_TLV_BYTE_ARRAY_SEARCH) || (iMultiTlvByteArrayType == iTlvType)) { //Set iMultiTlvByteArrayType = iTlvType; //Build DATA_TYPE_MULTI_TLV_BYTE_ARRAY try { tbMultiTlvByteArray.add(iTlvType,TlvBuilder.getTlvValue(bTopLevelTLV)); } catch (TlvException e) { e.printStackTrace(); } //Goto next TLV to get the next contiguous DATA_TYPE_MULTI_TLV_BYTE_ARRAY continue; //There may be a condition that 2 different DATA_TYPE_MULTI_TLV_BYTE_ARRAY are contiguous } else if (iMultiTlvByteArrayType != iTlvType) { iMultiTlvByteArrayType = RESET_DATA_TYPE_MULTI_TLV_BYTE_ARRAY_SEARCH; } //Create a TlvBuilder for the Top Level TLV that is not a DATA_TYPE_MULTI_TLV_BYTE_ARRAY } else { tbTopLevelTLV = new TlvBuilder(); } } catch (JSONException e1) { e1.printStackTrace(); } //At this point we may need to process the current type and the DATA_TYPE_MULTI_TLV_BYTE_ARRAY if (iMultiTlvByteArrayType != RESET_DATA_TYPE_MULTI_TLV_BYTE_ARRAY_SEARCH) { if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary()" + " - End Of MULTI_TLV_BYTE_ARRAY" + " - Current Type: " + iTlvType + " - Process MULTI_TLV_BYTE_ARRAY Type: " + iMultiTlvByteArrayType); //Compile total TLV Value and send to byte Array byte[] bMultiTlvByteArray = TlvBuilder.coupleMultipleTopLevelTlvValues(tbMultiTlvByteArray); //Create new TlvVariableBinding tvbMultiTlvByteArray = new TlvVariableBinding(); //Add try { tvbMultiTlvByteArray.add(iMultiTlvByteArrayType, bMultiTlvByteArray); } catch (TlvException e) { e.printStackTrace(); } if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary()" + " - TlvVariableBinding HEX: " + tvbMultiTlvByteArray.toString()); if (debug|localDebug) logger.debug("++++++++HERE++++++++"); //Get TopLevelTLV TlvDisassemble TlvDisassemble tdTopLevelTLV = new TlvDisassemble(tvbMultiTlvByteArray,sDictionaryTableName); //Get TopLevelTLV Dictionary and insert into Array List try { if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary() " + tdTopLevelTLV.getTlvDictionary().getJSONObject(0).toString()); aljoTopLevelTlvDictionary.add(tdTopLevelTLV.getTlvDictionary().getJSONObject(0)); } catch (JSONException e) { e.printStackTrace(); } //Reset iMultiTlvByteArrayType iMultiTlvByteArrayType = RESET_DATA_TYPE_MULTI_TLV_BYTE_ARRAY_SEARCH; } //If this is not a DATA_TYPE_MULTI_TLV_BYTE_ARRAY , its only a single Top Level TLV tbTopLevelTLV.add(new TlvVariableBinding(bTopLevelTLV,miiTopLevelTLV)); //Get TopLevelTLV TlvDisassemble TlvDisassemble tdTopLevelTLV = new TlvDisassemble(tbTopLevelTLV,sDictionaryTableName); //Get TopLevelTLV Dictionary and insert into Array List try { if (debug|localDebug) logger.debug("ConfigrationFileExport.tlvToDictionary() " + tdTopLevelTLV.getTlvDictionary().getJSONObject(0).toString()); aljoTopLevelTlvDictionary.add(tdTopLevelTLV.getTlvDictionary().getJSONObject(0)); } catch (JSONException e) { e.printStackTrace(); } } } /** * * @param joTopLevelTLV * @param iIndentation * @return StringBuilder * @throws JSONException */ private StringBuilder topLevelTLVCodeBlock (JSONObject joTopLevelTLV, int iIndentation) throws JSONException { Boolean localDebug = Boolean.FALSE; StringBuilder sbTopLevelTLVCodeBlock = new StringBuilder(); StringBuilder sbIndentation = new StringBuilder(); if ((!this.boolVerboseExport) && (!(joTopLevelTLV.has(Dictionary.VALUE)))) { return sbTopLevelTLVCodeBlock; } for (int iNumIndent = 1 ; iNumIndent < iIndentation; iNumIndent++) sbIndentation.append('\t'); //If the Value contain a JSON Array, it can only be a OID if ((joTopLevelTLV.has(Dictionary.VALUE)) && (JSONTools.containJSONArray(joTopLevelTLV,Dictionary.VALUE))) { JSONArray jaTopLevelTLVOID = joTopLevelTLV.getJSONArray(Dictionary.VALUE); jaTopLevelTLVOID.getJSONObject(0).getString("OID"); //Check to see if this is a 2 byte VarBind, if so convert from ASCII to HexSting if (joTopLevelTLV.getInt(Dictionary.BYTE_LENGTH) < 2) { sbTopLevelTLVCodeBlock .append('\t') .append(joTopLevelTLV.get(Dictionary.TLV_NAME)) .append(' ') .append(NetSNMP.toOIDFormat(jaTopLevelTLVOID.getJSONObject(0).getString("OID"),boolDottextOutputFormat)) .append(' ') .append(BER_DATA_TYPE.get(Integer.decode(jaTopLevelTLVOID.getJSONObject(0).getString("DATA_TYPE")))) .append(" \"") .append(jaTopLevelTLVOID.getJSONObject(0).getString("VALUE")) .append("\";") .append("\t /* TLV: ") .append(joTopLevelTLV.get(Dictionary.PARENT_TYPE_LIST).toString().replace("-1,", "").replaceAll("," , ".")) .append("*/\n"); } else { sbTopLevelTLVCodeBlock .append('\t') .append(joTopLevelTLV.get(Dictionary.TLV_NAME)) .append(' ') .append(NetSNMP.toOIDFormat(jaTopLevelTLVOID.getJSONObject(0).getString("OID"),boolDottextOutputFormat)) .append(' ') .append(BER_DATA_TYPE.get(Integer.decode(jaTopLevelTLVOID.getJSONObject(0).getString("DATA_TYPE")))) .append(" \"") .append(HexString.asciiToHex(jaTopLevelTLVOID.getJSONObject(0).getString("VALUE"),":")) .append("\";") .append("\t /* TLV: ") .append(joTopLevelTLV.get(Dictionary.PARENT_TYPE_LIST).toString().replace("-1,", "").replaceAll("," , ".")) .append("*/\n"); } if (debug|localDebug) logger.debug("topLevelTLVCodeBlock(jo,i): " + sbTopLevelTLVCodeBlock); //Top Level TLV Only } else { if (joTopLevelTLV.has(Dictionary.VALUE)) { sbTopLevelTLVCodeBlock .append('\t') .append(joTopLevelTLV.get(Dictionary.TLV_NAME)) .append(' ') .append(joTopLevelTLV.get(Dictionary.VALUE)) .append(';') .append("\t /* TLV: ") .append(joTopLevelTLV.get(Dictionary.PARENT_TYPE_LIST).toString().replace("-1,", "").replaceAll("," , ".")) .append("*/\n"); } else { if ((joTopLevelTLV.get(Dictionary.TLV_NAME).equals("Snmp11")) || (joTopLevelTLV.get(Dictionary.TLV_NAME).equals("Snmp64"))) { if (debug) { logger.debug("++++++++++++++++++++++Ignoring Snmp11 || Snmp64 +++++++++++++++++++++++++++++++++++++"); } return sbTopLevelTLVCodeBlock; } sbTopLevelTLVCodeBlock .append('\t') .append(joTopLevelTLV.get(Dictionary.TLV_NAME)) .append(' ').append(';') .append("\t /* TLV: ") .append(joTopLevelTLV.get(Dictionary.PARENT_TYPE_LIST).toString().replace("-1,", "").replaceAll("," , ".")) .append("*/\n"); } if (debug|localDebug) logger.debug("topLevelTLVCodeBlock(jo,i): " + sbTopLevelTLVCodeBlock); } return sbTopLevelTLVCodeBlock; } /** * * @param jaTopLevelTLV * @param iIndentation * @return StringBuilder * @throws JSONException */ private StringBuilder topLevelTLVCodeBlock (JSONArray jaTopLevelTLV , int iIndentation) throws JSONException { boolean localDebug = Boolean.FALSE; StringBuilder sbTopLevelTLVCodeBlock = new StringBuilder(); StringBuilder sbIndentation = new StringBuilder(); for (int iNumIndent = 1 ; iNumIndent < iIndentation; iNumIndent++) sbIndentation.append('\t'); for (int iJsonArrayIndex = 0 ; iJsonArrayIndex < jaTopLevelTLV.length() ; iJsonArrayIndex++ ) { JSONObject joTopLevelTLVLocal = null; try { joTopLevelTLVLocal = jaTopLevelTLV.getJSONObject(iJsonArrayIndex); } catch (JSONException e1) { e1.printStackTrace(); } try { if (joTopLevelTLVLocal.getBoolean(Dictionary.ARE_SUBTYPES)) { sbTopLevelTLVCodeBlock .append(sbIndentation).append('\t') .append(joTopLevelTLVLocal.get(Dictionary.TLV_NAME)) .append(" {\n"); if (debug|localDebug) logger.debug("topLevelTLVCodeBlock(ja): " + joTopLevelTLVLocal.getJSONArray(Dictionary.SUBTYPE_ARRAY).toString()); sbTopLevelTLVCodeBlock.append(topLevelTLVCodeBlock(joTopLevelTLVLocal.getJSONArray(Dictionary.SUBTYPE_ARRAY),iIndentation+1)); } else { sbTopLevelTLVCodeBlock .append(sbIndentation) .append(topLevelTLVCodeBlock(joTopLevelTLVLocal,iIndentation)); } } catch (JSONException e) { e.printStackTrace(); } } sbTopLevelTLVCodeBlock .append(sbIndentation) .append("} " + END_OF_CODE_BLOCK + "\n\n"); return sbTopLevelTLVCodeBlock; } /** * */ private void initBER() { BER_DATA_TYPE.put((int) BER.COUNTER32, "Counter32"); BER_DATA_TYPE.put((int) BER.COUNTER64, "Counter64"); BER_DATA_TYPE.put((int) BER.GAUGE32, "Gauge32"); BER_DATA_TYPE.put((int) BER.INTEGER32, "Integer32"); BER_DATA_TYPE.put((int) BER.TIMETICKS, "TimeTicks"); BER_DATA_TYPE.put((int) BER.IPADDRESS, "IpAddress"); BER_DATA_TYPE.put((int) BER.OCTETSTRING, "OctetString"); //This Type does not exists as a SNMP DataType, this is only for use in this program BER_DATA_TYPE.put(BinaryConversion.byteToUnsignedInteger(BERService.HEX), "HexString"); } /** * */ private void init() { initBER(); //Figure Out the Configuration file Type DOCSIS vs. PacketCable if (bTLV[0] != PacketCableConstants.FILE_MARKER ) { sConfigurationFileStart = "Docsis"; } else { sConfigurationFileStart = "PacketCable-X.X"; } } /** * Only Non DOCSIS and PacketCable files*/ private void init(int iConfigurationFileType) { initBER(); if ((iConfigurationFileType >= DPOE_VER_10) && (iConfigurationFileType <= DPOE_VER_20)) { removeNonDictionaryTopLevelTLV(); sConfigurationFileStart = "DPoE"; } } /** * * @return byte[] */ private byte[] docsisPsuedoTLVArray() { boolean localDebug = Boolean.FALSE; ByteArrayOutputStream baosTLV = new ByteArrayOutputStream(); byte bByte[] = {0x01, 0x01, 0x00}; for (int iIndex = 0 ; iIndex < 255 ; iIndex++) { if (localDebug|debug) logger.debug("docsisPsuedoTLVArray() - Index: " + iIndex); if (localDebug|debug) logger.debug("docsisPsuedoTLVArray()" + new HexString(baosTLV.toByteArray()).toString()); try { baosTLV.write(bByte); } catch (IOException e) { e.printStackTrace(); } bByte[0]++; } if (localDebug|debug) logger.debug("docsisPsuedoTLVArray()" + new HexString(baosTLV.toByteArray()).toString()); return baosTLV.toByteArray(); } /** * * @return byte[] */ private byte[] packetCablePsuedoTLVArray() { ByteArrayOutputStream baosTLV = new ByteArrayOutputStream(); byte bByte[] = {PacketCableConstants.FILE_MARKER, 0x01, 0x00}; for (int iIndex = 0 ; iIndex < 255 ; iIndex++) { try { baosTLV.write(bByte); } catch (IOException e) { e.printStackTrace(); } if (bByte[0] == PacketCableConstants.FILE_MARKER) { bByte[0] = 0x01; } else { bByte[0]++; } } return baosTLV.toByteArray(); } /** * * @param jaDict */ private void convertJSONArrayDictToJSONObjectArrayList (JSONArray jaDict) { boolean localDebug = Boolean.FALSE; aljoTopLevelTlvDictionary = new ArrayList<JSONObject>(); for (int iIndex = 0 ; iIndex < jaDict.length() ; iIndex++) { try { if (localDebug|debug) logger.debug("convertJSONArrayDictToJSONObjectArrayList() - Index: " + iIndex + " -> " + jaDict.getJSONObject(iIndex).toString()); aljoTopLevelTlvDictionary.add(jaDict.getJSONObject(iIndex)); } catch (JSONException e) { e.printStackTrace(); } } if (localDebug|debug) logger.debug("convertJSONArrayDictToJSONObjectArrayList() - ArraySize: " + aljoTopLevelTlvDictionary.size()); } /** * Method banner. * @return StringBuilder */ private StringBuilder banner() { StringBuilder sbBanner = new StringBuilder(); sbBanner.append("/*\n"); sbBanner.append(Constants.APACHE_20_LICENCE_DISCLAIMER + "\n\n"); sbBanner.append("\tSnmp11 OID DataType Value\n"); if (this.iConfigurationFileType > DOCSIS_VER_31) sbBanner.append("\tSnmp64 OID DataType Value\n\n"); else sbBanner.append('\n'); sbBanner.append("\tDOUBLE_BYTE_ARRAY_FORMAT: " + DataTypeFormatConversion.DOUBLE_BYTE_ARRAY_FORMAT + "\n"); sbBanner.append("\tIPV4_TRANSPORT_FORMAT: " + DataTypeFormatConversion.IPV4_TRANSPORT_FORMAT + "\n"); sbBanner.append("\tIPV6_TRANSPORT_FORMAT: " + DataTypeFormatConversion.IPV6_TRANSPORT_FORMAT + "\n"); sbBanner.append("\tSTRING_BITS_FORMAT: " + DataTypeFormatConversion.STRING_BITS_FORMAT + "\n"); sbBanner.append("\tIPV6_ADDRESS_FORMAT: " + DataTypeFormatConversion.IPV6_ADDRESS_FORMAT + "\n"); sbBanner.append("\tIPV4_ADDRESS_FORMAT: " + DataTypeFormatConversion.IPV4_ADDRESS_FORMAT + "\n"); sbBanner.append("\tMAC_ADDRESS_FORMAT: " + DataTypeFormatConversion.MAC_ADDRESS_FORMAT + "\n\n"); sbBanner.append("*/\n\n"); return sbBanner; } /** * * @param joTlvDictionary - JSON OBject of the Dictionary * @return the Hint for the datatype that is used */ private String getDisplayHint(JSONObject joTlvDictionary) { String sDisplayHint = ""; try { if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_DOUBLE_BYTE_ARRAY)) { sDisplayHint = DataTypeFormatConversion.DOUBLE_BYTE_ARRAY_FORMAT; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_TRANSPORT_ADDR_IPV4_ADDR)) { sDisplayHint = DataTypeFormatConversion.IPV4_TRANSPORT_FORMAT; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_TRANSPORT_ADDR_IPV6_ADDR)) { sDisplayHint = DataTypeFormatConversion.IPV6_TRANSPORT_FORMAT; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_STRING_BITS)) { sDisplayHint = DataTypeFormatConversion.STRING_BITS_FORMAT; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_BYTE_ARRAY_IPV4_ADDR)) { sDisplayHint = DataTypeFormatConversion.IPV4_ADDRESS_FORMAT; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_BYTE_ARRAY_IPV6_ADDR)) { sDisplayHint = DataTypeFormatConversion.IPV6_ADDRESS_FORMAT; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_OID)) { sDisplayHint = "docsDevFilterLLCUnmatchedAction.0 Integer32 \"1\" \n " + "vacmAccessStorageType.'readwritegroup'.''.2.noAuthNoPriv Integer \"2\"" + "1.3.6.1.2.1.69.1.3.5 Integer32 \"1\"" ; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_INTEGER)) { sDisplayHint = "Range: -2,147,483,648 to 2,147,483,647"; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_STRING)) { sDisplayHint = "Any ASCII String"; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_STRING_NULL_TERMINATED)) { sDisplayHint = "Any ASCII String with a Terminating NULL at the end /0 or 0x00"; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_BYTE_ARRAY)) { sDisplayHint = "xx:xx:xx......xx:xx:xx - Example: 01:23:34:56:78:9a:bc:cd:ef"; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_OID_ASN1_OBJECT_6)) { sDisplayHint = "docsDevFilterLLCUnmatchedAction.0 \n " + "vacmAccessStorageType.'readwritegroup'.''.2.noAuthNoPriv \n" + "1.3.6.1.2.1.69.1.3.5 " ; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_BYTE)) { sDisplayHint = "Byte: xx Example ff" ; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_MAC_ADDRESS)) { sDisplayHint = DataTypeFormatConversion.MAC_ADDRESS_FORMAT ; } else if (joTlvDictionary.getString(Dictionary.DATA_TYPE).equals(DataTypeDictionaryReference.DATA_TYPE_TRANSPORT_ADDR_INET_ADDR)) { sDisplayHint = DataTypeFormatConversion.IPV4_TRANSPORT_FORMAT + " \n\nOR\n\n" + DataTypeFormatConversion.IPV6_TRANSPORT_FORMAT; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sDisplayHint; } /** * This method will remove all TopLevel TLV that are not defined in the Dictionary * Currently support 1 byte Length TLVs */ private void removeNonDictionaryTopLevelTLV() { Boolean localDebug = Boolean.FALSE; /* Get TopLevel List*/ List<Integer> liTopLevelDict = dsqDictionarySQLQueries.getTopLevelTLV(); List<Integer> liTopLevelCFE = null; try { liTopLevelCFE = getTlvBuilder().getTopLevelTlvList(); } catch (TlvException e) { e.printStackTrace(); } /*This will create a single instance of each Type */ liTopLevelCFE = new ArrayList<Integer>(new LinkedHashSet<Integer>(liTopLevelCFE)); /*Remove Types that are not suppose to be There */ liTopLevelCFE.retainAll(liTopLevelDict); if(debug|localDebug) { logger.debug("removeNonDictionaryTopLevelTLV() -> DICT: " + liTopLevelDict); logger.debug("removeNonDictionaryTopLevelTLV() -> CFE remove DICT: " + liTopLevelCFE); } /*Create new ByteArray*/ bTLV = TlvBuilder.fetchTlv(liTopLevelCFE, bTLV); } }
/* * 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.testsuite.model; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.keycloak.common.util.Time; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserManager; import org.keycloak.models.UserModel; import org.keycloak.services.managers.ClientManager; import org.keycloak.services.managers.RealmManager; import org.keycloak.sessions.AuthenticationSessionModel; import org.keycloak.sessions.CommonClientSessionModel; import org.keycloak.testsuite.rule.KeycloakRule; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class AuthenticationSessionProviderTest { @ClassRule public static KeycloakRule kc = new KeycloakRule(); private KeycloakSession session; private RealmModel realm; @Before public void before() { session = kc.startSession(); realm = session.realms().getRealm("test"); session.users().addUser(realm, "user1").setEmail("user1@localhost"); session.users().addUser(realm, "user2").setEmail("user2@localhost"); } @After public void after() { resetSession(); UserModel user1 = session.users().getUserByUsername("user1", realm); UserModel user2 = session.users().getUserByUsername("user2", realm); UserManager um = new UserManager(session); if (user1 != null) { um.removeUser(realm, user1); } if (user2 != null) { um.removeUser(realm, user2); } kc.stopSession(session, true); } private void resetSession() { kc.stopSession(session, true); session = kc.startSession(); realm = session.realms().getRealm("test"); } @Test public void testLoginSessionsCRUD() { ClientModel client1 = realm.getClientByClientId("test-app"); UserModel user1 = session.users().getUserByUsername("user1", realm); AuthenticationSessionModel authSession = session.authenticationSessions().createAuthenticationSession(realm, client1); authSession.setAction("foo"); authSession.setTimestamp(100); resetSession(); // Ensure session is here authSession = session.authenticationSessions().getAuthenticationSession(realm, authSession.getId()); testAuthenticationSession(authSession, client1.getId(), null, "foo"); Assert.assertEquals(100, authSession.getTimestamp()); // Update and commit authSession.setAction("foo-updated"); authSession.setTimestamp(200); authSession.setAuthenticatedUser(session.users().getUserByUsername("user1", realm)); resetSession(); // Ensure session was updated authSession = session.authenticationSessions().getAuthenticationSession(realm, authSession.getId()); testAuthenticationSession(authSession, client1.getId(), user1.getId(), "foo-updated"); Assert.assertEquals(200, authSession.getTimestamp()); // Remove and commit session.authenticationSessions().removeAuthenticationSession(realm, authSession); resetSession(); // Ensure session was removed Assert.assertNull(session.authenticationSessions().getAuthenticationSession(realm, authSession.getId())); } @Test public void testAuthenticationSessionRestart() { ClientModel client1 = realm.getClientByClientId("test-app"); UserModel user1 = session.users().getUserByUsername("user1", realm); AuthenticationSessionModel authSession = session.authenticationSessions().createAuthenticationSession(realm, client1); authSession.setAction("foo"); authSession.setTimestamp(100); authSession.setAuthenticatedUser(user1); authSession.setAuthNote("foo", "bar"); authSession.setClientNote("foo2", "bar2"); authSession.setExecutionStatus("123", CommonClientSessionModel.ExecutionStatus.SUCCESS); resetSession(); client1 = realm.getClientByClientId("test-app"); authSession = session.authenticationSessions().getAuthenticationSession(realm, authSession.getId()); authSession.restartSession(realm, client1); resetSession(); authSession = session.authenticationSessions().getAuthenticationSession(realm, authSession.getId()); testAuthenticationSession(authSession, client1.getId(), null, null); Assert.assertTrue(authSession.getTimestamp() > 0); Assert.assertTrue(authSession.getClientNotes().isEmpty()); Assert.assertNull(authSession.getAuthNote("foo2")); Assert.assertTrue(authSession.getExecutionStatus().isEmpty()); } @Test public void testExpiredAuthSessions() { try { realm.setAccessCodeLifespan(10); realm.setAccessCodeLifespanUserAction(10); realm.setAccessCodeLifespanLogin(30); // Login lifespan is largest String authSessionId = session.authenticationSessions().createAuthenticationSession(realm, realm.getClientByClientId("test-app")).getId(); resetSession(); Time.setOffset(25); session.authenticationSessions().removeExpired(realm); resetSession(); assertNotNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId)); Time.setOffset(35); session.authenticationSessions().removeExpired(realm); resetSession(); assertNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId)); // User action is largest realm.setAccessCodeLifespanUserAction(40); Time.setOffset(0); authSessionId = session.authenticationSessions().createAuthenticationSession(realm, realm.getClientByClientId("test-app")).getId(); resetSession(); Time.setOffset(35); session.authenticationSessions().removeExpired(realm); resetSession(); assertNotNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId)); Time.setOffset(45); session.authenticationSessions().removeExpired(realm); resetSession(); assertNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId)); // Access code is largest realm.setAccessCodeLifespan(50); Time.setOffset(0); authSessionId = session.authenticationSessions().createAuthenticationSession(realm, realm.getClientByClientId("test-app")).getId(); resetSession(); Time.setOffset(45); session.authenticationSessions().removeExpired(realm); resetSession(); assertNotNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId)); Time.setOffset(55); session.authenticationSessions().removeExpired(realm); resetSession(); assertNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId)); } finally { Time.setOffset(0); realm.setAccessCodeLifespan(60); realm.setAccessCodeLifespanUserAction(300); realm.setAccessCodeLifespanLogin(1800); } } @Test public void testOnRealmRemoved() { RealmModel fooRealm = session.realms().createRealm("foo-realm"); ClientModel fooClient = fooRealm.addClient("foo-client"); String authSessionId = session.authenticationSessions().createAuthenticationSession(realm, realm.getClientByClientId("test-app")).getId(); String authSessionId2 = session.authenticationSessions().createAuthenticationSession(fooRealm, fooClient).getId(); resetSession(); new RealmManager(session).removeRealm(session.realms().getRealmByName("foo-realm")); resetSession(); AuthenticationSessionModel authSession = session.authenticationSessions().getAuthenticationSession(realm, authSessionId); testAuthenticationSession(authSession, realm.getClientByClientId("test-app").getId(), null, null); Assert.assertNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId2)); } @Test public void testOnClientRemoved() { String authSessionId = session.authenticationSessions().createAuthenticationSession(realm, realm.getClientByClientId("test-app")).getId(); String authSessionId2 = session.authenticationSessions().createAuthenticationSession(realm, realm.getClientByClientId("third-party")).getId(); String testAppClientUUID = realm.getClientByClientId("test-app").getId(); resetSession(); new ClientManager(new RealmManager(session)).removeClient(realm, realm.getClientByClientId("third-party")); resetSession(); AuthenticationSessionModel authSession = session.authenticationSessions().getAuthenticationSession(realm, authSessionId); testAuthenticationSession(authSession, testAppClientUUID, null, null); Assert.assertNull(session.authenticationSessions().getAuthenticationSession(realm, authSessionId2)); // Revert client realm.addClient("third-party"); } private void testAuthenticationSession(AuthenticationSessionModel authSession, String expectedClientId, String expectedUserId, String expectedAction) { Assert.assertEquals(expectedClientId, authSession.getClient().getId()); if (expectedUserId == null) { Assert.assertNull(authSession.getAuthenticatedUser()); } else { Assert.assertEquals(expectedUserId, authSession.getAuthenticatedUser().getId()); } if (expectedAction == null) { Assert.assertNull(authSession.getAction()); } else { Assert.assertEquals(expectedAction, authSession.getAction()); } } }
package admin.skin; import java.io.Serializable; import java.util.Collection; import javax.enterprise.context.SessionScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.inject.Named; import org.aries.runtime.BeanContext; import org.aries.ui.AbstractDomainListManager; import org.aries.ui.event.Cancelled; import org.aries.ui.event.Export; import org.aries.ui.event.Refresh; import org.aries.ui.manager.ExportManager; import admin.Skin; import admin.util.SkinUtil; import nam.ui.design.SelectionContext; @SessionScoped @Named("skinListManager") public class SkinListManager extends AbstractDomainListManager<Skin, SkinListObject> implements Serializable { @Inject private SkinDataManager skinDataManager; @Inject private SkinEventManager skinEventManager; @Inject private SkinInfoManager skinInfoManager; @Inject private SelectionContext selectionContext; @Override public String getClientId() { return "skinList"; } @Override public String getTitle() { return "Skin List"; } public Object getRecordId(Skin skin) { return skin.getId(); } @Override public Object getRecordKey(Skin skin) { return SkinUtil.getKey(skin); } @Override public String getRecordName(Skin skin) { return SkinUtil.getLabel(skin); } @Override protected Class<Skin> getRecordClass() { return Skin.class; } @Override protected Skin getRecord(SkinListObject rowObject) { return rowObject.getSkin(); } @Override public Skin getSelectedRecord() { return super.getSelectedRecord(); } public String getSelectedRecordLabel() { return selectedRecord != null ? SkinUtil.getLabel(selectedRecord) : null; } @Override public void setSelectedRecord(Skin skin) { super.setSelectedRecord(skin); fireSelectedEvent(skin); } protected void fireSelectedEvent(Skin skin) { skinEventManager.fireSelectedEvent(skin); } public boolean isSelected(Skin skin) { Skin selection = selectionContext.getSelection("skin"); boolean selected = selection != null && selection.equals(skin); return selected; } public boolean isChecked(Skin skin) { Collection<Skin> selection = selectionContext.getSelection("skinSelection"); boolean checked = selection != null && selection.contains(skin); return checked; } @Override protected SkinListObject createRowObject(Skin skin) { SkinListObject listObject = new SkinListObject(skin); listObject.setSelected(isSelected(skin)); listObject.setChecked(isChecked(skin)); return listObject; } @Override public void reset() { refresh(); } @Override public void initialize() { if (recordList != null) initialize(recordList); else refreshModel(); } @Override public void refreshModel() { refreshModel(createRecordList()); } @Override protected Collection<Skin> createRecordList() { try { Collection<Skin> skinList = skinDataManager.getSkinList(); if (skinList != null) return skinList; return recordList; } catch (Exception e) { handleException(e); return null; } } public String viewSkin() { return viewSkin(selectedRecordKey); } public String viewSkin(Object recordKey) { Skin skin = recordByKeyMap.get(recordKey); return viewSkin(skin); } public String viewSkin(Skin skin) { String url = skinInfoManager.viewSkin(skin); return url; } public String editSkin() { return editSkin(selectedRecordKey); } public String editSkin(Object recordKey) { Skin skin = recordByKeyMap.get(recordKey); return editSkin(skin); } public String editSkin(Skin skin) { String url = skinInfoManager.editSkin(skin); return url; } public void removeSkin() { removeSkin(selectedRecordKey); } public void removeSkin(Object recordKey) { Skin skin = recordByKeyMap.get(recordKey); removeSkin(skin); } public void removeSkin(Skin skin) { try { if (skinDataManager.removeSkin(skin)) clearSelection(); refresh(); } catch (Exception e) { handleException(e); } } public void cancelSkin(@Observes @Cancelled Skin skin) { try { //Object key = SkinUtil.getKey(skin); //recordByKeyMap.put(key, skin); initialize(recordByKeyMap.values()); BeanContext.removeFromSession("skin"); } catch (Exception e) { handleException(e); } } public boolean validateSkin(Collection<Skin> skinList) { return SkinUtil.validate(skinList); } public void exportSkinList(@Observes @Export String tableId) { //String tableId = "pageForm:skinListTable"; ExportManager exportManager = BeanContext.getFromSession("org.aries.exportManager"); exportManager.exportToXLS(tableId); } }
//======================================================================== // 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.xtuml.bp.ui.graphics.actions; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.UUID; import org.eclipse.draw2d.geometry.Point; import org.eclipse.gef.EditPart; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.editparts.AbstractGraphicalEditPart; import org.eclipse.gef.requests.ChangeBoundsRequest; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Event; import org.eclipse.ui.PlatformUI; import org.xtuml.bp.core.CorePlugin; import org.xtuml.bp.core.Ooaofooa; import org.xtuml.bp.core.common.ClassQueryInterface_c; import org.xtuml.bp.core.common.InstanceList; import org.xtuml.bp.core.common.ModelRoot; import org.xtuml.bp.core.common.ModelStreamProcessor; import org.xtuml.bp.core.common.NonRootModelElement; import org.xtuml.bp.core.common.TransactionManager; import org.xtuml.bp.core.ui.PasteAction; import org.xtuml.bp.core.ui.Selection; import org.xtuml.bp.ui.canvas.CanvasPlugin; import org.xtuml.bp.ui.canvas.Cl_c; import org.xtuml.bp.ui.canvas.Connector_c; import org.xtuml.bp.ui.canvas.ContainingShape_c; import org.xtuml.bp.ui.canvas.Diagram_c; import org.xtuml.bp.ui.canvas.Diagramelement_c; import org.xtuml.bp.ui.canvas.Graphconnector_c; import org.xtuml.bp.ui.canvas.Graphedge_c; import org.xtuml.bp.ui.canvas.Graphelement_c; import org.xtuml.bp.ui.canvas.GraphicalElement_c; import org.xtuml.bp.ui.canvas.Graphnode_c; import org.xtuml.bp.ui.canvas.Model_c; import org.xtuml.bp.ui.canvas.Ooaofgraphics; import org.xtuml.bp.ui.canvas.Shape_c; import org.xtuml.bp.ui.graphics.editor.GraphicalEditor; import org.xtuml.bp.ui.graphics.tools.GraphicalPanningSelectionTool; import org.xtuml.bp.ui.graphics.utilities.GraphicsUtil; public class CanvasPasteAction extends PasteAction { private GraphicalEditor m_editor; private int offsetX; private int offsetY; private GraphicalElement_c[] graphicElements; private ChangeBoundsRequest fRequest; public CanvasPasteAction(GraphicalEditor editor) { super(); m_editor = editor; } @Override public void runWithEvent(Event event) { // if the paste was initiated via // the keyboard, then clear the last // context press and use 0,0 for the // location (until a better layout is // provided) if(event.keyCode != 0) { GraphicalViewer viewer = (GraphicalViewer) m_editor .getAdapter(GraphicalViewer.class); GraphicalPanningSelectionTool tool = (GraphicalPanningSelectionTool) viewer .getEditDomain().getActiveTool(); tool.clearLastLeftClickLocation(); } super.runWithEvent(event); } @Override public void processGraphics(NonRootModelElement destination) throws Exception { // we only want to do graphical processing // if the destination is the diagram if (getDestinations().size() == 1 && getDestinations().get(0) == m_editor.getModel() .getRepresents() && !moveIsInProgress()) { NonRootModelElement[] elements = getLoadedGraphicalInstances((NonRootModelElement) m_editor .getModel().getRepresents()); graphicElements = getPastedGraphicalElements((NonRootModelElement) m_editor .getModel().getRepresents(), processorMap); if(graphicElements.length == 0) { // this is likely a copy from ME to diagram where // no graphics exist, one case and maybe the only // is copy a domain and paste to SYS diagram return; } boolean newParent = areGraphicalElementsExternal(); updateGraphicalElementRoots(elements, m_editor.getModel().getModelRoot()); for (int i = 0; i < graphicElements.length; i++) { graphicElements[i].unrelateAcrossR1From(Model_c.getOneGD_MDOnR1(graphicElements[i])); graphicElements[i].relateAcrossR1To(m_editor.getModel()); updateContainement(m_editor.getModel(), graphicElements[i]); } updateLocation(graphicElements, newParent); if(m_editor.getModel().Hascontainersymbol()) { Shape_c container = Shape_c.getOneGD_SHPOnR2(GraphicalElement_c .getOneGD_GEOnR1(m_editor.getModel())); ContainingShape_c cs = ContainingShape_c.getOneGD_CTROnR28(container); if(cs != null) { cs.Autoresize(); } } offsetX = 0; offsetY = 0; } else { handleNonDiagramElementAsDestination(destination, processorMap); } } public static void handleNonDiagramElementAsDestination( NonRootModelElement destination, HashMap<NonRootModelElement, ModelStreamProcessor> processorMap) throws Exception { // we are pasting into a shape, we need to move the // graphical elements to the new Model_c instance Model_c destGD_MD = getModel(destination); // skip if no diagram if (destGD_MD == null) { return; } if (moveIsInProgress()) { for (NonRootModelElement ooaElementMoved : ELEMENT_MOVE_SOURCE_SELECTION) { moveGraphicalElement(ooaElementMoved, destGD_MD); } } else { GraphicalElement_c[] pastedGraphicalElements = getPastedGraphicalElements( destination, processorMap); NonRootModelElement[] loadedGraphicalElements = processorMap.get( destination).getImporter().getLoadedGraphicalInstances(); updateGraphicalElementRoots(loadedGraphicalElements, destGD_MD.getModelRoot()); for (GraphicalElement_c element : pastedGraphicalElements) { element.relateAcrossR1To(destGD_MD); updateContainement(destGD_MD, element); } // move the elements so they do not overlap any existing elements moveGraphicalElementsToPreventOverlapping(pastedGraphicalElements, destGD_MD); } if (destGD_MD.Hascontainersymbol()) { Shape_c container = Shape_c.getOneGD_SHPOnR2(GraphicalElement_c .getOneGD_GEOnR1(destGD_MD)); ContainingShape_c cs = ContainingShape_c .getOneGD_CTROnR28(container); if (cs != null) { cs.Autoresize(); } } } /** * If there is a graphical element we need to update its * containment by un-associating it from it's source canvas * and associating it with the destination * * @param ooaElementMoved * @param destGD_MD */ private static void moveGraphicalElement(final NonRootModelElement ooaElementMoved, Model_c destGD_MD) { Model_c[] models = Model_c.ModelInstances(Ooaofgraphics.getInstance(ooaElementMoved.getModelRoot().getId())); Model_c[] systemModels = Model_c.ModelInstances(Ooaofgraphics.getDefaultInstance()); Model_c[] allModels = new Model_c[models.length + systemModels.length]; System.arraycopy(models, 0, allModels, 0, models.length); System.arraycopy(systemModels, 0, allModels, models.length, systemModels.length); GraphicalElement_c graphicalElementMoved = null; for(int i = 0; i < allModels.length; i++) { graphicalElementMoved = GraphicalElement_c.getOneGD_GEOnR1(allModels[i], new ClassQueryInterface_c() { @Override public boolean evaluate(Object candidate) { GraphicalElement_c element = (GraphicalElement_c) candidate; if(element.getRepresents() != null) { return element.getRepresents().equals(ooaElementMoved); } else { return element.getOoa_id().equals(ooaElementMoved.Get_ooa_id()); } } }); CanvasPlugin.setGraphicalRepresents(allModels[i]); if(graphicalElementMoved != null) { break; } } if (graphicalElementMoved != null) { // Every GraphicalElement is part of a diagram, so this will never be null. Model_c gd_mdThisElementIsPartOf = Model_c.getOneGD_MDOnR1(graphicalElementMoved); // This finds the GD_MD instance that has the same "represents" as the given // GD_GE. This is null unless the ooaElementMoved represents a container. Model_c gd_mdOftheElementMoved = getModel(ooaElementMoved); // If we are moving to a different graphical model root then we need to actually switch the root. // In this case we update self and children because the root moves for all of them if (gd_mdOftheElementMoved!= null && gd_mdOftheElementMoved != destGD_MD) { Diagram_c diag = Diagram_c.getOneDIM_DIAOnR18(gd_mdOftheElementMoved); diag.setComponent(destGD_MD.getPersistableComponent()); gd_mdOftheElementMoved.setComponent(destGD_MD.getPersistableComponent()); diag.updateRootForSelfAndChildren(gd_mdOftheElementMoved.getModelRoot(), destGD_MD.getModelRoot()); } graphicalElementMoved.setComponent(destGD_MD.getPersistableComponent()); graphicalElementMoved.unrelateAcrossR1From(gd_mdThisElementIsPartOf); graphicalElementMoved.relateAcrossR1To(destGD_MD); updateContainement(destGD_MD, graphicalElementMoved); GraphicalElement_c[] graphicalElementList = {graphicalElementMoved}; moveGraphicalElementsToPreventOverlapping(graphicalElementList, destGD_MD); } } static private void openCanvasEditor(final Object uut) { try { IStructuredSelection ss = new StructuredSelection(uut); Selection selection = Selection.getInstance(); selection.addToSelection(ss); OpenGraphicsEditor sca = new OpenGraphicsEditor(); selection.setSelection(ss); Action a = new Action() { }; sca.run(a); while(PlatformUI.getWorkbench().getDisplay().readAndDispatch()) ; PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().update(); } catch (Exception x) { CorePlugin.logError("Unable to open canvas editor.", x); } } private static void moveGraphicalElementsToPreventOverlapping( GraphicalElement_c[] elements, Model_c model) { // store current selection ISelection selection = Selection.getInstance().getSelection(); // clear the current selection and add all elements // to it, this allows connectors to move properly Selection.getInstance().clear(); Point northWestSelectionPoint = getNorthWestSelectionPoint(elements); Point nextAvailableEastLocation = getNextAvailableEastLocation(model); for(int i = 0; i < elements.length; i++) { Cl_c.Addtoselection(elements[i]); } for(int i = 0; i < elements.length; i++) { Connector_c connector = Connector_c.getOneGD_CONOnR2(elements[i]); if(connector == null) { elements[i] .Move(nextAvailableEastLocation.x - northWestSelectionPoint.x, nextAvailableEastLocation.y - northWestSelectionPoint.y); } } // restore the selection Selection.getInstance().setSelection(selection); } private static Point getNextAvailableEastLocation(Model_c model) { GraphicalElement_c[] existing = GraphicalElement_c.getManyGD_GEsOnR1(model); Point east = new Point(-1, Integer.MAX_VALUE); for(int i = 0; i < existing.length; i++) { Graphelement_c graphEle = Graphelement_c.getOneDIM_GEOnR23(existing[i]); Graphnode_c node = Graphnode_c.getOneDIM_NDOnR301(graphEle); Connector_c connector = Connector_c .getOneGD_CONOnR2(GraphicalElement_c .getOneGD_GEOnR23(graphEle)); if(connector == null) { if(east.x < graphEle.getPositionx() + node.getWidth()) { east.x = (int) (graphEle.getPositionx() + node.getWidth() + 50); } if(east.y > graphEle.getPositiony()) { east.y = (int) graphEle.getPositiony(); } } } return east; } private static Model_c getModel(NonRootModelElement destination) { Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(destination.getModelRoot().getId()); Model_c[] models = Model_c.ModelInstances(graphicsRoot); for(Model_c model : models) { if(model.getRepresents() == destination) { return model; } } return null; } private boolean areGraphicalElementsExternal() { // right now all graphical elements come from // the same location, so just check the first // in the list UUID copiedFromDiagramId = graphicElements[0].getDiagramidCachedValue(); Diagram_c destinationDiagram = Diagram_c.getOneDIM_DIAOnR18(m_editor .getModel()); if (!copiedFromDiagramId.equals(destinationDiagram.getDiagramid())) { return true; } return false; } private static void updateContainement(Model_c ptCanvas, GraphicalElement_c element_c) { Diagramelement_c diaElem = Diagramelement_c .getOneDIM_ELEOnR302(Graphelement_c .getOneDIM_GEOnR23(element_c)); if(ptCanvas.Hascontainersymbol()) { // if this shape is pasted into // a shape, make sure the necessary // containment associations are setup Graphelement_c container = Graphelement_c.getOneDIM_GEOnR307(diaElem); if(container == null) { container = Graphelement_c .getOneDIM_GEOnR23(GraphicalElement_c .getOneGD_GEOnR2(Shape_c .getOneGD_SHPOnR28(ContainingShape_c .getOneGD_CTROnR28(Shape_c .getOneGD_SHPOnR2(GraphicalElement_c .getOneGD_GEOnR1(ptCanvas)))))); diaElem.relateAcrossR307To(container); } } else { // if not pasted into a shape // make sure no containment // association is setup Graphelement_c container = Graphelement_c.getOneDIM_GEOnR307(diaElem); if(container != null) { diaElem.unrelateAcrossR307From(container); } } } private static void updateGraphicalElementRoots(NonRootModelElement[] elements, ModelRoot modelRoot) { for(int i = 0; i < elements.length; i++) { InstanceList list = elements[i].getModelRoot().getInstanceList( elements[i].getClass()); synchronized (list) { list.remove(elements[i]); } InstanceList parentList = modelRoot .getInstanceList(elements[i].getClass()); synchronized (parentList) { parentList.add(elements[i]); parentList.put(elements[i].getInstanceKey(), elements[i]); } elements[i].setModelRoot(modelRoot); } } private static GraphicalElement_c[] getPastedGraphicalElements( NonRootModelElement destination, HashMap<NonRootModelElement, ModelStreamProcessor> processorMap) { // do not process unless the destination is the diagram ArrayList<GraphicalElement_c> list = new ArrayList<GraphicalElement_c>(); GraphicalElement_c[] pastedElems = GraphicalElement_c .GraphicalElementInstances(Ooaofgraphics .getInstance(Ooaofooa.CLIPBOARD_MODEL_ROOT_NAME)); for (int i = 0; i < pastedElems.length; i++) { // skip containing shapes ContainingShape_c cs = ContainingShape_c.getOneGD_CTROnR28(Shape_c .getOneGD_SHPOnR2(pastedElems[i])); if (cs != null) { continue; } // skip connectors that start on a container shape // as they are never part of the copy, if we later // enable copy of a container then we will likely // need to remove these checks cs = ContainingShape_c .getOneGD_CTROnR28(Shape_c .getOneGD_SHPOnR2(GraphicalElement_c .getOneGD_GEOnR23(Graphelement_c .getOneDIM_GEOnR311(Graphconnector_c .getOneDIM_CONOnR320(Graphedge_c .getOneDIM_EDOnR20(Connector_c .getOneGD_CONOnR2(pastedElems[i]))))))); if (cs != null) { continue; } cs = ContainingShape_c .getOneGD_CTROnR28(Shape_c .getOneGD_SHPOnR2(GraphicalElement_c .getOneGD_GEOnR23(Graphelement_c .getOneDIM_GEOnR311(Graphconnector_c .getOneDIM_CONOnR321(Graphedge_c .getOneDIM_EDOnR20(Connector_c .getOneGD_CONOnR2(pastedElems[i]))))))); if (cs != null) { continue; } if (pastedElems[i].getRepresents() != null) { if(processorMap.get(destination).isTypePartOfExport((NonRootModelElement) pastedElems[i] .getRepresents())) { list.add(pastedElems[i]); } } } return list.toArray(new GraphicalElement_c[list.size()]); } /** * Determines the position for the pasted elements, then makes a call * to update their positional values. * * @param elements */ private void updateLocation(GraphicalElement_c[] elements, boolean newParent) { if(offsetX == 0 && offsetY == 0) { if(fRequest != null) { offsetX = fRequest.getMoveDelta().x; offsetY = fRequest.getMoveDelta().y; // clear the request cache fRequest = null; } else { // determine the offset based on the northwest corner // point of the selection and the mouse point where // the user decided to paste the selection Point nw = getNorthWestSelectionPoint(elements); Point location = getMouseLocation(); offsetX = (int) (location.x - nw.x); offsetY = (int) (location.y - nw.y); GraphicalViewer viewer = (GraphicalViewer) m_editor .getAdapter(GraphicalViewer.class); GraphicalPanningSelectionTool tool = (GraphicalPanningSelectionTool) viewer .getEditDomain().getActiveTool(); if (tool.getLastLeftClickLocation().x == 0 && tool.getLastLeftClickLocation().y == 0) { // there is no location hint, so we // just give a slight offset to the right // and down a bit, unless the elements are // being pasted from a different diagram if(newParent) { // then we simply use the top left corner Point topLeft = new Point(15, 15); ((AbstractGraphicalEditPart) viewer.getContents()) .getFigure().translateToRelative(topLeft); offsetX = topLeft.x - nw.x; offsetY = topLeft.y - nw.y; } else { offsetX = 15; offsetY = 15; } } } } updateLocations(offsetX, offsetY, elements); } private Point getMouseLocation() { GraphicalViewer viewer = (GraphicalViewer) m_editor .getAdapter(GraphicalViewer.class); GraphicalPanningSelectionTool tool = (GraphicalPanningSelectionTool) viewer .getEditDomain().getActiveTool(); Point lastLeftClickLocation = tool.getLastLeftClickLocation().getCopy(); ((AbstractGraphicalEditPart) viewer.getContents()).getFigure() .translateToRelative(lastLeftClickLocation); return lastLeftClickLocation; } /** * Updates the positional values of the elements on the clipboard, using * the given offset. Note the elements are added to the selection just in * case the selection was cleared before a paste, this allows for connectors * to move appropriately. * * @param offsetX2 * @param offsetY2 * @param elements */ private void updateLocations(int offsetX2, int offsetY2, GraphicalElement_c[] elements) { // set the selection before moving and after refreshing // the diagram contents (the refresh will create // the new edit parts) m_editor.refresh(); GraphicalViewer viewer = (GraphicalViewer) m_editor .getAdapter(GraphicalViewer.class); viewer.deselectAll(); for (int i = 0; i < elements.length; i++) { Object newModel = null; Shape_c shape = Shape_c.getOneGD_SHPOnR2(elements[i]); if(shape != null) { newModel = shape; } Connector_c connector = Connector_c.getOneGD_CONOnR2(elements[i]); if(connector != null) { newModel = connector; } List<?> children = viewer.getContents().getChildren(); for(Object child: children) { EditPart editPart = (EditPart) child; if(editPart.getModel() == newModel) { viewer.appendSelection(editPart); } } } for(int i = 0; i < elements.length; i++) { Connector_c connector = Connector_c.getOneGD_CONOnR2(elements[i]); if(connector == null) { elements[i].Move(offsetX2, offsetY2); } } } /** * Looks through the elements on the clipboard to determine * a reference point for location placement * * @param elements * @return */ private static Point getNorthWestSelectionPoint(GraphicalElement_c[] elements) { Point nw = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); for(int i = 0; i < elements.length; i++) { Graphelement_c graphEle = Graphelement_c.getOneDIM_GEOnR23(elements[i]); Connector_c connector = Connector_c .getOneGD_CONOnR2(GraphicalElement_c .getOneGD_GEOnR23(graphEle)); if(connector == null) { if(nw.x > graphEle.getPositionx()) { nw.x = (int) graphEle.getPositionx(); } if(nw.y > graphEle.getPositiony()) { nw.y = (int) graphEle.getPositiony(); } } } return nw; } @Override protected boolean supportsPaste(Object target, String child) { return Cl_c.supportsPaste(target, child); } public TransactionManager getTransactionManager() { return ((NonRootModelElement)m_editor.getModel().getRepresents()).getTransactionManager(); } @Override public List<NonRootModelElement> getDestinations() { if(fRequest != null) { // this is for the clone command, which always needs // the diagram host as the destination List<NonRootModelElement> destinations = new ArrayList<NonRootModelElement>(); destinations.add((NonRootModelElement) m_editor.getModel().getRepresents()); return destinations; } IStructuredSelection selection = (IStructuredSelection) m_editor .getSite().getSelectionProvider().getSelection(); return getDestinationsFromSelection(selection); } private List<NonRootModelElement> getDestinationsFromSelection(IStructuredSelection selection) { List<NonRootModelElement> destinations = new ArrayList<NonRootModelElement>(); for(Iterator<?> iterator = selection.iterator(); iterator.hasNext();) { Object selected = iterator.next(); if(selected instanceof EditPart) { EditPart part = (EditPart) selected; NonRootModelElement element = (NonRootModelElement) GraphicsUtil .getRepresentsFromEditPart(part); destinations.add(element); } } return destinations; } public void setRequest(ChangeBoundsRequest request) { fRequest = request; } @Override public boolean isEnabled() { if(!super.isEnabled() || (m_editor == null) ) { return false; } return true; } }
import android.content.Context; import android.text.TextUtils; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.CookieHandler; import java.net.CookieManager; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; public class JSONParser { static final String COOKIES_HEADER = "Set-Cookie"; static JSONObject jObj = null; // static String jsonString = ""; Context context; static String json = ""; public JSONParser(Context context) { this.context = context; } public JSONParser() { } public String sendReq(String strUrl, int reqType, String jsonData) throws IOException { String jsonString = ""; CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (cookieManager.getCookieStore().getCookies().size() > 0) { conn.setRequestProperty("Cookie", TextUtils.join(",", cookieManager .getCookieStore().getCookies())); } if (reqType == 0) { conn.setRequestMethod("GET"); } else if (reqType == 1) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setFixedLengthStreamingMode(jsonData.getBytes().length); PrintWriter out = new PrintWriter(conn.getOutputStream()); out.print(jsonData); out.close(); } conn.setConnectTimeout(10000); conn.connect(); Map<String, List<String>> headerFields = conn.getHeaderFields(); List<String> cookiesHeader = headerFields.get(COOKIES_HEADER); if (cookiesHeader != null) { for (String cookie : cookiesHeader) { cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0)); } } // read the response System.out.println("Response Code: " + conn.getResponseCode() + "---" + cookieManager.getCookieStore().getCookies()); try { InputStream is = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); jsonString = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return jsonString; } public String[] sendPostReq(String strurl, String jsonData) throws IOException { String jsonString = ""; CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); URL url = new URL(strurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (cookieManager.getCookieStore().getCookies().size() > 0) { conn.setRequestProperty("Cookie", TextUtils.join(",", cookieManager .getCookieStore().getCookies())); } conn.setRequestProperty("Authorization", "JWT " + UserDataPreferences.getToken(context)); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setFixedLengthStreamingMode(jsonData.getBytes().length); // conn.setConnectTimeout(1000); conn.setConnectTimeout(9000); PrintWriter out = new PrintWriter(conn.getOutputStream()); out.print(jsonData); out.close(); conn.connect(); Map<String, List<String>> headerFields = conn.getHeaderFields(); try { List<String> cookiesHeader = headerFields.get(COOKIES_HEADER); if (cookiesHeader != null) { for (String cookie : cookiesHeader) { cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0)); } } } catch (Exception e) { e.printStackTrace(); } try { InputStream is = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); jsonString = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return new String[]{String.valueOf(conn.getResponseCode()), jsonString}; } public String[] sendGetReq(String strUrl) throws IOException { String jsonString = ""; CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (cookieManager.getCookieStore().getCookies().size() > 0) { conn.setRequestProperty("Cookie", TextUtils.join(",", cookieManager .getCookieStore().getCookies())); } conn.setRequestProperty("Authorization", "JWT " + UserDataPreferences.getToken(context)); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.connect(); Map<String, List<String>> headerFields = conn.getHeaderFields(); List<String> cookiesHeader = headerFields.get(COOKIES_HEADER); if (cookiesHeader != null) { for (String cookie : cookiesHeader) { cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0)); } } try { InputStream is = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); jsonString = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return new String[]{String.valueOf(conn.getResponseCode()), jsonString}; } public String[] sendPostReq(String strurl) throws IOException { String jsonString = ""; CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); URL url = new URL(strurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (cookieManager.getCookieStore().getCookies().size() > 0) { conn.setRequestProperty("Cookie", TextUtils.join(",", cookieManager .getCookieStore().getCookies())); } conn.setRequestProperty("Authorization", "JWT " + UserDataPreferences.getToken(context)); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setConnectTimeout(10000); conn.connect(); Map<String, List<String>> headerFields = conn.getHeaderFields(); try { List<String> cookiesHeader = headerFields.get(COOKIES_HEADER); if (cookiesHeader != null) { for (String cookie : cookiesHeader) { cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0)); } } } catch (Exception e) { e.printStackTrace(); } try { InputStream is = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); jsonString = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); return new String[]{String.valueOf(conn.getResponseCode()), null}; } return new String[]{String.valueOf(conn.getResponseCode()), jsonString}; } public String sendMultiPartRequest(Context context, String url, MultipartEntity multipartEntity) { try { String sResponse = null; HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Authorization", "Bearer " + UserDataPreferences.getToken(context)); httpPost.setEntity(multipartEntity); HttpResponse response = httpClient.execute(httpPost, localContext); try { InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); sResponse = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return sResponse; } catch (Exception e) { e.printStackTrace(); return null; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.jackrabbit.oak.plugins.tree.impl; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.base.Objects; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.ReadOnlyBuilder; /** * Immutable implementation of the {@code Tree} interface in order to provide * the much feature rich API functionality for a given {@code NodeState}. * * <h3>Tree hierarchy</h3> * Due to the nature of this {@code Tree} implementation creating a proper * hierarchical view of the tree structure is the responsibility of the caller. * It is recommended to start with the state of the * {@link #ImmutableTree(org.apache.jackrabbit.oak.spi.state.NodeState) root node} * and build up the hierarchy by calling * {@link #ImmutableTree(ImmutableTree, String, org.apache.jackrabbit.oak.spi.state.NodeState)} * for every subsequent child state. Note, that this implementation will not * perform any kind of validation of the passed state and methods like {@link #isRoot()}, * {@link #getName()} or {@link #getPath()} will just make use of the hierarchy that has been * create by that sequence. In order to create a disconnected individual tree in cases where * the hierarchy information is not (yet) need or known it is suggested to use * {@link #ImmutableTree(ImmutableTree.ParentProvider, String, org.apache.jackrabbit.oak.spi.state.NodeState)} * an specify an appropriate {@code ParentProvider} implementation. * * <h3>ParentProvider</h3> * Apart from create the tree hierarchy in traversal mode this tree implementation * allows to instantiate disconnected trees that depending on the use may * never or on demand retrieve hierarchy information. The following default * implementations of this internal interface are present: * * <ul> * <li>{@link DefaultParentProvider}: used with the default usage where the * parent tree is passed to the constructor</li> * <li>{@link ParentProvider#ROOT_PROVIDER}: the default parent provider for * the root tree. All children will get {@link DefaultParentProvider}</li> * <li>{@link ParentProvider#UNSUPPORTED}: throws {@code UnsupportedOperationException} * upon hierarchy related methods like {@link #getParent()}, {@link #getPath()}</li> * </ul> * * <h3>Filtering 'hidden' items</h3> * This {@code Tree} implementation reflects the item hierarchy as exposed by the * underlying {@code NodeState}. In contrast to the mutable implementations it * does not filter out 'hidden' items as identified by * {@code org.apache.jackrabbit.oak.spi.state.NodeStateUtils#isHidden(String)}. * * <h3>Equality and hash code</h3> * In contrast to {@link org.apache.jackrabbit.oak.plugins.tree.impl.AbstractMutableTree} * the {@code ImmutableTree} implements * {@link Object#equals(Object)} and {@link Object#hashCode()}: Two {@code ImmutableTree}s * are consider equal if their name and the underlying {@code NodeState}s are equal. Note * however, that according to the contract defined in {@code NodeState} these * objects are not expected to be used as hash keys. */ public final class ImmutableTree extends AbstractTree { /** * Underlying node state */ private final NodeBuilder nodeBuilder; /** * Name of this tree */ private final String name; private final ParentProvider parentProvider; private String path; public ImmutableTree(@Nonnull NodeState rootState) { this(ParentProvider.ROOT_PROVIDER, "", rootState); } public ImmutableTree(@Nonnull ImmutableTree parent, @Nonnull String name, @Nonnull NodeState state) { this(new DefaultParentProvider(parent), name, state); } public ImmutableTree(@Nonnull ParentProvider parentProvider, @Nonnull String name, @Nonnull NodeState state) { this.nodeBuilder = new ReadOnlyBuilder(state); this.name = name; this.parentProvider = checkNotNull(parentProvider); } //-------------------------------------------------------< AbstractTree >--- @Override @Nonnull protected ImmutableTree createChild(@Nonnull String name) { return new ImmutableTree(this, name, nodeBuilder.getNodeState().getChildNode(name)); } @Override @CheckForNull protected AbstractTree getParentOrNull() { return parentProvider.getParent(); } @Nonnull @Override protected NodeBuilder getNodeBuilder() { return nodeBuilder; } @Override protected boolean isHidden(String name) { return false; } @Nonnull @Override protected String[] getInternalNodeNames() { return new String[0]; } //---------------------------------------------------------------< Tree >--- @Nonnull @Override public String getName() { return name; } @Override @Nonnull public String getPath() { if (path == null) { path = super.getPath(); } return path; } @Nonnull @Override public ImmutableTree getChild(@Nonnull String name) throws IllegalArgumentException { return createChild(name); } @Override public boolean remove() { throw new UnsupportedOperationException(); } @Override @Nonnull public Tree addChild(@Nonnull String name) { throw new UnsupportedOperationException(); } @Override public void setOrderableChildren(boolean enable) { throw new UnsupportedOperationException(); } @Override public boolean orderBefore(@Nullable String name) { throw new UnsupportedOperationException(); } @Override public void setProperty(@Nonnull PropertyState property) { throw new UnsupportedOperationException(); } @Override public <T> void setProperty(@Nonnull String name, @Nonnull T value) { throw new UnsupportedOperationException(); } @Override public <T> void setProperty(@Nonnull String name, @Nonnull T value, @Nonnull Type<T> type) { throw new UnsupportedOperationException(); } @Override public void removeProperty(@Nonnull String name) { throw new UnsupportedOperationException(); } //-------------------------------------------------------------< Object >--- @Override public int hashCode() { return Objects.hashCode(getName(), nodeBuilder.getNodeState()); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ImmutableTree) { ImmutableTree other = (ImmutableTree) o; return getName().equals(other.getName()) && nodeBuilder.getNodeState().equals(other.nodeBuilder.getNodeState()); } return false; } //-------------------------------------------------------------------------- public interface ParentProvider { ParentProvider UNSUPPORTED = new ParentProvider() { @Override public ImmutableTree getParent() { throw new UnsupportedOperationException("not supported."); } }; ParentProvider ROOT_PROVIDER = new ParentProvider() { @Override public ImmutableTree getParent() { return null; } }; @CheckForNull ImmutableTree getParent(); } public static final class DefaultParentProvider implements ParentProvider { private final ImmutableTree parent; DefaultParentProvider(@Nonnull ImmutableTree parent) { this.parent = checkNotNull(parent); } @Override public ImmutableTree getParent() { return parent; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.spark.sql.catalyst.expressions; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import org.apache.spark.sql.catalyst.util.ArrayData; import org.apache.spark.sql.types.*; import org.apache.spark.unsafe.Platform; import org.apache.spark.unsafe.array.ByteArrayMethods; import org.apache.spark.unsafe.bitset.BitSetMethods; import org.apache.spark.unsafe.hash.Murmur3_x86_32; import org.apache.spark.unsafe.types.CalendarInterval; import org.apache.spark.unsafe.types.UTF8String; import static org.apache.spark.unsafe.Platform.BYTE_ARRAY_OFFSET; /** * An Unsafe implementation of Array which is backed by raw memory instead of Java objects. * * Each array has four parts: * [numElements][null bits][values or offset&length][variable length portion] * * The `numElements` is 8 bytes storing the number of elements of this array. * * In the `null bits` region, we store 1 bit per element, represents whether an element is null * Its total size is ceil(numElements / 8) bytes, and it is aligned to 8-byte boundaries. * * In the `values or offset&length` region, we store the content of elements. For fields that hold * fixed-length primitive types, such as long, double, or int, we store the value directly * in the field. The whole fixed-length portion (even for byte) is aligned to 8-byte boundaries. * For fields with non-primitive or variable-length values, we store a relative offset * (w.r.t. the base address of the array) that points to the beginning of the variable-length field * and length (they are combined into a long). For variable length portion, each is aligned * to 8-byte boundaries. * * Instances of `UnsafeArrayData` act as pointers to row data stored in this format. */ public final class UnsafeArrayData extends ArrayData implements Externalizable, KryoSerializable { public static int calculateHeaderPortionInBytes(int numFields) { return (int)calculateHeaderPortionInBytes((long)numFields); } public static long calculateHeaderPortionInBytes(long numFields) { return 8 + ((numFields + 63)/ 64) * 8; } private Object baseObject; private long baseOffset; // The number of elements in this array private int numElements; // The size of this array's backing data, in bytes. // The 8-bytes header of `numElements` is also included. private int sizeInBytes; /** The position to start storing array elements, */ private long elementOffset; private long getElementOffset(int ordinal, int elementSize) { return elementOffset + ordinal * (long)elementSize; } public Object getBaseObject() { return baseObject; } public long getBaseOffset() { return baseOffset; } public int getSizeInBytes() { return sizeInBytes; } private void assertIndexIsValid(int ordinal) { assert ordinal >= 0 : "ordinal (" + ordinal + ") should >= 0"; assert ordinal < numElements : "ordinal (" + ordinal + ") should < " + numElements; } public Object[] array() { throw new UnsupportedOperationException("Not supported on UnsafeArrayData."); } /** * Construct a new UnsafeArrayData. The resulting UnsafeArrayData won't be usable until * `pointTo()` has been called, since the value returned by this constructor is equivalent * to a null pointer. */ public UnsafeArrayData() { } @Override public int numElements() { return numElements; } /** * Update this UnsafeArrayData to point to different backing data. * * @param baseObject the base object * @param baseOffset the offset within the base object * @param sizeInBytes the size of this array's backing data, in bytes */ public void pointTo(Object baseObject, long baseOffset, int sizeInBytes) { // Read the number of elements from the first 8 bytes. final long numElements = Platform.getLong(baseObject, baseOffset); assert numElements >= 0 : "numElements (" + numElements + ") should >= 0"; assert numElements <= Integer.MAX_VALUE : "numElements (" + numElements + ") should <= Integer.MAX_VALUE"; this.numElements = (int)numElements; this.baseObject = baseObject; this.baseOffset = baseOffset; this.sizeInBytes = sizeInBytes; this.elementOffset = baseOffset + calculateHeaderPortionInBytes(this.numElements); } @Override public boolean isNullAt(int ordinal) { assertIndexIsValid(ordinal); return BitSetMethods.isSet(baseObject, baseOffset + 8, ordinal); } @Override public Object get(int ordinal, DataType dataType) { return SpecializedGettersReader.read(this, ordinal, dataType, true, true); } @Override public boolean getBoolean(int ordinal) { assertIndexIsValid(ordinal); return Platform.getBoolean(baseObject, getElementOffset(ordinal, 1)); } @Override public byte getByte(int ordinal) { assertIndexIsValid(ordinal); return Platform.getByte(baseObject, getElementOffset(ordinal, 1)); } @Override public short getShort(int ordinal) { assertIndexIsValid(ordinal); return Platform.getShort(baseObject, getElementOffset(ordinal, 2)); } @Override public int getInt(int ordinal) { assertIndexIsValid(ordinal); return Platform.getInt(baseObject, getElementOffset(ordinal, 4)); } @Override public long getLong(int ordinal) { assertIndexIsValid(ordinal); return Platform.getLong(baseObject, getElementOffset(ordinal, 8)); } @Override public float getFloat(int ordinal) { assertIndexIsValid(ordinal); return Platform.getFloat(baseObject, getElementOffset(ordinal, 4)); } @Override public double getDouble(int ordinal) { assertIndexIsValid(ordinal); return Platform.getDouble(baseObject, getElementOffset(ordinal, 8)); } @Override public Decimal getDecimal(int ordinal, int precision, int scale) { if (isNullAt(ordinal)) return null; if (precision <= Decimal.MAX_LONG_DIGITS()) { return Decimal.apply(getLong(ordinal), precision, scale); } else { final byte[] bytes = getBinary(ordinal); final BigInteger bigInteger = new BigInteger(bytes); final BigDecimal javaDecimal = new BigDecimal(bigInteger, scale); return Decimal.apply(new scala.math.BigDecimal(javaDecimal), precision, scale); } } @Override public UTF8String getUTF8String(int ordinal) { if (isNullAt(ordinal)) return null; final long offsetAndSize = getLong(ordinal); final int offset = (int) (offsetAndSize >> 32); final int size = (int) offsetAndSize; return UTF8String.fromAddress(baseObject, baseOffset + offset, size); } @Override public byte[] getBinary(int ordinal) { if (isNullAt(ordinal)) return null; final long offsetAndSize = getLong(ordinal); final int offset = (int) (offsetAndSize >> 32); final int size = (int) offsetAndSize; final byte[] bytes = new byte[size]; Platform.copyMemory(baseObject, baseOffset + offset, bytes, Platform.BYTE_ARRAY_OFFSET, size); return bytes; } @Override public CalendarInterval getInterval(int ordinal) { if (isNullAt(ordinal)) return null; final long offsetAndSize = getLong(ordinal); final int offset = (int) (offsetAndSize >> 32); final int months = Platform.getInt(baseObject, baseOffset + offset); final int days = Platform.getInt(baseObject, baseOffset + offset + 4); final long microseconds = Platform.getLong(baseObject, baseOffset + offset + 8); return new CalendarInterval(months, days, microseconds); } @Override public UnsafeRow getStruct(int ordinal, int numFields) { if (isNullAt(ordinal)) return null; final long offsetAndSize = getLong(ordinal); final int offset = (int) (offsetAndSize >> 32); final int size = (int) offsetAndSize; final UnsafeRow row = new UnsafeRow(numFields); row.pointTo(baseObject, baseOffset + offset, size); return row; } @Override public UnsafeArrayData getArray(int ordinal) { if (isNullAt(ordinal)) return null; final long offsetAndSize = getLong(ordinal); final int offset = (int) (offsetAndSize >> 32); final int size = (int) offsetAndSize; final UnsafeArrayData array = new UnsafeArrayData(); array.pointTo(baseObject, baseOffset + offset, size); return array; } @Override public UnsafeMapData getMap(int ordinal) { if (isNullAt(ordinal)) return null; final long offsetAndSize = getLong(ordinal); final int offset = (int) (offsetAndSize >> 32); final int size = (int) offsetAndSize; final UnsafeMapData map = new UnsafeMapData(); map.pointTo(baseObject, baseOffset + offset, size); return map; } @Override public void update(int ordinal, Object value) { throw new UnsupportedOperationException(); } @Override public void setNullAt(int ordinal) { assertIndexIsValid(ordinal); BitSetMethods.set(baseObject, baseOffset + 8, ordinal); /* we assume the corresponding column was already 0 or will be set to 0 later by the caller side */ } @Override public void setBoolean(int ordinal, boolean value) { assertIndexIsValid(ordinal); Platform.putBoolean(baseObject, getElementOffset(ordinal, 1), value); } @Override public void setByte(int ordinal, byte value) { assertIndexIsValid(ordinal); Platform.putByte(baseObject, getElementOffset(ordinal, 1), value); } @Override public void setShort(int ordinal, short value) { assertIndexIsValid(ordinal); Platform.putShort(baseObject, getElementOffset(ordinal, 2), value); } @Override public void setInt(int ordinal, int value) { assertIndexIsValid(ordinal); Platform.putInt(baseObject, getElementOffset(ordinal, 4), value); } @Override public void setLong(int ordinal, long value) { assertIndexIsValid(ordinal); Platform.putLong(baseObject, getElementOffset(ordinal, 8), value); } @Override public void setFloat(int ordinal, float value) { assertIndexIsValid(ordinal); Platform.putFloat(baseObject, getElementOffset(ordinal, 4), value); } @Override public void setDouble(int ordinal, double value) { assertIndexIsValid(ordinal); Platform.putDouble(baseObject, getElementOffset(ordinal, 8), value); } // This `hashCode` computation could consume much processor time for large data. // If the computation becomes a bottleneck, we can use a light-weight logic; the first fixed bytes // are used to compute `hashCode` (See `Vector.hashCode`). // The same issue exists in `UnsafeRow.hashCode`. @Override public int hashCode() { return Murmur3_x86_32.hashUnsafeBytes(baseObject, baseOffset, sizeInBytes, 42); } @Override public boolean equals(Object other) { if (other instanceof UnsafeArrayData) { UnsafeArrayData o = (UnsafeArrayData) other; return (sizeInBytes == o.sizeInBytes) && ByteArrayMethods.arrayEquals(baseObject, baseOffset, o.baseObject, o.baseOffset, sizeInBytes); } return false; } public void writeToMemory(Object target, long targetOffset) { Platform.copyMemory(baseObject, baseOffset, target, targetOffset, sizeInBytes); } public void writeTo(ByteBuffer buffer) { assert(buffer.hasArray()); byte[] target = buffer.array(); int offset = buffer.arrayOffset(); int pos = buffer.position(); writeToMemory(target, Platform.BYTE_ARRAY_OFFSET + offset + pos); buffer.position(pos + sizeInBytes); } @Override public UnsafeArrayData copy() { UnsafeArrayData arrayCopy = new UnsafeArrayData(); final byte[] arrayDataCopy = new byte[sizeInBytes]; Platform.copyMemory( baseObject, baseOffset, arrayDataCopy, Platform.BYTE_ARRAY_OFFSET, sizeInBytes); arrayCopy.pointTo(arrayDataCopy, Platform.BYTE_ARRAY_OFFSET, sizeInBytes); return arrayCopy; } @Override public boolean[] toBooleanArray() { boolean[] values = new boolean[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.BOOLEAN_ARRAY_OFFSET, numElements); return values; } @Override public byte[] toByteArray() { byte[] values = new byte[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.BYTE_ARRAY_OFFSET, numElements); return values; } @Override public short[] toShortArray() { short[] values = new short[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.SHORT_ARRAY_OFFSET, numElements * 2L); return values; } @Override public int[] toIntArray() { int[] values = new int[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.INT_ARRAY_OFFSET, numElements * 4L); return values; } @Override public long[] toLongArray() { long[] values = new long[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.LONG_ARRAY_OFFSET, numElements * 8L); return values; } @Override public float[] toFloatArray() { float[] values = new float[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.FLOAT_ARRAY_OFFSET, numElements * 4L); return values; } @Override public double[] toDoubleArray() { double[] values = new double[numElements]; Platform.copyMemory( baseObject, elementOffset, values, Platform.DOUBLE_ARRAY_OFFSET, numElements * 8L); return values; } public static UnsafeArrayData fromPrimitiveArray( Object arr, int offset, int length, int elementSize) { final long headerInBytes = calculateHeaderPortionInBytes(length); final long valueRegionInBytes = (long)elementSize * length; final long totalSizeInLongs = (headerInBytes + valueRegionInBytes + 7) / 8; if (totalSizeInLongs > Integer.MAX_VALUE / 8) { throw new UnsupportedOperationException("Cannot convert this array to unsafe format as " + "it's too big."); } final long[] data = new long[(int)totalSizeInLongs]; Platform.putLong(data, Platform.LONG_ARRAY_OFFSET, length); if (arr != null) { Platform.copyMemory(arr, offset, data, Platform.LONG_ARRAY_OFFSET + headerInBytes, valueRegionInBytes); } UnsafeArrayData result = new UnsafeArrayData(); result.pointTo(data, Platform.LONG_ARRAY_OFFSET, (int)totalSizeInLongs * 8); return result; } public static UnsafeArrayData createFreshArray(int length, int elementSize) { final long headerInBytes = calculateHeaderPortionInBytes(length); final long valueRegionInBytes = (long)elementSize * length; final long totalSizeInLongs = (headerInBytes + valueRegionInBytes + 7) / 8; if (totalSizeInLongs > Integer.MAX_VALUE / 8) { throw new UnsupportedOperationException("Cannot convert this array to unsafe format as " + "it's too big."); } final long[] data = new long[(int)totalSizeInLongs]; Platform.putLong(data, Platform.LONG_ARRAY_OFFSET, length); UnsafeArrayData result = new UnsafeArrayData(); result.pointTo(data, Platform.LONG_ARRAY_OFFSET, (int)totalSizeInLongs * 8); return result; } public static boolean shouldUseGenericArrayData(int elementSize, long length) { final long headerInBytes = calculateHeaderPortionInBytes(length); final long valueRegionInBytes = elementSize * length; final long totalSizeInLongs = (headerInBytes + valueRegionInBytes + 7) / 8; return totalSizeInLongs > Integer.MAX_VALUE / 8; } public static UnsafeArrayData fromPrimitiveArray(boolean[] arr) { return fromPrimitiveArray(arr, Platform.BOOLEAN_ARRAY_OFFSET, arr.length, 1); } public static UnsafeArrayData fromPrimitiveArray(byte[] arr) { return fromPrimitiveArray(arr, Platform.BYTE_ARRAY_OFFSET, arr.length, 1); } public static UnsafeArrayData fromPrimitiveArray(short[] arr) { return fromPrimitiveArray(arr, Platform.SHORT_ARRAY_OFFSET, arr.length, 2); } public static UnsafeArrayData fromPrimitiveArray(int[] arr) { return fromPrimitiveArray(arr, Platform.INT_ARRAY_OFFSET, arr.length, 4); } public static UnsafeArrayData fromPrimitiveArray(long[] arr) { return fromPrimitiveArray(arr, Platform.LONG_ARRAY_OFFSET, arr.length, 8); } public static UnsafeArrayData fromPrimitiveArray(float[] arr) { return fromPrimitiveArray(arr, Platform.FLOAT_ARRAY_OFFSET, arr.length, 4); } public static UnsafeArrayData fromPrimitiveArray(double[] arr) { return fromPrimitiveArray(arr, Platform.DOUBLE_ARRAY_OFFSET, arr.length, 8); } @Override public void writeExternal(ObjectOutput out) throws IOException { byte[] bytes = UnsafeDataUtils.getBytes(baseObject, baseOffset, sizeInBytes); out.writeInt(bytes.length); out.writeInt(this.numElements); out.write(bytes); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.baseOffset = BYTE_ARRAY_OFFSET; this.sizeInBytes = in.readInt(); this.numElements = in.readInt(); this.elementOffset = baseOffset + calculateHeaderPortionInBytes(this.numElements); this.baseObject = new byte[sizeInBytes]; in.readFully((byte[]) baseObject); } @Override public void write(Kryo kryo, Output output) { byte[] bytes = UnsafeDataUtils.getBytes(baseObject, baseOffset, sizeInBytes); output.writeInt(bytes.length); output.writeInt(this.numElements); output.write(bytes); } @Override public void read(Kryo kryo, Input input) { this.baseOffset = BYTE_ARRAY_OFFSET; this.sizeInBytes = input.readInt(); this.numElements = input.readInt(); this.elementOffset = baseOffset + calculateHeaderPortionInBytes(this.numElements); this.baseObject = new byte[sizeInBytes]; input.read((byte[]) baseObject); } }
/** * Copyright Ambud Sharma * * 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.srotya.sidewinder.core.sql.calcite; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.apache.calcite.DataContext; import org.apache.calcite.linq4j.AbstractEnumerable; import org.apache.calcite.linq4j.Enumerable; import org.apache.calcite.linq4j.Enumerator; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexInputRef; import org.apache.calcite.rex.RexLiteral; import org.apache.calcite.rex.RexNode; import org.apache.calcite.schema.ProjectableFilterableTable; import org.apache.calcite.schema.Schema.TableType; import org.apache.calcite.schema.impl.AbstractTable; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.type.SqlTypeName; import com.srotya.sidewinder.core.storage.Series; import com.srotya.sidewinder.core.storage.StorageEngine; /** * @author ambud */ public class MeasurementTable extends AbstractTable implements ProjectableFilterableTable { private StorageEngine engine; private List<String> fieldNames; String measurementName; String dbName; private List<RelDataType> types; private List<String> names; private Set<String> tagKeys; private int maxResultCount; public MeasurementTable(StorageEngine engine, String dbName, String measurementName, Collection<String> fieldNames, Set<String> tagKeys, int maxResultCount) { this.engine = engine; this.dbName = dbName; this.measurementName = measurementName; this.tagKeys = tagKeys; this.maxResultCount = maxResultCount; this.fieldNames = new ArrayList<>(fieldNames); this.fieldNames.addAll(tagKeys); } @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) { types = new ArrayList<>(); names = new ArrayList<>(); for (String field : fieldNames) { names.add(field.toUpperCase()); if (tagKeys.contains(field)) { types.add(typeFactory.createSqlType(SqlTypeName.VARCHAR)); } else { try { if (engine.getOrCreateMeasurement(dbName, measurementName).isFieldFp(field)) { // value field; should be cast by the query to different type types.add(typeFactory.createSqlType(SqlTypeName.DOUBLE)); } else { types.add(typeFactory.createSqlType(SqlTypeName.BIGINT)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return typeFactory.createStructType(types, names); } @Override public TableType getJdbcTableType() { return TableType.TABLE; } @Override public Enumerable<Object[]> scan(DataContext root, List<RexNode> filters, int[] projects) { List<Boolean> fTypes = new ArrayList<>(); List<String> fields; if (projects != null) { fields = new ArrayList<>(); for (int i = 0; i < projects.length; i++) { fields.add(fieldNames.get(projects[i])); fTypes.add(types.get(projects[i]).getSqlTypeName() == SqlTypeName.DOUBLE); } } else { fields = fieldNames; for (int i = 0; i < types.size(); i++) { RelDataType relDataType = types.get(i); fTypes.add(relDataType.getSqlTypeName() == SqlTypeName.DOUBLE); } } Entry<Long, Long> findTimeRange = null; findTimeRange = extractAndBuildTimeRangeFilter(filters, findTimeRange); final Entry<Long, Long> range = findTimeRange; // System.out.println("Range filer:" + range.getKey() + " " + range.getValue()); return new AbstractEnumerable<Object[]>() { public Enumerator<Object[]> enumerator() { return new MeasurementEnumeratorImplementation(MeasurementTable.this, range, fields, fTypes); } }; } private Entry<Long, Long> extractAndBuildTimeRangeFilter(List<RexNode> filters, Entry<Long, Long> findTimeRange) { for (RexNode filter : filters) { Entry<Long, Long> temp = findTimeRange(filter); if (temp != null) { findTimeRange = temp; if (findTimeRange.getKey() > findTimeRange.getValue()) { // swap findTimeRange = new AbstractMap.SimpleEntry<Long, Long>(findTimeRange.getValue(), findTimeRange.getKey()); } } // System.err.println("Time range filter:" + findTimeRange); } if (findTimeRange == null) { // by default get last 1hr's data if no time range filter is // specified // System.currentTimeMillis() - (3600_000) findTimeRange = new AbstractMap.SimpleEntry<Long, Long>(0L, System.currentTimeMillis() + 10000); } else if (findTimeRange.getKey().equals(findTimeRange.getValue())) { findTimeRange = new AbstractMap.SimpleEntry<Long, Long>(findTimeRange.getKey(), System.currentTimeMillis()); } return findTimeRange; } private Entry<Long, Long> findTimeRange(RexNode filter) { List<Entry<Long, Long>> vals = new ArrayList<>(); if (filter.isA(SqlKind.AND) || filter.isA(SqlKind.OR)) { RexCall call = (RexCall) filter; for (RexNode rexNode : call.getOperands()) { Entry<Long, Long> val = findTimeRange(rexNode); if (val != null) { vals.add(val); } } if (vals.size() > 0) { long min = Long.MAX_VALUE, max = 1; for (Entry<Long, Long> val : vals) { if (min > val.getKey()) { System.err.println("Swapping min value:" + min + "\t" + val.getValue()); min = val.getKey(); } if (max < val.getValue()) { System.err.println("Swapping max value:" + max + "\t" + val.getValue()); max = val.getValue(); } } return new AbstractMap.SimpleEntry<Long, Long>(min, max); } else { return null; } } else { RexCall call = ((RexCall) filter); RexNode left = call.getOperands().get(0); RexNode right = call.getOperands().get(call.getOperands().size() - 1); if (left.isA(SqlKind.CAST)) { left = ((RexCall) left).operands.get(0); } else if (left.isA(SqlKind.FUNCTION)) { left = ((RexCall) left).operands.get(0); if (names.get(((RexInputRef) left).getIndex()).equals(Series.TS)) { // resolve the function } } // only timestamp field is filtered if (!names.get(((RexInputRef) left).getIndex()).equals(Series.TS)) { return null; } long val = 10; if (right.isA(SqlKind.CAST)) { right = ((RexCall) right).operands.get(0); } else if (right.isA(SqlKind.FUNCTION)) { if (((RexCall) right).operands.size() > 0) { right = ((RexCall) right).operands.get(0); val = (long) ((RexLiteral) right).getValue2(); // System.out.println("\n\nFunction parsed \n\n"); } else { System.err.println("Funtion:" + ((RexCall) right).op.getName() + "\t" + filter.getKind()); if (((RexCall) right).op.getName().equals("now")) { val = System.currentTimeMillis(); } } } else { @SuppressWarnings("rawtypes") Comparable value = ((RexLiteral) right).getValue(); if (value instanceof Number) { val = ((Number) value).longValue(); } } if (filter.isA(Arrays.asList(SqlKind.GREATER_THAN, SqlKind.GREATER_THAN_OR_EQUAL))) { return new AbstractMap.SimpleEntry<Long, Long>(val, Long.MAX_VALUE); } else if (filter.isA(Arrays.asList(SqlKind.LESS_THAN, SqlKind.LESS_THAN_OR_EQUAL))) { return new AbstractMap.SimpleEntry<Long, Long>(0L, val); } else { return new AbstractMap.SimpleEntry<Long, Long>(Long.MIN_VALUE, Long.MAX_VALUE); } } } public StorageEngine getStorageEngine() { return engine; } public int getMaxResultCount() { return maxResultCount; } }
/* * Copyright 2014 JBoss 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.teiid.authoring.client.widgets; import javax.enterprise.context.Dependent; import javax.inject.Inject; import org.teiid.authoring.backend.server.servlets.DataVirtUploadServlet; import org.teiid.authoring.client.dialogs.UploadDialog; import org.teiid.authoring.client.messages.ClientMessages; import org.teiid.authoring.client.services.NotificationService; import org.teiid.authoring.share.beans.NotificationBean; import org.teiid.authoring.share.exceptions.DataVirtUiException; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler; import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitHandler; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Widget; /** * The form submit handler used by the {@link ImportDataSourceTypeDialog}. * * @author mdrillin@redhat.com */ @Dependent public class ImportDataSourceTypeFormSubmitHandler implements SubmitHandler, SubmitCompleteHandler { @Inject protected ClientMessages i18n; @Inject private NotificationService notificationService; private UploadDialog dialog; private NotificationBean notification; private IImportCompletionHandler completionHandler; /** * Constructor. */ public ImportDataSourceTypeFormSubmitHandler() { } /** * @param dialog the dialog */ public void setDialog(UploadDialog dialog) { this.dialog = dialog; } /** * @see com.google.gwt.user.client.ui.FormPanel.SubmitHandler#onSubmit(com.google.gwt.user.client.ui.FormPanel.SubmitEvent) */ @Override public void onSubmit(SubmitEvent event) { // dialog.hide(false); notification = notificationService.startProgressNotification( i18n.format("import-datasource-type-submit.uploading.title"), //$NON-NLS-1$ i18n.format("import-datasource-type-submit.uploading.msg")); //$NON-NLS-1$ } /** * @see com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler#onSubmitComplete(com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent) */ @Override public void onSubmitComplete(SubmitCompleteEvent event) { dialog.hide(); ImportResult results = ImportResult.fromResult(event.getResults()); if (results.isError()) { if (results.getError() != null) { notificationService.completeProgressNotification( notification.getUuid(), i18n.format("import-datasource-type-submit.upload-error.title"), //$NON-NLS-1$ results.getError()); } else { notificationService.completeProgressNotification( notification.getUuid(), i18n.format("import-datasource-type-submit.upload-error.title"), //$NON-NLS-1$ i18n.format("import-datasource-type-submit.upload-error.msg")); //$NON-NLS-1$ } } else { Widget ty = new InlineLabel(i18n.format("import-datasource-type-submit.upload-complete.msg")); //$NON-NLS-1$ FlowPanel body = new FlowPanel(); body.add(ty); notificationService.completeProgressNotification( notification.getUuid(), i18n.format("import-datasource-type-submit.upload-complete.title"), //$NON-NLS-1$ body); if (completionHandler != null) { completionHandler.onImportComplete(); } } } /** * @return the completionHandler */ public IImportCompletionHandler getCompletionHandler() { return completionHandler; } /** * @param completionHandler the completionHandler to set */ public void setCompletionHandler(IImportCompletionHandler completionHandler) { this.completionHandler = completionHandler; } /** * The {@link DataVirtUploadServlet} returns a JSON map as the response. * @author mdrillin@redhat.com */ private static class ImportResult extends JavaScriptObject { /** * Constructor. */ protected ImportResult() { } /** * Convert the string returned by the {@link DataVirtUploadServlet} into JSON and * then from there into an {@link ImportResult} bean. * @param resultData */ public static final ImportResult fromResult(String resultData) { int startIdx = resultData.indexOf('{'); int endIdx = resultData.lastIndexOf('}') + 1; resultData = "(" + resultData.substring(startIdx, endIdx) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ return fromJSON(resultData); } /** * Gets a value from the map. * @param key */ public final native String get(String key) /*-{ if (this[key]) return this[key]; else return null; }-*/; /** * @return the uuid */ public final String getUuid() { return get("uuid"); //$NON-NLS-1$ } /** * @return the model */ public final String getModel() { return get("model"); //$NON-NLS-1$ } /** * @return the type */ public final String getType() { return get("type"); //$NON-NLS-1$ } /** * Returns true if the response is an error response. */ public final boolean isError() { return "true".equals(get("exception")); //$NON-NLS-1$ //$NON-NLS-2$ } /** * @return true if the response is due to a s-ramp package upload */ public final boolean isBatch() { return "true".equals(get("batch")); //$NON-NLS-1$ //$NON-NLS-2$ } /** * @return the total number of items in the s-ramp package */ public final int getBatchTotal() { return new Integer(get("batchTotal")); //$NON-NLS-1$ } /** * @return the number of successful items in the package */ public final int getBatchNumSuccess() { return new Integer(get("batchNumSuccess")); //$NON-NLS-1$ } /** * @return the number of failed items in the package */ public final int getBatchNumFailed() { return new Integer(get("batchNumFailed")); //$NON-NLS-1$ } /** * Gets the error. */ public final DataVirtUiException getError() { String errorMessage = get("exception-message"); //$NON-NLS-1$ DataVirtUiException error = new DataVirtUiException(errorMessage); return error; } /** * Convert a string of json data into a useful bean. * @param jsonData */ public static final native ImportResult fromJSON(String jsonData) /*-{ return eval(jsonData); }-*/; } }
package com.github.droidpl.android.jsonviewer; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; /** * Adapter that is able to visualise the json object or json array in a recycler view. */ public class RVJsonAdapter extends RecyclerView.Adapter<RVJsonAdapter.ViewHolder> { /** * The context for the adapter inflating. */ private Context mContext; /** * Map with the properties of the contained json object. Null if it is an array. */ private HashMap<String, Object> mMap; /** * The json array to display. Null if there is a map. */ private JSONArray mJsonArray; /** * The listener to send a clicked object. */ private JsonListener mListener; /** * Listener to return the object clicked if it is a complex one. */ public interface JsonListener { /** * Provides the clicked json object. * * @param object The object. */ void openJsonObject(@NonNull JSONObject object); /** * Provides the clicked array item. * * @param array The array to open. */ void openJsonArray(@NonNull JSONArray array); } /** * Constructor to create the recycler adapter with an object. * * @param context The context. * @param json The json object to display. * @param listener The listener. */ public RVJsonAdapter(@NonNull Context context, @Nullable JSONObject json, @Nullable JsonListener listener) { mContext = context; if (json != null) { mMap = new LinkedHashMap<>(json.length()); Iterator<String> keys = json.keys(); while (keys.hasNext()) { String key = keys.next(); mMap.put(key, json.opt(key)); } } mListener = listener; } /** * Constructor to create the recycler adapter with an array. * * @param context The context. * @param array The json array. * @param listener The listener. */ public RVJsonAdapter(@NonNull Context context, @Nullable JSONArray array, @Nullable JsonListener listener) { mContext = context; mJsonArray = array; mListener = listener; } /** * Without any object. * * @param context opens it with any object. */ public RVJsonAdapter(@NonNull Context context) { mContext = context; } @Override public RVJsonAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { final ViewHolder viewHolder = new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.json_item_adapter, parent, false)); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { Object obj = getItem(viewHolder.getAdapterPosition()); if (obj != null) { if (obj instanceof JSONObject) { mListener.openJsonObject((JSONObject) obj); } else if (obj instanceof JSONArray) { mListener.openJsonArray((JSONArray) obj); } } } } }); return viewHolder; } @Override public void onBindViewHolder(@NonNull RVJsonAdapter.ViewHolder holder, int position) { Object obj = getItem(position); String key = getItemKey(position); if (obj != null) { if (obj instanceof JSONObject) { holder.setObject(key, false); } else if (obj instanceof JSONArray) { holder.setObject(key, true); } else { holder.setText(key, obj.toString()); } } } @Override public int getItemCount() { if (mMap != null) { return mMap.size(); } else if (mJsonArray != null) { return mJsonArray.length(); } return 0; } /** * Provides the item key name. Number for array, property for object. * * @param position The position. * @return The key as string or null. */ @Nullable private String getItemKey(int position) { if (mMap != null) { return new ArrayList<>(mMap.entrySet()).get(position).getKey(); } else if (mJsonArray != null) { return String.valueOf(position); } return null; } /** * Provides the item in a given position. * * @param position The position. * @return The item in this position or null if no item. */ @Nullable private Object getItem(int position) { if (mMap != null) { return new ArrayList<>(mMap.entrySet()).get(position).getValue(); } else if (mJsonArray != null) { return mJsonArray.opt(position); } return null; } /** * The view holder for the adapter. */ public static class ViewHolder extends RecyclerView.ViewHolder { /** * A text view for the property. */ private TextView mProperty; /** * A text view for the value. */ private TextView mValue; /** * Image displayed in case of complex object. */ private ImageView mImage; /** * Constructor for the view holder. * * @param itemView The view. */ public ViewHolder(@NonNull View itemView) { super(itemView); mProperty = (TextView) itemView.findViewById(R.id.tv_property); mValue = (TextView) itemView.findViewById(R.id.tv_value); mImage = (ImageView) itemView.findViewById(R.id.iv_next); } /** * Sets the text in the property. * * @param property The property. * @param text The text. */ public void setText(@Nullable String property, @Nullable String text) { mImage.setVisibility(View.GONE); mProperty.setText(property); mValue.setText(text); } /** * Sets an object in the adapter. * * @param property The property to display. * @param isArray True if array, false otherwise. */ public void setObject(@Nullable String property, boolean isArray) { mImage.setVisibility(View.VISIBLE); mProperty.setText(property); if (isArray) { mValue.setText("[...]"); } else { mValue.setText("{...}"); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.beam.runners.flink.translation.functions; import static org.apache.beam.runners.core.construction.PTransformTranslation.PAR_DO_TRANSFORM_URN; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.Components; import org.apache.beam.model.pipeline.v1.RunnerApi.ExecutableStagePayload; import org.apache.beam.model.pipeline.v1.RunnerApi.PCollection; import org.apache.beam.runners.core.construction.Timer; import org.apache.beam.runners.flink.metrics.FlinkMetricContainer; import org.apache.beam.runners.fnexecution.control.BundleCheckpointHandler; import org.apache.beam.runners.fnexecution.control.BundleFinalizationHandler; import org.apache.beam.runners.fnexecution.control.BundleProgressHandler; import org.apache.beam.runners.fnexecution.control.ExecutableStageContext; import org.apache.beam.runners.fnexecution.control.InstructionRequestHandler; import org.apache.beam.runners.fnexecution.control.OutputReceiverFactory; import org.apache.beam.runners.fnexecution.control.ProcessBundleDescriptors; import org.apache.beam.runners.fnexecution.control.RemoteBundle; import org.apache.beam.runners.fnexecution.control.StageBundleFactory; import org.apache.beam.runners.fnexecution.control.TimerReceiverFactory; import org.apache.beam.runners.fnexecution.provisioning.JobInfo; import org.apache.beam.runners.fnexecution.state.StateRequestHandler; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.join.RawUnionValue; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.sdk.values.KV; import org.apache.beam.vendor.grpc.v1p36p0.com.google.protobuf.Struct; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap; import org.apache.flink.api.common.cache.DistributedCache; import org.apache.flink.api.common.functions.RuntimeContext; import org.apache.flink.configuration.Configuration; import org.apache.flink.util.Collector; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.powermock.reflect.Whitebox; /** Tests for {@link FlinkExecutableStageFunction}. */ @RunWith(Parameterized.class) @SuppressWarnings({ "rawtypes", // TODO(https://issues.apache.org/jira/browse/BEAM-10556) }) public class FlinkExecutableStageFunctionTest { @Parameterized.Parameters public static Object[] data() { return new Object[] {true, false}; } @Parameterized.Parameter public boolean isStateful; @Rule public ExpectedException thrown = ExpectedException.none(); @Mock private RuntimeContext runtimeContext; @Mock private DistributedCache distributedCache; @Mock private Collector<RawUnionValue> collector; @Mock private ExecutableStageContext stageContext; @Mock private StageBundleFactory stageBundleFactory; @Mock private StateRequestHandler stateRequestHandler; @Mock private ProcessBundleDescriptors.ExecutableProcessBundleDescriptor processBundleDescriptor; // NOTE: ExecutableStage.fromPayload expects exactly one input, so we provide one here. These unit // tests in general ignore the executable stage itself and mock around it. private final ExecutableStagePayload stagePayload = ExecutableStagePayload.newBuilder() .setInput("input") .setComponents( Components.newBuilder() .putTransforms( "transform", RunnerApi.PTransform.newBuilder() .putInputs("bla", "input") .setSpec(RunnerApi.FunctionSpec.newBuilder().setUrn(PAR_DO_TRANSFORM_URN)) .build()) .putPcollections("input", PCollection.getDefaultInstance()) .build()) .addUserStates( ExecutableStagePayload.UserStateId.newBuilder().setTransformId("transform").build()) .build(); private final JobInfo jobInfo = JobInfo.create("job-id", "job-name", "retrieval-token", Struct.getDefaultInstance()); @Before public void setUpMocks() throws Exception { MockitoAnnotations.initMocks(this); when(runtimeContext.getDistributedCache()).thenReturn(distributedCache); when(stageContext.getStageBundleFactory(any())).thenReturn(stageBundleFactory); RemoteBundle remoteBundle = Mockito.mock(RemoteBundle.class); when(stageBundleFactory.getBundle( any(), any(StateRequestHandler.class), any(BundleProgressHandler.class), any(BundleFinalizationHandler.class), any(BundleCheckpointHandler.class))) .thenReturn(remoteBundle); when(stageBundleFactory.getBundle( any(), any(TimerReceiverFactory.class), any(StateRequestHandler.class), any(BundleProgressHandler.class))) .thenReturn(remoteBundle); ImmutableMap input = ImmutableMap.builder().put("input", Mockito.mock(FnDataReceiver.class)).build(); when(remoteBundle.getInputReceivers()).thenReturn(input); when(processBundleDescriptor.getTimerSpecs()).thenReturn(Collections.emptyMap()); } @Test public void sdkErrorsSurfaceOnClose() throws Exception { FlinkExecutableStageFunction<Integer> function = getFunction(Collections.emptyMap()); function.open(new Configuration()); @SuppressWarnings("unchecked") RemoteBundle bundle = Mockito.mock(RemoteBundle.class); when(stageBundleFactory.getBundle( any(), any(StateRequestHandler.class), any(BundleProgressHandler.class), any(BundleFinalizationHandler.class), any(BundleCheckpointHandler.class))) .thenReturn(bundle); @SuppressWarnings("unchecked") FnDataReceiver<WindowedValue<?>> receiver = Mockito.mock(FnDataReceiver.class); when(bundle.getInputReceivers()).thenReturn(ImmutableMap.of("input", receiver)); Exception expected = new Exception(); doThrow(expected).when(bundle).close(); thrown.expect(is(expected)); function.mapPartition(Collections.emptyList(), collector); } @Test public void expectedInputsAreSent() throws Exception { FlinkExecutableStageFunction<Integer> function = getFunction(Collections.emptyMap()); function.open(new Configuration()); @SuppressWarnings("unchecked") RemoteBundle bundle = Mockito.mock(RemoteBundle.class); when(stageBundleFactory.getBundle( any(), any(StateRequestHandler.class), any(BundleProgressHandler.class), any(BundleFinalizationHandler.class), any(BundleCheckpointHandler.class))) .thenReturn(bundle); @SuppressWarnings("unchecked") FnDataReceiver<WindowedValue<?>> receiver = Mockito.mock(FnDataReceiver.class); when(bundle.getInputReceivers()).thenReturn(ImmutableMap.of("input", receiver)); WindowedValue<Integer> one = WindowedValue.valueInGlobalWindow(1); WindowedValue<Integer> two = WindowedValue.valueInGlobalWindow(2); WindowedValue<Integer> three = WindowedValue.valueInGlobalWindow(3); function.mapPartition(Arrays.asList(one, two, three), collector); verify(receiver).accept(one); verify(receiver).accept(two); verify(receiver).accept(three); verifyNoMoreInteractions(receiver); } @Test public void outputsAreTaggedCorrectly() throws Exception { WindowedValue<Integer> three = WindowedValue.valueInGlobalWindow(3); WindowedValue<Integer> four = WindowedValue.valueInGlobalWindow(4); WindowedValue<Integer> five = WindowedValue.valueInGlobalWindow(5); Map<String, Integer> outputTagMap = ImmutableMap.of( "one", 1, "two", 2, "three", 3); // We use a real StageBundleFactory here in order to exercise the output receiver factory. StageBundleFactory stageBundleFactory = new StageBundleFactory() { private boolean once; @Override public RemoteBundle getBundle( OutputReceiverFactory receiverFactory, TimerReceiverFactory timerReceiverFactory, StateRequestHandler stateRequestHandler, BundleProgressHandler progressHandler, BundleFinalizationHandler finalizationHandler, BundleCheckpointHandler checkpointHandler) { return new RemoteBundle() { @Override public String getId() { return "bundle-id"; } @Override public Map<String, FnDataReceiver> getInputReceivers() { return ImmutableMap.of( "input", input -> { /* Ignore input*/ }); } @Override public Map<KV<String, String>, FnDataReceiver<Timer>> getTimerReceivers() { return Collections.emptyMap(); } @Override public void requestProgress() { throw new UnsupportedOperationException(); } @Override public void split(double fractionOfRemainder) { throw new UnsupportedOperationException(); } @Override public void close() throws Exception { if (once) { return; } // Emit all values to the runner when the bundle is closed. receiverFactory.create("one").accept(three); receiverFactory.create("two").accept(four); receiverFactory.create("three").accept(five); once = true; } }; } @Override public ProcessBundleDescriptors.ExecutableProcessBundleDescriptor getProcessBundleDescriptor() { return processBundleDescriptor; } @Override public InstructionRequestHandler getInstructionRequestHandler() { return null; } @Override public void close() throws Exception {} }; // Wire the stage bundle factory into our context. when(stageContext.getStageBundleFactory(any())).thenReturn(stageBundleFactory); FlinkExecutableStageFunction<Integer> function = getFunction(outputTagMap); function.open(new Configuration()); if (isStateful) { function.reduce(Collections.emptyList(), collector); } else { function.mapPartition(Collections.emptyList(), collector); } // Ensure that the tagged values sent to the collector have the correct union tags as specified // in the output map. verify(collector).collect(new RawUnionValue(1, three)); verify(collector).collect(new RawUnionValue(2, four)); verify(collector).collect(new RawUnionValue(3, five)); verifyNoMoreInteractions(collector); } @Test public void testStageBundleClosed() throws Exception { FlinkExecutableStageFunction<Integer> function = getFunction(Collections.emptyMap()); function.open(new Configuration()); function.close(); verify(stageBundleFactory).getProcessBundleDescriptor(); verify(stageBundleFactory).close(); verifyNoMoreInteractions(stageBundleFactory); } @Test public void testAccumulatorRegistrationOnOperatorClose() throws Exception { FlinkExecutableStageFunction<Integer> function = getFunction(Collections.emptyMap()); function.open(new Configuration()); String metricContainerFieldName = "metricContainer"; FlinkMetricContainer monitoredContainer = Mockito.spy( (FlinkMetricContainer) Whitebox.getInternalState(function, metricContainerFieldName)); Whitebox.setInternalState(function, metricContainerFieldName, monitoredContainer); function.close(); Mockito.verify(monitoredContainer).registerMetricsForPipelineResult(); } /** * Creates a {@link FlinkExecutableStageFunction}. Sets the runtime context to {@link * #runtimeContext}. The context factory is mocked to return {@link #stageContext} every time. The * behavior of the stage context itself is unchanged. */ private FlinkExecutableStageFunction<Integer> getFunction(Map<String, Integer> outputMap) { FlinkExecutableStageContextFactory contextFactory = Mockito.mock(FlinkExecutableStageContextFactory.class); when(contextFactory.get(any())).thenReturn(stageContext); FlinkExecutableStageFunction<Integer> function = new FlinkExecutableStageFunction<>( "step", PipelineOptionsFactory.create(), stagePayload, jobInfo, outputMap, contextFactory, null, null); function.setRuntimeContext(runtimeContext); Whitebox.setInternalState(function, "stateRequestHandler", stateRequestHandler); return function; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.sql; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.ignite.cache.QueryIndex; import org.apache.ignite.internal.sql.command.SqlCreateIndexCommand; import org.apache.ignite.internal.sql.command.SqlIndexColumn; import org.apache.ignite.internal.util.typedef.F; import org.junit.Test; import static org.apache.ignite.internal.sql.SqlKeyword.INLINE_SIZE; import static org.apache.ignite.internal.sql.SqlKeyword.PARALLEL; /** * Tests for SQL parser: CREATE INDEX. */ @SuppressWarnings({"UnusedReturnValue"}) public class SqlParserCreateIndexSelfTest extends SqlParserAbstractSelfTest { /** Default properties */ private static final Map<String, Object> DEFAULT_PROPS = getProps(null, null); /** * Tests for CREATE INDEX command. * * @throws Exception If failed. */ @Test public void testCreateIndex() throws Exception { // Base. parseValidate(null, "CREATE INDEX idx ON tbl(a)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate(null, "CREATE INDEX idx ON tbl(a);", null, "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate(null, "CREATE INDEX idx ON tbl(a ASC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", true); assertParseError(null, "CREATE INDEX idx ON tbl(a) ,", "Unexpected token: \",\""); // Case (in)sensitivity. parseValidate(null, "CREATE INDEX IDX ON TBL(COL)", null, "TBL", "IDX", DEFAULT_PROPS, "COL", false); parseValidate(null, "CREATE INDEX iDx ON tBl(cOl)", null, "TBL", "IDX", DEFAULT_PROPS, "COL", false); parseValidate(null, "CREATE INDEX \"idx\" ON tbl(col)", null, "TBL", "idx", DEFAULT_PROPS, "COL", false); parseValidate(null, "CREATE INDEX \"iDx\" ON tbl(col)", null, "TBL", "iDx", DEFAULT_PROPS, "COL", false); parseValidate(null, "CREATE INDEX idx ON \"tbl\"(col)", null, "tbl", "IDX", DEFAULT_PROPS, "COL", false); parseValidate(null, "CREATE INDEX idx ON \"tBl\"(col)", null, "tBl", "IDX", DEFAULT_PROPS, "COL", false); parseValidate(null, "CREATE INDEX idx ON tbl(\"col\")", null, "TBL", "IDX", DEFAULT_PROPS, "col", false); parseValidate(null, "CREATE INDEX idx ON tbl(\"cOl\")", null, "TBL", "IDX", DEFAULT_PROPS, "cOl", false); parseValidate(null, "CREATE INDEX idx ON tbl(\"cOl\" ASC)", null, "TBL", "IDX", DEFAULT_PROPS, "cOl", false); parseValidate(null, "CREATE INDEX idx ON tbl(\"cOl\" DESC)", null, "TBL", "IDX", DEFAULT_PROPS, "cOl", true); // Columns. parseValidate(null, "CREATE INDEX idx ON tbl(a, b)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", false); parseValidate(null, "CREATE INDEX idx ON tbl(a ASC, b)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", false); parseValidate(null, "CREATE INDEX idx ON tbl(a, b ASC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", false); parseValidate(null, "CREATE INDEX idx ON tbl(a ASC, b ASC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", false); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC, b)", null, "TBL", "IDX", DEFAULT_PROPS, "A", true, "B", false); parseValidate(null, "CREATE INDEX idx ON tbl(a, b DESC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", true); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC, b DESC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", true, "B", true); parseValidate(null, "CREATE INDEX idx ON tbl(a ASC, b DESC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", true); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC, b ASC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", true, "B", false); parseValidate(null, "CREATE INDEX idx ON tbl(a, b, c)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", false, "C", false); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC, b, c)", null, "TBL", "IDX", DEFAULT_PROPS, "A", true, "B", false, "C", false); parseValidate(null, "CREATE INDEX idx ON tbl(a, b DESC, c)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", true, "C", false); parseValidate(null, "CREATE INDEX idx ON tbl(a, b, c DESC)", null, "TBL", "IDX", DEFAULT_PROPS, "A", false, "B", false, "C", true); // Negative cases. assertParseError(null, "CREATE INDEX idx ON tbl()", "Unexpected token"); assertParseError(null, "CREATE INDEX idx ON tbl(a, a)", "Column already defined: A"); assertParseError(null, "CREATE INDEX idx ON tbl(a, b, a)", "Column already defined: A"); assertParseError(null, "CREATE INDEX idx ON tbl(b, a, a)", "Column already defined: A"); // Tests with schema. parseValidate(null, "CREATE INDEX idx ON schema.tbl(a)", "SCHEMA", "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate(null, "CREATE INDEX idx ON \"schema\".tbl(a)", "schema", "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate(null, "CREATE INDEX idx ON \"sChema\".tbl(a)", "sChema", "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate("SCHEMA", "CREATE INDEX idx ON tbl(a)", "SCHEMA", "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate("schema", "CREATE INDEX idx ON tbl(a)", "schema", "TBL", "IDX", DEFAULT_PROPS, "A", false); parseValidate("sChema", "CREATE INDEX idx ON tbl(a)", "sChema", "TBL", "IDX", DEFAULT_PROPS, "A", false); // No index name. parseValidate(null, "CREATE INDEX ON tbl(a)", null, "TBL", null, DEFAULT_PROPS, "A", false); parseValidate(null, "CREATE INDEX ON schema.tbl(a)", "SCHEMA", "TBL", null, DEFAULT_PROPS, "A", false); // NOT EXISTS SqlCreateIndexCommand cmd; cmd = parseValidate(null, "CREATE INDEX idx ON schema.tbl(a)", "SCHEMA", "TBL", "IDX", DEFAULT_PROPS, "A", false); assertFalse(cmd.ifNotExists()); cmd = parseValidate(null, "CREATE INDEX IF NOT EXISTS idx ON schema.tbl(a)", "SCHEMA", "TBL", "IDX", DEFAULT_PROPS, "A", false); assertTrue(cmd.ifNotExists()); assertParseError(null, "CREATE INDEX IF idx ON tbl(a)", "Unexpected token: \"IDX\""); assertParseError(null, "CREATE INDEX IF NOT idx ON tbl(a)", "Unexpected token: \"IDX\""); assertParseError(null, "CREATE INDEX IF EXISTS idx ON tbl(a)", "Unexpected token: \"EXISTS\""); assertParseError(null, "CREATE INDEX NOT EXISTS idx ON tbl(a)", "Unexpected token: \"NOT\""); // SPATIAL cmd = parseValidate(null, "CREATE INDEX idx ON schema.tbl(a)", "SCHEMA", "TBL", "IDX", DEFAULT_PROPS, "A", false); assertFalse(cmd.spatial()); cmd = parseValidate(null, "CREATE SPATIAL INDEX idx ON schema.tbl(a)", "SCHEMA", "TBL", "IDX", DEFAULT_PROPS, "A", false); assertTrue(cmd.spatial()); // UNIQUE assertParseError(null, "CREATE UNIQUE INDEX idx ON tbl(a)", "Unsupported keyword: \"UNIQUE\""); // HASH assertParseError(null, "CREATE HASH INDEX idx ON tbl(a)", "Unsupported keyword: \"HASH\""); // PRIMARY KEY assertParseError(null, "CREATE PRIMARY KEY INDEX idx ON tbl(a)", "Unsupported keyword: \"PRIMARY\""); // PARALLEL parseValidate(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL 1", null, "TBL", "IDX", getProps(1, null), "A", true); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL 3", null, "TBL", "IDX", getProps(3, null), "A", true); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL 7", null, "TBL", "IDX", getProps(7, null), "A", true); parseValidate(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL 0", null, "TBL", "IDX", getProps(0, null), "A", true); assertParseError(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL ", "Failed to parse SQL statement \"CREATE INDEX idx ON tbl(a DESC) PARALLEL [*]\""); assertParseError(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL abc", "Unexpected token: \"ABC\""); assertParseError(null, "CREATE INDEX idx ON tbl(a DESC) PARALLEL -2", "Failed to parse SQL statement \"CREATE INDEX idx ON tbl(a DESC) PARALLEL -[*]2\": Illegal PARALLEL value. Should be positive: -2"); // INLINE_SIZE option assertParseError(null, "CREATE INDEX ON tbl(a) INLINE_SIZE", "Unexpected end of command (expected: \"[integer]\")"); assertParseError(null, "CREATE INDEX ON tbl(a) INLINE_SIZE HASH", "Unexpected token: \"HASH\" (expected: \"[integer]\")"); assertParseError(null, "CREATE INDEX ON tbl(a) INLINE_SIZE elegua", "Unexpected token: \"ELEGUA\" (expected: \"[integer]\")"); assertParseError(null, "CREATE INDEX ON tbl(a) INLINE_SIZE -9223372036854775808", "Unexpected token: \"9223372036854775808\" (expected: \"[integer]\")"); assertParseError(null, "CREATE INDEX ON tbl(a) INLINE_SIZE " + Integer.MIN_VALUE, "Illegal INLINE_SIZE value. Should be positive: " + Integer.MIN_VALUE); assertParseError(null, "CREATE INDEX ON tbl(a) INLINE_SIZE -1", "Failed to parse SQL statement \"CREATE INDEX ON tbl(a) INLINE_SIZE -[*]1\": Illegal INLINE_SIZE value. Should be positive: -1"); parseValidate(null, "CREATE INDEX idx ON schema.tbl(a) INLINE_SIZE 0", "SCHEMA", "TBL", "IDX", getProps(null, 0), "A", false); parseValidate(null, "CREATE INDEX idx ON schema.tbl(a) INLINE_SIZE 1", "SCHEMA", "TBL", "IDX", getProps(null, 1), "A", false); parseValidate(null, "CREATE INDEX idx ON schema.tbl(a) INLINE_SIZE " + Integer.MAX_VALUE, "SCHEMA", "TBL", "IDX", getProps(null, Integer.MAX_VALUE), "A", false); // Both parallel and inline size parseValidate(null, "CREATE INDEX idx ON schema.tbl(a) INLINE_SIZE 5 PARALLEL 7", "SCHEMA", "TBL", "IDX", getProps(7, 5), "A", false); parseValidate(null, "CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE 9 ", "SCHEMA", "TBL", "IDX", getProps(3, 9), "A", false); assertParseError(null, "CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE 9 PARALLEL 2", "Failed to parse SQL statement \"CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE [*]9 PARALLEL 2\": Only one PARALLEL clause may be specified."); assertParseError(null, "CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE 9 abc ", "Failed to parse SQL statement \"CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE 9 [*]abc \": Unexpected token: \"ABC\""); assertParseError(null, "CREATE INDEX idx ON schema.tbl(a) PARALLEL INLINE_SIZE 9 abc ", "Failed to parse SQL statement \"CREATE INDEX idx ON schema.tbl(a) PARALLEL [*]INLINE_SIZE 9 abc \": Unexpected token: \"INLINE_SIZE\" (expected: \"[integer]\")"); assertParseError(null, "CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE abc ", "Failed to parse SQL statement \"CREATE INDEX idx ON schema.tbl(a) PARALLEL 3 INLINE_SIZE [*]abc \": Unexpected token: \"ABC\" (expected: \"[integer]\")"); } /** * Parse and validate SQL script. * * @param schema Schema. * @param sql SQL. * @param expSchemaName Expected schema name. * @param expTblName Expected table name. * @param expIdxName Expected index name. * @param props Expected properties. * @param expColDefs Expected column definitions. * @return Command. */ private static SqlCreateIndexCommand parseValidate(String schema, String sql, String expSchemaName, String expTblName, String expIdxName, Map<String, Object> props, Object... expColDefs) { SqlCreateIndexCommand cmd = (SqlCreateIndexCommand)new SqlParser(schema, sql).nextCommand(); validate(cmd, expSchemaName, expTblName, expIdxName, props, expColDefs); return cmd; } /** * Validate create index command. * * @param cmd Command. * @param expSchemaName Expected schema name. * @param expTblName Expected table name. * @param expIdxName Expected index name. * @param props Expected properties. * @param expColDefs Expected column definitions. */ private static void validate(SqlCreateIndexCommand cmd, String expSchemaName, String expTblName, String expIdxName, Map<String, Object> props, Object... expColDefs) { assertEquals(expSchemaName, cmd.schemaName()); assertEquals(expTblName, cmd.tableName()); assertEquals(expIdxName, cmd.indexName()); Map<String, Object> cmpProps = getProps(cmd.parallel(), cmd.inlineSize()); assertEquals(cmpProps, props); if (F.isEmpty(expColDefs) || expColDefs.length % 2 == 1) throw new IllegalArgumentException("Column definitions must be even."); Collection<SqlIndexColumn> cols = cmd.columns(); assertEquals(expColDefs.length / 2, cols.size()); Iterator<SqlIndexColumn> colIter = cols.iterator(); for (int i = 0; i < expColDefs.length;) { SqlIndexColumn col = colIter.next(); String expColName = (String)expColDefs[i++]; Boolean expDesc = (Boolean) expColDefs[i++]; assertEquals(expColName, col.name()); assertEquals(expDesc, (Boolean)col.descending()); } } /** * Returns map with command properties. * * @param parallel Parallel property value. <code>Null</code> for a default value. * @param inlineSize Inline size property value. <code>Null</code> for a default value. * @return Command properties. */ private static Map<String, Object> getProps(Integer parallel, Integer inlineSize) { if (parallel == null) parallel = 0; if (inlineSize == null) inlineSize = QueryIndex.DFLT_INLINE_SIZE; Map<String, Object> props = new HashMap<>(); props.put(PARALLEL, parallel); props.put(INLINE_SIZE, inlineSize); return Collections.unmodifiableMap(props); } }
/* * Copyright 2013 * * 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.openntf.domino; import java.util.Vector; import org.openntf.domino.types.FactorySchema; import org.openntf.domino.types.SessionDescendant; /** * The Interface NotesCalendarEntry. */ public interface NotesCalendarEntry extends Base<lotus.domino.NotesCalendarEntry>, lotus.domino.NotesCalendarEntry, org.openntf.domino.ext.NotesCalendarEntry, SessionDescendant { public static class Schema extends FactorySchema<NotesCalendarEntry, lotus.domino.NotesCalendarEntry, NotesCalendar> { @Override public Class<NotesCalendarEntry> typeClass() { return NotesCalendarEntry.class; } @Override public Class<lotus.domino.NotesCalendarEntry> delegateClass() { return lotus.domino.NotesCalendarEntry.class; } @Override public Class<NotesCalendar> parentClass() { return NotesCalendar.class; } }; public static final Schema SCHEMA = new Schema(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#accept(java.lang.String) */ @Override public void accept(final String comments); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#accept(java.lang.String, int, java.lang.String) */ @Override public void accept(final String comments, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#cancel(java.lang.String) */ @Override public void cancel(final String comments); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#cancel(java.lang.String, int, java.lang.String) */ @Override public void cancel(final String comments, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#counter(java.lang.String, lotus.domino.DateTime, lotus.domino.DateTime) */ @Override public void counter(final String comments, final lotus.domino.DateTime start, final lotus.domino.DateTime end); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#counter(java.lang.String, lotus.domino.DateTime, lotus.domino.DateTime, boolean) */ @Override public void counter(final String comments, final lotus.domino.DateTime start, final lotus.domino.DateTime end, final boolean keepPlaceholder); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#counter(java.lang.String, lotus.domino.DateTime, lotus.domino.DateTime, boolean, int, * java.lang.String) */ @Override public void counter(final String comments, final lotus.domino.DateTime start, final lotus.domino.DateTime end, final boolean keepPlaceholder, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#counter(java.lang.String, lotus.domino.DateTime, lotus.domino.DateTime, int, java.lang.String) */ @Override public void counter(final String comments, final lotus.domino.DateTime start, final lotus.domino.DateTime end, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#decline(java.lang.String) */ @Override public void decline(final String comments); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#decline(java.lang.String, boolean) */ @Override public void decline(final String comments, final boolean keepInformed); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#decline(java.lang.String, boolean, int, java.lang.String) */ @Override public void decline(final String comments, final boolean keepInformed, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#delegate(java.lang.String, java.lang.String) */ @Override public void delegate(final String commentsToOrganizer, final String delegateTo); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#delegate(java.lang.String, java.lang.String, boolean) */ @Override public void delegate(final String commentsToOrganizer, final String delegateTo, final boolean keepInformed); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#delegate(java.lang.String, java.lang.String, boolean, int, java.lang.String) */ @Override public void delegate(final String commentsToOrganizer, final String delegateTo, final boolean keepInformed, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#delegate(java.lang.String, java.lang.String, int, java.lang.String) */ @Override public void delegate(final String commentsToOrganizer, final String delegateTo, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#getAsDocument() */ @Override public Document getAsDocument(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#getAsDocument(int) */ @Override public Document getAsDocument(final int flags); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#getAsDocument(int, java.lang.String) */ @Override public Document getAsDocument(final int flags, final String recurrenceId); /** * Gets the parent. * * @return the parent */ public NotesCalendar getParent(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#getNotices() */ @Override public Vector<NotesCalendarNotice> getNotices(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#getUID() */ @Override public String getUID(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#read() */ @Override public String read(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#read(java.lang.String) */ @Override public String read(final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#remove() */ @Override public void remove(); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#remove(int, java.lang.String) */ @Override public void remove(final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#requestInfo(java.lang.String) */ @Override public void requestInfo(final String comments); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#tentativelyAccept(java.lang.String) */ @Override public void tentativelyAccept(final String comments); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#tentativelyAccept(java.lang.String, int, java.lang.String) */ @Override public void tentativelyAccept(final String comments, final int scope, final String recurrenceId); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#update(java.lang.String) */ @Override public void update(final String iCalEntry); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#update(java.lang.String, java.lang.String) */ @Override public void update(final String iCalEntry, final String comments); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#update(java.lang.String, java.lang.String, long) */ @Override public void update(final String iCalEntry, final String comments, final long flags); /* * (non-Javadoc) * * @see lotus.domino.NotesCalendarEntry#update(java.lang.String, java.lang.String, long, java.lang.String) */ @Override public void update(final String iCalEntry, final String comments, final long flags, final String recurrenceId); }
package unisannino.denenderman; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.ChunkCoordinates; import net.minecraft.village.Village; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; public class DEHomeCollection extends WorldSavedData { private World worldObj; /** * This is a black hole. You can add data to this list through a public interface, but you can't query that * information in any way and it's not used internally either. */ private final List villagerPositionsList = new ArrayList(); private final List newDoors = new ArrayList(); private final List villageList = new ArrayList(); private int tickCounter = 0; public DEHomeCollection(String par1Str) { super(par1Str); } public DEHomeCollection(World par1World) { super("villages"); this.worldObj = par1World; this.markDirty(); } /** * This is a black hole. You can add data to this list through a public interface, but you can't query that * information in any way and it's not used internally either. */ public void addVillagerPosition(int par1, int par2, int par3) { if (this.villagerPositionsList.size() <= 64) { if (!this.isVillagerPositionPresent(par1, par2, par3)) { this.villagerPositionsList.add(new ChunkCoordinates(par1, par2, par3)); } } } /** * Runs a single tick for the village collection */ public void tick() { ++this.tickCounter; Iterator var1 = this.villageList.iterator(); while (var1.hasNext()) { DEHome var2 = (DEHome)var1.next(); var2.tick(this.tickCounter); } this.removeAnnihilatedVillages(); this.dropOldestVillagerPosition(); this.addNewDoorsToVillageOrCreateVillage(); } private void removeAnnihilatedVillages() { Iterator var1 = this.villageList.iterator(); while (var1.hasNext()) { DEHome var2 = (DEHome)var1.next(); if (var2.isAnnihilated()) { var1.remove(); } } } /** * Get a list of villages. */ public List getVillageList() { return this.villageList; } /** * Finds the nearest village, but only the given coordinates are withing it's bounding box plus the given the * distance. */ public DEHome findNearestDEHome(int par1, int par2, int par3, int par4) { DEHome var5 = null; float var6 = Float.MAX_VALUE; Iterator var7 = this.villageList.iterator(); while (var7.hasNext()) { DEHome var8 = (DEHome)var7.next(); float var9 = var8.getCenter().getDistanceSquared(par1, par2, par3); if (var9 < var6) { int var10 = par4 + var8.getVillageRadius(); if (var9 <= (var10 * var10)) { var5 = var8; var6 = var9; } } } return var5; } private void dropOldestVillagerPosition() { if (!this.villagerPositionsList.isEmpty()) { this.addUnassignedWoodenDoorsAroundToNewDoorsList((ChunkCoordinates)this.villagerPositionsList.remove(0)); } } private void addNewDoorsToVillageOrCreateVillage() { Iterator var1 = this.newDoors.iterator(); while (var1.hasNext()) { DEHomeGateInfo var2 = (DEHomeGateInfo)var1.next(); boolean var3 = false; Iterator var4 = this.villageList.iterator(); while (true) { if (var4.hasNext()) { DEHome var5 = (DEHome)var4.next(); int var6 = (int)var5.getCenter().getDistanceSquared(var2.posX, var2.posY, var2.posZ); int var7 = 32 + var5.getVillageRadius(); if (var6 > var7 * var7) { continue; } var5.addVillageDoorInfo(var2); var3 = true; } if (!var3) { DEHome var8 = new DEHome(this.worldObj); var8.addVillageDoorInfo(var2); this.villageList.add(var8); this.markDirty(); } break; } } this.newDoors.clear(); } private void addUnassignedWoodenDoorsAroundToNewDoorsList(ChunkCoordinates par1ChunkCoordinates) { byte var2 = 16; byte var3 = 4; byte var4 = 16; for (int var5 = par1ChunkCoordinates.posX - var2; var5 < par1ChunkCoordinates.posX + var2; ++var5) { for (int var6 = par1ChunkCoordinates.posY - var3; var6 < par1ChunkCoordinates.posY + var3; ++var6) { for (int var7 = par1ChunkCoordinates.posZ - var4; var7 < par1ChunkCoordinates.posZ + var4; ++var7) { if (this.isFanceGateAt(var5, var6, var7)) { DEHomeGateInfo var8 = this.getVillageDoorAt(var5, var6, var7); if (var8 == null) { this.addDoorToNewListIfAppropriate(var5, var6, var7); } else { var8.lastActivityTimestamp = this.tickCounter; } } } } } } private DEHomeGateInfo getVillageDoorAt(int par1, int par2, int par3) { Iterator var4 = this.newDoors.iterator(); DEHomeGateInfo var5; do { if (!var4.hasNext()) { var4 = this.villageList.iterator(); DEHomeGateInfo var6; do { if (!var4.hasNext()) { return null; } DEHome var7 = (DEHome)var4.next(); var6 = var7.getVillageDoorAt(par1, par2, par3); } while (var6 == null); return var6; } var5 = (DEHomeGateInfo)var4.next(); } while (var5.posX != par1 || var5.posZ != par3 || Math.abs(var5.posY - par2) > 1); return var5; } private void addDoorToNewListIfAppropriate(int par1, int par2, int par3) { int var4 = BlockDirectional.getDirection(this.worldObj.getBlockMetadata(par1, par2, par3)); //int var4 = this.worldObj.getBlockMetadata(par1, par2, par3) | 3; int var5; int var6; if (var4 == 0 && var4 == 2) { var5 = 0; for (var6 = -5; var6 < 0; ++var6) { if (this.worldObj.canBlockSeeTheSky(par1, par2, par3 + var6)) { --var5; } } for (var6 = 1; var6 <= 5; ++var6) { if (this.worldObj.canBlockSeeTheSky(par1, par2, par3 + var6)) { ++var5; } } if (var5 != 0) { this.newDoors.add(new DEHomeGateInfo(par1, par2, par3, 0, var5 > 0 ? -2 : 2, this.tickCounter)); } } else { var5 = 0; for (var6 = -5; var6 < 0; ++var6) { if (this.worldObj.canBlockSeeTheSky(par1 + var6, par2, par3)) { --var5; } } for (var6 = 1; var6 <= 5; ++var6) { if (this.worldObj.canBlockSeeTheSky(par1 + var6, par2, par3)) { ++var5; } } if (var5 != 0) { this.newDoors.add(new DEHomeGateInfo(par1, par2, par3, var5 > 0 ? -2 : 2, 0, this.tickCounter)); } } } private boolean isVillagerPositionPresent(int par1, int par2, int par3) { Iterator var4 = this.villagerPositionsList.iterator(); ChunkCoordinates var5; do { if (!var4.hasNext()) { return false; } var5 = (ChunkCoordinates)var4.next(); } while (var5.posX != par1 || var5.posY != par2 || var5.posZ != par3); return true; } private boolean isFanceGateAt(int par1, int par2, int par3) { int var4 = this.worldObj.getBlockId(par1, par2, par3); boolean var5 = this.worldObj.getBlockId(par1, par2 - 1, par3) == Block.glowStone.blockID; return var4 == Block.fenceGate.blockID && var5; } @Override public void readFromNBT(NBTTagCompound par1NBTTagCompound) { this.tickCounter = par1NBTTagCompound.getInteger("Tick"); NBTTagList var2 = par1NBTTagCompound.getTagList("Villages"); for (int var3 = 0; var3 < var2.tagCount(); ++var3) { NBTTagCompound var4 = (NBTTagCompound)var2.tagAt(var3); Village var5 = new Village(); var5.readVillageDataFromNBT(var4); this.villageList.add(var5); } } @Override public void writeToNBT(NBTTagCompound par1NBTTagCompound) { par1NBTTagCompound.setInteger("Tick", this.tickCounter); NBTTagList var2 = new NBTTagList("Villages"); Iterator var3 = this.villageList.iterator(); while (var3.hasNext()) { Village var4 = (Village)var3.next(); NBTTagCompound var5 = new NBTTagCompound("Village"); var4.writeVillageDataToNBT(var5); var2.appendTag(var5); } par1NBTTagCompound.setTag("Villages", var2); } }
/******************************************************************************* * Copyright (c) 2017 Pablo Pavon Marino and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the 2-clause BSD License * which accompanies this distribution, and is available at * https://opensource.org/licenses/BSD-2-Clause * * Contributors: * Pablo Pavon Marino and others - initial API and implementation *******************************************************************************/ package com.net2plan.documentation; import com.net2plan.interfaces.networkDesign.IAlgorithm; import com.net2plan.interfaces.networkDesign.IReport; import com.net2plan.interfaces.simulation.IEventGenerator; import com.net2plan.interfaces.simulation.IEventProcessor; import com.net2plan.utils.StringUtils; import com.net2plan.utils.Triple; import com.sun.javadoc.Tag; import com.sun.tools.doclets.Taglet; import java.io.File; import java.util.List; import java.util.Map; // Taglet API // Doclet API // Used in register(Map) @SuppressWarnings("unchecked") public class Taglet_InputParameters implements Taglet { private static final String NAME = "net2plan.inputParameters"; private static final String HEADER = "Input parameters:"; /** * Return the name of this custom tag. */ public String getName() { return NAME; } /** * Will return true since <code>@todo</code> * can be used in field documentation. * @return true since <code>@todo</code> * can be used in field documentation and false * otherwise. */ public boolean inField() { return true; } /** * Will return true since <code>@todo</code> * can be used in constructor documentation. * @return true since <code>@todo</code> * can be used in constructor documentation and false * otherwise. */ public boolean inConstructor() { return true; } /** * Will return true since <code>@todo</code> * can be used in method documentation. * @return true since <code>@todo</code> * can be used in method documentation and false * otherwise. */ public boolean inMethod() { return true; } /** * Will return true since <code>@todo</code> * can be used in method documentation. * @return true since <code>@todo</code> * can be used in overview documentation and false * otherwise. */ public boolean inOverview() { return true; } /** * Will return true since <code>@todo</code> * can be used in package documentation. * @return true since <code>@todo</code> * can be used in package documentation and false * otherwise. */ public boolean inPackage() { return true; } /** * Will return true since <code>@todo</code> * can be used in type documentation (classes or interfaces). * @return true since <code>@todo</code> * can be used in type documentation and false * otherwise. */ public boolean inType() { return true; } /** * Will return false since <code>@todo</code> * is not an inline tag. * @return false since <code>@todo</code> * is not an inline tag. */ public boolean isInlineTag() { return false; } /** * Register this Taglet. * @param tagletMap the map to register this tag to. */ public static void register(Map tagletMap) { Taglet_InputParameters tag = new Taglet_InputParameters(); Taglet t = (Taglet) tagletMap.get(tag.getName()); if (t != null) { tagletMap.remove(tag.getName()); } tagletMap.put(tag.getName(), tag); } /** * Given the <code>Tag</code> representation of this custom * tag, return its string representation. * @param tag the <code>Tag</code> representation of this custom tag. */ public String toString(Tag tag) { return toString (new Tag [] {tag}); } /** * Given an array of <code>Tag</code>s representing this custom * tag, return its string representation. * @param tags the array of <code>Tag</code>s representing of this custom tag. */ public String toString(Tag[] tags) { if (tags.length == 0) return null; String result = "\n<DT><B>" + HEADER + "</B></DT>"; result += "<div class=\"block\"><table cellpadding=2 cellspacing=0><tr><td>"; for (int i = 0; i < tags.length; i++) { if (i > 0) result += "<p></p>"; Object algorithm = getAlgorithmAssociatedToTag (tags[i]); if (algorithm == null) continue; if (algorithm instanceof IAlgorithm) result += printInformation(((IAlgorithm) algorithm).getParameters()); else if (algorithm instanceof IReport) result += printInformation(((IReport) algorithm).getParameters()); else if (algorithm instanceof IEventGenerator) result += printInformation(((IEventGenerator) algorithm).getParameters()); else if (algorithm instanceof IEventProcessor) result += printInformation(((IEventProcessor) algorithm).getParameters()); else throw new RuntimeException ("Bad: " + algorithm); } return result + "</td></tr></table></div>\n"; } private Object getAlgorithmAssociatedToTag (Tag tag) { File javaFileObject = tag.holder ().position ().file(); String theClassName = ""; while (!javaFileObject.getName ().equals("net2plan")) { theClassName = javaFileObject.getName () + "." + theClassName; if (javaFileObject.getParentFile() == null) break; else javaFileObject = javaFileObject.getParentFile(); } theClassName = "com.net2plan." + theClassName; theClassName = theClassName.substring(0 , theClassName.length ()-6); //without .java Object alg = null; try { Class algorithmClass = Taglet_Description.class.getClassLoader().loadClass(theClassName); if (IAlgorithm.class.isAssignableFrom(algorithmClass)) return (IAlgorithm) algorithmClass.getConstructor().newInstance(); if (IReport.class.isAssignableFrom(algorithmClass)) return (IReport)algorithmClass.getConstructor().newInstance(); if (IEventGenerator.class.isAssignableFrom(algorithmClass)) return (IEventGenerator)algorithmClass.getConstructor().newInstance(); if (IEventProcessor.class.isAssignableFrom(algorithmClass)) return (IEventProcessor)algorithmClass.getConstructor().newInstance(); return null; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException ("Unexpected exception trying to load class of '" + theClassName + "'"); } } private static String printInformation (List<Triple<String, String, String>> parameters) { StringBuilder st = new StringBuilder(); final String NEWLINE = System.lineSeparator(); st.append("<ul>" + NEWLINE); for (Triple<String, String, String> p : parameters) { final String name = p.getFirst().trim (); final String defaultString = p.getSecond ().trim (); final String description = p.getThird().trim (); st.append("<li>"); st.append("<code>" + name + "</code>: "); if (defaultString.startsWith("#boolean#")) { st.append ("<i>Boolean type (default: " + defaultString.substring ("#boolean#".length()) + ").</i> "); } else if (defaultString.startsWith("#select#")) { st.append ("<i>Value to select within {"); for (String value : StringUtils.split(defaultString.substring ("#select#".length()))) st.append (value + ", "); st.setLength(st.length() - 2); // deletes the last space and comma st.append ("}</i>"); } else { st.append ("<i>Default: " + defaultString + "</i>"); } st.append (" " + description); st.append("</li>" + NEWLINE); } st.append("</ul>" + NEWLINE); return st.toString(); } }
package com.ctrip.hermes.portal.service.monitor; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.fluent.Request; import org.apache.http.util.EntityUtils; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unidal.dal.jdbc.DalException; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import org.unidal.tuple.Pair; import com.alibaba.fastjson.JSON; import com.ctrip.hermes.core.env.ClientEnvironment; import com.ctrip.hermes.core.utils.HermesThreadFactory; import com.ctrip.hermes.meta.entity.ConsumerGroup; import com.ctrip.hermes.meta.entity.Endpoint; import com.ctrip.hermes.meta.entity.Meta; import com.ctrip.hermes.meta.entity.Partition; import com.ctrip.hermes.meta.entity.Storage; import com.ctrip.hermes.meta.entity.Topic; import com.ctrip.hermes.metaservice.service.PortalMetaService; import com.ctrip.hermes.portal.config.PortalConstants; import com.ctrip.hermes.portal.dal.HermesPortalDao; import com.ctrip.hermes.portal.resource.view.BrokerQPSBriefView; import com.ctrip.hermes.portal.resource.view.BrokerQPSDetailView; import com.ctrip.hermes.portal.resource.view.TopicDelayDetailView; import com.ctrip.hermes.portal.service.elastic.ElasticClient; @Named(type = MonitorService.class) public class DefaultMonitorService implements MonitorService, Initializable { private static final Logger log = LoggerFactory.getLogger(DefaultMonitorService.class); @Inject private HermesPortalDao m_dao; @Inject private PortalMetaService m_metaService; @Inject private ElasticClient m_elasticClient; @Inject private ClientEnvironment m_env; private List<String> m_latestBroker = new ArrayList<String>(); private Set<String> m_latestClients = new HashSet<String>(); private List<TopicDelayDetailView> m_topDelays = new ArrayList<TopicDelayDetailView>(); // key: topic & groupId, value.key: partitionId, value.value: latest produced date & latest consumed date private Map<Pair<String, Integer>, Map<Integer, Pair<Date, Date>>> m_delays = new HashMap<>(); // key: topic, value: latest produced date private Map<String, Date> m_latestProduced = new HashMap<>(); // key: topic, value: ips private Map<String, Set<String>> m_topic2producers = new HashMap<>(); // key: topic, vlaue.key: consumerName, value.value: ips> private Map<String, Map<String, Set<String>>> m_topic2consumers = new HashMap<>(); // key: producer ip, value: topics private Map<String, Set<String>> m_producer2topics = new HashMap<>(); // key: consumer ip, value.key: consumerName, value.value: topics private Map<String, Map<String, Set<String>>> m_consumer2topics = new HashMap<>(); @Override public Date getLatestProduced(String topic) { Date date = m_latestProduced.get(topic); return date == null ? new Date(0) : date; } @Override public Map<String, Set<String>> getTopic2ProducerIPs() { return m_topic2producers; } @Override public Map<String, Map<String, Set<String>>> getTopic2ConsumerIPs() { return m_topic2consumers; } @Override public Map<String, Map<String, Set<String>>> getConsumerIP2Topics() { return m_consumer2topics; } @Override public Map<String, Set<String>> getProducerIP2Topics() { return m_producer2topics; } @Override public List<String> getLatestBrokers() { return m_latestBroker; } private Meta loadMeta() { try { String url = String.format("http://%s:%s/%s", m_env.getMetaServerDomainName(), m_env.getGlobalConfig() .getProperty("meta.port", "1248").trim(), "/meta"); HttpResponse response = Request.Get(url).execute().returnResponse(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { String responseContent = EntityUtils.toString(response.getEntity()); return JSON.parseObject(responseContent, Meta.class); } log.warn("Loading meta from meta-servers, status code is {}", statusCode); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Load meta from meta-servers faied.", e); } } return m_metaService.getMeta(); } private void updateLatestBroker() { List<String> list = new ArrayList<String>(); Meta meta = loadMeta(); if (meta != null) { for (Entry<String, Endpoint> entry : meta.getEndpoints().entrySet()) { if (Endpoint.BROKER.equals(entry.getValue().getType())) { String host = entry.getValue().getHost(); host = host.equals("localhost") || host.equals("127.0.0.1") ? PortalConstants.LOCALHOST : host; list.add(host); } } } else { log.warn("Can not load meta from either meta-servers or db."); } m_latestBroker = list; } @Override public Pair<Date, Date> getDelay(String topic, int groupId) { Map<Integer, Pair<Date, Date>> delayDetail = getDelayDetails(topic, groupId); if (delayDetail != null) { Date latestProduced = new Date(0); Date latestConsumed = new Date(0); for (Entry<Integer, Pair<Date, Date>> entry : delayDetail.entrySet()) { if (entry.getValue().getKey().after(latestProduced)) { latestProduced = entry.getValue().getKey(); } if (entry.getValue().getValue().after(latestConsumed)) { latestConsumed = entry.getValue().getValue(); } } return new Pair<Date, Date>(latestProduced, latestConsumed); } log.warn("Delay information of {}:{} not found.", topic, groupId); return null; } // Map<Partition-ID, Pair<Latest-produced, Latest-consumed>> @Override public Map<Integer, Pair<Date, Date>> getDelayDetails(String topic, int groupId) { Map<Integer, Pair<Date, Date>> m = m_delays.get(new Pair<String, Integer>(topic, groupId)); return m == null ? new HashMap<Integer, Pair<Date, Date>>() : m; } private void updateDelayDetails() { Map<Pair<String, Integer>, Map<Integer, Pair<Date, Date>>> m = new HashMap<>(); for (Entry<String, Topic> entry : m_metaService.getTopics().entrySet()) { Topic t = entry.getValue(); if (t.getStorageType().equals(Storage.MYSQL)) { for (Partition p : t.getPartitions()) { for (ConsumerGroup c : t.getConsumerGroups()) { Pair<Date, Date> delay = null; try { delay = m_dao.getDelayTime(t.getName(), p.getId(), c.getId()); } catch (DalException e) { log.warn("Get delay of {}:{}:{} failed.", t.getName(), p.getId(), PortalConstants.PRIORITY_TRUE, e); continue; } Pair<String, Integer> k = new Pair<String, Integer>(t.getName(), c.getId()); if (!m.containsKey(k)) { m.put(k, new HashMap<Integer, Pair<Date, Date>>()); } m.get(k).put(p.getId(), delay); } } } } m_delays = m; } private void updateLatestProduced() { Map<String, Date> m = new HashMap<String, Date>(); for (Entry<String, Topic> entry : m_metaService.getTopics().entrySet()) { Topic topic = entry.getValue(); if (topic.getStorageType().equals(Storage.MYSQL)) { String topicName = topic.getName(); Date current = m_latestProduced.get(topicName) == null ? new Date(0) : m_latestProduced.get(topicName); Date latest = new Date(current.getTime()); for (Partition partition : m_metaService.findPartitionsByTopic(topicName)) { try { latest = m_dao.getLatestProduced(topicName, partition.getId()); } catch (DalException e) { log.warn("Find latest produced failed. {}:{}", topicName, partition.getId()); continue; } current = latest.after(current) ? latest : current; } m.put(topicName, current); } } m_latestProduced = m; } private void updateProducerTopicRelationship() { Map<String, Set<String>> topic2producers = new HashMap<String, Set<String>>(); for (String topic : m_metaService.getTopics().keySet()) { topic2producers.put(topic, new HashSet<String>(m_elasticClient.getLastWeekProducers(topic))); } m_topic2producers = topic2producers; Map<String, Set<String>> producer2topics = new HashMap<String, Set<String>>(); for (Entry<String, Set<String>> entry : topic2producers.entrySet()) { String topicName = entry.getKey(); for (String ip : entry.getValue()) { Set<String> topics = producer2topics.get(ip); if (topics == null) { producer2topics.put(ip, topics = new HashSet<String>()); } topics.add(topicName); } } m_producer2topics = producer2topics; } private void updateConsumerTopicRelationship() { Map<String, Map<String, Set<String>>> topic2consumers = new HashMap<>(); for (Entry<String, Topic> entry : m_metaService.getTopics().entrySet()) { String topic = entry.getKey(); for (ConsumerGroup c : entry.getValue().getConsumerGroups()) { String consumer = c.getName(); if (!topic2consumers.containsKey(topic)) { topic2consumers.put(topic, new HashMap<String, Set<String>>()); } HashSet<String> set = new HashSet<String>(m_elasticClient.getLastWeekConsumers(topic, consumer)); topic2consumers.get(topic).put(consumer, set); } } m_topic2consumers = topic2consumers; Map<String, Map<String, Set<String>>> consumer2topics = new HashMap<String, Map<String, Set<String>>>(); for (Entry<String, Map<String, Set<String>>> entry : topic2consumers.entrySet()) { String topicName = entry.getKey(); for (Entry<String, Set<String>> ips : entry.getValue().entrySet()) { String groupName = ips.getKey(); for (String ip : ips.getValue()) { Map<String, Set<String>> topics = consumer2topics.get(ip); if (topics == null) { consumer2topics.put(ip, topics = new HashMap<String, Set<String>>()); } Set<String> set = topics.get(groupName); if (set == null) { topics.put(groupName, set = new HashSet<String>()); } set.add(topicName); } } } m_consumer2topics = consumer2topics; } private void updateTopDelays() { Map<Integer, String> m = getConsumerNameMap(); Map<String, TopicDelayDetailView> delayMap = new HashMap<String, TopicDelayDetailView>(); for (Entry<Pair<String, Integer>, Map<Integer, Pair<Date, Date>>> entry : m_delays.entrySet()) { String topic = entry.getKey().getKey(); String consumer = m.get(entry.getKey().getValue()); TopicDelayDetailView view = delayMap.get(topic); if (view == null) { delayMap.put(topic, view = new TopicDelayDetailView(topic)); } int sum = 0; for (Entry<Integer, Pair<Date, Date>> pEntry : entry.getValue().entrySet()) { int partitionId = pEntry.getKey(); int delayInSeconds = (int) ((pEntry.getValue().getKey().getTime() - pEntry.getValue().getValue().getTime()) / 1000L); view.addDelay(consumer, partitionId, delayInSeconds); sum += delayInSeconds; } view.setAverageDelay(view.getDetails().size() > 0 ? sum / view.getDetails().size() : 0); } List<TopicDelayDetailView> list = new ArrayList<TopicDelayDetailView>(delayMap.values()); Collections.sort(list, new Comparator<TopicDelayDetailView>() { @Override public int compare(TopicDelayDetailView o1, TopicDelayDetailView o2) { return o2.getAverageDelay() - o1.getAverageDelay(); } }); m_topDelays = list; } private Map<Integer, String> getConsumerNameMap() { Map<Integer, String> map = new HashMap<Integer, String>(); for (Entry<String, Topic> entry : m_metaService.getTopics().entrySet()) { for (ConsumerGroup consumerGroup : entry.getValue().getConsumerGroups()) { map.put(consumerGroup.getId(), consumerGroup.getName()); } } return map; } private void updateLatestClients() { Set<String> set = new HashSet<String>(m_consumer2topics.keySet()); set.addAll(m_producer2topics.keySet()); m_latestClients = set; } @Override public void initialize() throws InitializationException { updateLatestBroker(); Executors.newSingleThreadScheduledExecutor(HermesThreadFactory.create("MONITOR_MYSQL_UPDATE_TASK", true)) .scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { updateDelayDetails(); updateTopDelays(); updateLatestProduced(); updateLatestBroker(); } catch (Throwable e) { log.error("Update mysql monitor information failed.", e); } } }, 0, 1, TimeUnit.MINUTES); Executors.newSingleThreadScheduledExecutor(HermesThreadFactory.create("MONITOR_ELASTIC_UPDATE_TASK", true)) .scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { updateProducerTopicRelationship(); updateConsumerTopicRelationship(); updateLatestClients(); } catch (Throwable e) { log.error("Update elastic monitor information failed.", e); } } }, 0, 30, TimeUnit.MINUTES); } @Override public List<String> getRelatedClients(String part) { List<String> list = new ArrayList<String>(); for (String client : m_latestClients) { if (client.contains(part)) { list.add(client); } } Collections.sort(list); return list; } @Override public List<TopicDelayDetailView> getTopDelays(int top) { top = top > m_topDelays.size() ? m_topDelays.size() : top; return m_topDelays.subList(0, top > 0 ? top : 0); } @Override public List<Entry<String, Date>> getTopOutdateTopic(int top) { List<Entry<String, Date>> list = new ArrayList<Entry<String, Date>>(m_latestProduced.entrySet()); Collections.sort(list, new Comparator<Entry<String, Date>>() { @Override public int compare(Entry<String, Date> o1, Entry<String, Date> o2) { return o1.getValue().compareTo(o2.getValue()); } }); top = top > list.size() ? list.size() : top; return list.subList(0, top > 0 ? top : 0); } private Map<String, Integer> normalizeBrokerQPSMap(Map<String, Integer> map) { for (String broker : m_latestBroker) { if (!map.containsKey(broker)) { map.put(broker, 0); } } return map; } @Override public List<BrokerQPSBriefView> getBrokerReceivedQPS() { return BrokerQPSBriefView.convertFromMap(normalizeBrokerQPSMap(m_elasticClient.getBrokerReceived())); } @Override public List<BrokerQPSBriefView> getBrokerDeliveredQPS() { return BrokerQPSBriefView.convertFromMap(normalizeBrokerQPSMap(m_elasticClient.getBrokerDelivered())); } @Override public BrokerQPSDetailView getBrokerReceivedDetailQPS(String brokerIp) { return new BrokerQPSDetailView(brokerIp, m_elasticClient.getBrokerTopicReceived(brokerIp, 50)); } @Override public BrokerQPSDetailView getBrokerDeliveredDetailQPS(String brokerIp) { return new BrokerQPSDetailView(brokerIp, m_elasticClient.getBrokerTopicDelivered(brokerIp, 50)); } }
/* * Copyright 2008 The Closure Compiler 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 com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.google.javascript.jscomp.CodingConvention.SubclassRelationship; import com.google.javascript.jscomp.DefinitionsRemover.Definition; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Garbage collection for variable and function definitions. Basically performs * a mark-and-sweep type algorithm over the JavaScript parse tree. * * For each scope: * (1) Scan the variable/function declarations at that scope. * (2) Traverse the scope for references, marking all referenced variables. * Unlike other compiler passes, this is a pre-order traversal, not a * post-order traversal. * (3) If the traversal encounters an assign without other side-effects, * create a continuation. Continue the continuation iff the assigned * variable is referenced. * (4) When the traversal completes, remove all unreferenced variables. * * If it makes it easier, you can think of the continuations of the traversal * as a reference graph. Each continuation represents a set of edges, where the * source node is a known variable, and the destination nodes are lazily * evaluated when the continuation is executed. * * This algorithm is similar to the algorithm used by {@code SmartNameRemoval}. * {@code SmartNameRemoval} maintains an explicit graph of dependencies * between global symbols. However, {@code SmartNameRemoval} cannot handle * non-trivial edges in the reference graph ("A is referenced iff both B and C * are referenced"), or local variables. {@code SmartNameRemoval} is also * substantially more complicated because it tries to handle namespaces * (which is largely unnecessary in the presence of {@code CollapseProperties}. * * This pass also uses a more complex analysis of assignments, where * an assignment to a variable or a property of that variable does not * necessarily count as a reference to that variable, unless we can prove * that it modifies external state. This is similar to * {@code FlowSensitiveInlineVariables}, except that it works for variables * used across scopes. * * @author nicksantos@google.com (Nick Santos) */ class RemoveUnusedVars implements CompilerPass, OptimizeCalls.CallGraphCompilerPass { private final AbstractCompiler compiler; private final CodingConvention codingConvention; private final boolean removeGlobals; private boolean preserveFunctionExpressionNames; /** * Keep track of variables that we've referenced. */ private final Set<Var> referenced = new HashSet<>(); /** * Keep track of variables that might be unreferenced. */ private final List<Var> maybeUnreferenced = new ArrayList<>(); /** * Keep track of scopes that we've traversed. */ private final List<Scope> allFunctionScopes = new ArrayList<>(); /** * Keep track of assigns to variables that we haven't referenced. */ private final Multimap<Var, Assign> assignsByVar = ArrayListMultimap.create(); /** * The assigns, indexed by the NAME node that they assign to. */ private final Map<Node, Assign> assignsByNode = new HashMap<>(); /** * Subclass name -> class-defining call EXPR node. (like inherits) */ private final Multimap<Var, Node> classDefiningCalls = ArrayListMultimap.create(); /** * Keep track of continuations that are finished iff the variable they're * indexed by is referenced. */ private final Multimap<Var, Continuation> continuations = ArrayListMultimap.create(); private boolean modifyCallSites; private CallSiteOptimizer callSiteOptimizer; RemoveUnusedVars( AbstractCompiler compiler, boolean removeGlobals, boolean preserveFunctionExpressionNames, boolean modifyCallSites) { this.compiler = compiler; this.codingConvention = compiler.getCodingConvention(); this.removeGlobals = removeGlobals; this.preserveFunctionExpressionNames = preserveFunctionExpressionNames; this.modifyCallSites = modifyCallSites; } /** * Traverses the root, removing all unused variables. Multiple traversals * may occur to ensure all unused variables are removed. */ @Override public void process(Node externs, Node root) { Preconditions.checkState(compiler.getLifeCycleStage().isNormalized()); boolean shouldResetModifyCallSites = false; if (this.modifyCallSites) { // When RemoveUnusedVars is run after OptimizeCalls, this.modifyCallSites // is true. But if OptimizeCalls stops making changes, PhaseOptimizer // stops running it, so we come to RemoveUnusedVars and the defFinder is // null. In this case, we temporarily set this.modifyCallSites to false // for this run, and then reset it back to true at the end, for // subsequent runs. if (compiler.getDefinitionFinder() == null) { this.modifyCallSites = false; shouldResetModifyCallSites = true; } } process(externs, root, compiler.getDefinitionFinder()); // When doing OptimizeCalls, RemoveUnusedVars is the last pass in the // sequence, so the def finder must not be used by any subsequent passes. compiler.setDefinitionFinder(null); if (shouldResetModifyCallSites) { this.modifyCallSites = true; } } @Override public void process( Node externs, Node root, DefinitionUseSiteFinder defFinder) { if (modifyCallSites) { Preconditions.checkNotNull(defFinder); callSiteOptimizer = new CallSiteOptimizer(compiler, defFinder); } traverseAndRemoveUnusedReferences(root); if (callSiteOptimizer != null) { callSiteOptimizer.applyChanges(); } } /** * Traverses a node recursively. Call this once per pass. */ private void traverseAndRemoveUnusedReferences(Node root) { Scope scope = SyntacticScopeCreator.makeUntyped(compiler).createScope(root, null); traverseNode(root, null, scope); if (removeGlobals) { collectMaybeUnreferencedVars(scope); } interpretAssigns(); removeUnreferencedVars(); for (Scope fnScope : allFunctionScopes) { removeUnreferencedFunctionArgs(fnScope); } } /** * Traverses everything in the current scope and marks variables that * are referenced. * * During traversal, we identify subtrees that will only be * referenced if their enclosing variables are referenced. Instead of * traversing those subtrees, we create a continuation for them, * and traverse them lazily. */ private void traverseNode(Node n, Node parent, Scope scope) { Token type = n.getToken(); Var var = null; switch (type) { case FUNCTION: // If this function is a removable var, then create a continuation // for it instead of traversing immediately. if (NodeUtil.isFunctionDeclaration(n)) { var = scope.getVar(n.getFirstChild().getString()); } if (var != null && isRemovableVar(var)) { continuations.put(var, new Continuation(n, scope)); } else { traverseFunction(n, scope); } return; case ASSIGN: Assign maybeAssign = Assign.maybeCreateAssign(n); if (maybeAssign != null) { // Put this in the assign map. It might count as a reference, // but we won't know that until we have an index of all assigns. var = scope.getVar(maybeAssign.nameNode.getString()); if (var != null) { assignsByVar.put(var, maybeAssign); assignsByNode.put(maybeAssign.nameNode, maybeAssign); if (isRemovableVar(var) && !maybeAssign.mayHaveSecondarySideEffects) { // If the var is unreferenced and performing this assign has // no secondary side effects, then we can create a continuation // for it instead of traversing immediately. continuations.put(var, new Continuation(n, scope)); return; } } } break; case CALL: Var modifiedVar = null; // Look for calls to inheritance-defining calls (such as goog.inherits). SubclassRelationship subclassRelationship = codingConvention.getClassesDefinedByCall(n); if (subclassRelationship != null) { modifiedVar = scope.getVar(subclassRelationship.subclassName); } else { // Look for calls to addSingletonGetter calls. String className = codingConvention.getSingletonGetterClassName(n); if (className != null) { modifiedVar = scope.getVar(className); } } // Don't try to track the inheritance calls for non-globals. It would // be more correct to only not track when the subclass does not // reference a constructor, but checking that it is a global is // easier and mostly the same. if (modifiedVar != null && modifiedVar.isGlobal() && !referenced.contains(modifiedVar)) { // Save a reference to the EXPR node. classDefiningCalls.put(modifiedVar, parent); continuations.put(modifiedVar, new Continuation(n, scope)); return; } break; case NAME: var = scope.getVar(n.getString()); if (parent.isVar()) { Node value = n.getFirstChild(); if (value != null && var != null && isRemovableVar(var) && !NodeUtil.mayHaveSideEffects(value, compiler)) { // If the var is unreferenced and creating its value has no side // effects, then we can create a continuation for it instead // of traversing immediately. continuations.put(var, new Continuation(n, scope)); return; } } else { // If arguments is escaped, we just assume the worst and continue // on all the parameters. if ("arguments".equals(n.getString()) && scope.isLocal()) { Node lp = scope.getRootNode().getSecondChild(); for (Node a = lp.getFirstChild(); a != null; a = a.getNext()) { markReferencedVar(scope.getVar(a.getString())); } } // All name references that aren't declarations or assigns // are references to other vars. if (var != null) { // If that var hasn't already been marked referenced, then // start tracking it. If this is an assign, do nothing // for now. if (isRemovableVar(var)) { if (!assignsByNode.containsKey(n)) { markReferencedVar(var); } } else { markReferencedVar(var); } } } break; default: break; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { traverseNode(c, n, scope); } } private boolean isRemovableVar(Var var) { // Global variables are off-limits if the user might be using them. if (!removeGlobals && var.isGlobal()) { return false; } // Referenced variables are off-limits. if (referenced.contains(var)) { return false; } // Exported variables are off-limits. return !codingConvention.isExported(var.getName()); } /** * Traverses a function, which creates a new scope in JavaScript. * * Note that CATCH blocks also create a new scope, but only for the * catch variable. Declarations within the block actually belong to the * enclosing scope. Because we don't remove catch variables, there's * no need to treat CATCH blocks differently like we do functions. */ private void traverseFunction(Node n, Scope parentScope) { Preconditions.checkState(n.getChildCount() == 3, n); Preconditions.checkState(n.isFunction(), n); final Node body = n.getLastChild(); Preconditions.checkState(body.getNext() == null && body.isNormalBlock(), body); Scope fnScope = SyntacticScopeCreator.makeUntyped(compiler).createScope(n, parentScope); traverseNode(body, n, fnScope); collectMaybeUnreferencedVars(fnScope); allFunctionScopes.add(fnScope); } /** * For each variable in this scope that we haven't found a reference * for yet, add it to the list of variables to check later. */ private void collectMaybeUnreferencedVars(Scope scope) { for (Var var : scope.getVarIterable()) { if (isRemovableVar(var)) { maybeUnreferenced.add(var); } } } /** * Removes unreferenced arguments from a function declaration and when * possible the function's callSites. * * @param fnScope The scope inside the function */ private void removeUnreferencedFunctionArgs(Scope fnScope) { // Notice that removing unreferenced function args breaks // Function.prototype.length. In advanced mode, we don't really care // about this: we consider "length" the equivalent of reflecting on // the function's lexical source. // // Rather than create a new option for this, we assume that if the user // is removing globals, then it's OK to remove unused function args. // // See http://blickly.github.io/closure-compiler-issues/#253 if (!removeGlobals) { return; } Node function = fnScope.getRootNode(); Preconditions.checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { // The parameters object literal setters can not be removed. return; } Node argList = NodeUtil.getFunctionParameters(function); boolean modifyCallers = modifyCallSites && callSiteOptimizer.canModifyCallers(function); if (!modifyCallers) { // Strip unreferenced args off the end of the function declaration. Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Var var = fnScope.getVar(lastArg.getString()); if (!referenced.contains(var)) { compiler.reportChangeToEnclosingScope(lastArg); argList.removeChild(lastArg); } else { break; } } } else { callSiteOptimizer.optimize(fnScope, referenced); } } private static class CallSiteOptimizer { private final AbstractCompiler compiler; private final DefinitionUseSiteFinder defFinder; private final List<Node> toRemove = new ArrayList<>(); private final List<Node> toReplaceWithZero = new ArrayList<>(); CallSiteOptimizer( AbstractCompiler compiler, DefinitionUseSiteFinder defFinder) { this.compiler = compiler; this.defFinder = defFinder; } public void optimize(Scope fnScope, Set<Var> referenced) { Node function = fnScope.getRootNode(); Preconditions.checkState(function.isFunction()); Node argList = NodeUtil.getFunctionParameters(function); // In this path we try to modify all the call sites to remove unused // function parameters. boolean changeCallSignature = canChangeSignature(function); markUnreferencedFunctionArgs( fnScope, function, referenced, argList.getFirstChild(), 0, changeCallSignature); } /** * Applies optimizations to all previously marked nodes. */ public void applyChanges() { for (Node n : toRemove) { compiler.reportChangeToEnclosingScope(n); n.getParent().removeChild(n); } for (Node n : toReplaceWithZero) { compiler.reportChangeToEnclosingScope(n); n.replaceWith(IR.number(0).srcref(n)); } } /** * For each unused function parameter, determine if it can be removed * from all the call sites, if so, remove it from the function signature * and the call sites otherwise replace the unused value where possible * with a constant (0). * * @param scope The function scope * @param function The function * @param param The current parameter node in the parameter list. * @param paramIndex The index of the current parameter * @param canChangeSignature Whether function signature can be change. * @return Whether there is a following function parameter. */ private boolean markUnreferencedFunctionArgs( Scope scope, Node function, Set<Var> referenced, Node param, int paramIndex, boolean canChangeSignature) { if (param != null) { // Take care of the following siblings first. boolean hasFollowing = markUnreferencedFunctionArgs( scope, function, referenced, param.getNext(), paramIndex + 1, canChangeSignature); Var var = scope.getVar(param.getString()); if (!referenced.contains(var)) { Preconditions.checkNotNull(var); // Remove call parameter if we can generally change the signature // or if it is the last parameter in the parameter list. boolean modifyAllCallSites = canChangeSignature || !hasFollowing; if (modifyAllCallSites) { modifyAllCallSites = canRemoveArgFromCallSites( function, paramIndex); } tryRemoveArgFromCallSites(function, paramIndex, modifyAllCallSites); // Remove an unused function parameter if all the call sites can // be modified to remove it, or if it is the last parameter. if (modifyAllCallSites || !hasFollowing) { toRemove.add(param); return hasFollowing; } } return true; } else { // Anything past the last formal parameter can be removed from the call // sites. tryRemoveAllFollowingArgs(function, paramIndex - 1); return false; } } /** * Remove all references to a parameter, otherwise simplify the known * references. * @return Whether all the references were removed. */ private boolean canRemoveArgFromCallSites(Node function, int argIndex) { Definition definition = getFunctionDefinition(function); // Check all the call sites. for (UseSite site : defFinder.getUseSites(definition)) { if (isModifiableCallSite(site)) { Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex); // TODO(johnlenz): try to remove parameters with side-effects by // decomposing the call expression. if (arg != null && NodeUtil.mayHaveSideEffects(arg, compiler)) { return false; } } else { return false; } } return true; } /** * Remove all references to a parameter if possible otherwise simplify the * side-effect free parameters. */ private void tryRemoveArgFromCallSites( Node function, int argIndex, boolean canModifyAllSites) { Definition definition = getFunctionDefinition(function); for (UseSite site : defFinder.getUseSites(definition)) { if (isModifiableCallSite(site)) { Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex); if (arg != null) { // Even if we can't change the signature in general we can always // remove an unused value off the end of the parameter list. if (canModifyAllSites || (arg.getNext() == null && !NodeUtil.mayHaveSideEffects(arg, compiler))) { toRemove.add(arg); } else { // replace the node in the arg with 0 if (!NodeUtil.mayHaveSideEffects(arg, compiler) && (!arg.isNumber() || arg.getDouble() != 0)) { toReplaceWithZero.add(arg); } } } } } } /** * Remove all the following parameters without side-effects */ private void tryRemoveAllFollowingArgs(Node function, final int argIndex) { Definition definition = getFunctionDefinition(function); for (UseSite site : defFinder.getUseSites(definition)) { if (!isModifiableCallSite(site)) { continue; } Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex + 1); while (arg != null) { if (!NodeUtil.mayHaveSideEffects(arg)) { toRemove.add(arg); } arg = arg.getNext(); } } } /** * Returns the nth argument node given a usage site for a direct function * call or for a func.call() node. */ private static Node getArgumentForCallOrNewOrDotCall(UseSite site, final int argIndex) { int adjustedArgIndex = argIndex; Node parent = site.node.getParent(); if (NodeUtil.isFunctionObjectCall(parent)) { adjustedArgIndex++; } return NodeUtil.getArgumentForCallOrNew(parent, adjustedArgIndex); } /** * @param function * @return Whether the callers to this function can be modified in any way. */ boolean canModifyCallers(Node function) { if (NodeUtil.isVarArgsFunction(function)) { return false; } DefinitionSite defSite = defFinder.getDefinitionForFunction(function); if (defSite == null) { return false; } Definition definition = defSite.definition; // Be conservative, don't try to optimize any declaration that isn't as // simple function declaration or assignment. if (!NodeUtil.isSimpleFunctionDeclaration(function)) { return false; } return defFinder.canModifyDefinition(definition); } /** * @param site The site to inspect * @return Whether the call site is suitable for modification */ private static boolean isModifiableCallSite(UseSite site) { return DefinitionUseSiteFinder.isCallOrNewSite(site) && !NodeUtil.isFunctionObjectApply(site.node.getParent()); } /** * @return Whether the definitionSite represents a function whose call * signature can be modified. */ private boolean canChangeSignature(Node function) { Definition definition = getFunctionDefinition(function); CodingConvention convention = compiler.getCodingConvention(); Preconditions.checkState(!definition.isExtern()); Collection<UseSite> useSites = defFinder.getUseSites(definition); for (UseSite site : useSites) { Node parent = site.node.getParent(); // This was a use site removed by something else before we run. // 1. By another pass before us which means the definition graph is // no updated properly. // 2. By the continuations algorithm above. if (parent == null) { continue; // Ignore it. } // Ignore references within goog.inherits calls. if (parent.isCall() && convention.getClassesDefinedByCall(parent) != null) { continue; } // Accessing the property directly prevents rewrite. if (!DefinitionUseSiteFinder.isCallOrNewSite(site)) { if (!(parent.isGetProp() && NodeUtil.isFunctionObjectCall(parent.getParent()))) { return false; } } if (NodeUtil.isFunctionObjectApply(parent)) { return false; } // TODO(johnlenz): support specialization // Multiple definitions prevent rewrite. // Attempt to validate the state of the simple definition finder. Node nameNode = site.node; Collection<Definition> singleSiteDefinitions = defFinder.getDefinitionsReferencedAt(nameNode); Preconditions.checkState(singleSiteDefinitions.size() == 1); Preconditions.checkState(singleSiteDefinitions.contains(definition)); } return true; } /** * @param function * @return the Definition object for the function. */ private Definition getFunctionDefinition(Node function) { DefinitionSite definitionSite = defFinder.getDefinitionForFunction( function); Preconditions.checkNotNull(definitionSite); Definition definition = definitionSite.definition; Preconditions.checkState(!definitionSite.inExterns); Preconditions.checkState(definition.getRValue() == function); return definition; } } /** * Look at all the property assigns to all variables. * These may or may not count as references. For example, * * <code> * var x = {}; * x.foo = 3; // not a reference. * var y = foo(); * y.foo = 3; // is a reference. * </code> * * Interpreting assignments could mark a variable as referenced that * wasn't referenced before, in order to keep it alive. Because we find * references by lazily traversing subtrees, marking a variable as * referenced could trigger new traversals of new subtrees, which could * find new references. * * Therefore, this interpretation needs to be run to a fixed point. */ private void interpretAssigns() { boolean changes = false; do { changes = false; // We can't use traditional iterators and iterables for this list, // because our lazily-evaluated continuations will modify it while // we traverse it. for (int current = 0; current < maybeUnreferenced.size(); current++) { Var var = maybeUnreferenced.get(current); if (referenced.contains(var)) { maybeUnreferenced.remove(current); current--; } else { boolean assignedToUnknownValue = false; boolean hasPropertyAssign = false; if (var.getParentNode().isVar() && !var.getParentNode().getParent().isForIn()) { Node value = var.getInitialValue(); assignedToUnknownValue = value != null && !NodeUtil.isLiteralValue(value, true); } else { // This was initialized to a function arg or a catch param // or a for...in variable. assignedToUnknownValue = true; } boolean maybeEscaped = false; for (Assign assign : assignsByVar.get(var)) { if (assign.isPropertyAssign) { hasPropertyAssign = true; } else if (!NodeUtil.isLiteralValue( assign.assignNode.getLastChild(), true)) { assignedToUnknownValue = true; } if (assign.maybeAliased) { maybeEscaped = true; } } if ((assignedToUnknownValue || maybeEscaped) && hasPropertyAssign) { changes = markReferencedVar(var) || changes; maybeUnreferenced.remove(current); current--; } } } } while (changes); } /** * Remove all assigns to a var. */ private void removeAllAssigns(Var var) { for (Assign assign : assignsByVar.get(var)) { compiler.reportChangeToEnclosingScope(assign.assignNode); assign.remove(); } } /** * Marks a var as referenced, recursing into any values of this var * that we skipped. * @return True if this variable had not been referenced before. */ private boolean markReferencedVar(Var var) { if (referenced.add(var)) { for (Continuation c : continuations.get(var)) { c.apply(); } return true; } return false; } /** * Removes any vars in the scope that were not referenced. Removes any * assignments to those variables as well. */ private void removeUnreferencedVars() { for (Var var : maybeUnreferenced) { // Remove calls to inheritance-defining functions where the unreferenced // class is the subclass. for (Node exprCallNode : classDefiningCalls.get(var)) { compiler.reportChangeToEnclosingScope(exprCallNode); NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode); } // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. removeAllAssigns(var); compiler.addToDebugLog("Unreferenced var: " + var.name); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); Node parent = toRemove.getParent(); Preconditions.checkState( toRemove.isVar() || toRemove.isFunction() || toRemove.isParamList() && parent.isFunction(), "We should only declare vars and functions and function args"); if (toRemove.isParamList() && parent.isFunction()) { // Don't remove function arguments here. That's a special case // that's taken care of in removeUnreferencedFunctionArgs. } else if (NodeUtil.isFunctionExpression(toRemove)) { if (!preserveFunctionExpressionNames) { Node fnNameNode = toRemove.getFirstChild(); compiler.reportChangeToEnclosingScope(fnNameNode); fnNameNode.setString(""); } // Don't remove bleeding functions. } else if (parent.isForIn()) { // foreach iterations have 3 children. Leave them alone. } else if (toRemove.isVar() && nameNode.hasChildren() && NodeUtil.mayHaveSideEffects(nameNode.getFirstChild(), compiler)) { // If this is a single var declaration, we can at least remove the // declaration itself and just leave the value, e.g., // var a = foo(); => foo(); if (toRemove.hasOneChild()) { compiler.reportChangeToEnclosingScope(toRemove); parent.replaceChild(toRemove, IR.exprResult(nameNode.removeFirstChild())); } } else if (toRemove.isVar() && toRemove.hasMoreThanOneChild()) { // For var declarations with multiple names (i.e. var a, b, c), // only remove the unreferenced name compiler.reportChangeToEnclosingScope(toRemove); toRemove.removeChild(nameNode); } else if (parent != null) { compiler.reportChangeToEnclosingScope(toRemove); NodeUtil.removeChild(parent, toRemove); } } } /** * Our progress in a traversal can be expressed completely as the * current node and scope. The continuation lets us save that * information so that we can continue the traversal later. */ private class Continuation { private final Node node; private final Scope scope; Continuation(Node node, Scope scope) { this.node = node; this.scope = scope; } void apply() { if (NodeUtil.isFunctionDeclaration(node)) { traverseFunction(node, scope); } else { for (Node child = node.getFirstChild(); child != null; child = child.getNext()) { traverseNode(child, node, scope); } } } } private static class Assign { final Node assignNode; final Node nameNode; // If false, then this is an assign to the normal variable. Otherwise, // this is an assign to a property of that variable. final boolean isPropertyAssign; // Secondary side effects are any side effects in this assign statement // that aren't caused by the assignment operation itself. For example, // a().b = 3; // a = b(); // var foo = (a = b); // In the first two cases, the sides of the assignment have side-effects. // In the last one, the result of the assignment is used, so we // are conservative and assume that it may be used in a side-effecting // way. final boolean mayHaveSecondarySideEffects; // If true, the value may have escaped and any modification is a use. final boolean maybeAliased; Assign(Node assignNode, Node nameNode, boolean isPropertyAssign) { Preconditions.checkState(NodeUtil.isAssignmentOp(assignNode)); this.assignNode = assignNode; this.nameNode = nameNode; this.isPropertyAssign = isPropertyAssign; this.maybeAliased = NodeUtil.isExpressionResultUsed(assignNode); this.mayHaveSecondarySideEffects = maybeAliased || NodeUtil.mayHaveSideEffects(assignNode.getFirstChild()) || NodeUtil.mayHaveSideEffects(assignNode.getLastChild()); } /** * If this is an assign to a variable or its property, return it. * Otherwise, return null. */ static Assign maybeCreateAssign(Node assignNode) { Preconditions.checkState(NodeUtil.isAssignmentOp(assignNode)); // Skip one level of GETPROPs or GETELEMs. // // Don't skip more than one level, because then we get into // situations where assigns to properties of properties will always // trigger side-effects, and the variable they're on cannot be removed. boolean isPropAssign = false; Node current = assignNode.getFirstChild(); if (NodeUtil.isGet(current)) { current = current.getFirstChild(); isPropAssign = true; if (current.isGetProp() && current.getLastChild().getString().equals("prototype")) { // Prototype properties sets should be considered like normal // property sets. current = current.getFirstChild(); } } if (current.isName()) { return new Assign(assignNode, current, isPropAssign); } return null; } /** * Replace the current assign with its right hand side. */ void remove() { Node parent = assignNode.getParent(); if (mayHaveSecondarySideEffects) { Node replacement = assignNode.getLastChild().detach(); // Aggregate any expressions in GETELEMs. for (Node current = assignNode.getFirstChild(); !current.isName(); current = current.getFirstChild()) { if (current.isGetElem()) { replacement = IR.comma( current.getLastChild().detach(), replacement); replacement.useSourceInfoIfMissingFrom(current); } } parent.replaceChild(assignNode, replacement); } else { Node grandparent = parent.getParent(); if (parent.isExprResult()) { grandparent.removeChild(parent); } else { parent.replaceChild(assignNode, assignNode.getLastChild().detach()); } } } } }
package org.apereo.cas.pm.rest; import org.apereo.cas.audit.spi.config.CasCoreAuditConfiguration; import org.apereo.cas.authentication.CoreAuthenticationTestUtils; import org.apereo.cas.config.CasCoreNotificationsConfiguration; import org.apereo.cas.config.CasCoreUtilConfiguration; import org.apereo.cas.config.pm.RestPasswordManagementConfiguration; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.pm.PasswordChangeRequest; import org.apereo.cas.pm.PasswordHistoryService; import org.apereo.cas.pm.PasswordManagementQuery; import org.apereo.cas.pm.PasswordManagementService; import org.apereo.cas.pm.config.PasswordManagementConfiguration; import org.apereo.cas.util.MockWebServer; import org.apereo.cas.util.crypto.CipherExecutor; import lombok.val; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration; import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.context.annotation.Import; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link RestPasswordManagementServiceTests}. * * @author Misagh Moayyed * @since 5.3.0 */ @Tag("RestfulApi") public class RestPasswordManagementServiceTests { @ImportAutoConfiguration({ MailSenderAutoConfiguration.class, AopAutoConfiguration.class, RefreshAutoConfiguration.class }) @SpringBootConfiguration @Import({ RestPasswordManagementConfiguration.class, PasswordManagementConfiguration.class, RestTemplateAutoConfiguration.class, CasCoreNotificationsConfiguration.class, CasCoreAuditConfiguration.class, CasCoreUtilConfiguration.class }) public static class SharedTestConfiguration { } @Nested @SpringBootTest(classes = SharedTestConfiguration.class) @SuppressWarnings("ClassCanBeStatic") public class UndefinedConfigurationOperations { @Autowired @Qualifier(PasswordManagementService.DEFAULT_BEAN_NAME) private PasswordManagementService passwordChangeService; @Test public void verifyEmailFound() { assertFalse(passwordChangeService.change(CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), new PasswordChangeRequest("casuser", "123456", "123456"))); assertNull(passwordChangeService.findEmail(PasswordManagementQuery.builder().username("casuser").build())); assertNull(passwordChangeService.findUsername(PasswordManagementQuery.builder().username("casuser").build())); assertNull(passwordChangeService.findPhone(PasswordManagementQuery.builder().username("casuser").build())); assertNull(passwordChangeService.getSecurityQuestions(PasswordManagementQuery.builder().username("casuser").build())); } } @Nested @SpringBootTest(classes = SharedTestConfiguration.class, properties = { "cas.authn.pm.rest.endpoint-url-change=http://localhost:9090", "cas.authn.pm.rest.endpoint-url-security-questions=http://localhost:9090", "cas.authn.pm.rest.endpoint-url-email=http://localhost:9091", "cas.authn.pm.rest.endpoint-url-user=http://localhost:9090", "cas.authn.pm.rest.endpoint-url-phone=http://localhost:9092", "cas.authn.pm.rest.endpoint-username=username", "cas.authn.pm.rest.endpoint-password=password" }) @SuppressWarnings("ClassCanBeStatic") public class BasicOperations { @Autowired @Qualifier(PasswordManagementService.DEFAULT_BEAN_NAME) private PasswordManagementService passwordChangeService; @Autowired @Qualifier("passwordManagementCipherExecutor") private CipherExecutor passwordManagementCipherExecutor; @Autowired @Qualifier("passwordHistoryService") private PasswordHistoryService passwordHistoryService; @Test public void verifyEmailFound() { val data = "casuser@example.org"; try (val webServer = new MockWebServer(9091, new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) { webServer.start(); val email = this.passwordChangeService.findEmail(PasswordManagementQuery.builder().username("casuser").build()); webServer.stop(); assertNotNull(email); assertEquals(data, email); } try (val webServer = new MockWebServer(9091, HttpStatus.NO_CONTENT)) { webServer.start(); assertNull(passwordChangeService.findEmail(PasswordManagementQuery.builder().username("casuser").build())); webServer.stop(); } } @Test public void verifyUserFound() { val data = "casuser"; try (val webServer = new MockWebServer(9090, new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) { webServer.start(); val username = this.passwordChangeService.findUsername(PasswordManagementQuery.builder().email("casuser@example.org").build()); webServer.stop(); assertNotNull(username); assertEquals(data, username); } try (val webServer = new MockWebServer(9090, HttpStatus.NO_CONTENT)) { webServer.start(); assertNull(passwordChangeService.findUsername(PasswordManagementQuery.builder().username("casuser").build())); webServer.stop(); } } @Test public void verifyPhoneFound() { val data = "1234567890"; try (val webServer = new MockWebServer(9092, new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) { webServer.start(); val ph = this.passwordChangeService.findPhone(PasswordManagementQuery.builder().username("casuser").build()); webServer.stop(); assertNotNull(ph); assertEquals(data, ph); } try (val webServer = new MockWebServer(9092, HttpStatus.NO_CONTENT)) { webServer.start(); assertNull(passwordChangeService.findPhone(PasswordManagementQuery.builder().username("casuser").build())); webServer.stop(); } } @Test public void verifySecurityQuestions() { val data = "{\"question1\":\"answer1\"}"; try (val webServer = new MockWebServer(9308, new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) { webServer.start(); val props = new CasConfigurationProperties(); val rest = props.getAuthn().getPm().getRest(); rest.setEndpointUrlChange("http://localhost:9308"); rest.setEndpointUrlSecurityQuestions("http://localhost:9308"); rest.setEndpointUrlEmail("http://localhost:9308"); val passwordService = new RestPasswordManagementService(passwordManagementCipherExecutor, props.getServer().getPrefix(), new RestTemplate(), props.getAuthn().getPm(), passwordHistoryService); val questions = passwordService.getSecurityQuestions(PasswordManagementQuery.builder().username("casuser").build()); assertFalse(questions.isEmpty()); assertTrue(questions.containsKey("question1")); webServer.stop(); } try (val webServer = new MockWebServer(9090, HttpStatus.NO_CONTENT)) { webServer.start(); assertNull(passwordChangeService.getSecurityQuestions(PasswordManagementQuery.builder().username("casuser").build())); webServer.stop(); } } @Test public void verifyUpdateSecurityQuestions() { val query = PasswordManagementQuery.builder().username("casuser").build(); query.securityQuestion("Q1", "A1"); try (val webServer = new MockWebServer(9308, HttpStatus.OK)) { webServer.start(); val props = new CasConfigurationProperties(); val rest = props.getAuthn().getPm().getRest(); rest.setEndpointUrlChange("http://localhost:9308"); rest.setEndpointUrlSecurityQuestions("http://localhost:9308"); rest.setEndpointUrlEmail("http://localhost:9308"); val passwordService = new RestPasswordManagementService( passwordManagementCipherExecutor, props.getServer().getPrefix(), new RestTemplate(), props.getAuthn().getPm(), passwordHistoryService); assertDoesNotThrow(new Executable() { @Override public void execute() throws Throwable { passwordService.updateSecurityQuestions(query); } }); } } @Test public void verifyPasswordChanged() { val data = "true"; try (val webServer = new MockWebServer(9309, new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) { webServer.start(); val props = new CasConfigurationProperties(); val rest = props.getAuthn().getPm().getRest(); rest.setEndpointUrlChange("http://localhost:9309"); rest.setEndpointUrlSecurityQuestions("http://localhost:9309"); rest.setEndpointUrlEmail("http://localhost:9309"); val passwordService = new RestPasswordManagementService(passwordManagementCipherExecutor, props.getServer().getPrefix(), new RestTemplate(), props.getAuthn().getPm(), passwordHistoryService); val result = passwordService.change(CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), new PasswordChangeRequest("casuser", "123456", "123456")); assertTrue(result); webServer.stop(); } try (val webServer = new MockWebServer(9090, HttpStatus.NO_CONTENT)) { webServer.start(); val result = passwordChangeService.change(CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), new PasswordChangeRequest("casuser", "123456", "123456")); assertFalse(result); webServer.stop(); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataproc/v1/jobs.proto package com.google.cloud.dataproc.v1; /** * <pre> * A request to delete a job. * </pre> * * Protobuf type {@code google.cloud.dataproc.v1.DeleteJobRequest} */ public final class DeleteJobRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.DeleteJobRequest) DeleteJobRequestOrBuilder { // Use DeleteJobRequest.newBuilder() to construct. private DeleteJobRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteJobRequest() { projectId_ = ""; region_ = ""; jobId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private DeleteJobRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); projectId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); jobId_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); region_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_DeleteJobRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_DeleteJobRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataproc.v1.DeleteJobRequest.class, com.google.cloud.dataproc.v1.DeleteJobRequest.Builder.class); } public static final int PROJECT_ID_FIELD_NUMBER = 1; private volatile java.lang.Object projectId_; /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public java.lang.String getProjectId() { java.lang.Object ref = projectId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); projectId_ = s; return s; } } /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public com.google.protobuf.ByteString getProjectIdBytes() { java.lang.Object ref = projectId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); projectId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REGION_FIELD_NUMBER = 3; private volatile java.lang.Object region_; /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public java.lang.String getRegion() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } } /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int JOB_ID_FIELD_NUMBER = 2; private volatile java.lang.Object jobId_; /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public java.lang.String getJobId() { java.lang.Object ref = jobId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); jobId_ = s; return s; } } /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public com.google.protobuf.ByteString getJobIdBytes() { java.lang.Object ref = jobId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); jobId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getProjectIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, projectId_); } if (!getJobIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, jobId_); } if (!getRegionBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, region_); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getProjectIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, projectId_); } if (!getJobIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, jobId_); } if (!getRegionBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, region_); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataproc.v1.DeleteJobRequest)) { return super.equals(obj); } com.google.cloud.dataproc.v1.DeleteJobRequest other = (com.google.cloud.dataproc.v1.DeleteJobRequest) obj; boolean result = true; result = result && getProjectId() .equals(other.getProjectId()); result = result && getRegion() .equals(other.getRegion()); result = result && getJobId() .equals(other.getJobId()); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); hash = (37 * hash) + PROJECT_ID_FIELD_NUMBER; hash = (53 * hash) + getProjectId().hashCode(); hash = (37 * hash) + REGION_FIELD_NUMBER; hash = (53 * hash) + getRegion().hashCode(); hash = (37 * hash) + JOB_ID_FIELD_NUMBER; hash = (53 * hash) + getJobId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.DeleteJobRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataproc.v1.DeleteJobRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A request to delete a job. * </pre> * * Protobuf type {@code google.cloud.dataproc.v1.DeleteJobRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.DeleteJobRequest) com.google.cloud.dataproc.v1.DeleteJobRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_DeleteJobRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_DeleteJobRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataproc.v1.DeleteJobRequest.class, com.google.cloud.dataproc.v1.DeleteJobRequest.Builder.class); } // Construct using com.google.cloud.dataproc.v1.DeleteJobRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); projectId_ = ""; region_ = ""; jobId_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_DeleteJobRequest_descriptor; } public com.google.cloud.dataproc.v1.DeleteJobRequest getDefaultInstanceForType() { return com.google.cloud.dataproc.v1.DeleteJobRequest.getDefaultInstance(); } public com.google.cloud.dataproc.v1.DeleteJobRequest build() { com.google.cloud.dataproc.v1.DeleteJobRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.cloud.dataproc.v1.DeleteJobRequest buildPartial() { com.google.cloud.dataproc.v1.DeleteJobRequest result = new com.google.cloud.dataproc.v1.DeleteJobRequest(this); result.projectId_ = projectId_; result.region_ = region_; result.jobId_ = jobId_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dataproc.v1.DeleteJobRequest) { return mergeFrom((com.google.cloud.dataproc.v1.DeleteJobRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataproc.v1.DeleteJobRequest other) { if (other == com.google.cloud.dataproc.v1.DeleteJobRequest.getDefaultInstance()) return this; if (!other.getProjectId().isEmpty()) { projectId_ = other.projectId_; onChanged(); } if (!other.getRegion().isEmpty()) { region_ = other.region_; onChanged(); } if (!other.getJobId().isEmpty()) { jobId_ = other.jobId_; onChanged(); } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dataproc.v1.DeleteJobRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dataproc.v1.DeleteJobRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object projectId_ = ""; /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public java.lang.String getProjectId() { java.lang.Object ref = projectId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); projectId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public com.google.protobuf.ByteString getProjectIdBytes() { java.lang.Object ref = projectId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); projectId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public Builder setProjectId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } projectId_ = value; onChanged(); return this; } /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public Builder clearProjectId() { projectId_ = getDefaultInstance().getProjectId(); onChanged(); return this; } /** * <pre> * [Required] The ID of the Google Cloud Platform project that the job * belongs to. * </pre> * * <code>optional string project_id = 1;</code> */ public Builder setProjectIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); projectId_ = value; onChanged(); return this; } private java.lang.Object region_ = ""; /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public java.lang.String getRegion() { java.lang.Object ref = region_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public Builder setRegion( java.lang.String value) { if (value == null) { throw new NullPointerException(); } region_ = value; onChanged(); return this; } /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public Builder clearRegion() { region_ = getDefaultInstance().getRegion(); onChanged(); return this; } /** * <pre> * [Required] The Cloud Dataproc region in which to handle the request. * </pre> * * <code>optional string region = 3;</code> */ public Builder setRegionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); region_ = value; onChanged(); return this; } private java.lang.Object jobId_ = ""; /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public java.lang.String getJobId() { java.lang.Object ref = jobId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); jobId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public com.google.protobuf.ByteString getJobIdBytes() { java.lang.Object ref = jobId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); jobId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public Builder setJobId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } jobId_ = value; onChanged(); return this; } /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public Builder clearJobId() { jobId_ = getDefaultInstance().getJobId(); onChanged(); return this; } /** * <pre> * [Required] The job ID. * </pre> * * <code>optional string job_id = 2;</code> */ public Builder setJobIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); jobId_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:google.cloud.dataproc.v1.DeleteJobRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.DeleteJobRequest) private static final com.google.cloud.dataproc.v1.DeleteJobRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.DeleteJobRequest(); } public static com.google.cloud.dataproc.v1.DeleteJobRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteJobRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteJobRequest>() { public DeleteJobRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DeleteJobRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DeleteJobRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteJobRequest> getParserForType() { return PARSER; } public com.google.cloud.dataproc.v1.DeleteJobRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver11; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFBadActionErrorMsgVer11 implements OFBadActionErrorMsg { private static final Logger logger = LoggerFactory.getLogger(OFBadActionErrorMsgVer11.class); // version: 1.1 final static byte WIRE_VERSION = 2; final static int MINIMUM_LENGTH = 12; private final static long DEFAULT_XID = 0x0L; private final static OFErrorCauseData DEFAULT_DATA = OFErrorCauseData.NONE; // OF message fields private final long xid; private final OFBadActionCode code; private final OFErrorCauseData data; // // package private constructor - used by readers, builders, and factory OFBadActionErrorMsgVer11(long xid, OFBadActionCode code, OFErrorCauseData data) { if(code == null) { throw new NullPointerException("OFBadActionErrorMsgVer11: property code cannot be null"); } if(data == null) { throw new NullPointerException("OFBadActionErrorMsgVer11: property data cannot be null"); } this.xid = xid; this.code = code; this.data = data; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_11; } @Override public OFType getType() { return OFType.ERROR; } @Override public long getXid() { return xid; } @Override public OFErrorType getErrType() { return OFErrorType.BAD_ACTION; } @Override public OFBadActionCode getCode() { return code; } @Override public OFErrorCauseData getData() { return data; } public OFBadActionErrorMsg.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFBadActionErrorMsg.Builder { final OFBadActionErrorMsgVer11 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean codeSet; private OFBadActionCode code; private boolean dataSet; private OFErrorCauseData data; BuilderWithParent(OFBadActionErrorMsgVer11 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_11; } @Override public OFType getType() { return OFType.ERROR; } @Override public long getXid() { return xid; } @Override public OFBadActionErrorMsg.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFErrorType getErrType() { return OFErrorType.BAD_ACTION; } @Override public OFBadActionCode getCode() { return code; } @Override public OFBadActionErrorMsg.Builder setCode(OFBadActionCode code) { this.code = code; this.codeSet = true; return this; } @Override public OFErrorCauseData getData() { return data; } @Override public OFBadActionErrorMsg.Builder setData(OFErrorCauseData data) { this.data = data; this.dataSet = true; return this; } @Override public OFBadActionErrorMsg build() { long xid = this.xidSet ? this.xid : parentMessage.xid; OFBadActionCode code = this.codeSet ? this.code : parentMessage.code; if(code == null) throw new NullPointerException("Property code must not be null"); OFErrorCauseData data = this.dataSet ? this.data : parentMessage.data; if(data == null) throw new NullPointerException("Property data must not be null"); // return new OFBadActionErrorMsgVer11( xid, code, data ); } } static class Builder implements OFBadActionErrorMsg.Builder { // OF message fields private boolean xidSet; private long xid; private boolean codeSet; private OFBadActionCode code; private boolean dataSet; private OFErrorCauseData data; @Override public OFVersion getVersion() { return OFVersion.OF_11; } @Override public OFType getType() { return OFType.ERROR; } @Override public long getXid() { return xid; } @Override public OFBadActionErrorMsg.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFErrorType getErrType() { return OFErrorType.BAD_ACTION; } @Override public OFBadActionCode getCode() { return code; } @Override public OFBadActionErrorMsg.Builder setCode(OFBadActionCode code) { this.code = code; this.codeSet = true; return this; } @Override public OFErrorCauseData getData() { return data; } @Override public OFBadActionErrorMsg.Builder setData(OFErrorCauseData data) { this.data = data; this.dataSet = true; return this; } // @Override public OFBadActionErrorMsg build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; if(!this.codeSet) throw new IllegalStateException("Property code doesn't have default value -- must be set"); if(code == null) throw new NullPointerException("Property code must not be null"); OFErrorCauseData data = this.dataSet ? this.data : DEFAULT_DATA; if(data == null) throw new NullPointerException("Property data must not be null"); return new OFBadActionErrorMsgVer11( xid, code, data ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFBadActionErrorMsg> { @Override public OFBadActionErrorMsg readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 2 byte version = bb.readByte(); if(version != (byte) 0x2) throw new OFParseError("Wrong version: Expected=OFVersion.OF_11(2), got="+version); // fixed value property type == 1 byte type = bb.readByte(); if(type != (byte) 0x1) throw new OFParseError("Wrong type: Expected=OFType.ERROR(1), got="+type); int length = U16.f(bb.readShort()); if(length < MINIMUM_LENGTH) throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property errType == 2 short errType = bb.readShort(); if(errType != (short) 0x2) throw new OFParseError("Wrong errType: Expected=OFErrorType.BAD_ACTION(2), got="+errType); OFBadActionCode code = OFBadActionCodeSerializerVer11.readFrom(bb); OFErrorCauseData data = OFErrorCauseData.read(bb, length - (bb.readerIndex() - start), OFVersion.OF_11); OFBadActionErrorMsgVer11 badActionErrorMsgVer11 = new OFBadActionErrorMsgVer11( xid, code, data ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", badActionErrorMsgVer11); return badActionErrorMsgVer11; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFBadActionErrorMsgVer11Funnel FUNNEL = new OFBadActionErrorMsgVer11Funnel(); static class OFBadActionErrorMsgVer11Funnel implements Funnel<OFBadActionErrorMsgVer11> { private static final long serialVersionUID = 1L; @Override public void funnel(OFBadActionErrorMsgVer11 message, PrimitiveSink sink) { // fixed value property version = 2 sink.putByte((byte) 0x2); // fixed value property type = 1 sink.putByte((byte) 0x1); // FIXME: skip funnel of length sink.putLong(message.xid); // fixed value property errType = 2 sink.putShort((short) 0x2); OFBadActionCodeSerializerVer11.putTo(message.code, sink); message.data.putTo(sink); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFBadActionErrorMsgVer11> { @Override public void write(ByteBuf bb, OFBadActionErrorMsgVer11 message) { int startIndex = bb.writerIndex(); // fixed value property version = 2 bb.writeByte((byte) 0x2); // fixed value property type = 1 bb.writeByte((byte) 0x1); // length is length of variable message, will be updated at the end int lengthIndex = bb.writerIndex(); bb.writeShort(U16.t(0)); bb.writeInt(U32.t(message.xid)); // fixed value property errType = 2 bb.writeShort((short) 0x2); OFBadActionCodeSerializerVer11.writeTo(bb, message.code); message.data.writeTo(bb); // update length field int length = bb.writerIndex() - startIndex; bb.setShort(lengthIndex, length); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFBadActionErrorMsgVer11("); b.append("xid=").append(xid); b.append(", "); b.append("code=").append(code); b.append(", "); b.append("data=").append(data); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFBadActionErrorMsgVer11 other = (OFBadActionErrorMsgVer11) obj; if( xid != other.xid) return false; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((code == null) ? 0 : code.hashCode()); result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } }
/* * Copyright (c) 2004-2013 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * Copyright (c) 2014 Martin Stockhammer */ package prefux.data.tuple; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Logger; import prefux.data.Table; import prefux.data.Tuple; import prefux.data.event.TupleSetListener; import prefux.data.expression.Expression; import prefux.data.expression.Predicate; import prefux.data.expression.parser.ExpressionParser; import prefux.util.collections.CompositeIterator; /** * <p>TupleSet implementation for treating a collection of tuple sets * as a single, composite tuple set. This composite does not take * overlap between contained TupleSets into account.</p> * * <p>The {@link TupleSet#addTuple(Tuple)} and {@link #setTuple(Tuple)} * methods are not supported by this class, and calling these methods will * result in a UnsupportedOperationException. Instead, use the add or set * methods on the desired non-composite tuple set.</p> * * @author <a href="http://jheer.org">jeffrey heer</a> */ public class CompositeTupleSet extends AbstractTupleSet { private static final Logger s_logger = Logger.getLogger(CompositeTupleSet.class.getName()); private Map<String, TupleSet> m_map; // map names to tuple sets private Set<TupleSet> m_sets; // support quick reverse lookup private int m_count; // count of total tuples private Listener m_lstnr; /** * Create a new, empty CompositeTupleSet */ public CompositeTupleSet() { this(true); } protected CompositeTupleSet(boolean listen) { m_map = new LinkedHashMap<>(); m_sets = new HashSet<>(); m_count = 0; m_lstnr = listen ? new Listener() : null; } /** * Add a TupleSet to this composite. * @param name the name of the TupleSet to add * @param set the set to add */ public void addSet(String name, TupleSet set) { if ( hasSet(name) ) { throw new IllegalArgumentException("Name already in use: "+name); } m_map.put(name, set); m_sets.add(set); m_count += set.getTupleCount(); if ( m_lstnr != null ) set.addTupleSetListener(m_lstnr); } /** * Indicates if this composite contains a TupleSet with the given name. * @param name the name to look for * @return true if a TupleSet with the given name is found, false otherwise */ public boolean hasSet(String name) { return m_map.containsKey(name); } /** * Indicates if this composite contains the given TupleSet. * @param set the TupleSet to check for containment * @return true if the TupleSet is contained in this composite, * false otherwise */ public boolean containsSet(TupleSet set) { return m_sets.contains(set); } /** * Get the TupleSet associated with the given name. * @param name the name of the TupleSet to get * @return the associated TupleSet, or null if not found */ public TupleSet getSet(String name) { return (TupleSet)m_map.get(name); } /** * Get an iterator over the names of all the TupleSets in this composite. * @return the iterator over contained set names. */ public Iterator<String> setNames() { return m_map.keySet().iterator(); } /** * Get an iterator over all the TupleSets in this composite. * @return the iterator contained sets. */ public Iterator<TupleSet> sets() { return m_map.values().iterator(); } /** * Remove the TupleSet with the given name from this composite. * @param name the name of the TupleSet to remove * @return the removed TupleSet, or null if not found */ public TupleSet removeSet(String name) { TupleSet ts = (TupleSet)m_map.remove(name); if ( ts != null ) { m_sets.remove(ts); if ( m_lstnr != null ) ts.removeTupleSetListener(m_lstnr); } return ts; } /** * Remove all contained TupleSets from this composite. */ public void removeAllSets() { Iterator<Entry<String, TupleSet>> sets = m_map.entrySet().iterator(); while ( sets.hasNext() ) { Entry<String, TupleSet> entry = sets.next(); TupleSet ts = entry.getValue(); sets.remove(); m_sets.remove(ts); if ( m_lstnr != null ) ts.removeTupleSetListener(m_lstnr); } m_count = 0; } /** * Clear this TupleSet, calling clear on all contained TupleSet * instances. All contained TupleSets remain members of this * composite, but they have their data cleared. * @see prefux.data.tuple.TupleSet#clear() */ public void clear() { Iterator<Entry<String,TupleSet>> sets = m_map.entrySet().iterator(); while ( sets.hasNext() ) { Entry<String, TupleSet> entry = sets.next(); entry.getValue().clear(); } m_count = 0; } // ------------------------------------------------------------------------ // TupleSet Interface /** * Not supported. * @see prefux.data.tuple.TupleSet#addTuple(prefux.data.Tuple) */ public Tuple addTuple(Tuple t) { throw new UnsupportedOperationException(); } /** * Not supported. * @see prefux.data.tuple.TupleSet#setTuple(prefux.data.Tuple) */ public Tuple setTuple(Tuple t) { throw new UnsupportedOperationException(); } /** * Removes the tuple from its source set if that source set is contained * within this composite. * @see prefux.data.tuple.TupleSet#removeTuple(prefux.data.Tuple) */ public boolean removeTuple(Tuple t) { Table table = t.getTable(); if ( m_sets.contains(table) ) { return table.removeTuple(t); } else { return false; } } /** * @see prefux.data.tuple.TupleSet#containsTuple(prefux.data.Tuple) */ public boolean containsTuple(Tuple t) { Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); while ( it.hasNext() ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); if ( ts.containsTuple(t) ) return true; } return false; } /** * @see prefux.data.tuple.TupleSet#getTupleCount() */ public int getTupleCount() { if ( m_lstnr != null ) { return m_count; } else { int count = 0; Iterator<Entry<String,TupleSet>> it = m_map.entrySet().iterator(); while ( it.hasNext()) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); count += ts.getTupleCount(); } return count; } } /** * @see prefux.data.tuple.TupleSet#tuples() */ @SuppressWarnings("unchecked") public Iterator<Tuple> tuples() { CompositeIterator<Tuple> ci = new CompositeIterator<Tuple>(m_map.size()); Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); for ( int i=0; it.hasNext(); ++i ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); ci.setIterator(i, (Iterator<Tuple>) ts.tuples()); } return ci; } /** * @see prefux.data.tuple.TupleSet#tuples(prefux.data.expression.Predicate) */ @SuppressWarnings("unchecked") public Iterator<Tuple> tuples(Predicate filter) { CompositeIterator<Tuple> ci = new CompositeIterator<Tuple>(m_map.size()); Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); for ( int i=0; it.hasNext(); ++i ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); ci.setIterator(i, (Iterator<Tuple>) ts.tuples(filter)); } return ci; } // -- Data Field Methods -------------------------------------------------- /** * Returns true. * @see prefux.data.tuple.TupleSet#isAddColumnSupported() */ public boolean isAddColumnSupported() { return true; } /** * Adds the value to all contained TupleSets that return a true value for * {@link TupleSet#isAddColumnSupported()}. * @see prefux.data.tuple.TupleSet#addColumn(java.lang.String, java.lang.Class, java.lang.Object) */ public void addColumn(String name, Class<?> type, Object defaultValue) { Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); while ( it.hasNext() ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); if ( ts.isAddColumnSupported() ) { try { ts.addColumn(name, type, defaultValue); } catch ( IllegalArgumentException iae ) { // already exists } } else { s_logger.fine("Skipped addColumn for "+entry.getKey()); } } } /** * Adds the value to all contained TupleSets that return a true value for * {@link TupleSet#isAddColumnSupported()}. * @see prefux.data.tuple.TupleSet#addColumn(java.lang.String, java.lang.Class) */ public void addColumn(String name, Class<?> type) { Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); while ( it.hasNext() ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); if ( ts.isAddColumnSupported() ) { try { ts.addColumn(name, type); } catch ( IllegalArgumentException iae ) { // already exists } } else { s_logger.fine("Skipped addColumn for "+entry.getKey()); } } } /** * Adds the value to all contained TupleSets that return a true value for * {@link TupleSet#isAddColumnSupported()}. * @see prefux.data.tuple.TupleSet#addColumn(java.lang.String, prefux.data.expression.Expression) */ public void addColumn(String name, Expression expr) { Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); while ( it.hasNext() ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); if ( ts.isAddColumnSupported() ) { try { ts.addColumn(name, expr); } catch ( IllegalArgumentException iae ) { // already exists } } else { s_logger.fine("Skipped addColumn for "+entry.getKey()); } } } public boolean hasColumn(String columnName) { Iterator<Entry<String, TupleSet>> it = m_map.entrySet().iterator(); while ( it.hasNext() ) { Entry<String, TupleSet> entry = it.next(); TupleSet ts = entry.getValue(); if (ts.hasColumn(columnName)) { return true; } } return false; } /** * Adds the value to all contained TupleSets that return a true value for * {@link TupleSet#isAddColumnSupported()}. * @see prefux.data.tuple.TupleSet#addColumn(java.lang.String, java.lang.String) */ public void addColumn(String name, String expr) { Expression ex = ExpressionParser.parse(expr); Throwable t = ExpressionParser.getError(); if ( t != null ) { throw new RuntimeException(t); } else { addColumn(name, ex); } } // ------------------------------------------------------------------------ // Internal TupleSet Listener /** * Listener that relays tuple set change events as they occur and updates * the total tuple count appropriately. */ private class Listener implements TupleSetListener { public void tupleSetChanged(TupleSet tset, Tuple[] add, Tuple[] rem) { m_count += add.length - rem.length; fireTupleEvent(add, rem); } } } // end of class CompositeTupleSet
/******************************************************************************* * Copyright (c) 2006, 2012 Oracle Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Oracle Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.bpel.ui.preferences; import org.eclipse.bpel.ui.BPELUIPlugin; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.swt.graphics.RGB; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; /** * @author Michal Chmielewski (michal.chmielewski@oracle.com) * @date Oct 27, 2006 * */ public class PreferenceConstants { /** * Matching brackets enabled */ static final public String EDITOR_MATCHING_BRACKETS = "org.eclipse.bpel.ui.xpath.editor.MatchingBrackets"; //$NON-NLS-1$ /** * The matching brackets color. */ static final public String EDITOR_MATCHING_BRACKETS_COLOR = "org.eclipse.bpel.ui.xpath.editor.MatchingBracketsColor"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close strings' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * */ static final public String EDITOR_CLOSE_STRINGS = "closeString"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close brackets' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ public final static RGB AXIS = new RGB(0, 136, 0); public final static RGB BRACKET = new RGB(0, 0, 0); public final static RGB DEFAULT = new RGB(0, 0, 0); public final static RGB NUMBER = new RGB(100, 100, 100); public final static RGB OPERAND = new RGB(155, 68, 208); public final static RGB PARENS = new RGB(255, 0, 0); public final static RGB PATH_SEPARATOR = new RGB(0, 0, 255); public final static RGB STRING = new RGB(0, 136, 0); public final static RGB TAG = new RGB(0, 0, 128); public final static RGB FUNCTIONS_XPATH = new RGB(0,0,200); public static final RGB VARIABLES = new RGB(10,10,10); public static final RGB VARIABLE_PART = new RGB(0xe0,80,0); /** * Initializes the given preference store with the default values. * * @param store the preference store to be initialized * * @since 2.1 */ public static void initializeDefaultValues(IPreferenceStore store) { // set the default values from AbstractDecoratedTextEditor AbstractDecoratedTextEditorPreferenceConstants.initializeDefaultValues(store); // store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); // // // JavaBasePreferencePage // store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false); // store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); // store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); // store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); // store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); // store.setToDefault(PreferenceConstants.UPDATE_JAVA_VIEWS); // clear preference, update on save not supported anymore // // store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true); // store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true); // store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true); // store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true); // // store.setDefault(PreferenceConstants.SEARCH_USE_REDUCED_MENU, true); // // AppearancePreferencePage // store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); // store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); // store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); // store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); // store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); // // // ImportOrganizePreferencePage // store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); // store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); // // // TypeFilterPreferencePage // store.setDefault(PreferenceConstants.TYPEFILTER_ENABLED, ""); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.TYPEFILTER_DISABLED, ""); //$NON-NLS-1$ // // // ClasspathVariablesPreferencePage // // CodeFormatterPreferencePage // // CompilerPreferencePage // // no initialization needed // // // RefactoringPreferencePage // store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); // store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); // // // TemplatePreferencePage // store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); // // // CodeGenerationPreferencePage // // compatibility code // if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) { // String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); // if (prefix.length() > 0) { // JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix); // store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX); // store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); // } // } // if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) { // String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); // if (suffix.length() > 0) { // JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix); // store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX); // store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); // } // } // store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); // store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); // store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); // // // MembersOrderPreferencePage // store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SF,SI,SM,I,F,C,M"); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, "B,V,R,D"); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, false); // // must add here to guarantee that it is the first in the listener list // store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache()); // // // // JavaEditorPreferencePage store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192)); // // store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(232, 242, 254)); // // store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); // store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180)); // // store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); // store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); // // store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); // // store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); // // store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(121, 121, 121)); // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); // // store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); // // store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); // // store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); // store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); // store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); // store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); // store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); // store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)); // store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_STRING_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); // store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR, new RGB(0, 0, 0)); // store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR, new RGB(127, 0, 85)); // store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_BOLD, true); // store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR, new RGB(0, 0, 0)); // store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191)); // store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true); // store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_ITALIC, false); // // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); // store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_ITALIC, false); // // store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); // store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); // // store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); // PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(255, 255, 255)); // PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); // PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(255, 255, 255)); // PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); // PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); // PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); // store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@#"); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); // store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); // store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); // store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); // store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); // store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); // store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); // store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, false); // // store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); // store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); // store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); // store.setDefault(PreferenceConstants.EDITOR_IMPORTS_ON_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); // store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); // store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); // store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true); // store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS, false); // store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); // store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); // store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, false); // // String mod1Name= Action.findModifierString(SWT.MOD1); // SWT.COMMAND on Mac; SWT.CONTROL elsewhere // store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + mod1Name); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + SWT.MOD1); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, true); // // store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); // store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, mod1Name); // store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.MOD1); // // store.setDefault(PreferenceConstants.EDITOR_SMART_TAB, true); // store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true); // store.setDefault(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER, false); // // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMAT, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, false); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, false); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHTML, true); // store.setDefault(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, 80); // // store.setDefault(PreferenceConstants.FORMATTER_PROFILE, ProfileManager.JAVA_PROFILE); // ProfileStore.checkCurrentOptionsVersion(); // // // mark occurrences // store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, false); // store.setDefault(PreferenceConstants.EDITOR_STICKY_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, true); // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, true); // // // spell checking // store.setDefault(PreferenceConstants.SPELLING_CHECK_SPELLING, false); // store.setDefault(PreferenceConstants.SPELLING_LOCALE, SpellCheckEngine.getDefaultLocale().toString()); // store.setDefault(PreferenceConstants.SPELLING_IGNORE_DIGITS, true); // store.setDefault(PreferenceConstants.SPELLING_IGNORE_MIXED, true); // store.setDefault(PreferenceConstants.SPELLING_IGNORE_SENTENCE, true); // store.setDefault(PreferenceConstants.SPELLING_IGNORE_UPPER, true); // store.setDefault(PreferenceConstants.SPELLING_IGNORE_URLS, true); // store.setDefault(PreferenceConstants.SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD, 20); // store.setDefault(PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST, false); // // // folding // store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true); // store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, "org.eclipse.jdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$ // store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, false); // store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true); // store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false); // store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, true); // // // override default extended text editor prefs // store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS, true); // // // SemanticHighlightings.initDefaults(store); // // // do more complicated stuff // NewJavaProjectPreferencePage.initDefaults(store); } /** * Returns the preference store. * * @return the preference store */ public static IPreferenceStore getPreferenceStore() { return BPELUIPlugin.INSTANCE.getPreferenceStore(); } }
/* * 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.metrics; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.aggregations.AggregationTestScriptsPlugin; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.global.Global; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.missing.Missing; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.ExtendedStats.Bounds; import org.elasticsearch.search.aggregations.BucketOrder; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.extendedStats; import static org.elasticsearch.search.aggregations.AggregationBuilders.filter; import static org.elasticsearch.search.aggregations.AggregationBuilders.global; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.missing; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.sameInstance; public class ExtendedStatsIT extends AbstractNumericTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(AggregationTestScriptsPlugin.class); } private static double stdDev(int... vals) { return Math.sqrt(variance(vals)); } private static double stdDevPopulation(int... vals) { return Math.sqrt(variancePopulation(vals)); } private static double stdDevSampling(int... vals) { return Math.sqrt(varianceSampling(vals)); } private static double variance(int... vals) { return variancePopulation(vals); } private static double variancePopulation(int... vals) { double sum = 0; double sumOfSqrs = 0; for (int val : vals) { sum += val; sumOfSqrs += val * val; } double variance = (sumOfSqrs - ((sum * sum) / vals.length)) / vals.length; return variance < 0 ? 0 : variance; } private static double varianceSampling(int... vals) { double sum = 0; double sumOfSqrs = 0; for (int val : vals) { sum += val; sumOfSqrs += val * val; } double variance = (sumOfSqrs - ((sum * sum) / vals.length)) / (vals.length - 1); return variance < 0 ? 0 : variance; } @Override public void testEmptyAggregation() throws Exception { SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation( histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(extendedStats("stats").field("value"))) .get(); assertThat(searchResponse.getHits().getTotalHits().value, equalTo(2L)); Histogram histo = searchResponse.getAggregations().get("histo"); assertThat(histo, notNullValue()); Histogram.Bucket bucket = histo.getBuckets().get(1); assertThat(bucket, notNullValue()); ExtendedStats stats = bucket.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getSumOfSquares(), equalTo(0.0)); assertThat(stats.getCount(), equalTo(0L)); assertThat(stats.getSum(), equalTo(0.0)); assertThat(stats.getMin(), equalTo(Double.POSITIVE_INFINITY)); assertThat(stats.getMax(), equalTo(Double.NEGATIVE_INFINITY)); assertThat(Double.isNaN(stats.getStdDeviation()), is(true)); assertThat(Double.isNaN(stats.getStdDeviationPopulation()), is(true)); assertThat(Double.isNaN(stats.getStdDeviationSampling()), is(true)); assertThat(Double.isNaN(stats.getAvg()), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER_POPULATION)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER_POPULATION)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER_SAMPLING)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER_SAMPLING)), is(true));} @Override public void testUnmapped() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx_unmapped") .setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").field("value")) .get(); assertThat(searchResponse.getHits().getTotalHits().value, equalTo(0L)); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo(Double.NaN)); assertThat(stats.getMin(), equalTo(Double.POSITIVE_INFINITY)); assertThat(stats.getMax(), equalTo(Double.NEGATIVE_INFINITY)); assertThat(stats.getSum(), equalTo(0.0)); assertThat(stats.getCount(), equalTo(0L)); assertThat(stats.getSumOfSquares(), equalTo(0.0)); assertThat(stats.getVariance(), equalTo(Double.NaN)); assertThat(stats.getVariancePopulation(), equalTo(Double.NaN)); assertThat(stats.getVarianceSampling(), equalTo(Double.NaN)); assertThat(stats.getStdDeviation(), equalTo(Double.NaN)); assertThat(stats.getStdDeviationPopulation(), equalTo(Double.NaN)); assertThat(stats.getStdDeviationSampling(), equalTo(Double.NaN)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER_POPULATION)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER_POPULATION)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER_SAMPLING)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER_SAMPLING)), is(true)); } public void testPartiallyUnmapped() { double sigma = randomDouble() * 5; ExtendedStats s1 = client().prepareSearch("idx") .addAggregation(extendedStats("stats").field("value").sigma(sigma)).get() .getAggregations().get("stats"); ExtendedStats s2 = client().prepareSearch("idx", "idx_unmapped") .addAggregation(extendedStats("stats").field("value").sigma(sigma)).get() .getAggregations().get("stats"); assertEquals(s1.getAvg(), s2.getAvg(), 1e-10); assertEquals(s1.getCount(), s2.getCount()); assertEquals(s1.getMin(), s2.getMin(), 0d); assertEquals(s1.getMax(), s2.getMax(), 0d); assertEquals(s1.getStdDeviation(), s2.getStdDeviation(), 1e-10); assertEquals(s1.getStdDeviationPopulation(), s2.getStdDeviationPopulation(), 1e-10); assertEquals(s1.getStdDeviationSampling(), s2.getStdDeviationSampling(), 1e-10); assertEquals(s1.getSumOfSquares(), s2.getSumOfSquares(), 1e-10); assertEquals(s1.getStdDeviationBound(Bounds.LOWER), s2.getStdDeviationBound(Bounds.LOWER), 1e-10); assertEquals(s1.getStdDeviationBound(Bounds.UPPER), s2.getStdDeviationBound(Bounds.UPPER), 1e-10); assertEquals(s1.getStdDeviationBound(Bounds.LOWER_POPULATION), s2.getStdDeviationBound(Bounds.LOWER_POPULATION), 1e-10); assertEquals(s1.getStdDeviationBound(Bounds.UPPER_POPULATION), s2.getStdDeviationBound(Bounds.UPPER_POPULATION), 1e-10); assertEquals(s1.getStdDeviationBound(Bounds.LOWER_SAMPLING), s2.getStdDeviationBound(Bounds.LOWER_SAMPLING), 1e-10); assertEquals(s1.getStdDeviationBound(Bounds.UPPER_SAMPLING), s2.getStdDeviationBound(Bounds.UPPER_SAMPLING), 1e-10);} @Override public void testSingleValuedField() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").field("value").sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); checkUpperLowerBounds(stats, sigma); } public void testSingleValuedFieldDefaultSigma() throws Exception { // Same as previous test, but uses a default value for sigma SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").field("value")) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); checkUpperLowerBounds(stats, 2); } public void testSingleValuedField_WithFormatter() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").format("0000.0").field("value").sigma(sigma)).get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) / 10)); assertThat(stats.getAvgAsString(), equalTo("0005.5")); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMinAsString(), equalTo("0001.0")); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getMaxAsString(), equalTo("0010.0")); assertThat(stats.getSum(), equalTo((double) 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)); assertThat(stats.getSumAsString(), equalTo("0055.0")); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100)); assertThat(stats.getSumOfSquaresAsString(), equalTo("0385.0")); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVarianceAsString(), equalTo("0008.2")); assertThat(stats.getVariancePopulationAsString(), equalTo("0008.2")); assertThat(stats.getVarianceSamplingAsString(), equalTo("0009.2")); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationAsString(), equalTo("0002.9")); assertThat(stats.getStdDeviationPopulationAsString(), equalTo("0002.9")); assertThat(stats.getStdDeviationSamplingAsString(), equalTo("0003.0")); checkUpperLowerBounds(stats, sigma); } @Override public void testSingleValuedFieldGetProperty() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(global("global").subAggregation(extendedStats("stats").field("value"))).get(); assertHitCount(searchResponse, 10); Global global = searchResponse.getAggregations().get("global"); assertThat(global, notNullValue()); assertThat(global.getName(), equalTo("global")); assertThat(global.getDocCount(), equalTo(10L)); assertThat(global.getAggregations(), notNullValue()); assertThat(global.getAggregations().asMap().size(), equalTo(1)); ExtendedStats stats = global.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); ExtendedStats statsFromProperty = (ExtendedStats) ((InternalAggregation)global).getProperty("stats"); assertThat(statsFromProperty, notNullValue()); assertThat(statsFromProperty, sameInstance(stats)); double expectedAvgValue = (double) (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) / 10; assertThat(stats.getAvg(), equalTo(expectedAvgValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.avg"), equalTo(expectedAvgValue)); double expectedMinValue = 1.0; assertThat(stats.getMin(), equalTo(expectedMinValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.min"), equalTo(expectedMinValue)); double expectedMaxValue = 10.0; assertThat(stats.getMax(), equalTo(expectedMaxValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.max"), equalTo(expectedMaxValue)); double expectedSumValue = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10; assertThat(stats.getSum(), equalTo(expectedSumValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.sum"), equalTo(expectedSumValue)); long expectedCountValue = 10; assertThat(stats.getCount(), equalTo(expectedCountValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.count"), equalTo((double) expectedCountValue)); double expectedSumOfSquaresValue = (double) 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100; assertThat(stats.getSumOfSquares(), equalTo(expectedSumOfSquaresValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.sum_of_squares"), equalTo(expectedSumOfSquaresValue)); double expectedVarianceValue = variance(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertThat(stats.getVariance(), equalTo(expectedVarianceValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.variance"), equalTo(expectedVarianceValue)); double expectedVariancePopulationValue = variancePopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertThat(stats.getVariancePopulation(), equalTo(expectedVariancePopulationValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.variance_population"), equalTo(expectedVariancePopulationValue)); double expectedVarianceSamplingValue = varianceSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertThat(stats.getVarianceSampling(), equalTo(expectedVarianceSamplingValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.variance_sampling"), equalTo(expectedVarianceSamplingValue)); double expectedStdDevValue = stdDev(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertThat(stats.getStdDeviation(), equalTo(expectedStdDevValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.std_deviation"), equalTo(expectedStdDevValue)); double expectedStdDevPopulationValue = stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertThat(stats.getStdDeviationPopulation(), equalTo(expectedStdDevValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.std_deviation_population"), equalTo(expectedStdDevPopulationValue)); double expectedStdDevSamplingValue = stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertThat(stats.getStdDeviationSampling(), equalTo(expectedStdDevSamplingValue)); assertThat((double) ((InternalAggregation)global).getProperty("stats.std_deviation_sampling"), equalTo(expectedStdDevSamplingValue)); } @Override public void testSingleValuedFieldPartiallyUnmapped() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx", "idx_unmapped") .setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").field("value").sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); checkUpperLowerBounds(stats, sigma); } @Override public void testSingleValuedFieldWithValueScript() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .field("value") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value + 1", Collections.emptyMap())) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); assertThat(stats.getMin(), equalTo(2.0)); assertThat(stats.getMax(), equalTo(11.0)); assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 4+9+16+25+36+49+64+81+100+121)); assertThat(stats.getVariance(), equalTo(variance(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getStdDeviation(), equalTo(stdDev(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); checkUpperLowerBounds(stats, sigma); } @Override public void testSingleValuedFieldWithValueScriptWithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .field("value") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value + inc", params)) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); assertThat(stats.getMin(), equalTo(2.0)); assertThat(stats.getMax(), equalTo(11.0)); assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 4+9+16+25+36+49+64+81+100+121)); assertThat(stats.getVariance(), equalTo(variance(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getStdDeviation(), equalTo(stdDev(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); checkUpperLowerBounds(stats, sigma); } @Override public void testMultiValuedField() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").field("values").sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12) / 20)); assertThat(stats.getMin(), equalTo(2.0)); assertThat(stats.getMax(), equalTo(12.0)); assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12)); assertThat(stats.getCount(), equalTo(20L)); assertThat(stats.getSumOfSquares(), equalTo((double) 4+9+16+25+36+49+64+81+100+121+9+16+25+36+49+64+81+100+121+144)); assertThat(stats.getVariance(), equalTo(variance(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))); assertThat(stats.getStdDeviation(), equalTo(stdDev(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))); checkUpperLowerBounds(stats, sigma); } @Override public void testMultiValuedFieldWithValueScript() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .field("values") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value - 1", Collections.emptyMap())) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11) / 20)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(11.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11)); assertThat(stats.getCount(), equalTo(20L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100+4+9+16+25+36+49+64+81+100+121)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); checkUpperLowerBounds(stats, sigma); } @Override public void testMultiValuedFieldWithValueScriptWithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .field("values") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value - dec", params)) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11) / 20)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(11.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11)); assertThat(stats.getCount(), equalTo(20L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100+4+9+16+25+36+49+64+81+100+121)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); checkUpperLowerBounds(stats, sigma); } @Override public void testScriptSingleValued() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "doc['value'].value", Collections.emptyMap())) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10))); checkUpperLowerBounds(stats, sigma); } @Override public void testScriptSingleValuedWithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); Script script = new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "doc['value'].value + inc", params); double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .script(script) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); assertThat(stats.getMin(), equalTo(2.0)); assertThat(stats.getMax(), equalTo(11.0)); assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 4+9+16+25+36+49+64+81+100+121)); assertThat(stats.getVariance(), equalTo(variance(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviation(), equalTo(stdDev(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11))); checkUpperLowerBounds(stats, sigma); } @Override public void testScriptMultiValued() throws Exception { double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "doc['values']", Collections.emptyMap())) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12) / 20)); assertThat(stats.getMin(), equalTo(2.0)); assertThat(stats.getMax(), equalTo(12.0)); assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12)); assertThat(stats.getCount(), equalTo(20L)); assertThat(stats.getSumOfSquares(), equalTo((double) 4+9+16+25+36+49+64+81+100+121+9+16+25+36+49+64+81+100+121+144)); assertThat(stats.getVariance(), equalTo(variance(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12))); assertThat(stats.getStdDeviation(), equalTo(stdDev(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12))); checkUpperLowerBounds(stats, sigma); } @Override public void testScriptMultiValuedWithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); Script script = new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "[ doc['value'].value, doc['value'].value - dec ]", params); double sigma = randomDouble() * randomIntBetween(1, 10); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( extendedStats("stats") .script(script) .sigma(sigma)) .get(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10+0+1+2+3+4+5+6+7+8+9) / 20)); assertThat(stats.getMin(), equalTo(0.0)); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10+0+1+2+3+4+5+6+7+8+9)); assertThat(stats.getCount(), equalTo(20L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100+0+1+4+9+16+25+36+49+64+81)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8 ,9))); assertThat(stats.getVariancePopulation(), equalTo(variancePopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8 ,9))); assertThat(stats.getVarianceSampling(), equalTo(varianceSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8 ,9))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8 ,9))); assertThat(stats.getStdDeviationPopulation(), equalTo(stdDevPopulation(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8 ,9))); assertThat(stats.getStdDeviationSampling(), equalTo(stdDevSampling(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8 ,9))); checkUpperLowerBounds(stats, sigma); } public void testEmptySubAggregation() { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(terms("value").field("value") .subAggregation(missing("values").field("values") .subAggregation(extendedStats("stats").field("value")))) .get(); assertHitCount(searchResponse, 10); Terms terms = searchResponse.getAggregations().get("value"); assertThat(terms, notNullValue()); assertThat(terms.getBuckets().size(), equalTo(10)); for (Terms.Bucket bucket : terms.getBuckets()) { assertThat(bucket.getDocCount(), equalTo(1L)); Missing missing = bucket.getAggregations().get("values"); assertThat(missing, notNullValue()); assertThat(missing.getDocCount(), equalTo(0L)); ExtendedStats stats = missing.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getSumOfSquares(), equalTo(0.0)); assertThat(stats.getCount(), equalTo(0L)); assertThat(stats.getSum(), equalTo(0.0)); assertThat(stats.getMin(), equalTo(Double.POSITIVE_INFINITY)); assertThat(stats.getMax(), equalTo(Double.NEGATIVE_INFINITY)); assertThat(Double.isNaN(stats.getStdDeviation()), is(true)); assertThat(Double.isNaN(stats.getStdDeviationPopulation()), is(true)); assertThat(Double.isNaN(stats.getStdDeviationSampling()), is(true)); assertThat(Double.isNaN(stats.getAvg()), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER_POPULATION)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER_POPULATION)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.UPPER_SAMPLING)), is(true)); assertThat(Double.isNaN(stats.getStdDeviationBound(Bounds.LOWER_SAMPLING)), is(true)); } } @Override public void testOrderByEmptyAggregation() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(terms("terms").field("value") .order(BucketOrder.compound(BucketOrder.aggregation("filter>extendedStats.avg", true))) .subAggregation( filter("filter", termQuery("value", 100)).subAggregation(extendedStats("extendedStats").field("value")))) .get(); assertHitCount(searchResponse, 10); Terms terms = searchResponse.getAggregations().get("terms"); assertThat(terms, notNullValue()); List<? extends Terms.Bucket> buckets = terms.getBuckets(); assertThat(buckets, notNullValue()); assertThat(buckets.size(), equalTo(10)); for (int i = 0; i < 10; i++) { Terms.Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKeyAsNumber(), equalTo((long) i + 1)); assertThat(bucket.getDocCount(), equalTo(1L)); Filter filter = bucket.getAggregations().get("filter"); assertThat(filter, notNullValue()); assertThat(filter.getDocCount(), equalTo(0L)); ExtendedStats extendedStats = filter.getAggregations().get("extendedStats"); assertThat(extendedStats, notNullValue()); assertThat(extendedStats.getMin(), equalTo(Double.POSITIVE_INFINITY)); assertThat(extendedStats.getMax(), equalTo(Double.NEGATIVE_INFINITY)); assertThat(extendedStats.getAvg(), equalTo(Double.NaN)); assertThat(extendedStats.getSum(), equalTo(0.0)); assertThat(extendedStats.getCount(), equalTo(0L)); assertThat(extendedStats.getStdDeviation(), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationPopulation(), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationSampling(), equalTo(Double.NaN)); assertThat(extendedStats.getSumOfSquares(), equalTo(0.0)); assertThat(extendedStats.getVariance(), equalTo(Double.NaN)); assertThat(extendedStats.getVariancePopulation(), equalTo(Double.NaN)); assertThat(extendedStats.getVarianceSampling(), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationBound(Bounds.LOWER), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationBound(Bounds.UPPER), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationBound(Bounds.LOWER_POPULATION), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationBound(Bounds.UPPER_POPULATION), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationBound(Bounds.LOWER_SAMPLING), equalTo(Double.NaN)); assertThat(extendedStats.getStdDeviationBound(Bounds.UPPER_SAMPLING), equalTo(Double.NaN)); } } private void checkUpperLowerBounds(ExtendedStats stats, double sigma) { assertThat(stats.getStdDeviationBound(ExtendedStats.Bounds.UPPER), equalTo(stats.getAvg() + (stats.getStdDeviation() * sigma))); assertThat(stats.getStdDeviationBound(ExtendedStats.Bounds.LOWER), equalTo(stats.getAvg() - (stats.getStdDeviation() * sigma))); assertThat(stats.getStdDeviationBound(Bounds.UPPER_POPULATION), equalTo(stats.getAvg() + (stats.getStdDeviationPopulation() * sigma))); assertThat(stats.getStdDeviationBound(Bounds.LOWER_POPULATION), equalTo(stats.getAvg() - (stats.getStdDeviationPopulation() * sigma))); assertThat(stats.getStdDeviationBound(Bounds.UPPER_SAMPLING), equalTo(stats.getAvg() + (stats.getStdDeviationSampling() * sigma))); assertThat(stats.getStdDeviationBound(Bounds.LOWER_SAMPLING), equalTo(stats.getAvg() - (stats.getStdDeviationSampling() * sigma))); } /** * Make sure that a request using a deterministic script or not using a script get cached. * Ensure requests using nondeterministic scripts do not get cached. */ public void testScriptCaching() throws Exception { assertAcked(prepareCreate("cache_test_idx").setMapping("d", "type=long") .setSettings(Settings.builder().put("requests.cache.enable", true).put("number_of_shards", 1).put("number_of_replicas", 1)) .get()); indexRandom(true, client().prepareIndex("cache_test_idx").setId("1").setSource("s", 1), client().prepareIndex("cache_test_idx").setId("2").setSource("s", 2)); // Make sure we are starting with a clear cache assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getHitCount(), equalTo(0L)); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getMissCount(), equalTo(0L)); // Test that a request using a nondeterministic script does not get cached SearchResponse r = client().prepareSearch("cache_test_idx").setSize(0) .addAggregation(extendedStats("foo").field("d") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "Math.random()", Collections.emptyMap()))) .get(); assertSearchResponse(r); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getHitCount(), equalTo(0L)); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getMissCount(), equalTo(0L)); // Test that a request using a deterministic script gets cached r = client().prepareSearch("cache_test_idx").setSize(0) .addAggregation(extendedStats("foo").field("d") .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value + 1", Collections.emptyMap()))) .get(); assertSearchResponse(r); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getHitCount(), equalTo(0L)); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getMissCount(), equalTo(1L)); // Ensure that non-scripted requests are cached as normal r = client().prepareSearch("cache_test_idx").setSize(0).addAggregation(extendedStats("foo").field("d")).get(); assertSearchResponse(r); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getHitCount(), equalTo(0L)); assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache() .getMissCount(), equalTo(2L)); } }
package com.github.choonchernlim.security.adfs.saml2; import static com.github.choonchernlim.betterPreconditions.preconditions.PreconditionFactory.expect; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.velocity.app.VelocityEngine; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider; import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.xml.parse.StaticBasicParserPool; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.MethodInvokingFactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.saml.SAMLAuthenticationProvider; import org.springframework.security.saml.SAMLBootstrap; import org.springframework.security.saml.SAMLDiscovery; import org.springframework.security.saml.SAMLEntryPoint; import org.springframework.security.saml.SAMLLogoutFilter; import org.springframework.security.saml.SAMLLogoutProcessingFilter; import org.springframework.security.saml.SAMLProcessingFilter; import org.springframework.security.saml.SAMLWebSSOHoKProcessingFilter; import org.springframework.security.saml.context.SAMLContextProviderLB; import org.springframework.security.saml.key.JKSKeyManager; import org.springframework.security.saml.key.KeyManager; import org.springframework.security.saml.log.SAMLDefaultLogger; import org.springframework.security.saml.metadata.CachingMetadataManager; import org.springframework.security.saml.metadata.ExtendedMetadataDelegate; import org.springframework.security.saml.metadata.MetadataDisplayFilter; import org.springframework.security.saml.metadata.MetadataGenerator; import org.springframework.security.saml.metadata.MetadataGeneratorFilter; import org.springframework.security.saml.parser.ParserPoolHolder; import org.springframework.security.saml.processor.HTTPArtifactBinding; import org.springframework.security.saml.processor.HTTPPAOS11Binding; import org.springframework.security.saml.processor.HTTPPostBinding; import org.springframework.security.saml.processor.HTTPRedirectDeflateBinding; import org.springframework.security.saml.processor.HTTPSOAP11Binding; import org.springframework.security.saml.processor.SAMLBinding; import org.springframework.security.saml.processor.SAMLProcessorImpl; import org.springframework.security.saml.trust.httpclient.TLSProtocolConfigurer; import org.springframework.security.saml.trust.httpclient.TLSProtocolSocketFactory; import org.springframework.security.saml.userdetails.SAMLUserDetailsService; import org.springframework.security.saml.util.VelocityFactory; import org.springframework.security.saml.websso.ArtifactResolutionProfileImpl; import org.springframework.security.saml.websso.SingleLogoutProfile; import org.springframework.security.saml.websso.SingleLogoutProfileImpl; import org.springframework.security.saml.websso.WebSSOProfile; import org.springframework.security.saml.websso.WebSSOProfileConsumer; import org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl; import org.springframework.security.saml.websso.WebSSOProfileConsumerImpl; import org.springframework.security.saml.websso.WebSSOProfileECPImpl; import org.springframework.security.saml.websso.WebSSOProfileImpl; import org.springframework.security.saml.websso.WebSSOProfileOptions; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.util.Timer; /** * Spring Security configuration to authenticate against ADFS using SAML protocol. * This class should be extended by Sp's Java-based Spring configuration for web security. */ public abstract class SAMLWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { /** * Provides an opportunity for child class to access any Spring beans, if needed. */ @Autowired protected ApplicationContext applicationContext; @Autowired private SAMLAuthenticationProvider samlAuthenticationProvider; // Initialization of OpenSAML library, must be static to prevent "ObjectPostProcessor is a required bean" exception // By default, Spring Security SAML uses SHA-1. So, use `DefaultSAMLBootstrap` to use SHA-256. @Bean public static SAMLBootstrap samlBootstrap() { return new DefaultSAMLBootstrap(); } /** * Sp's SAMLConfigBean to further customize this security configuration. * * @return SAML config bean */ @Bean protected abstract SAMLConfigBean samlConfigBean(); /** * Fluent API that pre-configures HttpSecurity with SAML specific configuration. * * @param http HttpSecurity instance * @return Same HttpSecurity instance * @throws Exception Exception */ // CSRF must be disabled when processing /saml/** to prevent "Expected CSRF token not found" exception. // See: http://stackoverflow.com/questions/26508835/spring-saml-extension-and-spring-security-csrf-protection-conflict/26560447 protected final HttpSecurity samlizedConfig(final HttpSecurity http) throws Exception { http.httpBasic().authenticationEntryPoint(samlEntryPoint()) .and() .csrf().ignoringAntMatchers("/saml/**") .and() .authorizeRequests().antMatchers("/saml/**").permitAll() .and() .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class) .addFilterAfter(filterChainProxy(), BasicAuthenticationFilter.class); // store CSRF token in cookie if (samlConfigBean().getStoreCsrfTokenInCookie()) { http.csrf() .csrfTokenRepository(csrfTokenRepository()) .and() .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class); } return http; } /** * Configure CSRF token repository to accept CSRF token from AngularJS friendly header. * * @return CsrfTokenRepository */ private CsrfTokenRepository csrfTokenRepository() { HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); repository.setHeaderName(CsrfHeaderFilter.HEADER_NAME); return repository; } /** * Mocks security by hardcoding a given user so that it will always appear that user is accessing the protected * resources. This is useful to allow developer to bypass any web authentication against ADFS during rapid * app development. * * @param http HttpSecurity instance * @param user User instance * @return HttpSecurity that will never authenticate against ADFS */ protected final HttpSecurity mockSecurity(final HttpSecurity http, final User user) { expect(user, "user").not().toBeNull().check(); if (samlConfigBean().getSamlUserDetailsService() == null) { throw new SpringSecurityAdfsSaml2Exception( "`samlConfigBean.samlUserDetailsService` cannot be null. " + "When mocking security, the given user details object will be set as principal. " + "Because setting `samlConfigBean.samlUserDetailsService` will set the user details object as principal, " + "this property must be configured to ensure the mock security mimics the actual security configuration." ); } return http.addFilterBefore(new MockFilterSecurityInterceptor(user), FilterSecurityInterceptor.class); } /** * Fluent API that pre-configures WebSecurity with SAML specific configuration. * * @param web WebSecurity instance * @return Same WebSecurity instance * @throws Exception Exception */ protected final WebSecurity samlizedConfig(final WebSecurity web) throws Exception { web.ignoring().antMatchers(samlConfigBean().getSuccessLogoutUrl()); return web; } // IDP metadata URL private String getMetdataUrl() { return String.format("https://%s/federationmetadata/2007-06/federationmetadata.xml", samlConfigBean().getIdpServerName()); } // Entry point to initialize authentication @Bean public SAMLEntryPoint samlEntryPoint() { SAMLEntryPoint samlEntryPoint = new SAMLEntryPoint(); samlEntryPoint.setDefaultProfileOptions(webSSOProfileOptions()); return samlEntryPoint; } /** * Customizing SAML request message to be sent to the IDP. * * @return WebSSOProfileOptions */ @Bean public WebSSOProfileOptions webSSOProfileOptions() { WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions(); // Disable element scoping when sending requests to IdP to prevent // "Response has invalid status code urn:oasis:names:tc:SAML:2.0:status:Responder, status message is null" // exception webSSOProfileOptions.setIncludeScoping(false); // Always use HTTP-Redirect instead of HTTP-Post, although both works with ADFS webSSOProfileOptions.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); // Force IdP to re-authenticate user if issued token is too old to prevent // "Authentication statement is too old to be used with value" exception // See: http://stackoverflow.com/questions/30528636/saml-login-errors webSSOProfileOptions.setForceAuthN(true); // Determine what authentication method to use (WIA, user/password, etc). // If not set, it will use authentication method order defined by IdP if (!samlConfigBean().getAuthnContexts().isEmpty()) { webSSOProfileOptions.setAuthnContexts(samlConfigBean().getAuthnContexts()); } return webSSOProfileOptions; } // Filter automatically generates default SP metadata @Bean public MetadataGeneratorFilter metadataGeneratorFilter() { // generates base URL that matches `SAMLContextProviderLB` configuration // to ensure SAML endpoints work for server doing SSL termination StringBuilder sb = new StringBuilder(); sb.append("https://").append(samlConfigBean().getSpServerName()); if (samlConfigBean().getSpHttpsPort() != 443) { sb.append(":").append(samlConfigBean().getSpHttpsPort()); } sb.append(samlConfigBean().getSpContextPath()); String entityBaseUrl = sb.toString(); MetadataGenerator metadataGenerator = new MetadataGenerator(); metadataGenerator.setKeyManager(keyManager()); metadataGenerator.setEntityBaseURL(entityBaseUrl); return new MetadataGeneratorFilter(metadataGenerator); } // HTTP client @Bean public HttpClient httpClient() { return new HttpClient(new MultiThreadedHttpConnectionManager()); } // Filters for processing of SAML messages @Bean public FilterChainProxy filterChainProxy() throws Exception { //@formatter:off return new FilterChainProxy(ImmutableList.<SecurityFilterChain>of( new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"), samlEntryPoint()), new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"), samlLogoutFilter()), new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"), metadataDisplayFilter()), new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"), samlProcessingFilter()), new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"), samlWebSSOHoKProcessingFilter()), new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"), samlLogoutProcessingFilter()), new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"), samlIDPDiscovery()) )); //@formatter:on } // Handler deciding where to redirect user after successful login @Bean public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() { SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successRedirectHandler.setDefaultTargetUrl(samlConfigBean().getSuccessLoginDefaultUrl()); return successRedirectHandler; } // Handler deciding where to redirect user after failed login @Bean public SimpleUrlAuthenticationFailureHandler failureRedirectHandler() { SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler(); // The precondition on `setDefaultFailureUrl(..)` will cause an exception if the value is null. // So, only set this value if it is not null if (!samlConfigBean().getFailedLoginDefaultUrl().isEmpty()) { failureHandler.setDefaultFailureUrl(samlConfigBean().getFailedLoginDefaultUrl()); } return failureHandler; } // Handler for successful logout @Bean public SimpleUrlLogoutSuccessHandler successLogoutHandler() { SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler(); successLogoutHandler.setDefaultTargetUrl(samlConfigBean().getSuccessLogoutUrl()); return successLogoutHandler; } // Authentication manager @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } // Register authentication manager for SAML provider @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(samlAuthenticationProvider); } // Logger for SAML messages and events @Bean public SAMLDefaultLogger samlLogger() { return new SAMLDefaultLogger(); } // Central storage of cryptographic keys @Bean public KeyManager keyManager() { return new JKSKeyManager(samlConfigBean().getKeystoreResource(), samlConfigBean().getKeystorePassword(), ImmutableMap.of(samlConfigBean().getKeystoreAlias(), samlConfigBean().getKeystorePrivateKeyPassword()), samlConfigBean().getKeystoreAlias()); } // IDP Discovery service @Bean public SAMLDiscovery samlIDPDiscovery() { return new SAMLDiscovery(); } // The filter is waiting for connections on URL suffixed with filterSuffix and presents SP metadata there @Bean public MetadataDisplayFilter metadataDisplayFilter() { return new MetadataDisplayFilter(); } // Configure HTTP Client to accept certificates from the keystore or from JDK cacerts for IDP SSL verification @Bean public TLSProtocolConfigurer tlsProtocolConfigurer() { // To perform IDP SSL verification against app keystore file, return `TLSProtocolConfigurer`. // Otherwise, return null so that it will try to find the IDP certs in JDK's cacerts. // // See https://stackoverflow.com/questions/28505824/spring-security-saml-https-to-another-page/28538799#28538799 return !samlConfigBean().getUseJdkCacertsForSslVerification() ? new TLSProtocolConfigurer() : null; } // Configure TLSProtocolConfigurer @Bean public ProtocolSocketFactory protocolSocketFactory() { return new TLSProtocolSocketFactory(keyManager(), null, "default"); } // Configure TLSProtocolConfigurer @Bean public Protocol protocol() { return new Protocol("https", protocolSocketFactory(), 443); } // Configure TLSProtocolConfigurer @Bean public MethodInvokingFactoryBean socketFactoryInitialization() { // Since it is not possible to return `null`, if app needs to perform SSL verification against JDK cacerts, // just set the protocol ID to anything but "http" or "https" so that it will be ignored. String protocolId = !samlConfigBean().getUseJdkCacertsForSslVerification() ? "https" : "ignored"; MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean(); methodInvokingFactoryBean.setTargetClass(Protocol.class); methodInvokingFactoryBean.setTargetMethod("registerProtocol"); methodInvokingFactoryBean.setArguments(protocolId, protocol()); return methodInvokingFactoryBean; } // IDP Metadata configuration - paths to metadata of IDPs in circle of trust is here @Bean public CachingMetadataManager metadata() throws MetadataProviderException { HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(new Timer(true), httpClient(), getMetdataUrl()); httpMetadataProvider.setParserPool(parserPool()); ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider); // Disable metadata trust check to prevent "Signature trust establishment failed for metadata entry" exception extendedMetadataDelegate.setMetadataTrustCheck(false); return new CachingMetadataManager(ImmutableList.<MetadataProvider>of(extendedMetadataDelegate)); } // SAML Authentication Provider responsible for validating of received SAML messages @Bean public SAMLAuthenticationProvider samlAuthenticationProvider() { SAMLAuthenticationProvider samlAuthenticationProvider = new SAMLAuthenticationProvider(); SAMLUserDetailsService samlUserDetailsService = samlConfigBean().getSamlUserDetailsService(); if (samlUserDetailsService != null) { samlAuthenticationProvider.setUserDetails(samlUserDetailsService); // By default, `principal` is always going to be `NameID` even though the `Authentication` object // contain `userDetails` object. So, if `userDetails` is provided, then don't force `principal` as // string so that `principal` represents `userDetails` object. // See: http://stackoverflow.com/questions/33786861/how-to-override-the-nameid-value-in-samlauthenticationprovider samlAuthenticationProvider.setForcePrincipalAsString(false); } return samlAuthenticationProvider; } // In order to get SAML to work for Sp servers doing SSL termination, `SAMLContextProviderLB` has // to be used instead of `SAMLContextProviderImpl` to prevent the following exception:- // // "SAML message intended destination endpoint 'https://server/app/saml/SSO' did not match the // recipient endpoint 'http://server/app/saml/SSO'" // // This configuration will work for Sp servers (not) doing SSL termination. @Bean public SAMLContextProviderLB contextProvider() { SAMLContextProviderLB contextProviderLB = new SAMLContextProviderLB(); contextProviderLB.setScheme("https"); contextProviderLB.setServerName(samlConfigBean().getSpServerName()); contextProviderLB.setServerPort(samlConfigBean().getSpHttpsPort()); contextProviderLB.setIncludeServerPortInRequestURL(samlConfigBean().getSpHttpsPort() != 443); contextProviderLB.setContextPath(samlConfigBean().getSpContextPath()); return contextProviderLB; } // Processing filter for WebSSO profile messages @Bean public SAMLProcessingFilter samlProcessingFilter() throws Exception { SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter(); samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager()); samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler()); samlWebSSOProcessingFilter.setAuthenticationFailureHandler(failureRedirectHandler()); return samlWebSSOProcessingFilter; } // Processing filter for WebSSO Holder-of-Key profile @Bean public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter() throws Exception { SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter = new SAMLWebSSOHoKProcessingFilter(); samlWebSSOHoKProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler()); samlWebSSOHoKProcessingFilter.setAuthenticationManager(authenticationManager()); samlWebSSOHoKProcessingFilter.setAuthenticationFailureHandler(failureRedirectHandler()); return samlWebSSOHoKProcessingFilter; } // Logout handler terminating local session @Bean public SecurityContextLogoutHandler logoutHandler() { SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler(); logoutHandler.setInvalidateHttpSession(true); logoutHandler.setClearAuthentication(true); return logoutHandler; } // Override default logout processing filter with the one processing SAML messages @Bean public SAMLLogoutFilter samlLogoutFilter() { return new SAMLLogoutFilter(successLogoutHandler(), new LogoutHandler[]{logoutHandler()}, new LogoutHandler[]{logoutHandler()}); } // Filter processing incoming logout messages // First argument determines URL user will be redirected to after successful global logout @Bean public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() { return new SAMLLogoutProcessingFilter(successLogoutHandler(), logoutHandler()); } // Class loading incoming SAML messages from httpRequest stream @Bean public SAMLProcessorImpl processor() { return new SAMLProcessorImpl(ImmutableList.<SAMLBinding>of(redirectDeflateBinding(), postBinding(), artifactBinding(), soapBinding(), paosBinding())); } // SAML 2.0 WebSSO Assertion Consumer @Bean public WebSSOProfileConsumer webSSOprofileConsumer() { return new WebSSOProfileConsumerImpl(); } // SAML 2.0 Holder-of-Key WebSSO Assertion Consumer @Bean public WebSSOProfileConsumerHoKImpl hokWebSSOprofileConsumer() { return new WebSSOProfileConsumerHoKImpl(); } // SAML 2.0 Web SSO profile @Bean public WebSSOProfile webSSOprofile() { return new WebSSOProfileImpl(); } // SAML 2.0 Holder-of-Key Web SSO profile @Bean public WebSSOProfileConsumerHoKImpl hokWebSSOProfile() { return new WebSSOProfileConsumerHoKImpl(); } // SAML 2.0 ECP profile @Bean public WebSSOProfileECPImpl ecpprofile() { return new WebSSOProfileECPImpl(); } // SAML 2.0 Logout profile @Bean public SingleLogoutProfile logoutprofile() { return new SingleLogoutProfileImpl(); } // Bindings, encoders and decoders used for creating and parsing messages @Bean public HTTPPostBinding postBinding() { return new HTTPPostBinding(parserPool(), velocityEngine()); } @Bean public HTTPRedirectDeflateBinding redirectDeflateBinding() { return new HTTPRedirectDeflateBinding(parserPool()); } @Bean public HTTPArtifactBinding artifactBinding() { ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(httpClient()); artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding())); return new HTTPArtifactBinding(parserPool(), velocityEngine(), artifactResolutionProfile); } @Bean public HTTPSOAP11Binding soapBinding() { return new HTTPSOAP11Binding(parserPool()); } @Bean public HTTPPAOS11Binding paosBinding() { return new HTTPPAOS11Binding(parserPool()); } // Initialization of the velocity engine @Bean public VelocityEngine velocityEngine() { return VelocityFactory.getEngine(); } // XML parser pool needed for OpenSAML parsing @Bean(initMethod = "initialize") public StaticBasicParserPool parserPool() { return new StaticBasicParserPool(); } @Bean public ParserPoolHolder parserPoolHolder() { return new ParserPoolHolder(); } }
/* * Copyright 2015 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. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.drools.compiler.reteoo.compiled; import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.core.base.ClassObjectType; import org.drools.core.base.ValueType; import org.drools.compiler.compiler.PackageRegistry; import org.drools.compiler.lang.descr.PackageDescr; import org.drools.core.reteoo.ObjectTypeNode; import org.drools.core.reteoo.compiled.AssertHandler; import org.drools.core.reteoo.compiled.CompiledNetwork; import org.drools.core.reteoo.compiled.DeclarationsHandler; import org.drools.core.reteoo.compiled.HashedAlphasDeclaration; import org.drools.core.reteoo.compiled.ObjectTypeNodeParser; import org.drools.core.reteoo.compiled.SetNodeReferenceHandler; import org.drools.compiler.rule.builder.dialect.java.JavaDialect; import org.drools.core.util.IoUtils; import java.util.Collection; /** * todo: document */ public class ObjectTypeNodeCompiler { private static final String NEWLINE = "\n"; private static final String PACKAGE_NAME = "org.drools.core.reteoo.compiled"; private static final String BINARY_PACKAGE_NAME = PACKAGE_NAME.replace('.', '/'); /** * This field hold the fully qualified class name that the {@link ObjectTypeNode} is representing. */ private String className; /** * This field will hold the "simple" name of the generated class */ private String generatedClassSimpleName; /** * OTN we are creating a compiled network for */ private ObjectTypeNode objectTypeNode; private StringBuilder builder = new StringBuilder(); private ObjectTypeNodeCompiler(ObjectTypeNode objectTypeNode) { this.objectTypeNode = objectTypeNode; ClassObjectType classObjectType = (ClassObjectType) objectTypeNode.getObjectType(); this.className = classObjectType.getClassName(); generatedClassSimpleName = "Compiled" + classObjectType.getClassName().replace('.', '_') + "Network"; } private String generateSource() { createClassDeclaration(); ObjectTypeNodeParser parser = new ObjectTypeNodeParser(objectTypeNode); // create declarations DeclarationsHandler declarations = new DeclarationsHandler(builder); parser.accept(declarations); // we need the hashed declarations when creating the constructor Collection<HashedAlphasDeclaration> hashedAlphaDeclarations = declarations.getHashedAlphaDeclarations(); createConstructor(hashedAlphaDeclarations); // create set node method SetNodeReferenceHandler setNode = new SetNodeReferenceHandler(builder); parser.accept(setNode); // create assert method AssertHandler assertHandler = new AssertHandler(builder, className, hashedAlphaDeclarations.size() > 0); parser.accept(assertHandler); // end of class builder.append("}").append(NEWLINE); return builder.toString(); } /** * This method will output the package statement, followed by the opening of the class declaration */ private void createClassDeclaration() { builder.append("package ").append(PACKAGE_NAME).append(";").append(NEWLINE); builder.append("public class ").append(generatedClassSimpleName).append(" extends "). append(CompiledNetwork.class.getName()).append("{ ").append(NEWLINE); } /** * Creates the constructor for the generated class. If the hashedAlphaDeclarations is empty, it will just * output a empty default constructor; if it is not, the constructor will contain code to fill the hash * alpha maps with the values and node ids. * * @param hashedAlphaDeclarations declarations used for creating statements to populate the hashed alpha * maps for the generate class */ private void createConstructor(Collection<HashedAlphasDeclaration> hashedAlphaDeclarations) { builder.append("public ").append(generatedClassSimpleName).append("() {").append(NEWLINE); // for each hashed alpha, we need to fill in the map member variable with the hashed values to node Ids for (HashedAlphasDeclaration declaration : hashedAlphaDeclarations) { String mapVariableName = declaration.getVariableName(); for (Object hashedValue : declaration.getHashedValues()) { Object value = hashedValue; // need to quote value if it is a string if (declaration.getValueType() == ValueType.STRING_TYPE) { value = "\"" + value + "\""; } String nodeId = declaration.getNodeId(hashedValue); // generate the map.put(hashedValue, nodeId) call builder.append(mapVariableName).append(".put(").append(value).append(", ").append(nodeId).append(");"); builder.append(NEWLINE); } } builder.append("}").append(NEWLINE); } /** * Returns the fully qualified name of the generated subclass of {@link CompiledNetwork} * * @return name of generated class */ private String getName() { return getPackageName() + "." + generatedClassSimpleName; } /** * Returns the fully qualified binary name of the generated subclass of {@link CompiledNetwork} * * @return binary name of generated class */ private String getBinaryName() { return BINARY_PACKAGE_NAME + "." + generatedClassSimpleName + ".class"; } private String getPackageName() { return PACKAGE_NAME; } /** * Creates a {@link CompiledNetwork} for the specified {@link ObjectTypeNode}. The {@link PackageBuilder} is used * to compile the generated source and load the class. * * @param kBuilder builder used to compile and load class * @param objectTypeNode OTN we are generating a compiled network for * @return CompiledNetwork */ public static CompiledNetwork compile(KnowledgeBuilderImpl kBuilder, ObjectTypeNode objectTypeNode) { if (objectTypeNode == null) { throw new IllegalArgumentException("ObjectTypeNode cannot be null!"); } if (kBuilder == null) { throw new IllegalArgumentException("PackageBuilder cannot be null!"); } ObjectTypeNodeCompiler compiler = new ObjectTypeNodeCompiler(objectTypeNode); String packageName = compiler.getPackageName(); PackageRegistry pkgReg = kBuilder.getPackageRegistry(packageName); if (pkgReg == null) { kBuilder.addPackage(new PackageDescr(packageName)); pkgReg = kBuilder.getPackageRegistry(packageName); } String source = compiler.generateSource(); String generatedSourceName = compiler.getName(); JavaDialect dialect = (JavaDialect) pkgReg.getDialectCompiletimeRegistry().getDialect("java"); dialect.addSrc(compiler.getBinaryName(), source.getBytes(IoUtils.UTF8_CHARSET)); kBuilder.compileAll(); kBuilder.updateResults(); CompiledNetwork network; try { network = (CompiledNetwork) Class.forName(generatedSourceName, true, kBuilder.getRootClassLoader()).newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException("This is a bug. Please contact the development team", e); } catch (IllegalAccessException e) { throw new RuntimeException("This is a bug. Please contact the development team", e); } catch (InstantiationException e) { throw new RuntimeException("This is a bug. Please contact the development team", e); } return network; } }
package com.ctrip.zeus.logstats.analyzer.nginx; import com.ctrip.zeus.LogFormat; import com.ctrip.zeus.logstats.StatsDelegate; import com.ctrip.zeus.logstats.analyzer.LogStatsAnalyzer; import com.ctrip.zeus.logstats.analyzer.LogStatsAnalyzerConfig; import com.ctrip.zeus.logstats.common.AccessLogStateMachineFormat; import com.ctrip.zeus.logstats.common.LineFormat; import com.ctrip.zeus.logstats.parser.AccessLogStateMachineParser; import com.ctrip.zeus.logstats.parser.KeyValue; import com.ctrip.zeus.logstats.parser.LogParser; import com.ctrip.zeus.logstats.tracker.AccessLogTracker; import com.ctrip.zeus.logstats.tracker.LogTracker; import com.ctrip.zeus.logstats.tracker.LogTrackerStrategy; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by zhoumy on 2015/11/16. */ public class AccessLogStatsAnalyzer implements LogStatsAnalyzer { private static final String AccessLogFormat = LogFormat.getMainCompactString(); private static final String AccessLogSeparator = LogFormat.getSeparator(); private final LogStatsAnalyzerConfig config; private final LogTracker logTracker; private final LogParser logParser; private final AtomicBoolean running = new AtomicBoolean(false); private AccessLogConsumers consumers; public AccessLogStatsAnalyzer() { this(new LogStatsAnalyzerConfigBuilder() .isStartFromHead(false) .setDefaultLogFormat(new AccessLogStateMachineFormat(LogFormat.getDefaultMainCompactString(), LogFormat.getDefaultSeparator()).generate()) .addLogFormat(new AccessLogStateMachineFormat(AccessLogFormat, AccessLogSeparator).generate()) .setLogFilename("/opt/logs/nginx/access.log") .setReadBufferSize(1024 * 5) .build()); } public AccessLogStatsAnalyzer(LogStatsAnalyzerConfig config) { this.config = config; logTracker = config.getLogTracker(); logParser = new AccessLogStateMachineParser(config.getDefaultLineFormat(),config.getLineFormats()); if (config.allowDelegate()) { consumers = new AccessLogConsumers(this, logParser, config.getNumberOfConsumers()); } } @Override public LogStatsAnalyzerConfig getConfig() { return config; } @Override public void start() throws IOException { logTracker.start(); if (consumers != null) { consumers.start(); } running.set(true); } @Override public void stop() throws IOException { if (running.compareAndSet(true, false)) { if (consumers != null) { consumers.shutDown(); } logTracker.stop(); } } @Override public boolean reachFileEnd() throws IOException { if (running.get()) return logTracker.reachFileEnd(); return true; } @Override public void run() throws IOException { logTracker.fastMove(new StatsDelegate<String>() { @Override public void delegate(String input) { if (running.get()) { if (consumers != null) { consumers.accept(input); } } } @Override public void delegate(String raw, String input) { } }); } @Override public String analyze() throws IOException { if (running.get()) { String raw = logTracker.move(); return logParser.parseToJsonString(raw); } else { return ""; } } public static class LogStatsAnalyzerConfigBuilder { private List<LineFormat> logFormats = new ArrayList<>(); private LineFormat logFormat; private String logFilename; private boolean startFromHead; private Boolean dropOnFileChange; private int readBufferSize = 5; private StatsDelegate statsDelegator; private int numberOfConsumers = 2; private boolean allowTracking; private String trackingFilename; public LogStatsAnalyzerConfigBuilder setLogFilename(String logFilename) { this.logFilename = logFilename; return this; } public LogStatsAnalyzerConfigBuilder setDefaultLogFormat(LineFormat logFormat) { this.logFormat = logFormat; return this; } public LogStatsAnalyzerConfigBuilder addLogFormat(LineFormat logFormat) { this.logFormats.add(logFormat); return this; } public LogStatsAnalyzerConfigBuilder setReadBufferSize(int size) { this.readBufferSize = size; return this; } public LogStatsAnalyzerConfigBuilder allowTracking(String trackingFilename) { this.allowTracking = true; this.trackingFilename = trackingFilename; return this; } public LogStatsAnalyzerConfigBuilder isStartFromHead(boolean startFromHead) { this.startFromHead = startFromHead; return this; } public LogStatsAnalyzerConfigBuilder registerLogStatsDelegator(StatsDelegate<List<KeyValue>> statsDelegator) { this.statsDelegator = statsDelegator; return this; } public LogStatsAnalyzerConfigBuilder setNumberOfConsumers(int count) { this.numberOfConsumers = count; return this; } public LogStatsAnalyzerConfigBuilder isDropOnFileChange(boolean dropOnFileChange) { this.dropOnFileChange = dropOnFileChange; return this; } public LogStatsAnalyzerConfig build() { File f = new File(logFilename); String rootDir = f.getAbsoluteFile().getParentFile().getAbsolutePath(); LogTrackerStrategy strategy = new LogTrackerStrategy() .setLogFilename(logFilename) .setAllowLogRotate(true, LogTrackerStrategy.LOGROTATE_RENAME) .setReadBufferSize(readBufferSize) .setStartMode(startFromHead ? LogTrackerStrategy.START_FROM_HEAD : LogTrackerStrategy.START_FROM_CURRENT) .setAllowTrackerMemo(allowTracking) .setTrackerMemoFilename(allowTracking ? rootDir + "/" + trackingFilename : null) .setDoAsRoot(true); if (dropOnFileChange != null) { strategy.isDropOnFileChange(dropOnFileChange); } List<StatsDelegate> delegatorRegistry = new ArrayList<>(); delegatorRegistry.add(statsDelegator); LogStatsAnalyzerConfig config = new LogStatsAnalyzerConfig(delegatorRegistry) .setNumberOfConsumers(numberOfConsumers) .setLogTracker(new AccessLogTracker(strategy)); config.getLineFormats().addAll(logFormats); config.setDefaultLineFormat(logFormat); return config; } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Robin Chutaux * * 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.xiaozhi.beautygallery.view; import com.xiaozhi.beautygallery.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.os.Handler; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ListView; import android.widget.RelativeLayout; /** * Author : Chutaux Robin Date : 10/8/2014 */ public class RippleView extends RelativeLayout { private int WIDTH; private int HEIGHT; private int FRAME_RATE = 10; private int DURATION = 400; private int PAINT_ALPHA = 90; private Handler canvasHandler; private float radiusMax = 0; private boolean animationRunning = false; private int timer = 0; private int timerEmpty = 0; private int durationEmpty = -1; private float x = -1; private float y = -1; private int zoomDuration; private float zoomScale; private ScaleAnimation scaleAnimation; private Boolean hasToZoom; private Boolean isCentered; private Integer rippleType; private Paint paint; private Bitmap originBitmap; private int rippleColor; private int ripplePadding; private GestureDetector gestureDetector; private final Runnable runnable = new Runnable() { @Override public void run() { invalidate(); } }; public RippleView(Context context) { super(context); } public RippleView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public RippleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } private void init(final Context context, final AttributeSet attrs) { if (isInEditMode()) return; final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RippleView); rippleColor = typedArray.getColor(R.styleable.RippleView_rv_color, getResources().getColor(R.color.rippelColor)); rippleType = typedArray.getInt(R.styleable.RippleView_rv_type, 0); hasToZoom = typedArray .getBoolean(R.styleable.RippleView_rv_zoom, false); isCentered = typedArray.getBoolean(R.styleable.RippleView_rv_centered, false); DURATION = typedArray.getInteger( R.styleable.RippleView_rv_rippleDuration, DURATION); FRAME_RATE = typedArray.getInteger(R.styleable.RippleView_rv_framerate, FRAME_RATE); PAINT_ALPHA = typedArray.getInteger(R.styleable.RippleView_rv_alpha, PAINT_ALPHA); ripplePadding = typedArray.getDimensionPixelSize( R.styleable.RippleView_rv_ripplePadding, 0); canvasHandler = new Handler(); zoomScale = typedArray.getFloat(R.styleable.RippleView_rv_zoomScale, 1.03f); zoomDuration = typedArray.getInt( R.styleable.RippleView_rv_zoomDuration, 200); typedArray.recycle(); paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); paint.setColor(rippleColor); paint.setAlpha(PAINT_ALPHA); this.setWillNotDraw(false); gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public void onLongPress(MotionEvent event) { super.onLongPress(event); animateRipple(event); sendClickEvent(true); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { return true; } @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }); this.setDrawingCacheEnabled(true); this.setClickable(true); } @Override public void draw(@NonNull Canvas canvas) { super.draw(canvas); if (animationRunning) { if (DURATION <= timer * FRAME_RATE) { animationRunning = false; timer = 0; durationEmpty = -1; timerEmpty = 0; canvas.restore(); invalidate(); return; } else canvasHandler.postDelayed(runnable, FRAME_RATE); if (timer == 0) canvas.save(); canvas.drawCircle(x, y, (radiusMax * (((float) timer * FRAME_RATE) / DURATION)), paint); paint.setColor(Color.parseColor("#ffff4444")); if (rippleType == 1 && originBitmap != null && (((float) timer * FRAME_RATE) / DURATION) > 0.4f) { if (durationEmpty == -1) durationEmpty = DURATION - timer * FRAME_RATE; timerEmpty++; final Bitmap tmpBitmap = getCircleBitmap((int) ((radiusMax) * (((float) timerEmpty * FRAME_RATE) / (durationEmpty)))); canvas.drawBitmap(tmpBitmap, 0, 0, paint); tmpBitmap.recycle(); } paint.setColor(rippleColor); if (rippleType == 1) { if ((((float) timer * FRAME_RATE) / DURATION) > 0.6f) paint.setAlpha((int) (PAINT_ALPHA - ((PAINT_ALPHA) * (((float) timerEmpty * FRAME_RATE) / (durationEmpty))))); else paint.setAlpha(PAINT_ALPHA); } else paint.setAlpha((int) (PAINT_ALPHA - ((PAINT_ALPHA) * (((float) timer * FRAME_RATE) / DURATION)))); timer++; } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); WIDTH = w; HEIGHT = h; scaleAnimation = new ScaleAnimation(1.0f, zoomScale, 1.0f, zoomScale, w / 2, h / 2); scaleAnimation.setDuration(zoomDuration); scaleAnimation.setRepeatMode(Animation.REVERSE); scaleAnimation.setRepeatCount(1); } public void animateRipple(MotionEvent event) { createAnimation(event.getX(), event.getY()); } public void animateRipple(final float x, final float y) { createAnimation(x, y); } private void createAnimation(final float x, final float y) { if (!animationRunning) { if (hasToZoom) this.startAnimation(scaleAnimation); radiusMax = Math.max(WIDTH, HEIGHT); if (rippleType != 2) radiusMax /= 2; radiusMax -= ripplePadding; if (isCentered || rippleType == 1) { this.x = getMeasuredWidth() / 2; this.y = getMeasuredHeight() / 2; } else { this.x = x; this.y = y; } animationRunning = true; if (rippleType == 1 && originBitmap == null) originBitmap = getDrawingCache(true); invalidate(); } } @Override public boolean onTouchEvent(@NonNull MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { animateRipple(event); sendClickEvent(false); } return super.onTouchEvent(event); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { this.onTouchEvent(event); return super.onInterceptTouchEvent(event); } private void sendClickEvent(final Boolean isLongClick) { if (getParent() instanceof ListView) { final int position = ((ListView) getParent()) .getPositionForView(this); final long id = ((ListView) getParent()) .getItemIdAtPosition(position); if (isLongClick) { if (((ListView) getParent()).getOnItemLongClickListener() != null) ((ListView) getParent()).getOnItemLongClickListener() .onItemLongClick(((ListView) getParent()), this, position, id); } else { if (((ListView) getParent()).getOnItemClickListener() != null) ((ListView) getParent()).getOnItemClickListener() .onItemClick(((ListView) getParent()), this, position, id); } } } private Bitmap getCircleBitmap(final int radius) { final Bitmap output = Bitmap.createBitmap(originBitmap.getWidth(), originBitmap.getHeight(), Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect((int) (x - radius), (int) (y - radius), (int) (x + radius), (int) (y + radius)); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawCircle(x, y, radius, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(originBitmap, rect, rect, paint); return output; } public void setRippleColor(int rippleColor) { this.rippleColor = rippleColor; } public int getRippleColor() { return rippleColor; } }
/* * Copyright (C) 2012 Red Hat, 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.commonjava.maven.ext.core.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Component that reads a version string and makes various modifications to it such as converting to a valid OSGi * version string and/or incrementing a version suffix. See: http://www.aqute.biz/Bnd/Versioning for an explanation of * OSGi versioning. Parses versions into the following format: &lt;major&gt;.&lt;minor&gt;.&lt;micro&gt; * .&lt;qualifierBase&gt;-&lt;buildnumber&gt;-&lt;buildnumber&gt;-&lt;snapshot&gt; */ @SuppressWarnings("WeakerAccess") // Public API. public class Version { private static final Logger logger = LoggerFactory.getLogger( Version.class ); private final static String EMPTY_STRING = ""; private final static Character[] DEFAULT_DELIMITERS = {'.', '-', '_'}; private final static String OSGI_VERSION_DELIMITER = "."; private final static String OSGI_QUALIFIER_DELIMITER = "-"; private final static String DEFAULT_DELIMITER = "."; /** * The default delimiter between the different parts of the qualifier */ private final static String DEFAULT_QUALIFIER_DELIMITER = "-"; private final static List<Character> versionStringDelimiters = Arrays.asList( DEFAULT_DELIMITERS ); /** * Regular expression used to match version string delimiters */ private final static String DELIMITER_REGEX = "[.\\-_]"; /** * Regular expression used to match version string delimiters */ private final static String LEADING_DELIMITER_REGEX = "^" + DELIMITER_REGEX; /** * Regular expression used to match the major, minor, and micro versions */ private final static String MMM_REGEX = "(\\d+)(" + DELIMITER_REGEX + "(\\d+)(" + DELIMITER_REGEX + "(\\d+))?)?"; private final static Pattern mmmPattern = Pattern.compile(MMM_REGEX); private final static String SNAPSHOT_SUFFIX = "SNAPSHOT"; private final static String SNAPSHOT_REGEX = "(.*?)((" + DELIMITER_REGEX + ")?((?i:" + SNAPSHOT_SUFFIX + ")))$"; private final static Pattern snapshotPattern = Pattern.compile(SNAPSHOT_REGEX); /** * Regular expression used to match the parts of the qualifier "base-buildnum-snapshot" * Note : Technically within the rebuild-numeric the dash is currently optional and can be any * delimeter type within the regex. It could be made mandatory via '{1}'. */ private final static String QUALIFIER_REGEX = "(.*?)((" + DELIMITER_REGEX + ")?(\\d+))?((" + DELIMITER_REGEX + ")?((?i:" + SNAPSHOT_SUFFIX + ")))?$"; private final static Pattern qualifierPattern = Pattern.compile(QUALIFIER_REGEX); /** * Version string must start with a digit to match the regex. Otherwise we have only a * qualifier. */ private final static String VERSION_REGEX = "(" + MMM_REGEX + ")" + "((" + DELIMITER_REGEX + ")?" + "(" + QUALIFIER_REGEX + "))"; private final static Pattern versionPattern = Pattern.compile(VERSION_REGEX); /** * Used to match valid OSGi version based on section 3.2.5 of the OSGi specification */ private final static String OSGI_VERSION_REGEX = "(\\d+)(\\.\\d+(\\.\\d+(\\.[\\w\\-_]+)?)?)?"; private final static Pattern osgiPattern = Pattern.compile(OSGI_VERSION_REGEX); public static final String PROJECT_VERSION = "${project.version}"; // Prevent construction. private Version () {} public static String getBuildNumber(String version) { Matcher qualifierMatcher = qualifierPattern.matcher( getQualifier( version ) ); if( qualifierMatcher.matches() && !isEmpty( qualifierMatcher.group( 4 ) ) ) { return qualifierMatcher.group( 4 ); } return EMPTY_STRING; } /** * This function will examine the set of known versions and, assuming there is no forced * incrementalSerialSuffixPadding override, locate the padding to apply to the new version. * This allows us to maintain any existing padding transparently. * * @param incrementalSerialSuffixPadding if there is an explicit padding override. * @param versions the candidate versions to examine. * @return the amount of padding (indexed from 1) to apply. */ public static int getBuildNumberPadding( int incrementalSerialSuffixPadding, Set<String> versions ) { int result = incrementalSerialSuffixPadding; // Serial padding has not been explicitly defined so determine current padding to preserve. if ( result == 0 ) { result = getBuildNumber( versions.stream().max( Comparator.comparing( v -> getBuildNumber( v ).length() ) ).orElse("") ).length(); } logger.debug( "Returning padding of {}", result ); return result; } /** * Returns the initial numeric portion (which may be up to 3 digits long) excluding * any delimeter suffix. * @param version the version to examine * @return a parsed string version. */ public static String getMMM(String version) { Matcher versionMatcher = versionPattern.matcher( version ); if ( versionMatcher.matches() ) { return versionMatcher.group( 1 ); } return EMPTY_STRING; } /** * Get the major, minor, micro version in OSGi format * * @param version The version to parse * @param fill Whether to fill the minor and micro versions with zeros if they are missing * @return OSGi formatted major, minor, micro */ static String getOsgiMMM(String version, boolean fill) { String mmm = getMMM( version ); Matcher mmmMatcher = mmmPattern.matcher( mmm ); if ( mmmMatcher.matches() ) { String osgiMMM = mmmMatcher.group( 1 ); String minorVersion = mmmMatcher.group( 3 ); if ( !isEmpty( minorVersion ) ) { osgiMMM += OSGI_VERSION_DELIMITER + minorVersion; } else if ( fill ) { osgiMMM += OSGI_VERSION_DELIMITER + "0"; } String microVersion = mmmMatcher.group( 5 ); if ( !isEmpty( microVersion ) ) { osgiMMM += OSGI_VERSION_DELIMITER + microVersion; } else if ( fill ) { osgiMMM += OSGI_VERSION_DELIMITER + "0"; } return osgiMMM; } return EMPTY_STRING; } public static String getOsgiVersion(String version) { String qualifier = getQualifier( version ); if ( !isEmpty( qualifier ) ) { qualifier = OSGI_VERSION_DELIMITER + qualifier.replace( OSGI_VERSION_DELIMITER, OSGI_QUALIFIER_DELIMITER ); } String mmm = getOsgiMMM( version, !isEmpty( qualifier ) ); if ( isEmpty( mmm ) ) { logger.warn( "Unable to parse version for OSGi: {}", version ); return version; } return mmm + qualifier; } public static String getQualifier(String version) { Matcher versionMatcher = versionPattern.matcher( version ); if ( versionMatcher.matches() ) { return versionMatcher.group( 9 ); } return removeLeadingDelimiter( version ); } /** * This will return the OSGi qualifier portion without the numeric rebuild increment. * For example * * <blockquote><table> * <caption>Version conversion</caption> * <tr> * <th>Version</th><th>Qualifier</th> * </tr> * <tr><td>1.0.0.Beta1</td><td>Beta1</td> * <tr><td>1.0.0.Beta10-rebuild-1</td><td>Beta10-rebuild</td> * <tr><td>1.0.0.GA-rebuild1</td><td>GA-rebuild</td> * <tr><td>1.0.0.Final-Beta-1</td><td>Final-Beta</td> * </tr> * </table></blockquote> * * @param version a {@code String} to parse * @return the qualifier */ public static String getQualifierBase(String version) { Matcher versionMatcher = versionPattern.matcher( version ); if ( versionMatcher.matches() ) { return versionMatcher.group( 10 ); } Matcher qualifierMatcher = qualifierPattern.matcher( version ); if ( qualifierMatcher.matches() ) { return qualifierMatcher.group( 1 ); } return removeLeadingDelimiter( version ); } public static String getQualifierWithDelim(String version) { Matcher versionMatcher = versionPattern.matcher( version ); if ( versionMatcher.matches() ) { return versionMatcher.group( 7 ); } return version; } public static String getSnapshot( String version ) { Matcher snapshotMatcher = snapshotPattern.matcher( version ); if ( snapshotMatcher.matches() ) { return snapshotMatcher.group(4); } return EMPTY_STRING; } public static String getSnapshotWithDelim( String version ) { Matcher snapshotMatcher = snapshotPattern.matcher( version ); if ( snapshotMatcher.matches() ) { return snapshotMatcher.group(2); } return EMPTY_STRING; } public static boolean hasBuildNumber( String version ) { return !isEmpty( getBuildNumber( version ) ); } public static boolean hasQualifier( String version ) { return !isEmpty( getQualifier( version ) ); } public static boolean isEmpty( String string ) { return ( string == null || EMPTY_STRING.equals( string.trim() ) ); } public static boolean isSnapshot( String version ) { Matcher snapshotMatcher = snapshotPattern.matcher( version ); return snapshotMatcher.matches(); } /** * Checks if the string is a valid version according to section 3.2.5 of the OSGi specification * * @param version the version * @return true if the version is valid */ public static boolean isValidOSGi(String version) { return osgiPattern.matcher( version ).matches(); } /** * Remove the build number (and associated delimiter) portion of the version string. * * @param version the version * @return the version with the build number portion removed */ public static String removeBuildNumber( String version ) { Matcher qualifierMatcher = qualifierPattern.matcher( version ); if ( qualifierMatcher.matches() ) { return qualifierMatcher.replaceFirst( "$1$5" ); } return version; } /** * Remove the snapshot (and associated delimiter) portion of the version string. * Converts something like "1.0-SNAPSHOT" to "1.0". * * @param version the version * @return the version with the snapshot portion removed */ public static String removeSnapshot( String version ) { Matcher snapshotMatcher = snapshotPattern.matcher( version ); if ( snapshotMatcher.matches() ) { return snapshotMatcher.group(1); } return version; } private static boolean hasLeadingDelimiter( String versionPart ) { if ( versionPart.length() < 1 ) { return false; } return versionStringDelimiters.contains( versionPart.charAt( 0 ) ); } /** * Remove any leading delimiters from the partial version string. * * @param versionPart the partial version * @return the partial version with any leading delimiters removed */ static String removeLeadingDelimiter( String versionPart ) { return versionPart.replaceAll(LEADING_DELIMITER_REGEX, ""); } /** * Prepends the given delimiter only if the versionPart does not already start with a delimiter. * * @param versionPart the partial version * @param delimiter the delimiter * @return the partial version with the delimiter prepended (if necessary) */ private static String prependDelimiter( String versionPart, String delimiter ) { if ( hasLeadingDelimiter( versionPart ) ) { return versionPart; } return delimiter + versionPart; } /** * Check if all the characters in the string are digits * * @param str a string to check * @return whether all the characters in the string are digits */ private static boolean isNumeric( String str ) { for ( char c : str.toCharArray() ) { if ( !Character.isDigit( c ) ) return false; } return true; } /** * Appends the given qualifier suffix. Attempts to match the given qualifier suffix to the current suffix * to avoid duplicates like "1.0-beta-beta. If the suffix matches the existing one, does nothing. * * @param version the version * @param suffix The qualifier suffix to append. This can be a simple string like "foo", or it can optionally * include a build number, for example "foo-1", which will automatically be set as the build number for * this version. * @return the version with the qualifier suffix appended (if necessary) */ public static String appendQualifierSuffix( final String version, final String suffix ) { logger.debug( "Applying suffix: {} to version {}", suffix, version ); if ( isEmpty( suffix ) ) { return version; } if ( isEmpty( getQualifier( version ) ) ) { return version + prependDelimiter( suffix, DEFAULT_DELIMITER); } Matcher suffixMatcher = createSuffixMatcher( version, suffix ); if ( suffixMatcher.matches() ) { return version; } final String suffixWoSnapshot = removeSnapshot( suffix ); final String suffixBuildNumber = getBuildNumber( suffix ); final String suffixWoBuildNumber = removeBuildNumber( suffixWoSnapshot ); final String suffixWoBuildNumDelim = removeLeadingDelimiter( suffixWoBuildNumber ); Matcher suffixWoDelimMatcher = createSuffixMatcher( version, suffixWoBuildNumDelim ); if (suffixWoDelimMatcher.matches()) { String newVersion = suffixWoDelimMatcher.replaceFirst("$1$2" + suffixWoBuildNumber + "$4$7"); if ( hasLeadingDelimiter( suffix ) ) { newVersion = suffixWoDelimMatcher.replaceFirst("$1" + suffixWoBuildNumber + "$4$7"); } if ( !isEmpty( suffixBuildNumber ) ) { newVersion = setBuildNumber( newVersion, suffixBuildNumber ); } if ( isSnapshot( suffix ) ) { newVersion = setSnapshot( newVersion, true ); } return newVersion; } Matcher qualifierMatcher = qualifierPattern.matcher( version ); if ( qualifierMatcher.matches() ) { if ( hasLeadingDelimiter( suffixWoSnapshot ) ) { String newVersion = qualifierMatcher.replaceFirst( "$1$3$4" + suffixWoSnapshot + "$5"); if ( isSnapshot( suffix ) ) { newVersion = Version.setSnapshot( newVersion, true ); } return newVersion; } String delimiter = DEFAULT_QUALIFIER_DELIMITER; if ( isEmpty( getQualifierBase( version ) ) ) { delimiter = DEFAULT_DELIMITER; } String newVersion = qualifierMatcher.replaceFirst( "$1$3$4" + delimiter + suffixWoSnapshot + "$5"); if ( isSnapshot( suffix ) ) { newVersion = Version.setSnapshot( newVersion, true ); } return newVersion; } return version; } private static Matcher createSuffixMatcher( String version, String suffix ) { final String SUFFIX_REGEX = "(.*?)(" + DELIMITER_REGEX + ")?(" + suffix + ")((" + DELIMITER_REGEX + ")?(\\d+))?((" + DELIMITER_REGEX + ")?((?i:" + SNAPSHOT_SUFFIX + ")))?$"; return Pattern.compile( SUFFIX_REGEX ).matcher( version ); } /** * Appends a build number to the qualifier. The build number should be a string of digits, or null if the build * number should be removed. * * @param version the version * @param buildNumber the build number to append to the qualifier * @return the version with the build number appended (if necessary) */ public static String setBuildNumber( String version, String buildNumber ) { if ( !isNumeric( buildNumber ) ) { logger.warn("Failed attempt to set non-numeric build number '{}' for version '{}'", buildNumber, version); return version; } if ( isEmpty( buildNumber ) ) { buildNumber = EMPTY_STRING; } if ( isEmpty( getQualifier( version ) ) ) { return version + DEFAULT_DELIMITER + buildNumber; } Matcher qualifierMatcher = qualifierPattern.matcher( version ); if ( qualifierMatcher.matches() ) { if ( isEmpty( qualifierMatcher.group( 2 ) ) ) { buildNumber = prependDelimiter( buildNumber, DEFAULT_QUALIFIER_DELIMITER ); } return qualifierMatcher.replaceFirst( "$1$3" + buildNumber + "$5" ); } return version; } /** * Appends the "SNAPSHOT" suffix to this version if not already present * * @param version the version to modify * @param snapshot set to true if the version should be a snapshot, false otherwise * @return the updated version string */ public static String setSnapshot( String version, boolean snapshot ) { if ( isEmpty( version ) ) { return EMPTY_STRING; } if ( isSnapshot( version ) == snapshot ) { return version; } else if ( snapshot ) { return (version + DEFAULT_QUALIFIER_DELIMITER + SNAPSHOT_SUFFIX); } else { return removeSnapshot( version ); } } /** * Matches a version object to versions in a set by comparing the non build number portion of the string. Then find * which of the matching versions has the highest build number and is therefore the latest version. * * @param version the Version object to use * @param versionSet a collection of versions to compare to * @return the highest build number, or 0 if no matching build numbers are found. */ public static int findHighestMatchingBuildNumber( String version, Set<String> versionSet ) { int highestBuildNum = 0; String osgiVersion = getOsgiVersion( version ); String qualifier = getQualifier( osgiVersion ); Matcher qualifierMatcher = qualifierPattern.matcher( qualifier ); if ( qualifierMatcher.matches() ) { qualifier = removeLeadingDelimiter( qualifierMatcher.group( 1 ) ); } // Build version pattern regex, matches something like "<mmm>.<qualifier>.<buildnum>". StringBuilder versionPatternBuf = new StringBuilder(); versionPatternBuf.append( '(' ) .append( Pattern.quote( getMMM( version ) ) ).append('(').append( DELIMITER_REGEX ).append("0)*") // Match zeros appended to a major only version .append( ")?" ) .append( DELIMITER_REGEX ); if ( !isEmpty( qualifier ) ) { versionPatternBuf.append( Pattern.quote( qualifier ) ); versionPatternBuf.append( DELIMITER_REGEX ); } versionPatternBuf.append( "(\\d+)" ); String candidatePatternStr = versionPatternBuf.toString(); logger.debug( "Using pattern: '{}' to find compatible versions from metadata.", candidatePatternStr ); final Pattern candidateSuffixPattern = Pattern.compile( candidatePatternStr ); for ( final String compareVersion : versionSet ) { final Matcher candidateSuffixMatcher = candidateSuffixPattern.matcher( compareVersion ); if ( candidateSuffixMatcher.matches() ) { String buildNumberStr = candidateSuffixMatcher.group( 3 ); int compareBuildNum = Integer.parseInt( buildNumberStr ); if ( compareBuildNum > highestBuildNum ) { highestBuildNum = compareBuildNum; } } } logger.debug ("Found highest matching build number {} from set {}", highestBuildNum, versionSet); return highestBuildNum; } /** * Get the build number as an integer instead of a string for each numeric comparison. * * @param version the version * @return the build number as an integer. */ public static int getIntegerBuildNumber( String version ) { String buildNumber = getBuildNumber( version ); if ( isEmpty( buildNumber ) ) { return 0; } try { return Integer.parseInt( buildNumber ); } catch(NumberFormatException e) { return 0; } } }
/* * Copyright 2016 Space Dynamics Laboratory - Utah State University Research 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 edu.usu.sdl.openstorefront.core.spi.parser.mapper; import org.apache.commons.lang3.StringUtils; /** * * @author dshurtleff */ public enum StringTransforms implements DataTransform<String> { UPPERCASE("Uppercase"){ @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { return input.toUpperCase(); } else { return input; } } }, LOWERCASE("Lowercase"){ @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { return input.toLowerCase(); } else { return input; } } }, TRIM("Trim"){ @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { return input.trim(); } else { return input; } } }, BOLD("Bold"){ @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { return "<b>" + input + "</b>"; } else { return input; } } }, REMOVEUNDERSCORE("Remove Underscore") { @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { return input.replace("_", ""); } else { return input; } } }, TRANSLATEESCAPES("Translate escaped characters"){ @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { input = input.replace("x0020", " "); input = input.replace("x0028", "("); input = input.replace("x0029", ")"); input = input.replace("x002F", "/"); input = input.replace("x005E", "^"); input = input.replace("x007C", "|"); input = input.replace("x007B", "{"); input = input.replace("x007D", "}"); input = input.replace("x007E", "~"); input = input.replace("x0060", "`"); input = input.replace("x0025", "%"); input = input.replace("x0026", "&"); input = input.replace("x0023", "#"); input = input.replace("x0040", "@"); return input; } else { return input; } } }, TRANSLATEHTMLESCAPES("Translate HTML escaped characters"){ @Override public String transform(String input) { if (StringUtils.isNotBlank(input)) { input = input.replace("&gt;", ">"); input = input.replace("&amp;#58;", "://"); input = input.replace("&amp;", "&"); return input; } else { return input; } } }, SPLITLASTUNDERSCORE("Split Last Underscore"){ @Override public String transform(String input) { return StringTransforms.splitLast(input, "_"); } }, SPLITLASTDASH("Split Last Dash"){ @Override public String transform(String input) { return StringTransforms.splitLast(input, "-"); } }, SPLITLASTSPACE("Split Last Space"){ @Override public String transform(String input) { return StringTransforms.splitLast(input, " "); } }, SPLITLASTDOT("Split Last Dot"){ @Override public String transform(String input) { return StringTransforms.splitLast(input, "\\."); } }, SPLITLASTCOMMA("Split Last Comma"){ @Override public String transform(String input) { return StringTransforms.splitLast(input, ","); } }; private static String splitLast(String input, String splitChar) { if (StringUtils.isNotBlank(input)) { String data[] = input.split(splitChar); return data[data.length-1]; } else { return input; } } private String description; private StringTransforms(String description) { this.description = description; } public String getDescription() { return description; } }