text
stringlengths
7
1.01M
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ package org.springframework.beans.factory.support; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Utility methods that are useful for bean definition reader implementations. * Mainly intended for internal use. * * @author Juergen Hoeller * @author Rob Harrop * @since 1.1 * @see PropertiesBeanDefinitionReader * @see org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader */ public abstract class BeanDefinitionReaderUtils { /** * Separator for generated bean names. If a class name or parent name is not * unique, "#1", "#2" etc will be appended, until the name becomes unique. */ public static final String GENERATED_BEAN_NAME_SEPARATOR = BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR; /** * Create a new GenericBeanDefinition for the given parent name and class name, * eagerly loading the bean class if a ClassLoader has been specified. * @param parentName the name of the parent bean, if any * @param className the name of the bean class, if any * @param classLoader the ClassLoader to use for loading bean classes * (can be {@code null} to just register bean classes by name) * @return the bean definition * @throws ClassNotFoundException if the bean class could not be loaded */ public static AbstractBeanDefinition createBeanDefinition( @Nullable String parentName, @Nullable String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException { GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setParentName(parentName); if (className != null) { if (classLoader != null) { bd.setBeanClass(ClassUtils.forName(className, classLoader)); } else { bd.setBeanClassName(className); } } return bd; } /** * Generate a bean name for the given top-level bean definition, * unique within the given bean factory. * @param beanDefinition the bean definition to generate a bean name for * @param registry the bean factory that the definition is going to be * registered with (to check for existing bean names) * @return the generated bean name * @throws BeanDefinitionStoreException if no unique name can be generated * for the given bean definition * @see #generateBeanName(BeanDefinition, BeanDefinitionRegistry, boolean) */ public static String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { return generateBeanName(beanDefinition, registry, false); } /** * Generate a bean name for the given bean definition, unique within the * given bean factory. * @param definition the bean definition to generate a bean name for * @param registry the bean factory that the definition is going to be * registered with (to check for existing bean names) * @param isInnerBean whether the given bean definition will be registered * as inner bean or as top-level bean (allowing for special name generation * for inner beans versus top-level beans) * @return the generated bean name * @throws BeanDefinitionStoreException if no unique name can be generated * for the given bean definition */ public static String generateBeanName( BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean) throws BeanDefinitionStoreException { String generatedBeanName = definition.getBeanClassName(); if (generatedBeanName == null) { if (definition.getParentName() != null) { generatedBeanName = definition.getParentName() + "$child"; } else if (definition.getFactoryBeanName() != null) { generatedBeanName = definition.getFactoryBeanName() + "$created"; } } if (!StringUtils.hasText(generatedBeanName)) { throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " + "'class' nor 'parent' nor 'factory-bean' - can't generate bean name"); } String id = generatedBeanName; if (isInnerBean) { // Inner bean: generate identity hashcode suffix. id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition); } else { // Top-level bean: use plain class name with unique suffix if necessary. return uniqueBeanName(generatedBeanName, registry); } return id; } /** * Turn the given bean name into a unique bean name for the given bean factory, * appending a unique counter as suffix if necessary. * @param beanName the original bean name * @param registry the bean factory that the definition is going to be * registered with (to check for existing bean names) * @return the unique bean name to use * @since 5.1 */ public static String uniqueBeanName(String beanName, BeanDefinitionRegistry registry) { String id = beanName; int counter = -1; // Increase counter until the id is unique. while (counter == -1 || registry.containsBeanDefinition(id)) { counter++; id = beanName + GENERATED_BEAN_NAME_SEPARATOR + counter; } return id; } /** * Register the given bean definition with the given bean factory. * @param definitionHolder the bean definition including name and aliases * @param registry the bean factory to register with * @throws BeanDefinitionStoreException if registration failed */ public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); //BeanDefinition是AnnotatedBeanDefinition的父类,就是前面获取到的bean得元数据信息 //将bd 和beanName存到DefaultListableBeanFactory的Map<String, BeanDefinition> beanDefinitionMap 当中去 //同时将beanName存到List<String> beanDefinitionNames registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); //处理别名 Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String alias : aliases) { registry.registerAlias(beanName, alias); } } } /** * Register the given bean definition with a generated name, * unique within the given bean factory. * @param definition the bean definition to generate a bean name for * @param registry the bean factory to register with * @return the generated bean name * @throws BeanDefinitionStoreException if no unique name can be generated * for the given bean definition or the definition cannot be registered */ public static String registerWithGeneratedName( AbstractBeanDefinition definition, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { String generatedName = generateBeanName(definition, registry, false); registry.registerBeanDefinition(generatedName, definition); return generatedName; } }
package com.obvious.gateway.config; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper; import org.springframework.context.annotation.Bean; @Configurable @EnableZuulProxy public class ZuulConfig { }
/* * 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.accumulo.core.conf; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CliConfiguration { private static final Logger log = LoggerFactory.getLogger(CliConfiguration.class); private static volatile Map<String,String> config = new HashMap<>(); /** * Sets CliConfiguration with map of configuration. Additional calls will overwrite existing * properties and values. * * @param conf * Map of configuration */ public static void set(Map<String,String> conf) { Objects.requireNonNull(conf); config = conf; } public static void print() { log.info("The following configuration was set on the command line:"); for (Map.Entry<String,String> entry : config.entrySet()) { String key = entry.getKey(); log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue())); } } public static String get(Property property) { return config.get(property.getKey()); } public static void getProperties(Map<String,String> props, Predicate<String> filter) { for (Map.Entry<String,String> entry : config.entrySet()) { if (filter.test(entry.getKey())) { props.put(entry.getKey(), entry.getValue()); } } } }
// // Decompiled by Procyon v0.5.36 // package org.codehaus.groovy.runtime; import java.io.File; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.GeneratedMetaMethod; public class dgm$440 extends GeneratedMetaMethod { public dgm$440(final String name, final CachedClass declaringClass, final Class returnType, final Class[] parameters) { super(name, declaringClass, returnType, parameters); } public Object invoke(final Object o, final Object[] array) { return DefaultGroovyMethods.newPrintWriter((File)o); } public final Object doMethodInvoke(final Object o, Object[] coerceArgumentsToClasses) { coerceArgumentsToClasses = this.coerceArgumentsToClasses(coerceArgumentsToClasses); return DefaultGroovyMethods.newPrintWriter((File)o); } }
/* * 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.lucene.tests.analysis; import static org.apache.lucene.util.automaton.Operations.DEFAULT_DETERMINIZE_WORK_LIMIT; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import java.util.Random; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.AnalyzerWrapper; import org.apache.lucene.analysis.DelegatingAnalyzerWrapper; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.tests.index.RandomIndexWriter; import org.apache.lucene.tests.util.TestUtil; import org.apache.lucene.tests.util.automaton.AutomatonTestUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.automaton.Automata; import org.apache.lucene.util.automaton.Automaton; import org.apache.lucene.util.automaton.CharacterRunAutomaton; import org.apache.lucene.util.automaton.Operations; import org.apache.lucene.util.automaton.RegExp; public class TestMockAnalyzer extends BaseTokenStreamTestCase { /** Test a configuration that behaves a lot like WhitespaceAnalyzer */ public void testWhitespace() throws Exception { Analyzer a = new MockAnalyzer(random()); assertAnalyzesTo( a, "A bc defg hiJklmn opqrstuv wxy z ", new String[] {"a", "bc", "defg", "hijklmn", "opqrstuv", "wxy", "z"}); assertAnalyzesTo(a, "aba cadaba shazam", new String[] {"aba", "cadaba", "shazam"}); assertAnalyzesTo(a, "break on whitespace", new String[] {"break", "on", "whitespace"}); } /** Test a configuration that behaves a lot like SimpleAnalyzer */ public void testSimple() throws Exception { Analyzer a = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true); assertAnalyzesTo( a, "a-bc123 defg+hijklmn567opqrstuv78wxy_z ", new String[] {"a", "bc", "defg", "hijklmn", "opqrstuv", "wxy", "z"}); assertAnalyzesTo(a, "aba4cadaba-Shazam", new String[] {"aba", "cadaba", "shazam"}); assertAnalyzesTo(a, "break+on/Letters", new String[] {"break", "on", "letters"}); } /** Test a configuration that behaves a lot like KeywordAnalyzer */ public void testKeyword() throws Exception { Analyzer a = new MockAnalyzer(random(), MockTokenizer.KEYWORD, false); assertAnalyzesTo( a, "a-bc123 defg+hijklmn567opqrstuv78wxy_z ", new String[] {"a-bc123 defg+hijklmn567opqrstuv78wxy_z "}); assertAnalyzesTo(a, "aba4cadaba-Shazam", new String[] {"aba4cadaba-Shazam"}); assertAnalyzesTo(a, "break+on/Nothing", new String[] {"break+on/Nothing"}); // currently though emits no tokens for empty string: maybe we can do it, // but we don't want to emit tokens infinitely... assertAnalyzesTo(a, "", new String[0]); } // Test some regular expressions as tokenization patterns /** Test a configuration where each character is a term */ public void testSingleChar() throws Exception { CharacterRunAutomaton single = new CharacterRunAutomaton(new RegExp(".").toAutomaton()); Analyzer a = new MockAnalyzer(random(), single, false); assertAnalyzesTo( a, "foobar", new String[] {"f", "o", "o", "b", "a", "r"}, new int[] {0, 1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5, 6}); checkRandomData(random(), a, 100); } /** Test a configuration where two characters makes a term */ public void testTwoChars() throws Exception { CharacterRunAutomaton single = new CharacterRunAutomaton(new RegExp("..").toAutomaton()); Analyzer a = new MockAnalyzer(random(), single, false); assertAnalyzesTo( a, "foobar", new String[] {"fo", "ob", "ar"}, new int[] {0, 2, 4}, new int[] {2, 4, 6}); // make sure when last term is a "partial" match that end() is correct assertTokenStreamContents( a.tokenStream("bogus", "fooba"), new String[] {"fo", "ob"}, new int[] {0, 2}, new int[] {2, 4}, new int[] {1, 1}, 5); checkRandomData(random(), a, 100); } /** Test a configuration where three characters makes a term */ public void testThreeChars() throws Exception { CharacterRunAutomaton single = new CharacterRunAutomaton(new RegExp("...").toAutomaton()); Analyzer a = new MockAnalyzer(random(), single, false); assertAnalyzesTo(a, "foobar", new String[] {"foo", "bar"}, new int[] {0, 3}, new int[] {3, 6}); // make sure when last term is a "partial" match that end() is correct assertTokenStreamContents( a.tokenStream("bogus", "fooba"), new String[] {"foo"}, new int[] {0}, new int[] {3}, new int[] {1}, 5); checkRandomData(random(), a, 100); } /** Test a configuration where word starts with one uppercase */ public void testUppercase() throws Exception { CharacterRunAutomaton single = new CharacterRunAutomaton(new RegExp("[A-Z][a-z]*").toAutomaton()); Analyzer a = new MockAnalyzer(random(), single, false); assertAnalyzesTo( a, "FooBarBAZ", new String[] {"Foo", "Bar", "B", "A", "Z"}, new int[] {0, 3, 6, 7, 8}, new int[] {3, 6, 7, 8, 9}); assertAnalyzesTo(a, "aFooBar", new String[] {"Foo", "Bar"}, new int[] {1, 4}, new int[] {4, 7}); checkRandomData(random(), a, 100); } /** Test a configuration that behaves a lot like StopAnalyzer */ public void testStop() throws Exception { Analyzer a = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET); assertAnalyzesTo( a, "the quick brown a fox", new String[] {"quick", "brown", "fox"}, new int[] {2, 1, 2}); } /** Test a configuration that behaves a lot like KeepWordFilter */ public void testKeep() throws Exception { CharacterRunAutomaton keepWords = new CharacterRunAutomaton( Operations.complement( Operations.union( Arrays.asList(Automata.makeString("foo"), Automata.makeString("bar"))), DEFAULT_DETERMINIZE_WORK_LIMIT)); Analyzer a = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, keepWords); assertAnalyzesTo( a, "quick foo brown bar bar fox foo", new String[] {"foo", "bar", "bar", "foo"}, new int[] {2, 2, 1, 2}); } /** Test a configuration that behaves a lot like LengthFilter */ public void testLength() throws Exception { CharacterRunAutomaton length5 = new CharacterRunAutomaton(new RegExp(".{5,}").toAutomaton()); Analyzer a = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, true, length5); assertAnalyzesTo(a, "ok toolong fine notfine", new String[] {"ok", "fine"}, new int[] {1, 2}); } /** Test MockTokenizer encountering a too long token */ public void testTooLongToken() throws Exception { Analyzer whitespace = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer t = new MockTokenizer(MockTokenizer.WHITESPACE, false, 5); return new TokenStreamComponents(t, t); } }; assertTokenStreamContents( whitespace.tokenStream("bogus", "test 123 toolong ok "), new String[] {"test", "123", "toolo", "ng", "ok"}, new int[] {0, 5, 9, 14, 17}, new int[] {4, 8, 14, 16, 19}, 20); assertTokenStreamContents( whitespace.tokenStream("bogus", "test 123 toolo"), new String[] {"test", "123", "toolo"}, new int[] {0, 5, 9}, new int[] {4, 8, 14}, 14); } public void testLUCENE_3042() throws Exception { String testString = "t"; Analyzer analyzer = new MockAnalyzer(random()); try (TokenStream stream = analyzer.tokenStream("dummy", testString)) { stream.reset(); while (stream.incrementToken()) { // consume } stream.end(); } assertAnalyzesTo(analyzer, testString, new String[] {"t"}); } /** blast some random strings through the analyzer */ public void testRandomStrings() throws Exception { checkRandomData(random(), new MockAnalyzer(random()), atLeast(1000)); } /** blast some random strings through differently configured tokenizers */ public void testRandomRegexps() throws Exception { int iters = TEST_NIGHTLY ? atLeast(30) : atLeast(1); for (int i = 0; i < iters; i++) { Automaton automaton = Operations.determinize( AutomatonTestUtil.randomAutomaton(random()), Operations.DEFAULT_DETERMINIZE_WORK_LIMIT); final CharacterRunAutomaton dfa = new CharacterRunAutomaton(automaton); final boolean lowercase = random().nextBoolean(); final int limit = TestUtil.nextInt(random(), 0, 500); Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer t = new MockTokenizer(dfa, lowercase, limit); return new TokenStreamComponents(t, t); } }; checkRandomData(random(), a, 100); a.close(); } } public void testForwardOffsets() throws Exception { int num = atLeast(1000); for (int i = 0; i < num; i++) { String s = TestUtil.randomHtmlishString(random(), 20); StringReader reader = new StringReader(s); MockCharFilter charfilter = new MockCharFilter(reader, 2); MockAnalyzer analyzer = new MockAnalyzer(random()); try (TokenStream ts = analyzer.tokenStream("bogus", charfilter)) { ts.reset(); while (ts.incrementToken()) {} ts.end(); } } } public void testWrapReader() throws Exception { // LUCENE-5153: test that wrapping an analyzer's reader is allowed final Random random = random(); final Analyzer delegate = new MockAnalyzer(random); Analyzer a = new AnalyzerWrapper(delegate.getReuseStrategy()) { @Override protected Reader wrapReader(String fieldName, Reader reader) { return new MockCharFilter(reader, 7); } @Override protected Analyzer getWrappedAnalyzer(String fieldName) { return delegate; } }; checkOneTerm(a, "abc", "aabc"); } public void testChangeGaps() throws Exception { // LUCENE-5324: check that it is possible to change the wrapper's gaps final int positionGap = random().nextInt(1000); final int offsetGap = random().nextInt(1000); final Analyzer delegate = new MockAnalyzer(random()); final Analyzer a = new DelegatingAnalyzerWrapper(delegate.getReuseStrategy()) { @Override protected Analyzer getWrappedAnalyzer(String fieldName) { return delegate; } @Override public int getPositionIncrementGap(String fieldName) { return positionGap; } @Override public int getOffsetGap(String fieldName) { return offsetGap; } }; final RandomIndexWriter writer = new RandomIndexWriter(random(), newDirectory(), a); final Document doc = new Document(); final FieldType ft = new FieldType(); ft.setIndexOptions(IndexOptions.DOCS); ft.setTokenized(true); ft.setStoreTermVectors(true); ft.setStoreTermVectorPositions(true); ft.setStoreTermVectorOffsets(true); doc.add(new Field("f", "a", ft)); doc.add(new Field("f", "a", ft)); writer.addDocument(doc); final LeafReader reader = getOnlyLeafReader(writer.getReader()); final Fields fields = reader.getTermVectors(0); final Terms terms = fields.terms("f"); final TermsEnum te = terms.iterator(); assertEquals(new BytesRef("a"), te.next()); final PostingsEnum dpe = te.postings(null, PostingsEnum.ALL); assertEquals(0, dpe.nextDoc()); assertEquals(2, dpe.freq()); assertEquals(0, dpe.nextPosition()); assertEquals(0, dpe.startOffset()); final int endOffset = dpe.endOffset(); assertEquals(1 + positionGap, dpe.nextPosition()); assertEquals(1 + endOffset + offsetGap, dpe.endOffset()); assertEquals(null, te.next()); reader.close(); writer.close(); writer.w.getDirectory().close(); } }
package org.tests.o2m.jointable; import io.ebean.xtest.BaseTestCase; import io.ebean.DB; import io.ebean.test.LoggedSql; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class TestOneToManyJoinTableNoTableName extends BaseTestCase { private JtMonkeyGroup troop = new JtMonkeyGroup("Pink"); private JtMonkey m0 = new JtMonkey("Sim3"); private JtMonkey m1 = new JtMonkey("Tim3"); private JtMonkey m2 = new JtMonkey("Uim3"); private void initialInsert() { DB.saveAll(Arrays.asList(troop, m0, m1, m2)); } @Test public void base() { initialInsert(); LoggedSql.start(); // make m0 dirty ... but no cascade saved? m0.setFoodPreference("camera"); troop.getMonkeys().add(m0); troop.getMonkeys().add(m1); DB.save(troop); List<String> sql = LoggedSql.collect(); if (isPersistBatchOnCascade()) { assertThat(sql).hasSize(3); assertSql(sql.get(0)).contains("insert into mkeygroup_monkey (mkeygroup_pid, monkey_mid) values (?, ?)"); assertSqlBind(sql, 1, 2); } else { assertThat(sql).hasSize(2); assertSql(sql.get(0)).contains("insert into mkeygroup_monkey (mkeygroup_pid, monkey_mid) values (?, ?)"); assertSql(sql.get(1)).contains("insert into mkeygroup_monkey (mkeygroup_pid, monkey_mid) values (?, ?)"); } int intersectionRows = DB.sqlQuery("select count(*) as total from mkeygroup_monkey where mkeygroup_pid = ?") .setParameter(troop.getPid()) .findOne() .getInteger("total"); assertThat(intersectionRows).isEqualTo(2); LoggedSql.collect(); JtMonkeyGroup fetchTroop = DB.find(JtMonkeyGroup.class) .fetch("monkeys") .where().idEq(troop.getPid()) .findOne(); assertThat(fetchTroop.getMonkeys()).hasSize(2); sql = LoggedSql.collect(); assertThat(sql).hasSize(1); assertSql(sql.get(0)).contains("from mkeygroup t0 left join mkeygroup_monkey t1z_ on t1z_.mkeygroup_pid = t0.pid left join monkey t1 on t1.mid = t1z_.monkey_mid where t0.pid = ?"); assertSql(sql.get(0)).contains("select t0.pid, t0.name, t0.version, t1.mid, t1.name, t1.food_preference, t1.version"); DB.delete(troop); sql = LoggedSql.stop(); assertThat(sql).hasSize(2); assertSql(sql.get(0)).contains("delete from mkeygroup_monkey where mkeygroup_pid = ?"); assertSql(sql.get(1)).contains("delete from mkeygroup where pid=? and version=?"); } }
package dev.kauanmocelin.springbootrestapi.customer; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CustomerConfig { @Bean CommandLineRunner commandLineRunner(CustomerRepository customerRepository) { return args -> { // Customer maria = new Customer( // "Maria", // "maria@gmail.com", // LocalDate.of(2000, Month.JANUARY, 1) // ); // Customer alex = new Customer( // "Alex", // "alex@gmail.com", // LocalDate.of(1998, Month.DECEMBER, 10) // ); //customerRepository.saveAll(List.of(maria, alex)); }; } }
package com.mygdx.game.Entitys; import com.badlogic.gdx.math.Vector2; import com.mygdx.game.Components.Renderable; import com.mygdx.game.Components.RigidBody; import com.mygdx.game.Components.Transform; import com.mygdx.game.Managers.GameManager; import com.mygdx.game.Managers.RenderLayer; import com.mygdx.game.Physics.CollisionCallBack; import com.mygdx.game.Physics.CollisionInfo; import com.mygdx.game.Physics.PhysicsBodyType; /** * Cannonball entity and the methods to get it flying. */ public class CannonBall extends Entity implements CollisionCallBack { private static float speed; private boolean toggleLife; private Ship shooter; public CannonBall() { super(3); setName("ball"); toggleLife = false; Transform t = new Transform(); t.setPosition(-100, 100); t.setScale(0.5f, 0.5f); Renderable r = new Renderable(4, "ball", RenderLayer.Transparent); RigidBody rb = new RigidBody(PhysicsBodyType.Dynamic, r, t, true); rb.setCallback(this); addComponents(t, r, rb); speed = GameManager.getSettings().get("starting").getFloat("cannonSpeed"); r.hide(); } @Override public void update() { super.update(); removeOnCollision(); } /** * Removes the cannonball offscreen once it hits a target. */ private void removeOnCollision() { if (toggleLife) { getComponent(Renderable.class).hide(); Transform t = getComponent(Transform.class); t.setPosition(10000, 10000); RigidBody rb = getComponent(RigidBody.class); rb.setPosition(t.getPosition()); rb.setVelocity(0, 0); toggleLife = false; } } /** * Teleport the cannonball in from offscreen and set in flying away from the ship. * * @param pos 2D vector location from where it sets off * @param dir 2D vector direction for its movement * @param sender ship entity firing it */ public void fire(Vector2 pos, Vector2 dir, Ship sender) { Transform t = getComponent(Transform.class); t.setPosition(pos); RigidBody rb = getComponent(RigidBody.class); Vector2 ta = dir.cpy().scl(speed); // was speed*EntityManager.getDeltaTime() for some randomness //Vector2 o = new Vector2(TILE_SIZE * t.getScale().x, TILE_SIZE * t.getScale().y); //Vector2 v = ta.cpy().sub(o); //rb.setVelocity(v); Not sure of the purpose of this code, but it made the cannonball shoot slightly down/left rb.setVelocity(ta); getComponent(Renderable.class).show(); shooter = sender; } /** * Marks cannonball for removal on next update. */ public void kill() { toggleLife = false; } public Ship getShooter() { return shooter; } @Override public void BeginContact(CollisionInfo info) { } @Override public void EndContact(CollisionInfo info) { } @Override public void EnterTrigger(CollisionInfo info) { } @Override public void ExitTrigger(CollisionInfo info) { } }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 用户实名信息参数 * * @author auto create * @since 1.0, 2019-06-17 17:43:36 */ public class IdentityParams extends AlipayObject { private static final long serialVersionUID = 2811172391872947556L; /** * 用户身份证号 */ @ApiField("cert_no") private String certNo; /** * 用户实名信息hash值 */ @ApiField("identity_hash") private String identityHash; /** * 签约指定用户的uid,如用户登录的uid和指定的用户uid不一致则报错 */ @ApiField("sign_user_id") private String signUserId; /** * 用户姓名 */ @ApiField("user_name") private String userName; public String getCertNo() { return this.certNo; } public void setCertNo(String certNo) { this.certNo = certNo; } public String getIdentityHash() { return this.identityHash; } public void setIdentityHash(String identityHash) { this.identityHash = identityHash; } public String getSignUserId() { return this.signUserId; } public void setSignUserId(String signUserId) { this.signUserId = signUserId; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } }
package com.bookshelf.api; import com.bookshelf.data.Item; import com.bookshelf.data.collection.Categories; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface CategoryService { @GET("/api/categories?transform=1&filter=id,gt,1&?order=name,desc") Call<Categories> getCategories(); }
/* * 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.geode.internal.cache.tier.sockets; import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.apache.geode.test.dunit.Assert.assertEquals; import static org.apache.geode.test.dunit.Assert.assertFalse; import static org.apache.geode.test.dunit.Assert.assertNotNull; import static org.apache.geode.test.dunit.Assert.assertTrue; import static org.apache.geode.test.dunit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import org.junit.BeforeClass; import org.junit.experimental.categories.Category; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.InterestResultPolicy; import org.apache.geode.cache.MirrorType; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.Scope; import org.apache.geode.cache.client.PoolManager; import org.apache.geode.cache.client.internal.PoolImpl; import org.apache.geode.cache.client.internal.RegisterInterestTracker; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.distributed.internal.ServerLocation; import org.apache.geode.internal.AvailablePort; import org.apache.geode.internal.cache.CacheServerImpl; import org.apache.geode.internal.cache.ClientServerObserver; import org.apache.geode.internal.cache.ClientServerObserverAdapter; import org.apache.geode.internal.cache.ClientServerObserverHolder; import org.apache.geode.test.dunit.Assert; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.IgnoredException; import org.apache.geode.test.dunit.NetworkUtils; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.Wait; import org.apache.geode.test.dunit.WaitCriterion; import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase; import org.apache.geode.test.junit.categories.ClientSubscriptionTest; import org.apache.geode.test.junit.categories.DistributedTest; /** * Tests Redundancy Level Functionality */ @Category({DistributedTest.class, ClientSubscriptionTest.class}) public class RedundancyLevelTestBase extends JUnit4DistributedTestCase { protected static volatile boolean registerInterestCalled = false; protected static volatile boolean makePrimaryCalled = false; static Cache cache = null; VM server0 = null; VM server1 = null; VM server2 = null; VM server3 = null; static int PORT1; static int PORT2; static int PORT3; static int PORT4; static String SERVER1; static String SERVER2; static String SERVER3; static String SERVER4; static final String k1 = "k1"; static final String k2 = "k2"; static final String REGION_NAME = "RedundancyLevelTestBase_region"; static PoolImpl pool = null; static ClientServerObserver oldBo = null; static boolean FailOverDetectionByCCU = false; @BeforeClass public static void caseSetUp() throws Exception { disconnectAllFromDS(); } @Override public final void postSetUp() throws Exception { final Host host = Host.getHost(0); server0 = host.getVM(0); server1 = host.getVM(1); server2 = host.getVM(2); server3 = host.getVM(3); IgnoredException.addIgnoredException("java.net.SocketException||java.net.ConnectException"); // start servers first PORT1 = ((Integer) server0.invoke(() -> RedundancyLevelTestBase.createServerCache())).intValue(); PORT2 = ((Integer) server1.invoke(() -> RedundancyLevelTestBase.createServerCache())).intValue(); PORT3 = ((Integer) server2.invoke(() -> RedundancyLevelTestBase.createServerCache())).intValue(); PORT4 = ((Integer) server3.invoke(() -> RedundancyLevelTestBase.createServerCache())).intValue(); String hostName = NetworkUtils.getServerHostName(Host.getHost(0)); SERVER1 = hostName + PORT1; SERVER2 = hostName + PORT2; SERVER3 = hostName + PORT3; SERVER4 = hostName + PORT4; CacheServerTestUtil.disableShufflingOfEndpoints(); } public static void doPuts() { putEntriesK1andK2(); putEntriesK1andK2(); putEntriesK1andK2(); putEntriesK1andK2(); } public static void putEntriesK1andK2() { try { Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(r1); r1.put(k1, k1); r1.put(k2, k2); assertEquals(r1.getEntry(k1).getValue(), k1); assertEquals(r1.getEntry(k2).getValue(), k2); } catch (Exception ignore) { // not sure why it's ok to ignore but if you don't ignore it, RedundancyLevelPart3DUnitTest // will fail } } public static void verifyDispatcherIsAlive() { try { WaitCriterion wc = new WaitCriterion() { String excuse; public boolean done() { return cache.getCacheServers().size() == 1; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 3 * 60 * 1000, 1000, true); CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next(); assertNotNull(bs); assertNotNull(bs.getAcceptor()); assertNotNull(bs.getAcceptor().getCacheClientNotifier()); final CacheClientNotifier ccn = bs.getAcceptor().getCacheClientNotifier(); wc = new WaitCriterion() { String excuse; public boolean done() { return ccn.getClientProxies().size() > 0; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 60 * 1000, 1000, true); Iterator iter_prox = ccn.getClientProxies().iterator(); if (iter_prox.hasNext()) { final CacheClientProxy proxy = (CacheClientProxy) iter_prox.next(); wc = new WaitCriterion() { String excuse; public boolean done() { if (proxy._messageDispatcher == null) { return false; } return proxy._messageDispatcher.isAlive(); } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 60 * 1000, 1000, true); // assertTrue("Dispatcher on primary should be alive", proxy._messageDispatcher.isAlive()); } } catch (Exception ex) { Assert.fail("while setting verifyDispatcherIsAlive ", ex); } } public static void verifyDispatcherIsNotAlive() { try { WaitCriterion wc = new WaitCriterion() { String excuse; public boolean done() { return cache.getCacheServers().size() == 1; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 3 * 60 * 1000, 1000, true); CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next(); assertNotNull(bs); assertNotNull(bs.getAcceptor()); assertNotNull(bs.getAcceptor().getCacheClientNotifier()); final CacheClientNotifier ccn = bs.getAcceptor().getCacheClientNotifier(); wc = new WaitCriterion() { String excuse; public boolean done() { return ccn.getClientProxies().size() > 0; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 3 * 60 * 1000, 1000, true); Iterator iter_prox = ccn.getClientProxies().iterator(); if (iter_prox.hasNext()) { CacheClientProxy proxy = (CacheClientProxy) iter_prox.next(); assertFalse("Dispatcher on secondary should not be alive", proxy._messageDispatcher.isAlive()); } } catch (Exception ex) { Assert.fail("while setting verifyDispatcherIsNotAlive ", ex); } } public static void verifyRedundantServersContain(final String server) { WaitCriterion wc = new WaitCriterion() { public boolean done() { return pool.getRedundantNames().contains(server); } public String description() { return "Redundant servers (" + pool.getRedundantNames() + ") does not contain " + server; } }; Wait.waitForCriterion(wc, 60 * 1000, 2000, true); } public static void verifyLiveAndRedundantServers(final int liveServers, final int redundantServers) { WaitCriterion wc = new WaitCriterion() { public boolean done() { return pool.getConnectedServerCount() == liveServers && pool.getRedundantNames().size() == redundantServers; } public String description() { return "Expected connected server count (" + pool.getConnectedServerCount() + ") to become " + liveServers + "and redundant count (" + pool.getRedundantNames().size() + ") to become " + redundantServers; } }; Wait.waitForCriterion(wc, 120 * 1000, 2 * 1000, true); } public static void verifyDeadServers(int deadServers) { // this is now deadcode since it is always followed by verifyLiveAndRedundant // long maxWaitTime = 180000; // long start = System.currentTimeMillis(); // while (proxy.getDeadServers().size() != deadServers) { // wait until condition is // // met // assertTrue("Waited over " + maxWaitTime + "for dead servers to become " // + deadServers, (System.currentTimeMillis() - start) < maxWaitTime); // try { // Thread.yield(); // synchronized(delayLock) {delayLock.wait(4000);} // } // catch (InterruptedException ie) { // fail("Interrupted while waiting ", ie); // } // } } public static void createEntriesK1andK2() { try { Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(r1); if (!r1.containsKey(k1)) { r1.create(k1, k1); } if (!r1.containsKey(k2)) { r1.create(k2, k2); } assertEquals(r1.getEntry(k1).getValue(), k1); assertEquals(r1.getEntry(k2).getValue(), k2); } catch (Exception ex) { Assert.fail("failed while createEntries()", ex); } } public static void registerK1AndK2() { try { Region r = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(r); List list = new ArrayList(); list.add(k1); list.add(k2); r.registerInterest(list, InterestResultPolicy.KEYS_VALUES); } catch (Exception ex) { ex.printStackTrace(); Assert.fail("failed while region.registerK1AndK2()", ex); } } public static void unregisterInterest() { try { Region r = cache.getRegion(Region.SEPARATOR + REGION_NAME); r.unregisterInterest("k1"); } catch (Exception e) { Assert.fail("test failed due to ", e); } } public static void verifyNoCCP() { assertEquals("More than one BridgeServer", 1, cache.getCacheServers().size()); CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next(); assertNotNull(bs); assertNotNull(bs.getAcceptor()); assertNotNull(bs.getAcceptor().getCacheClientNotifier()); // no client is connected to this server assertTrue(0 == bs.getAcceptor().getCacheClientNotifier().getClientProxies().size()); } public static void verifyCCP() { try { WaitCriterion wc = new WaitCriterion() { String excuse; public boolean done() { return cache.getCacheServers().size() == 1; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 3 * 60 * 1000, 1000, true); CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next(); assertNotNull(bs); assertNotNull(bs.getAcceptor()); assertNotNull(bs.getAcceptor().getCacheClientNotifier()); // one client is connected to this server final CacheClientNotifier ccn = bs.getAcceptor().getCacheClientNotifier(); wc = new WaitCriterion() { String excuse; public boolean done() { return ccn.getClientProxies().size() == 1; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 3 * 60 * 1000, 1000, true); } catch (Exception ex) { Assert.fail("exception in verifyCCP()", ex); } } public static void verifyInterestRegistration() { try { WaitCriterion wc = new WaitCriterion() { public boolean done() { return cache.getCacheServers().size() == 1; } public String description() { return "Number of bridge servers (" + cache.getCacheServers().size() + ") never became 1"; } }; Wait.waitForCriterion(wc, 180 * 1000, 2000, true); CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next(); assertNotNull(bs); assertNotNull(bs.getAcceptor()); assertNotNull(bs.getAcceptor().getCacheClientNotifier()); final CacheClientNotifier ccn = bs.getAcceptor().getCacheClientNotifier(); wc = new WaitCriterion() { public boolean done() { return ccn.getClientProxies().size() > 0; } public String description() { return "Notifier's proxies is empty"; } }; Wait.waitForCriterion(wc, 180 * 1000, 2000, true); Iterator iter_prox = ccn.getClientProxies().iterator(); if (iter_prox.hasNext()) { final CacheClientProxy ccp = (CacheClientProxy) iter_prox.next(); wc = new WaitCriterion() { String excuse; public boolean done() { Set keysMap = (Set) ccp.cils[RegisterInterestTracker.interestListIndex] .getProfile(Region.SEPARATOR + REGION_NAME).getKeysOfInterestFor(ccp.getProxyID()); if (keysMap == null) { excuse = "keys of interest is null"; return false; } if (keysMap.size() != 2) { excuse = "keys of interest size (" + keysMap.size() + ") not 2"; return false; } return true; } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 180 * 1000, 2 * 1000, true); Set keysMap = ccp.cils[RegisterInterestTracker.interestListIndex] .getProfile(Region.SEPARATOR + REGION_NAME).getKeysOfInterestFor(ccp.getProxyID()); assertTrue(keysMap.contains(k1)); assertTrue(keysMap.contains(k2)); } else { fail("A CCP was expected . Wasn't it?"); } } catch (Exception ex) { fail("while setting verifyInterestRegistration", ex); } } public static void stopServer() { try { Iterator iter = cache.getCacheServers().iterator(); if (iter.hasNext()) { CacheServer server = (CacheServer) iter.next(); server.stop(); } } catch (Exception e) { Assert.fail("failed while stopServer()", e); } } public static void startServer() { try { Cache c = CacheFactory.getAnyInstance(); CacheServerImpl bs = (CacheServerImpl) c.getCacheServers().iterator().next(); assertNotNull(bs); bs.start(); } catch (Exception ex) { Assert.fail("while startServer()", ex); } } private void createCache(Properties props) throws Exception { DistributedSystem ds = getSystem(props); assertNotNull(ds); ds.disconnect(); ds = getSystem(props); cache = CacheFactory.create(ds); assertNotNull(cache); } public static void createClientCache(String host, int port1, int port2, int port3, int port4, int redundancy) throws Exception { createClientCache(host, port1, port2, port3, port4, redundancy, 3000, /* defaul socket timeout of 250 millisec */ 10 /* default retry interval */); } public static void createClientCache(String host, int port1, int port2, int port3, int port4, int redundancy, int socketReadTimeout, int retryInterval) throws Exception { if (!FailOverDetectionByCCU) { oldBo = ClientServerObserverHolder.setInstance(new ClientServerObserverAdapter() { public void beforeFailoverByCacheClientUpdater(ServerLocation epFailed) { try { Thread.sleep(300000); } catch (InterruptedException ie) { // expected - test will shut down the cache which will interrupt // the CacheClientUpdater thread that invoked this method Thread.currentThread().interrupt(); } } }); } Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOCATORS, ""); new RedundancyLevelTestBase().createCache(props); PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(host, PORT1) .addServer(host, PORT2).addServer(host, PORT3).addServer(host, PORT4) .setSubscriptionEnabled(true).setReadTimeout(socketReadTimeout).setSocketBufferSize(32768) .setMinConnections(8).setSubscriptionRedundancy(redundancy).setRetryAttempts(5) .setPingInterval(retryInterval).create("DurableClientReconnectDUnitTestPool"); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); factory.setPoolName(p.getName()); RegionAttributes attrs = factory.createRegionAttributes(); cache.createRegion(REGION_NAME, attrs); pool = p; createEntriesK1andK2(); registerK1AndK2(); } public static Integer createServerCache() throws Exception { new RedundancyLevelTestBase().createCache(new Properties()); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); factory.setEnableConflation(true); factory.setMirrorType(MirrorType.KEYS_VALUES); RegionAttributes attrs = factory.createRegionAttributes(); cache.createVMRegion(REGION_NAME, attrs); CacheServer server1 = cache.addCacheServer(); int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET); server1.setMaximumTimeBetweenPings(180000); server1.setPort(port); // ensures updates to be sent instead of invalidations server1.setNotifyBySubscription(true); server1.start(); return new Integer(server1.getPort()); } public static void verifyOrderOfEndpoints() { // I'm not sure this validation is needed anymore // Endpoint[] eplist = proxy.getEndpoints(); // int len = eplist.length; // int redundancyLevel = proxy.getRedundancyLevel(); // if (len > 0) { // assertTrue(((EndpointImpl)eplist[0]).isPrimary()); // if (redundancyLevel == -1) // redundancyLevel = len - 1; // for (int i = len - 1, cnt = 0; i >= 1; i--, cnt++) { // if (cnt < redundancyLevel) // assertTrue(((EndpointImpl)eplist[i]).isRedundant()); // else // assertFalse(((EndpointImpl)eplist[i]).isRedundant()); // } // } } @Override public final void preTearDown() throws Exception { try { if (!FailOverDetectionByCCU) ClientServerObserverHolder.setInstance(oldBo); FailOverDetectionByCCU = false; // close the clients first closeCache(); // then close the servers server0.invoke(() -> RedundancyLevelTestBase.closeCache()); server1.invoke(() -> RedundancyLevelTestBase.closeCache()); server2.invoke(() -> RedundancyLevelTestBase.closeCache()); server3.invoke(() -> RedundancyLevelTestBase.closeCache()); } finally { CacheServerTestUtil.enableShufflingOfEndpoints(); } CacheServerTestUtil.resetDisableShufflingOfEndpointsFlag(); } public static void closeCache() { if (cache != null && !cache.isClosed()) { cache.close(); cache.getDistributedSystem().disconnect(); } } }
package com.buuz135.industrial.jei; import com.buuz135.industrial.api.recipe.BioReactorEntry; import com.buuz135.industrial.api.recipe.FluidDictionaryEntry; import com.buuz135.industrial.api.recipe.LaserDrillEntry; import com.buuz135.industrial.api.recipe.ProteinReactorEntry; import com.buuz135.industrial.book.BookCategory; import com.buuz135.industrial.config.CustomConfiguration; import com.buuz135.industrial.jei.fluiddictionary.FluidDictionaryCategory; import com.buuz135.industrial.jei.fluiddictionary.FluidDictionaryWrapper; import com.buuz135.industrial.jei.laser.LaserRecipeCategory; import com.buuz135.industrial.jei.laser.LaserRecipeWrapper; import com.buuz135.industrial.jei.machineproduce.MachineProduceCategory; import com.buuz135.industrial.jei.machineproduce.MachineProduceWrapper; import com.buuz135.industrial.jei.manual.ManualCategory; import com.buuz135.industrial.jei.manual.ManualWrapper; import com.buuz135.industrial.jei.petrifiedgen.PetrifiedBurnTimeCategory; import com.buuz135.industrial.jei.petrifiedgen.PetrifiedBurnTimeWrapper; import com.buuz135.industrial.jei.reactor.ReactorRecipeCategory; import com.buuz135.industrial.jei.reactor.ReactorRecipeWrapper; import com.buuz135.industrial.jei.sludge.SludgeRefinerRecipeCategory; import com.buuz135.industrial.jei.sludge.SludgeRefinerRecipeWrapper; import com.buuz135.industrial.proxy.BlockRegistry; import com.buuz135.industrial.proxy.FluidsRegistry; import com.buuz135.industrial.proxy.ItemRegistry; import com.buuz135.industrial.tile.block.CustomOrientedBlock; import com.buuz135.industrial.tile.world.MaterialStoneWorkFactoryTile; import com.buuz135.industrial.utils.CraftingUtils; import com.buuz135.industrial.utils.ItemStackWeightedItem; import mezz.jei.api.*; import mezz.jei.api.ingredients.IModIngredientRegistration; import mezz.jei.api.recipe.IFocus; import mezz.jei.api.recipe.IRecipeCategoryRegistration; import mezz.jei.api.recipe.VanillaRecipeCategoryUid; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.NonNullList; import net.minecraft.util.WeightedRandom; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @JEIPlugin public class JEICustomPlugin implements IModPlugin { private static IRecipesGui recipesGui; private static IRecipeRegistry recipeRegistry; private SludgeRefinerRecipeCategory sludgeRefinerRecipeCategory; private ReactorRecipeCategory bioReactorRecipeCategory; private ReactorRecipeCategory proteinReactorRecipeCategory; private LaserRecipeCategory laserRecipeCategory; private MachineProduceCategory machineProduceCategory; private PetrifiedBurnTimeCategory petrifiedBurnTimeCategory; private ManualCategory manualCategory; private FluidDictionaryCategory fluidDictionaryCategory; public static void showUses(ItemStack stack) { if (recipesGui != null && recipeRegistry != null) recipesGui.show(recipeRegistry.createFocus(IFocus.Mode.INPUT, stack)); } @Override public void registerItemSubtypes(ISubtypeRegistry subtypeRegistry) { } @Override public void registerIngredients(IModIngredientRegistration registry) { } @Override public void registerCategories(IRecipeCategoryRegistration registry) { if (BlockRegistry.sludgeRefinerBlock.isEnabled()) { sludgeRefinerRecipeCategory = new SludgeRefinerRecipeCategory(registry.getJeiHelpers().getGuiHelper()); registry.addRecipeCategories(sludgeRefinerRecipeCategory); } if (BlockRegistry.bioReactorBlock.isEnabled()) { bioReactorRecipeCategory = new ReactorRecipeCategory(registry.getJeiHelpers().getGuiHelper(), "Bioreactor accepted items"); registry.addRecipeCategories(bioReactorRecipeCategory); } if (BlockRegistry.proteinReactorBlock.isEnabled()) { proteinReactorRecipeCategory = new ReactorRecipeCategory(registry.getJeiHelpers().getGuiHelper(), "Protein reactor accepted items"); registry.addRecipeCategories(proteinReactorRecipeCategory); } if (BlockRegistry.laserBaseBlock.isEnabled() || BlockRegistry.laserDrillBlock.isEnabled()) { laserRecipeCategory = new LaserRecipeCategory(registry.getJeiHelpers().getGuiHelper()); registry.addRecipeCategories(laserRecipeCategory); } machineProduceCategory = new MachineProduceCategory(registry.getJeiHelpers().getGuiHelper()); registry.addRecipeCategories(machineProduceCategory); if (BlockRegistry.petrifiedFuelGeneratorBlock.isEnabled()) { petrifiedBurnTimeCategory = new PetrifiedBurnTimeCategory(registry.getJeiHelpers().getGuiHelper()); registry.addRecipeCategories(petrifiedBurnTimeCategory); } if (CustomConfiguration.enableBookEntriesInJEI) { manualCategory = new ManualCategory(registry.getJeiHelpers().getGuiHelper()); registry.addRecipeCategories(manualCategory); } if (BlockRegistry.fluidDictionaryConverterBlock.isEnabled() && !FluidDictionaryEntry.FLUID_DICTIONARY_RECIPES.isEmpty()) { fluidDictionaryCategory = new FluidDictionaryCategory(registry.getJeiHelpers().getGuiHelper()); registry.addRecipeCategories(fluidDictionaryCategory); } } @Override public void register(IModRegistry registry) { if (BlockRegistry.sludgeRefinerBlock.isEnabled()) { int maxWeight = WeightedRandom.getTotalWeight(BlockRegistry.sludgeRefinerBlock.getItems()); List<SludgeRefinerRecipeWrapper> wrapperList = new ArrayList<>(); BlockRegistry.sludgeRefinerBlock.getItems().forEach(itemStackWeightedItem -> wrapperList.add(new SludgeRefinerRecipeWrapper(itemStackWeightedItem, maxWeight))); registry.addRecipes(wrapperList, sludgeRefinerRecipeCategory.getUid()); registry.addRecipeCatalyst(new ItemStack(BlockRegistry.sludgeRefinerBlock), sludgeRefinerRecipeCategory.getUid()); } if (BlockRegistry.bioReactorBlock.isEnabled()) { List<ReactorRecipeWrapper> bioreactor = new ArrayList<>(); BioReactorEntry.BIO_REACTOR_ENTRIES.forEach(entry -> bioreactor.add(new ReactorRecipeWrapper(entry.getStack(), FluidsRegistry.BIOFUEL, BlockRegistry.bioReactorBlock.getBaseAmount()))); registry.addRecipes(bioreactor, bioReactorRecipeCategory.getUid()); registry.addRecipeCatalyst(new ItemStack(BlockRegistry.bioReactorBlock), bioReactorRecipeCategory.getUid()); } if (BlockRegistry.proteinReactorBlock.isEnabled()) { List<ReactorRecipeWrapper> proteinreactor = new ArrayList<>(); ProteinReactorEntry.PROTEIN_REACTOR_ENTRIES.forEach(entry -> proteinreactor.add(new ReactorRecipeWrapper(entry.getStack(), FluidsRegistry.PROTEIN, BlockRegistry.proteinReactorBlock.getBaseAmount()))); registry.addRecipes(proteinreactor, proteinReactorRecipeCategory.getUid()); registry.addRecipeCatalyst(new ItemStack(BlockRegistry.proteinReactorBlock), proteinReactorRecipeCategory.getUid()); } if (BlockRegistry.laserBaseBlock.isEnabled() || BlockRegistry.laserDrillBlock.isEnabled()) { List<ItemStackWeightedItem> item = new ArrayList<>(); LaserDrillEntry.LASER_DRILL_ENTRIES.forEach(entry -> item.add(new ItemStackWeightedItem(entry.getStack(), entry.getWeight()))); final int laserMaxWeight = WeightedRandom.getTotalWeight(item); List<LaserRecipeWrapper> laserRecipeWrappers = new ArrayList<>(); LaserDrillEntry.LASER_DRILL_ENTRIES.forEach(entry -> laserRecipeWrappers.add(new LaserRecipeWrapper(new ItemStackWeightedItem(entry.getStack(), entry.getWeight()), laserMaxWeight, entry.getLaserMeta()))); registry.addRecipes(laserRecipeWrappers, laserRecipeCategory.getUid()); registry.addRecipeCatalyst(new ItemStack(BlockRegistry.laserDrillBlock), laserRecipeCategory.getUid()); registry.addRecipeCatalyst(new ItemStack(BlockRegistry.laserBaseBlock), laserRecipeCategory.getUid()); } if (BlockRegistry.resourcefulFurnaceBlock.isEnabled()) registry.addRecipeCatalyst(new ItemStack(BlockRegistry.resourcefulFurnaceBlock), VanillaRecipeCategoryUid.SMELTING); if (BlockRegistry.potionEnervatorBlock.isEnabled()) registry.addRecipeCatalyst(new ItemStack(BlockRegistry.potionEnervatorBlock), VanillaRecipeCategoryUid.BREWING); registry.addRecipes(Arrays.asList( new MachineProduceWrapper(BlockRegistry.sporesRecreatorBlock, new ItemStack(Blocks.BROWN_MUSHROOM)), new MachineProduceWrapper(BlockRegistry.sporesRecreatorBlock, new ItemStack(Blocks.RED_MUSHROOM)), new MachineProduceWrapper(BlockRegistry.sewageCompostSolidiferBlock, new ItemStack(ItemRegistry.fertilizer)), new MachineProduceWrapper(BlockRegistry.dyeMixerBlock, new ItemStack(Items.DYE, 1, OreDictionary.WILDCARD_VALUE)), new MachineProduceWrapper(BlockRegistry.lavaFabricatorBlock, new ItemStack(Items.LAVA_BUCKET)), new MachineProduceWrapper(BlockRegistry.waterResourcesCollectorBlock, new ItemStack(Items.FISH, 1, OreDictionary.WILDCARD_VALUE)), new MachineProduceWrapper(BlockRegistry.mobRelocatorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.ESSENCE, 1000))), new MachineProduceWrapper(BlockRegistry.cropRecolectorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.SLUDGE, 1000))), new MachineProduceWrapper(BlockRegistry.waterCondensatorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidRegistry.WATER, 1000))), new MachineProduceWrapper(BlockRegistry.animalResourceHarvesterBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.MILK, 1000))), new MachineProduceWrapper(BlockRegistry.mobSlaughterFactoryBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.MEAT, 1000))), new MachineProduceWrapper(BlockRegistry.mobSlaughterFactoryBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.PINK_SLIME, 1000))), new MachineProduceWrapper(BlockRegistry.treeFluidExtractorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.LATEX, 1000))), new MachineProduceWrapper(BlockRegistry.latexProcessingUnitBlock, new ItemStack(ItemRegistry.tinyDryRubber)), new MachineProduceWrapper(BlockRegistry.animalByproductRecolectorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.SEWAGE, 1000))), new MachineProduceWrapper(BlockRegistry.lavaFabricatorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidRegistry.LAVA, 1000))), new MachineProduceWrapper(BlockRegistry.proteinReactorBlock, FluidUtil.getFilledBucket(new FluidStack(FluidsRegistry.PROTEIN, 1000)))).stream().filter(machineProduceWrapper -> ((CustomOrientedBlock) machineProduceWrapper.getBlock()).isEnabled()).collect(Collectors.toList()), machineProduceCategory.getUid()); if (BlockRegistry.materialStoneWorkFactoryBlock.isEnabled()) { NonNullList<ItemStack> wrappers = NonNullList.create(); findAllStoneWorkOutputs(wrappers, new ItemStack(Blocks.COBBLESTONE), 0); wrappers.stream().filter(stack -> !stack.isEmpty()).forEach(stack -> registry.addRecipes(Collections.singletonList(new MachineProduceWrapper(BlockRegistry.materialStoneWorkFactoryBlock, stack)), machineProduceCategory.getUid())); } if (BlockRegistry.petrifiedFuelGeneratorBlock.isEnabled()) { List<PetrifiedBurnTimeWrapper> petrifiedBurnTimeWrappers = new ArrayList<>(); registry.getIngredientRegistry().getFuels().stream().filter(stack -> !(stack.getItem() instanceof ItemBucket)).forEach(stack -> petrifiedBurnTimeWrappers.add(new PetrifiedBurnTimeWrapper(stack, TileEntityFurnace.getItemBurnTime(stack)))); registry.addRecipes(petrifiedBurnTimeWrappers, petrifiedBurnTimeCategory.getUid()); registry.addRecipeCatalyst(new ItemStack(BlockRegistry.petrifiedFuelGeneratorBlock), petrifiedBurnTimeCategory.getUid()); } if (CustomConfiguration.enableBookEntriesInJEI) { for (BookCategory category : BookCategory.values()) { registry.addRecipes(category.getEntries().values().stream().map(ManualWrapper::new).collect(Collectors.toList()), manualCategory.getUid()); } registry.addRecipeCatalyst(new ItemStack(ItemRegistry.bookManualItem), manualCategory.getUid()); } if (fluidDictionaryCategory != null) { registry.addRecipeCatalyst(new ItemStack(BlockRegistry.fluidDictionaryConverterBlock), fluidDictionaryCategory.getUid()); registry.addRecipes(FluidDictionaryEntry.FLUID_DICTIONARY_RECIPES.stream().map(FluidDictionaryWrapper::new).collect(Collectors.toList()), fluidDictionaryCategory.getUid()); } } public ItemStack getStoneWorkOutputFrom(ItemStack stack, MaterialStoneWorkFactoryTile.Mode mode) { if (mode == MaterialStoneWorkFactoryTile.Mode.FURNACE) return FurnaceRecipes.instance().getSmeltingResult(stack).copy(); if (mode == MaterialStoneWorkFactoryTile.Mode.CRAFT_BIG || mode == MaterialStoneWorkFactoryTile.Mode.CRAFT_SMALL) { return CraftingUtils.findOutput(mode == MaterialStoneWorkFactoryTile.Mode.CRAFT_BIG ? 3 : 2, stack, null); } if (mode == MaterialStoneWorkFactoryTile.Mode.GRIND) { return CraftingUtils.getCrushOutput(stack); } return ItemStack.EMPTY; } public void findAllStoneWorkOutputs(NonNullList<ItemStack> stacks, ItemStack last, int deep) { if (last.isEmpty()) return; for (MaterialStoneWorkFactoryTile.Mode mode : MaterialStoneWorkFactoryTile.Mode.values()) { ItemStack out = getStoneWorkOutputFrom(last, mode); if (!out.isEmpty() && stacks.stream().noneMatch(stack -> stack.isItemEqual(out))) stacks.add(out); if (deep < 3) findAllStoneWorkOutputs(stacks, out, deep + 1); } } @Override public void onRuntimeAvailable(IJeiRuntime jeiRuntime) { recipesGui = jeiRuntime.getRecipesGui(); recipeRegistry = jeiRuntime.getRecipeRegistry(); } }
package com.xlauch.rest.config; import com.xlauch.core.context.ActionContext; import com.xlauch.rest.config.properties.JwtProperties; import io.jsonwebtoken.JwtException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p> * 类描述:jwt授权拦截器 * </p> * * @author huangxy * @version 0.1 * @since 2017/12/21. */ public class AuthInterceptor extends HandlerInterceptorAdapter { private final Log logger = LogFactory.getLog(this.getClass()); @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private JwtProperties jwtProperties; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(request.getParameterMap().toString()); System.out.println(request.getContentType()); if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) { return true; } final String requestHeader = request.getHeader(jwtProperties.getHeader()); String authToken; if (requestHeader != null && requestHeader.startsWith("Bearer ")) { authToken = requestHeader.substring(7); //验证token是否过期 try { boolean flag = jwtTokenUtil.isTokenExpired(authToken); if (flag) { return false; } } catch (JwtException e) { //有异常就是token解析失败 return false; } } else { //header没有带Bearer字段 return false; } //校验签名 String token = request.getHeader(jwtProperties.getHeader()).substring(7); //设置用户ID至上下文 String userId = jwtTokenUtil.getUsernameFromToken(token); if (userId != null){ ActionContext.getContext().setData(ActionContext.USER_ID, userId); } return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { super.afterCompletion(request, response, handler, ex); ActionContext.getContext().destory(); } }
/* * Copyright 2010-2012 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.simpleworkflow.model.transform; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.simpleworkflow.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; import static com.amazonaws.http.HttpMethodName.POST; /** * Count Open Workflow Executions Request Marshaller */ public class CountOpenWorkflowExecutionsRequestMarshaller implements Marshaller<Request<CountOpenWorkflowExecutionsRequest>, CountOpenWorkflowExecutionsRequest> { public Request<CountOpenWorkflowExecutionsRequest> marshall(CountOpenWorkflowExecutionsRequest countOpenWorkflowExecutionsRequest) { if (countOpenWorkflowExecutionsRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<CountOpenWorkflowExecutionsRequest> request = new DefaultRequest<CountOpenWorkflowExecutionsRequest>(countOpenWorkflowExecutionsRequest, "AmazonSimpleWorkflow"); String target = "SimpleWorkflowService.CountOpenWorkflowExecutions"; request.addHeader("X-Amz-Target", target); request.addHeader("Content-Type", "application/x-amz-json-1.0"); request.setHttpMethod(POST); try { StringWriter stringWriter = new StringWriter(); JSONWriter jsonWriter = new JSONWriter(stringWriter); jsonWriter.object(); if (countOpenWorkflowExecutionsRequest.getDomain() != null) { jsonWriter.key("domain").value(countOpenWorkflowExecutionsRequest.getDomain()); } ExecutionTimeFilter startTimeFilter = countOpenWorkflowExecutionsRequest.getStartTimeFilter(); if (startTimeFilter != null) { jsonWriter.key("startTimeFilter").object(); if (startTimeFilter.getOldestDate() != null) { jsonWriter.key("oldestDate").value(startTimeFilter.getOldestDate()); } if (startTimeFilter.getLatestDate() != null) { jsonWriter.key("latestDate").value(startTimeFilter.getLatestDate()); } jsonWriter.endObject(); } WorkflowTypeFilter typeFilter = countOpenWorkflowExecutionsRequest.getTypeFilter(); if (typeFilter != null) { jsonWriter.key("typeFilter").object(); if (typeFilter.getName() != null) { jsonWriter.key("name").value(typeFilter.getName()); } if (typeFilter.getVersion() != null) { jsonWriter.key("version").value(typeFilter.getVersion()); } jsonWriter.endObject(); } TagFilter tagFilter = countOpenWorkflowExecutionsRequest.getTagFilter(); if (tagFilter != null) { jsonWriter.key("tagFilter").object(); if (tagFilter.getTag() != null) { jsonWriter.key("tag").value(tagFilter.getTag()); } jsonWriter.endObject(); } WorkflowExecutionFilter executionFilter = countOpenWorkflowExecutionsRequest.getExecutionFilter(); if (executionFilter != null) { jsonWriter.key("executionFilter").object(); if (executionFilter.getWorkflowId() != null) { jsonWriter.key("workflowId").value(executionFilter.getWorkflowId()); } jsonWriter.endObject(); } jsonWriter.endObject(); String snippet = stringWriter.toString(); byte[] content = snippet.getBytes("UTF-8"); request.setContent(new StringInputStream(snippet)); request.addHeader("Content-Length", Integer.toString(content.length)); return request; } catch(Throwable t) { throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } } }
// PEMS (Police Evidence Management System) Version 0.1 // Copyright 2015 - Jacob Jones and Andrew Rottier // SelectImagesPrintDialogue.java package gui.display.dialogues; import java.awt.event.*; import java.util.*; import javax.swing.*; import gui.components.icon.*; import gui.display.*; /** Subclass of <code>SelectImagesDialogue</code> displayed when the user is selecting images to print. * * @author Jacob Jones * @author Andrew Rottier * @since 0.1 * @version 0.1 */ public class SelectImagesPrintDialogue extends SelectImagesDialogue implements MouseListener { private ArrayList<CaseIcon> caseIcons; private ArrayList<CaseIcon> selectedIcons; /** Calls the parent constructor, populates <code>caseIcons</code>, initializes <code>selectedIcons</code>. * * @param manager the instance of <code>FrameManager</code> that initialized this dialogue * @param caseNum the number of the case that the images are being selected from */ public SelectImagesPrintDialogue(FrameManager manager, String caseNum) { super(manager, caseNum, "Please select all of the images you would like to print:"); this.caseIcons = this.generateIcons(); this.selectedIcons = new ArrayList<CaseIcon>(); super.refreshIconContainer(0, this.caseIcons, this.selectedIcons); super.revalidate(); super.repaint(); } /** Mandatory method required in all classes that implement <code>MouseListener</code>. * <p> * <b>Below is a list of possible source objects and their corresponding actions:</b> * <ul> * <li>An instance of <code>CaseIcon</code> contained within both the <code>caseIcons</code> and <code>selectedIcons</code> <code>ArrayLists</code>.</li> * <ul> * <li>Said instance is removed from <code>selectedIcons</code>.</li> * </ul> * <li>An instance of <code>CaseIcon</code> contained within the <code>caseIcons</code> <code>ArrayList</code>, but not within the <code>selectedIcons</code> <code>ArrayList</code>.</li> * <ul> * <li>Said instance is added to <code>selectedIcons</code>.</li> * </ul> * </ul> */ public void mouseClicked(MouseEvent e) { if (this.selectedIcons.contains(e.getSource())) { this.selectedIcons.remove((CaseIcon)e.getSource()); } else if (this.caseIcons.contains(e.getSource())) { this.selectedIcons.add((CaseIcon)e.getSource()); } super.refreshIconContainer(super.getIconPlace(), this.caseIcons, this.selectedIcons); } /** Mandatory method required in all classes that implement <code>MouseListener</code>. */ public void mousePressed(MouseEvent e) { } /** Mandatory method required in all classes that implement <code>MouseListener</code>. */ public void mouseReleased(MouseEvent e) { } /** Mandatory method required in all classes that implement <code>MouseListener</code>. */ public void mouseEntered(MouseEvent e) { } /** Mandatory method required in all classes that implement <code>MouseListener</code>. */ public void mouseExited(MouseEvent e) { } /** Override method - attempts to load the next six images from the case within <code>iconContainer</code>. */ protected void nextButtonClicked() { if (super.getIconPlace() + 6 < this.caseIcons.size()) { super.refreshIconContainer(super.getIconPlace() + 6, this.caseIcons, this.selectedIcons); } } /** Override method - attempts to load the previous six images from the case within <code>iconContainer</code>. */ protected void prevButtonClicked() { if (super.getIconPlace() >= 6) { super.refreshIconContainer(super.getIconPlace() - 6, this.caseIcons, this.selectedIcons); } } /** Override method - attempts to push <code>PrintSetUpDialogue</code> and displays an error message if this fails. */ protected void continueButtonClicked() { if (this.selectedIcons.size() > 0) { super.getManager().closeDialogue(); super.getManager().openDialogue("Print Setup", new PrintSetUpDialogue(super.getManager(), super.getCaseNum(), this.selectedIcons), 60, 75); } else { JOptionPane.showMessageDialog(this, "You have not selected any images to print!", "Error", JOptionPane.ERROR_MESSAGE); } } /** Returns an <code>ArrayList</code> of <code>CaseIcon</code> objects representing all of the images contained within the currently selected case. * * @return <code>ArrayList</code> of <code>CaseIcon</code> objects representing all of the images contained within the currently selected case */ private ArrayList<CaseIcon> generateIcons() { for (int i = 0; i < super.getManager().getStorageManager().getCases().size(); i++) { if (super.getManager().getStorageManager().getCases().get(i).getCaseNum().equalsIgnoreCase(super.getCaseNum())) { return super.getManager().getStorageManager().getCases().get(i).getCaseIcons(140, this, CENTER_ALIGNMENT); } } return new ArrayList<CaseIcon>(); } }
/******************************************************************************* * Copyright (c) Contributors to the Eclipse 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. * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ package org.osgi.impl.service.upnp.cp.description; import java.net.URL; import org.osgi.framework.BundleContext; public class RootDevice { private String urn; private String urlbase; private int major; private int minor; private String deviceType; private String friendlyName; private String manufacturer; private String manufacturerURL; private String modelDescription; private String modelName; private String modelNumber; private String modelURL; private String serialNumber; private String udn; private String upc; private String presentationURL = ""; private RootDevice devices[]; @SuppressWarnings("unused") private RootDevice rdev; @SuppressWarnings("unused") private RootDevice device; private Icon icons[]; private ServiceInfo serviceList[]; private ServiceInfo servi1[]; public BundleContext bc1; // This constructor creates the RootDevice object RootDevice(RootDevice rd, BundleContext bc) { rdev = rd; bc1 = bc; } // This constructor creates the RootDevice object RootDevice(BundleContext bc) { bc1 = bc; } // This method returns the root attributes of the device xml file. public String getRootAttribute() { return urn; } // This method returns the URLBase of the device xml file. public String getURLBase() { return urlbase; } // This method returns the type of the device. public String getDeviceType() { return deviceType; } // This method returns the friendly name of the device. public String getFriendlyName() { return friendlyName; } // This method returns the manufacturers name of the device. public String getManufacturer() { return manufacturer; } // This method returns the manufacturers URL of the device. public String getManufacturerURL() { return manufacturerURL; } // This method returns the model description of the device. public String getModelDescription() { return modelDescription; } // This method returns the model number of the device. public String getModelNumber() { return modelNumber; } // This method returns the model name of the device. public String getModelName() { return modelName; } // This method returns the modelURL of the device. public String getModelURL() { return modelURL; } // This method returns the serial number of the device. public String getSerialNumber() { return serialNumber; } // This method returns the UDN of the device. public String getUDN() { return udn; } // This method returns the UPC of the device. public String getUPC() { return upc; } // This method returns the presentationURL of the device. public String getPresentationURL() { return presentationURL; } // This method returns the embedded devices of the device. public RootDevice[] getEmbededDevices() { if (devices == null) { return new RootDevice[0]; } else { return devices; } } // This method returns the icons of the device. public Icon[] getIcons() { return icons; } // This method returns all the services which are matching the eventSubURL // of the services. public ServiceInfo getServiceBasedOnURL(String urlValue) { ServiceInfo serv[] = servi1; if (urlValue == null) { urlValue = ""; } urlValue = urlValue.trim(); for (int servCtr = 0; servCtr < serv.length; servCtr++) { if (serv[servCtr].getEventSubURL().trim() .equalsIgnoreCase(urlValue)) { return serv[servCtr]; } } return null; } // This method returns the services of the device. public ServiceInfo[] getServices() { return servi1; } // This method sets the service type for the device. public void setDeviceType(String type) { deviceType = type; } // This method sets the friendly name for the device. public void setFriendlyName(String friendlyname) { friendlyName = friendlyname; } // This method sets the manyfacturers name for the device. public void setManufacturer(String manufacturerName) { manufacturer = manufacturerName; } // This method sets the manufacturer URL for the device. public void setManufacturerURL(String manufacturerurl) { manufacturerURL = manufacturerurl; } // This method sets the model description for the device. public void setModelDescription(String modelDesc) { modelDescription = modelDesc; } // This method sets the model number for the device. public void setModelNumber(String nam) { modelNumber = nam; } // This method sets the model name for the device. public void setModelName(String modelname) { modelName = modelname; } // This method sets the model URL for the device. public void setModelURL(String modelurl) { modelURL = modelurl; } // This method sets the serial number for the device. public void setSerialNumber(String serNumber) { serialNumber = serNumber; } // This method sets the UDN for the device. public void setUDN(String udnValue) { udn = udnValue; } // This method sets the UPC for the device. public void setUPC(String upcValue) { upc = upcValue; } // This method sets the presentation URL for the device. public void setPresentationURL(String presURL) { if (presURL == null) { presURL = ""; } presentationURL = presURL; } // This method sets the embedded devices for the device. public void setEmbeddedDevices(RootDevice arr[]) { devices = arr; } // This method sets the icons for the device. public void setIcons(Icon allIcons[]) { icons = allIcons; } // This method sets the services for the device. public void setServices(ServiceInfo sl[], RootDevice rootdev) { serviceList = sl; servi1 = new ServiceInfo[serviceList.length]; final Description desc = new Description(bc1); String ub = rootdev.getURLBase(); // Sets the urlBase if the urlBase is not specified. if (ub == null || ub.trim().length() == 0) { int slashCtr = Description.cdPath.lastIndexOf('/'); ub = Description.cdPath.substring(0, slashCtr); rootdev.setURLBase(ub); } String bas = ub; //Attaches the services to device based on the SCPDURL. final String bas1 = bas; //Thread t = new Thread(){ // public void run() { Document doc1 = null; for (int k = 0; k < serviceList.length; k++) { try { URL base = new URL(bas1); URL docurl = new URL(base, serviceList[k].getSCPDURL()); //System.out.println(docurl.toString()); doc1 = desc.getDocument(docurl.toString()); servi1[k] = doc1.getServiceInfo(); servi1[k].setSCPDURL(serviceList[k].getSCPDURL()); servi1[k].setControlURL(serviceList[k].getControlURL()); servi1[k].setEventSubURL(serviceList[k].getEventSubURL()); servi1[k].setServiceID(serviceList[k].getServiceID()); servi1[k].setServiceType(serviceList[k].getServiceType()); } catch (Exception e) { System.out.println(e.getMessage()); } } //} //}; } // This method returns the major version of the device xml file. public int getMajor() { return major; } // This method returns the minor version of the device xml file. public int getMinor() { return minor; } // This method returns the device object of the device xml file. public RootDevice getDevice() { return this; } // This method sets the root attributes of the device xml file. public void setRootAttribute(String attrKey, String attrValue) { urn = attrValue; } // This method sets the URLBase for the device object from the device xml // file. public void setURLBase(String base) { urlbase = base; } // This method sets the major version for the device object from the device // xml file. public void setMajor(int ma) { major = ma; } // This method sets the minor version for the device object from the device // xml file. public void setMinor(int mi) { minor = mi; } // This method sets the device object. public void setDevice(RootDevice deviceDetails) { device = deviceDetails; } }
package logic; public class ShopImpl implements Shop{ private UserCatalog userCatalog; public void setUserCatalog(UserCatalog userCatalog) { this.userCatalog = userCatalog; } public User getUserByUserIdAndPassword(String userId, String password) { return this.userCatalog.getUserByUserIdAndPassword(userId, password); } }
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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.alibaba.polardbx.optimizer.parse.bean; import org.apache.calcite.sql.SqlNode; import java.util.List; /** * Created by simiao on 14-12-10. */ public class DBPartitionDefinition { private SqlNode partition_name; private DBPartitionDefinitionType type; private SqlNode lessThan; // used by private Integer startWith; private Integer endWith; // RANGE private List<TBPartitionDefinition> tbpartitionDefinitionList; public List<TBPartitionDefinition> getTbpartitionDefinitionList() { return tbpartitionDefinitionList; } public void setTbpartitionDefinitionList(List<TBPartitionDefinition> tbpartitionDefinitionList) { this.tbpartitionDefinitionList = tbpartitionDefinitionList; } public SqlNode getPartition_name() { return partition_name; } public void setPartition_name(SqlNode partition_name) { this.partition_name = partition_name; } public DBPartitionDefinitionType getType() { return type; } public void setType(DBPartitionDefinitionType type) { this.type = type; } public SqlNode getLessThan() { return lessThan; } public void setLessThan(SqlNode lessThan) { this.lessThan = lessThan; } public Integer getStartWith() { return startWith; } public void setStartWith(Integer startWith) { this.startWith = startWith; } public Integer getEndWith() { return endWith; } public void setEndWith(Integer endWith) { this.endWith = endWith; } }
/* * Copyright (C) 2019 LitterBox contributors * * This file is part of LitterBox. * * LitterBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * LitterBox is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LitterBox. If not, see <http://www.gnu.org/licenses/>. */ package de.uni_passau.fim.se2.litterbox.ast.model.literals; import de.uni_passau.fim.se2.litterbox.ast.model.ASTLeaf; import de.uni_passau.fim.se2.litterbox.ast.model.AbstractNode; import de.uni_passau.fim.se2.litterbox.ast.model.expression.string.StringExpr; import de.uni_passau.fim.se2.litterbox.ast.visitor.ScratchVisitor; import java.util.Objects; public class StringLiteral extends AbstractNode implements StringExpr, ASTLeaf { private final String text; public StringLiteral(String text) { super(); this.text = text; } public String getText() { return text; } @Override public void accept(ScratchVisitor visitor) { visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } StringLiteral that = (StringLiteral) o; return Objects.equals(text, that.text); } @Override public int hashCode() { return Objects.hash(super.hashCode(), text); } }
package app.roam.se.ui.dialogs; import app.roam.se.App; import app.roam.se.ui.misc.Icons; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import javax.swing.*; import javax.swing.plaf.FontUIResource; import javax.swing.text.StyleContext; import java.awt.*; import java.awt.event.*; import java.util.Locale; public class ProjectSettingsDialog extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTabbedPane tabbedPane1; private JLabel lblProjectName; private JLabel lblAuthor; private JLabel lblCreatedDate; private JLabel lblLastModified; private JLabel lblLastRun; private JTabbedPane tabbedPane2; private JTextField textField1; private JList chromeArgumentsList; private JList list2; private JLabel chromeExperimentation; private JList driversList; private JButton addButton; private JButton removeButton; public ProjectSettingsDialog() { setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); setIconImage(Icons.getLogo()); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); // // addButton.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // JTextField key = new JTextField(32); // JTextField val = new JTextField(32); // JPanel panel = new JPanel(); // panel.setLayout(new FlowLayout()); // panel.add(new JLabel("Key")); // panel.add(key); // panel.add(Box.createHorizontalStrut(15)); // panel.add(new JLabel("Value")); // panel.add(val); // int result = JOptionPane.showConfirmDialog(null, panel,"Specify key-value pair for webdrivers",JOptionPane.OK_CANCEL_OPTION); // if(result ==JOptionPane.OK_OPTION){ // if(key.getText().isEmpty()||val.getText().isEmpty()){ // UIUtil.showErrorMessage(null,"Invalid driver","Please provide valuid key-pair entry."); // }else { // App.testProject.addDriver(key.getText(), val.getText()); // refreshSettingsDialog(); // } // } // } // }); // removeButton.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int selected = driversList.getSelectedIndex(); // if (selected > 0) { // if (UIUtil.showYesNoDialog(null, "Remove Driver", "Are you sure to delete '" + driversList.getSelectedValue() + "'?")){ // String value = (String) driversList.getSelectedValue(); // String key = value.split(":")[0]; // App.testProject.removeDriver(key); // refreshSettingsDialog(); // } // } // } // }); refreshSettingsDialog(); } private void onOK() { // add your code here dispose(); } private void onCancel() { // add your code here if necessary dispose(); } public static void showDialog() { ProjectSettingsDialog dialog = new ProjectSettingsDialog(); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setVisible(true); } public void refreshSettingsDialog() { if (App.testProject != null) { lblProjectName.setText(App.testProject.getName()); lblAuthor.setText("Author:" + App.testProject.getAuthor()); lblCreatedDate.setText("Created date: " + App.testProject.getCreatedDate()); lblLastModified.setText("Last Modified: " + App.testProject.getLastModifiedDate()); lblLastRun.setText(App.testProject.getLastRun()); // driversList.removeAll(); // Set<String> keys = App.testProject.getDrivers().keySet(); // // DefaultListModel list = new DefaultListModel(); // for (String key : keys) { // String pair = key +":"+App.testProject.getDrivers().get(key); // list.addElement(pair); // } // driversList.setModel(list); // driversList.addListSelectionListener(new ListSelectionListener() { // @Override // public void valueChanged(ListSelectionEvent e) { // // removeButton.setEnabled(driversList.getSelectedIndex()>=0?true:false); // // } // }); } } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { contentPane = new JPanel(); contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1)); contentPane.setMinimumSize(new Dimension(300, 151)); contentPane.setPreferredSize(new Dimension(640, 480)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); buttonOK = new JButton(); buttonOK.setText("OK"); panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); buttonCancel = new JButton(); buttonCancel.setText("Cancel"); panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); tabbedPane1 = new JTabbedPane(); tabbedPane1.setTabPlacement(2); panel3.add(tabbedPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, 200), null, 0, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridBagLayout()); tabbedPane1.addTab("About", panel4); lblProjectName = new JLabel(); Font lblProjectNameFont = this.$$$getFont$$$(null, Font.BOLD, 16, lblProjectName.getFont()); if (lblProjectNameFont != null) lblProjectName.setFont(lblProjectNameFont); lblProjectName.setHorizontalAlignment(2); lblProjectName.setText("Label"); GridBagConstraints gbc; gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; panel4.add(lblProjectName, gbc); lblAuthor = new JLabel(); lblAuthor.setHorizontalAlignment(0); lblAuthor.setText("Label"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; panel4.add(lblAuthor, gbc); lblCreatedDate = new JLabel(); lblCreatedDate.setHorizontalAlignment(0); lblCreatedDate.setText("Label"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; panel4.add(lblCreatedDate, gbc); lblLastModified = new JLabel(); lblLastModified.setHorizontalAlignment(0); lblLastModified.setText("Label"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 3; panel4.add(lblLastModified, gbc); lblLastRun = new JLabel(); lblLastRun.setHorizontalAlignment(0); lblLastRun.setText("Label"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 4; panel4.add(lblLastRun, gbc); final JPanel panel5 = new JPanel(); panel5.setLayout(new BorderLayout(0, 0)); tabbedPane1.addTab("Drivers", panel5); tabbedPane2 = new JTabbedPane(); panel5.add(tabbedPane2, BorderLayout.CENTER); final JPanel panel6 = new JPanel(); panel6.setLayout(new GridLayoutManager(7, 1, new Insets(0, 0, 0, 0), -1, -1)); tabbedPane2.addTab("Chrome", panel6); textField1 = new JTextField(); panel6.add(textField1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); final Spacer spacer2 = new Spacer(); panel6.add(spacer2, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); final JLabel label1 = new JLabel(); label1.setText("Binary:"); panel6.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); chromeArgumentsList = new JList(); panel6.add(chromeArgumentsList, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(150, 50), null, 0, false)); list2 = new JList(); panel6.add(list2, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(150, 50), null, 0, false)); final JPanel panel7 = new JPanel(); panel7.setLayout(new BorderLayout(0, 0)); panel6.add(panel7, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); chromeExperimentation = new JLabel(); chromeExperimentation.setText("Experimentation:"); panel7.add(chromeExperimentation, BorderLayout.WEST); final JPanel panel8 = new JPanel(); panel8.setLayout(new BorderLayout(0, 0)); panel6.add(panel8, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label2 = new JLabel(); label2.setText("Chrome Options:"); panel8.add(label2, BorderLayout.WEST); } /** * @noinspection ALL */ private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) { if (currentFont == null) return null; String resultName; if (fontName == null) { resultName = currentFont.getName(); } else { Font testFont = new Font(fontName, Font.PLAIN, 10); if (testFont.canDisplay('a') && testFont.canDisplay('1')) { resultName = fontName; } else { resultName = currentFont.getName(); } } Font font = new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize()); boolean isMac = System.getProperty("os.name", "").toLowerCase(Locale.ENGLISH).startsWith("mac"); Font fontWithFallback = isMac ? new Font(font.getFamily(), font.getStyle(), font.getSize()) : new StyleContext().getFont(font.getFamily(), font.getStyle(), font.getSize()); return fontWithFallback instanceof FontUIResource ? fontWithFallback : new FontUIResource(fontWithFallback); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return contentPane; } }
/* * The MIT License * Copyright © 2014-2019 Ilkka Seppälä * * 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.iluwatar.decorator; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} * throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
/** * MIT License * * Copyright (c) 2018 Anatoly Gudkov * * 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 org.green.jelly; import static org.green.jelly.JsonGenerator.HEX_DIGITS; public final class AsciiByteArrayWriter implements JsonBufferedWriter { private final Frame frame = new Frame() { @Override public void setCharAt(final int index, final char c) { assert c > 0x1f // all chars <= 0x1f are expected to be encoded to \\uXXXX by JsonGenerator already && c < 0x7f; // only ASCII supported by the Frame array[frameStart + index] = (byte) c; } @Override public char charAt(final int index) { return (char) array[frameStart + index]; } @Override public CharSequence subSequence(final int start, final int end) { throw new UnsupportedOperationException("Not supported."); } @Override public int length() { return frameSize; } @Override public String toString() { return new String(array, frameStart, frameSize); } }; private byte[] array; private int start; private int length; private int frameStart; private int frameSize; public AsciiByteArrayWriter() { } public AsciiByteArrayWriter(final int initialSize) { this(new byte[initialSize]); } public AsciiByteArrayWriter(final byte[] array) { this(array, 0); } public AsciiByteArrayWriter(final byte[] array, final int start) { set(array, start); } public void set(final byte[] array) { set(array, 0); } public void set(final byte[] array, final int start) { assert array.length > start; this.array = array; this.start = start; this.length = 0; } public byte[] array() { return array; } public int start() { return start; } public int length() { return length; } public void clear() { length = 0; } @Override public Frame append(final int size) { assert size > 0; makeSureRoomSize(size); frameStart = start + length; frameSize = size; length += size; return frame; } @Override public void append(final char c) { assert array != null; assert c > 0x1f; // all chars <= 0x1f are expected to be encoded to \\uXXXX by JsonGenerator already int charIndex = start + length; if (c < 0x7f) { makeSureRoomSize(1); length++; array[charIndex] = (byte) c; return; } makeSureRoomSize(6); length = length + 6; array[charIndex++] = (byte) '\\'; array[charIndex++] = (byte) 'u'; if (c < 0x800) { // 2 bytes array[charIndex++] = (byte) '0'; array[charIndex++] = (byte) '0'; array[charIndex++] = (byte) HEX_DIGITS[c >>> 4 & 0x000f]; array[charIndex++] = (byte) HEX_DIGITS[c & 0x000f]; return; } if (c < 0x8000) { // 3 bytes array[charIndex++] = (byte) '0'; array[charIndex++] = (byte) HEX_DIGITS[c >>> 8 & 0x000f]; array[charIndex++] = (byte) HEX_DIGITS[c >>> 4 & 0x000f]; array[charIndex++] = (byte) HEX_DIGITS[c & 0x000f]; return; } // 4 bytes array[charIndex++] = (byte) HEX_DIGITS[c >>> 12 & 0x000f]; array[charIndex++] = (byte) HEX_DIGITS[c >>> 8 & 0x000f]; array[charIndex++] = (byte) HEX_DIGITS[c >>> 4 & 0x000f]; array[charIndex++] = (byte) HEX_DIGITS[c & 0x000f]; } @Override public void append(final CharSequence data) { append(data, 0, data.length()); } @Override public void append(final CharSequence data, final int start, final int len) { for (int i = start; i < len; i++) { append(data.charAt(i)); } } @Override public void flush() { } private void makeSureRoomSize(final int roomSize) { final int delta = array.length - (start + length + roomSize); if (delta < 0) { final int newSize = Math.max(roomSize, array.length - start) << 1; final byte[] newArray = new byte[newSize]; System.arraycopy(array, start, newArray, 0, length); array = newArray; start = 0; } } @Override public String toString() { if (array == null) { return "null"; } return new String(array, start, length); } }
/* * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.codemodel; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Collection; import java.util.Collections; /** * A Java package. */ public final class JPackage implements JDeclaration, JGenerable, JClassContainer, JAnnotatable, Comparable<JPackage>, JDocCommentable { /** * Name of the package. * May be the empty string for the root package. */ private String name; private final JCodeModel owner; /** * List of classes contained within this package keyed by their name. */ private final Map<String,JDefinedClass> classes = new TreeMap<>(); /** * List of resources files inside this package. */ private final Set<JResourceFile> resources = new HashSet<>(); /** * All {@link JClass}s in this package keyed the upper case class name. * * This field is non-null only on Windows, to detect * "Foo" and "foo" as a collision. */ private final Map<String,JDefinedClass> upperCaseClassMap; /** * Lazily created list of package annotations. */ private List<JAnnotationUse> annotations = null; /** * package javadoc. */ private JDocComment jdoc = null; /** * JPackage constructor * * @param name * Name of package * * @param cw The code writer being used to create this package * * @throws IllegalArgumentException * If each part of the package name is not a valid identifier */ JPackage(String name, JCodeModel cw) { this.owner = cw; if (name.equals(".")) { String msg = "Package name . is not allowed"; throw new IllegalArgumentException(msg); } if(JCodeModel.isCaseSensitiveFileSystem) upperCaseClassMap = null; else upperCaseClassMap = new HashMap<>(); this.name = name; } @Override public JClassContainer parentContainer() { return parent(); } /** * Gets the parent package, or null if this class is the root package. * @return */ public JPackage parent() { if(name.length()==0) return null; int idx = name.lastIndexOf('.'); return owner._package(name.substring(0,idx)); } @Override public boolean isClass() { return false; } @Override public boolean isPackage() { return true; } @Override public JPackage getPackage() { return this; } /** * Add a class to this package. * * @param mods * Modifiers for this class declaration * * @param name * Name of class to be added to this package * * @return Newly generated class * * @exception JClassAlreadyExistsException * When the specified class/interface was already created. */ @Override public JDefinedClass _class(int mods, String name) throws JClassAlreadyExistsException { return _class(mods,name,ClassType.CLASS); } /** * {@inheritDoc} * @deprecated */ @Deprecated @Override public JDefinedClass _class( int mods, String name, boolean isInterface ) throws JClassAlreadyExistsException { return _class(mods,name, isInterface?ClassType.INTERFACE:ClassType.CLASS ); } @Override public JDefinedClass _class( int mods, String name, ClassType classTypeVal ) throws JClassAlreadyExistsException { if(classes.containsKey(name)) throw new JClassAlreadyExistsException(classes.get(name)); else { // XXX problems caught in the NC constructor JDefinedClass c = new JDefinedClass(this, mods, name, classTypeVal); if( upperCaseClassMap!=null ) { JDefinedClass dc = upperCaseClassMap.get(name.toUpperCase()); if(dc!=null) throw new JClassAlreadyExistsException(dc); upperCaseClassMap.put(name.toUpperCase(),c); } classes.put(name,c); return c; } } /** * Adds a public class to this package. * * @param name * @return * @throws JClassAlreadyExistsException */ @Override public JDefinedClass _class(String name) throws JClassAlreadyExistsException { return _class(JMod.PUBLIC, name); } /** * Gets a reference to the already created {@link JDefinedClass}. * * @param name * @return null * If the class is not yet created. */ public JDefinedClass _getClass(String name) { if(classes.containsKey(name)) return classes.get(name); else return null; } /** * Order is based on the lexicological order of the package name. * @param that */ @Override public int compareTo(JPackage that) { return this.name.compareTo(that.name); } /** * Add an interface to this package. * * @param mods * Modifiers for this interface declaration * * @param name * Name of interface to be added to this package * * @return Newly generated interface * @throws JClassAlreadyExistsException */ @Override public JDefinedClass _interface(int mods, String name) throws JClassAlreadyExistsException { return _class(mods,name,ClassType.INTERFACE); } /** * Adds a public interface to this package. * @param name * @return * @throws JClassAlreadyExistsException */ @Override public JDefinedClass _interface(String name) throws JClassAlreadyExistsException { return _interface(JMod.PUBLIC, name); } /** * Add an annotationType Declaration to this package * @param name * Name of the annotation Type declaration to be added to this package * @return * newly created Annotation Type Declaration * @exception JClassAlreadyExistsException * When the specified class/interface was already created. */ @Override public JDefinedClass _annotationTypeDeclaration(String name) throws JClassAlreadyExistsException { return _class (JMod.PUBLIC,name,ClassType.ANNOTATION_TYPE_DECL); } /** * Add a public enum to this package * @param name * Name of the enum to be added to this package * @return * newly created Enum * @exception JClassAlreadyExistsException * When the specified class/interface was already created. */ @Override public JDefinedClass _enum (String name) throws JClassAlreadyExistsException { return _class (JMod.PUBLIC,name,ClassType.ENUM); } /** * Adds a new resource file to this package. * @param rsrc * @return */ public JResourceFile addResourceFile(JResourceFile rsrc) { resources.add(rsrc); return rsrc; } /** * Checks if a resource of the given name exists. * @param name * @return */ public boolean hasResourceFile(String name) { for (JResourceFile r : resources) if (r.name().equals(name)) return true; return false; } /** * Iterates all resource files in this package. * @return */ public Iterator<JResourceFile> propertyFiles() { return resources.iterator(); } /** * Creates, if necessary, and returns the package javadoc for this * JDefinedClass. * * @return JDocComment containing javadocs for this class */ @Override public JDocComment javadoc() { if (jdoc == null) jdoc = new JDocComment(owner()); return jdoc; } /** * Removes a class from this package. * @param c */ public void remove(JClass c) { if (c._package() != this) throw new IllegalArgumentException( "the specified class is not a member of this package," + " or it is a referenced class"); // note that c may not be a member of classes. // this happens when someone is trying to remove a non generated class classes.remove(c.name()); if (upperCaseClassMap != null) upperCaseClassMap.remove(c.name().toUpperCase()); } /** * Reference a class within this package. * @param name * @return * @throws java.lang.ClassNotFoundException */ public JClass ref(String name) throws ClassNotFoundException { if (name.indexOf('.') >= 0) throw new IllegalArgumentException("JClass name contains '.': " + name); String n = ""; if (!isUnnamed()) n = this.name + '.'; n += name; return owner.ref(Class.forName(n)); } /** * Gets a reference to a sub package of this package. * @param pkg * @return */ public JPackage subPackage( String pkg ) { if(isUnnamed()) return owner()._package(pkg); else return owner()._package(name+'.'+pkg); } /** * Returns an iterator that walks the top-level classes defined in this * package. * @return */ @Override public Iterator<JDefinedClass> classes() { return classes.values().iterator(); } /** * Checks if this package contains any classes. * @return {@code true} if this package contains any classes * or {@code false} otherwise. */ public boolean hasClasses() { return !classes.isEmpty(); } /** * Checks if a given name is already defined as a class/interface * @param classLocalName * @return */ public boolean isDefined(String classLocalName) { Iterator<JDefinedClass> itr = classes(); while (itr.hasNext()) { if ((itr.next()).name().equals(classLocalName)) return true; } return false; } /** * Checks if this package is the root, unnamed package. * @return */ public final boolean isUnnamed() { return name.length() == 0; } /** * Get the name of this package * * @return * The name of this package, or the empty string if this is the null * package. For example, this method returns strings like * <code>"java.lang"</code> */ public String name() { return name; } /** * Return the code model root object being used to create this package. * @return */ @Override public final JCodeModel owner() { return owner; } @Override public JAnnotationUse annotate(JClass clazz) { if(isUnnamed()) throw new IllegalArgumentException("the root package cannot be annotated"); if(annotations==null) annotations = new ArrayList<>(); JAnnotationUse a = new JAnnotationUse(clazz); annotations.add(a); return a; } @Override public JAnnotationUse annotate(Class<? extends Annotation> clazz) { return annotate(owner.ref(clazz)); } @Override public <W extends JAnnotationWriter> W annotate2(Class<W> clazz) { return TypedAnnotationWriter.create(clazz,this); } @Override public boolean removeAnnotation(JAnnotationUse annotation) { return this.annotations.remove(annotation); } @Override public Collection<JAnnotationUse> annotations() { if (annotations == null) annotations = new ArrayList<>(); return Collections.unmodifiableList(annotations); } /** * Convert the package name to directory path equivalent */ File toPath(File dir) { if (name == null) return dir; return new File(dir, name.replace('.', File.separatorChar)); } @Override public void declare(JFormatter f ) { if (name.length() != 0) f.p("package").p(name).p(';').nl(); } @Override public void generate(JFormatter f) { f.p(name); } void build( CodeWriter src, CodeWriter res ) throws IOException { // write classes for (JDefinedClass c : classes.values()) { if (c.isHidden()) continue; // don't generate this file JFormatter f = createJavaSourceFileWriter(src, c.name()); f.write(c); f.close(); } // write package annotations if ((annotations!=null && !annotations.isEmpty()) || jdoc != null) { JFormatter f = createJavaSourceFileWriter(src,"package-info"); if (jdoc != null) f.g(jdoc); // TODO: think about importing if (annotations != null){ for (JAnnotationUse a : annotations) f.g(a).nl(); } f.d(this); f.close(); } // write resources for (JResourceFile rsrc : resources) { CodeWriter cw = rsrc.isResource() ? res : src; OutputStream os = new BufferedOutputStream(cw.openBinary(this, rsrc.name())); rsrc.build(os); os.close(); } } /*package*/ int countArtifacts() { int r = 0; for (JDefinedClass c : classes.values()) { if (c.isHidden()) continue; // don't generate this file r++; } if ((annotations!=null && !annotations.isEmpty()) || jdoc != null) { r++; } r+= resources.size(); return r; } private JFormatter createJavaSourceFileWriter(CodeWriter src, String className) throws IOException { Writer bw = new BufferedWriter(src.openSource(this,className+".java")); return new JFormatter(new PrintWriter(bw), owner.classNameReplacer()); } }
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.api.client.googleapis.util.Utils; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.testing.http.MockHttpTransport; import com.google.common.collect.ImmutableMap; import java.io.IOException; import org.junit.Test; public class OutgoingHttpRequestTest { private static final String TEST_URL = "https://firebase.google.com/request"; @Test(expected = NullPointerException.class) public void testNullHttpRequest() { new OutgoingHttpRequest(null); } @Test(expected = IllegalArgumentException.class) public void testNullMethod() { new OutgoingHttpRequest(null, TEST_URL); } @Test(expected = IllegalArgumentException.class) public void testEmptyMethod() { new OutgoingHttpRequest("", TEST_URL); } @Test(expected = IllegalArgumentException.class) public void testNullUrl() { new OutgoingHttpRequest(HttpMethods.GET, null); } @Test(expected = IllegalArgumentException.class) public void testEmptyUrl() { new OutgoingHttpRequest(HttpMethods.GET, ""); } @Test public void testOutgoingHttpRequest() { OutgoingHttpRequest request = new OutgoingHttpRequest(HttpMethods.GET, TEST_URL); assertEquals(HttpMethods.GET, request.getMethod()); assertEquals(TEST_URL, request.getUrl()); assertNull(request.getContent()); assertTrue(request.getHeaders().isEmpty()); } @Test public void testOutgoingHttpRequestWithContent() throws IOException { JsonHttpContent streamingContent = new JsonHttpContent( Utils.getDefaultJsonFactory(), ImmutableMap.of("key", "value")); HttpRequest httpRequest = new MockHttpTransport().createRequestFactory() .buildPostRequest(new GenericUrl(TEST_URL), streamingContent); httpRequest.getHeaders().set("X-Firebase-Client", "test-version"); OutgoingHttpRequest request = new OutgoingHttpRequest(httpRequest); assertEquals(HttpMethods.POST, request.getMethod()); assertEquals(TEST_URL, request.getUrl()); assertSame(streamingContent, request.getContent()); assertEquals("test-version", request.getHeaders().get("x-firebase-client")); } }
package com.zftlive.android.library.base; import java.util.ArrayList; import java.util.Collection; import java.util.List; import android.app.Activity; /** * Adapter基类 * @author 曾繁添 * @version 1.0 * @param <T> Adapter绑定的数据源行类型Bean/Map/Object */ public abstract class BaseMAdapter<T> extends android.widget.BaseAdapter { /** 数据存储集合 **/ private List<T> mDataList = new ArrayList<T>(); /** Context上下文 **/ private Activity mContext; /** 每一页显示条数 **/ private int mPerPageSize = 10; /**日志输出标志**/ protected final String TAG = this.getClass().getSimpleName(); public BaseMAdapter() { this(null); } public BaseMAdapter(Activity mContext) { this(mContext,10); } public BaseMAdapter(Activity mContext,int mPerPageSize){ this.mContext = mContext; this.mPerPageSize = mPerPageSize; } @Override public int getCount() { return mDataList.size(); } @Override public T getItem(int position) { if (position < mDataList.size()) return mDataList.get(position); else return null; } @Override public long getItemId(int position) { return position; } /** * 获取当前页 * @return 当前页 */ public int getPageNo(){ return (getCount() / mPerPageSize) + 1; } /** * 添加数据 * @param item 数据项 */ public boolean addItem(T object){ return mDataList.add(object); } /** * 在指定索引位置添加数据 * @param location 索引 * @param object 数据 */ public void addItem(int location,T object){ mDataList.add(location, object); } /** * 集合方式添加数据 * @param collection 集合 */ public boolean addItem(Collection collection){ return mDataList.addAll(collection); } /** * 在指定索引位置添加数据集合 * @param location 索引 * @param collection 数据集合 */ public boolean addItem(int location,Collection collection){ return mDataList.addAll(location,collection); } /** * 移除指定对象数据 * @param object 移除对象 * @return 是否移除成功 */ public boolean removeItem(Object object){ return mDataList.remove(object); } /** * 移除指定索引位置对象 * @param location 删除对象索引位置 * @return 被删除的对象 */ public Object removeItem(int location){ return mDataList.remove(location); } /** * 移除指定集合对象 * @param collection 待移除的集合 * @return 是否移除成功 */ public boolean removeAll(Collection collection){ return mDataList.removeAll(collection); } /** * 清空数据 */ public void clear() { mDataList.clear(); } /** * 获取Activity方法 * @return Activity的子类 */ public Activity getActivity(){ return mContext; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds.scm.node; import org.apache.hadoop.hdds.HddsConfigKeys; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.protocol.DatanodeDetails; import org.apache.hadoop.hdds.protocol.MockDatanodeDetails; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.apache.hadoop.hdds.scm.HddsTestUtils; import org.apache.hadoop.hdds.scm.DatanodeAdminError; import org.apache.hadoop.hdds.scm.ha.SCMContext; import org.apache.hadoop.hdds.scm.node.states.NodeNotFoundException; import org.apache.hadoop.hdds.scm.server.StorageContainerManager; import org.apache.hadoop.hdds.server.events.EventQueue; import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.ozone.test.GenericTestUtils; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.Arrays; import java.util.ArrayList; import static junit.framework.TestCase.assertEquals; import static org.assertj.core.api.Fail.fail; import static org.junit.Assert.assertNotEquals; /** * Unit tests for the decommision manager. */ public class TestNodeDecommissionManager { private NodeDecommissionManager decom; private StorageContainerManager scm; private NodeManager nodeManager; private OzoneConfiguration conf; private String storageDir; @Before public void setup() throws Exception { conf = new OzoneConfiguration(); storageDir = GenericTestUtils.getTempPath( TestDeadNodeHandler.class.getSimpleName() + UUID.randomUUID()); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, storageDir); nodeManager = createNodeManager(conf); decom = new NodeDecommissionManager(conf, nodeManager, null, SCMContext.emptyContext(), new EventQueue(), null); } @Test public void testHostStringsParseCorrectly() throws InvalidHostStringException { NodeDecommissionManager.HostDefinition def = new NodeDecommissionManager.HostDefinition("foobar"); assertEquals("foobar", def.getHostname()); assertEquals(-1, def.getPort()); def = new NodeDecommissionManager.HostDefinition(" foobar "); assertEquals("foobar", def.getHostname()); assertEquals(-1, def.getPort()); def = new NodeDecommissionManager.HostDefinition("foobar:1234"); assertEquals("foobar", def.getHostname()); assertEquals(1234, def.getPort()); def = new NodeDecommissionManager.HostDefinition( "foobar.mycompany.com:1234"); assertEquals("foobar.mycompany.com", def.getHostname()); assertEquals(1234, def.getPort()); try { new NodeDecommissionManager.HostDefinition("foobar:abcd"); fail("InvalidHostStringException should have been thrown"); } catch (InvalidHostStringException e) { } } @Test public void testAnyInvalidHostThrowsException() throws InvalidHostStringException { List<DatanodeDetails> dns = generateDatanodes(); // Try to decommission a host that does exist, but give incorrect port try { decom.decommissionNodes(Arrays.asList(dns.get(1).getIpAddress() + ":10")); fail("InvalidHostStringException expected"); } catch (InvalidHostStringException e) { } // Try to decommission a host that does not exist try { decom.decommissionNodes(Arrays.asList("123.123.123.123")); fail("InvalidHostStringException expected"); } catch (InvalidHostStringException e) { } // Try to decommission a host that does exist and a host that does not try { decom.decommissionNodes(Arrays.asList( dns.get(1).getIpAddress(), "123,123,123,123")); fail("InvalidHostStringException expected"); } catch (InvalidHostStringException e) { } // Try to decommission a host with many DNs on the address with no port try { decom.decommissionNodes(Arrays.asList( dns.get(0).getIpAddress())); fail("InvalidHostStringException expected"); } catch (InvalidHostStringException e) { } // Try to decommission a host with many DNs on the address with a port // that does not exist try { decom.decommissionNodes(Arrays.asList( dns.get(0).getIpAddress() + ":10")); fail("InvalidHostStringException expected"); } catch (InvalidHostStringException e) { } } @Test public void testNodesCanBeDecommissionedAndRecommissioned() throws InvalidHostStringException, NodeNotFoundException { List<DatanodeDetails> dns = generateDatanodes(); // Decommission 2 valid nodes decom.decommissionNodes(Arrays.asList(dns.get(1).getIpAddress(), dns.get(2).getIpAddress())); assertEquals(HddsProtos.NodeOperationalState.DECOMMISSIONING, nodeManager.getNodeStatus(dns.get(1)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.DECOMMISSIONING, nodeManager.getNodeStatus(dns.get(2)).getOperationalState()); // Running the command again gives no error - nodes already decommissioning // are silently ignored. decom.decommissionNodes(Arrays.asList(dns.get(1).getIpAddress(), dns.get(2).getIpAddress())); // Attempt to decommission dn(10) which has multiple hosts on the same IP // and we hardcoded ports to 3456, 4567, 5678 DatanodeDetails multiDn = dns.get(10); String multiAddr = multiDn.getIpAddress() + ":" + multiDn.getPorts().get(0).getValue(); decom.decommissionNodes(Arrays.asList(multiAddr)); assertEquals(HddsProtos.NodeOperationalState.DECOMMISSIONING, nodeManager.getNodeStatus(multiDn).getOperationalState()); // Recommission all 3 hosts decom.recommissionNodes(Arrays.asList( multiAddr, dns.get(1).getIpAddress(), dns.get(2).getIpAddress())); decom.getMonitor().run(); assertEquals(HddsProtos.NodeOperationalState.IN_SERVICE, nodeManager.getNodeStatus(dns.get(1)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.IN_SERVICE, nodeManager.getNodeStatus(dns.get(2)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.IN_SERVICE, nodeManager.getNodeStatus(dns.get(10)).getOperationalState()); } @Test public void testNodesCanBePutIntoMaintenanceAndRecommissioned() throws InvalidHostStringException, NodeNotFoundException { List<DatanodeDetails> dns = generateDatanodes(); // Put 2 valid nodes into maintenance decom.startMaintenanceNodes(Arrays.asList(dns.get(1).getIpAddress(), dns.get(2).getIpAddress()), 100); assertEquals(HddsProtos.NodeOperationalState.ENTERING_MAINTENANCE, nodeManager.getNodeStatus(dns.get(1)).getOperationalState()); assertNotEquals(0, nodeManager.getNodeStatus( dns.get(1)).getOpStateExpiryEpochSeconds()); assertEquals(HddsProtos.NodeOperationalState.ENTERING_MAINTENANCE, nodeManager.getNodeStatus(dns.get(2)).getOperationalState()); assertNotEquals(0, nodeManager.getNodeStatus( dns.get(2)).getOpStateExpiryEpochSeconds()); // Running the command again gives no error - nodes already decommissioning // are silently ignored. decom.startMaintenanceNodes(Arrays.asList(dns.get(1).getIpAddress(), dns.get(2).getIpAddress()), 100); // Attempt to decommission dn(10) which has multiple hosts on the same IP // and we hardcoded ports to 3456, 4567, 5678 DatanodeDetails multiDn = dns.get(10); String multiAddr = multiDn.getIpAddress() + ":" + multiDn.getPorts().get(0).getValue(); decom.startMaintenanceNodes(Arrays.asList(multiAddr), 100); assertEquals(HddsProtos.NodeOperationalState.ENTERING_MAINTENANCE, nodeManager.getNodeStatus(multiDn).getOperationalState()); // Recommission all 3 hosts decom.recommissionNodes(Arrays.asList( multiAddr, dns.get(1).getIpAddress(), dns.get(2).getIpAddress())); decom.getMonitor().run(); assertEquals(HddsProtos.NodeOperationalState.IN_SERVICE, nodeManager.getNodeStatus(dns.get(1)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.IN_SERVICE, nodeManager.getNodeStatus(dns.get(2)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.IN_SERVICE, nodeManager.getNodeStatus(dns.get(10)).getOperationalState()); } @Test public void testNodesCannotTransitionFromDecomToMaint() throws Exception { List<DatanodeDetails> dns = generateDatanodes(); // Put 1 node into maintenance and another into decom decom.startMaintenance(dns.get(1), 100); decom.startDecommission(dns.get(2)); assertEquals(HddsProtos.NodeOperationalState.ENTERING_MAINTENANCE, nodeManager.getNodeStatus(dns.get(1)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.DECOMMISSIONING, nodeManager.getNodeStatus(dns.get(2)).getOperationalState()); // Try to go from maint to decom: List<String> dn = new ArrayList<>(); dn.add(dns.get(1).getIpAddress()); List<DatanodeAdminError> errors = decom.decommissionNodes(dn); assertEquals(1, errors.size()); assertEquals(dns.get(1).getHostName(), errors.get(0).getHostname()); // Try to go from decom to maint: dn = new ArrayList<>(); dn.add(dns.get(2).getIpAddress()); errors = decom.startMaintenanceNodes(dn, 100); assertEquals(1, errors.size()); assertEquals(dns.get(2).getHostName(), errors.get(0).getHostname()); // Ensure the states are still as before assertEquals(HddsProtos.NodeOperationalState.ENTERING_MAINTENANCE, nodeManager.getNodeStatus(dns.get(1)).getOperationalState()); assertEquals(HddsProtos.NodeOperationalState.DECOMMISSIONING, nodeManager.getNodeStatus(dns.get(2)).getOperationalState()); } @Test public void testNodeDecommissionManagerOnBecomeLeader() throws Exception { List<DatanodeDetails> dns = generateDatanodes(); long maintenanceEnd = (System.currentTimeMillis() / 1000L) + (100 * 60L * 60L); // Put 1 node into entering_maintenance, 1 node into decommissioning // and 1 node into in_maintenance. nodeManager.setNodeOperationalState(dns.get(1), HddsProtos.NodeOperationalState.ENTERING_MAINTENANCE, maintenanceEnd); nodeManager.setNodeOperationalState(dns.get(2), HddsProtos.NodeOperationalState.DECOMMISSIONING, 0); nodeManager.setNodeOperationalState(dns.get(3), HddsProtos.NodeOperationalState.IN_MAINTENANCE, maintenanceEnd); // trackedNodes should be empty now. assertEquals(decom.getMonitor().getTrackedNodes().size(), 0); // all nodes with decommissioning, entering_maintenance and in_maintenance // should be added to trackedNodes decom.onBecomeLeader(); decom.getMonitor().run(); // so size of trackedNodes will be 3. assertEquals(decom.getMonitor().getTrackedNodes().size(), 3); } private SCMNodeManager createNodeManager(OzoneConfiguration config) throws IOException, AuthenticationException { scm = HddsTestUtils.getScm(config); return (SCMNodeManager) scm.getScmNodeManager(); } /** * Generate a list of random DNs and return the list. A total of 11 DNs will * be generated and registered with the node manager. Index 0 and 10 will * have the same IP and host and the rest will have unique IPs and Hosts. * The DN at index 10, has 3 hard coded ports of 3456, 4567, 5678. All other * DNs will have ports set to 0. * @return The list of DatanodeDetails Generated */ private List<DatanodeDetails> generateDatanodes() { List<DatanodeDetails> dns = new ArrayList<>(); for (int i = 0; i < 10; i++) { DatanodeDetails dn = MockDatanodeDetails.randomDatanodeDetails(); dns.add(dn); nodeManager.register(dn, null, null); } // We have 10 random DNs, we want to create another one that is on the same // host as some of the others. DatanodeDetails multiDn = dns.get(0); DatanodeDetails.Builder builder = DatanodeDetails.newBuilder(); builder.setUuid(UUID.randomUUID()) .setHostName(multiDn.getHostName()) .setIpAddress(multiDn.getIpAddress()) .addPort(DatanodeDetails.newPort( DatanodeDetails.Port.Name.STANDALONE, 3456)) .addPort(DatanodeDetails.newPort( DatanodeDetails.Port.Name.RATIS, 4567)) .addPort(DatanodeDetails.newPort( DatanodeDetails.Port.Name.REST, 5678)) .setNetworkLocation(multiDn.getNetworkLocation()); DatanodeDetails dn = builder.build(); nodeManager.register(dn, null, null); dns.add(dn); return dns; } }
package frc.robot.subsystems.BallPath; import java.util.concurrent.TimeUnit; import ca.team3161.lib.robot.LifecycleEvent; import ca.team3161.lib.robot.subsystem.RepeatingPooledSubsystem; import frc.robot.subsystems.BallPath.Elevator.Elevator; import frc.robot.subsystems.BallPath.Elevator.Elevator.ElevatorAction; import frc.robot.subsystems.BallPath.Intake.Intake; import frc.robot.subsystems.BallPath.Intake.Intake.IntakeAction; import frc.robot.subsystems.BallPath.Shooter.Shooter; import frc.robot.subsystems.BallPath.Shooter.Shooter.ShotPosition; public class BallPathImpl extends RepeatingPooledSubsystem implements BallPath { private final Intake intake; private final Elevator elevator; private final Shooter shooter; private BallAction action = BallAction.NONE; public BallPathImpl(Intake intake, Elevator elevator, Shooter shooter) { super(20, TimeUnit.MILLISECONDS); this.intake = intake; this.elevator = elevator; this.shooter = shooter; } @Override public void defineResources(){ require(intake); require(elevator); require(shooter); } @Override public void setAction(BallAction action) { this.action = action; } @Override public void task() { boolean intakeLoaded = intake.ballPrimed(); boolean elevatorLoaded = elevator.ballPrimed(); boolean robotEmpty = !intakeLoaded && !elevatorLoaded; boolean elevatorOnly = elevatorLoaded && !intakeLoaded; boolean intakeOnly = intakeLoaded && !elevatorLoaded; boolean full = intakeLoaded && elevatorLoaded; switch (action) { case FEED: if (robotEmpty) { intake.setAction(IntakeAction.FEED); elevator.setAction(ElevatorAction.FEED); shooter.setShotPosition(ShotPosition.NONE); } if (elevatorOnly) { elevator.setAction(ElevatorAction.NONE); intake.setAction(IntakeAction.FEED); shooter.setShotPosition(ShotPosition.NONE); } if (intakeOnly) { elevator.setAction(ElevatorAction.FEED); intake.setAction(IntakeAction.PRIME); shooter.setShotPosition(ShotPosition.NONE); } if (full) { elevator.setAction(ElevatorAction.NONE); intake.setAction(IntakeAction.NONE); shooter.setShotPosition(ShotPosition.NONE); } break; case SHOOT: if (robotEmpty) { elevator.setAction(ElevatorAction.FEED); intake.setAction(IntakeAction.NONE); shooter.setShotPosition(ShotPosition.NONE); } if (elevatorOnly) { if (shooter.readyToShoot()) { elevator.setAction(ElevatorAction.PRIME); } intake.setAction(IntakeAction.NONE); } if (intakeOnly) { elevator.setAction(ElevatorAction.PRIME); intake.setAction(IntakeAction.PRIME); } if (full) { if(shooter.readyToShoot()){ elevator.setAction(ElevatorAction.PRIME); intake.setAction(IntakeAction.PRIME); } } break; case NONE: default: intake.setAction(IntakeAction.NONE); elevator.setAction(ElevatorAction.NONE); shooter.setShotPosition(ShotPosition.NONE); break; } } @Override public void lifecycleStatusChanged(LifecycleEvent previous, LifecycleEvent current) { switch (current) { case ON_INIT: case ON_AUTO: case ON_TELEOP: case ON_TEST: this.start(); break; case ON_DISABLED: case NONE: default: this.cancel(); break; } } }
package io.dwak.android.knockknock; import com.google.gson.annotations.SerializedName; import java.util.List; public class Joke { @SerializedName("joke") public final List<String> mJokeArray; public Joke(List<String> jokeArray) { mJokeArray = jokeArray; } }
package com.dlink.catalog.function; import com.dlink.constant.FlinkFunctionConstant; import com.dlink.ud.udf.GetKey; import com.dlink.ud.udtaf.RowsToMap; import com.dlink.ud.udtaf.Top2; import java.util.HashMap; import java.util.Map; /** * FunctionManager * * @author wenmo * @since 2021/6/14 21:19 */ @Deprecated public class FunctionManager { private static Map<String, UDFunction> functions = new HashMap<String, UDFunction>() { { put(FlinkFunctionConstant.GET_KEY, new UDFunction(FlinkFunctionConstant.GET_KEY, UDFunction.UDFunctionType.Scalar, new GetKey())); put(FlinkFunctionConstant.TO_MAP, new UDFunction(FlinkFunctionConstant.TO_MAP, UDFunction.UDFunctionType.TableAggregate, new RowsToMap())); put(FlinkFunctionConstant.TOP2, new UDFunction(FlinkFunctionConstant.TOP2, UDFunction.UDFunctionType.TableAggregate, new Top2())); } }; public static Map<String, UDFunction> getUsedFunctions(String statement) { Map<String, UDFunction> map = new HashMap<>(); String sql = statement.toLowerCase(); for (Map.Entry<String, UDFunction> entry : functions.entrySet()) { if (sql.contains(entry.getKey().toLowerCase())) { map.put(entry.getKey(), entry.getValue()); } } return map; } }
package cloneproject.Instagram.domain.search.dto; import java.util.List; import com.querydsl.core.annotations.QueryProjection; import cloneproject.Instagram.domain.follow.dto.FollowDto; import cloneproject.Instagram.domain.member.dto.MemberDto; import cloneproject.Instagram.domain.member.entity.Member; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) public class SearchMemberDto extends SearchDto { private MemberDto member; private boolean isFollowing; private boolean isFollower; private List<FollowDto> followingMemberFollow; @QueryProjection public SearchMemberDto(String dtype, Member member, boolean isFollowing, boolean isFollower) { super(dtype); this.member = new MemberDto(member); this.isFollowing = isFollowing; this.isFollower = isFollower; // this.followingMemberFollow = followingMemberFollow; } public void setFollowingMemberFollow(List<FollowDto> followingMemberFollow) { this.followingMemberFollow = followingMemberFollow; } }
/* * Copyright 2012-2019 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 * * 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. */ package org.springframework.boot.autoconfigure.rsocket; import java.net.InetAddress; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.rsocket.server.RSocketServer; /** * {@link ConfigurationProperties properties} for RSocket support. * * @author Brian Clozel * @since 2.2.0 */ @ConfigurationProperties("spring.rsocket") public class RSocketProperties { private final Server server = new Server(); public Server getServer() { return this.server; } public static class Server { /** * Server port. */ private Integer port; /** * Network address to which the server should bind. */ private InetAddress address; /** * RSocket transport protocol. */ private RSocketServer.TRANSPORT transport = RSocketServer.TRANSPORT.TCP; /** * Path under which RSocket handles requests (only works with websocket * transport). */ private String mappingPath; public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; } public InetAddress getAddress() { return this.address; } public void setAddress(InetAddress address) { this.address = address; } public RSocketServer.TRANSPORT getTransport() { return this.transport; } public void setTransport(RSocketServer.TRANSPORT transport) { this.transport = transport; } public String getMappingPath() { return this.mappingPath; } public void setMappingPath(String mappingPath) { this.mappingPath = mappingPath; } } }
package com.aem.exercise.romannumeral.controller; import com.aem.exercise.romannumeral.exception.UnsupportedInputException; import org.junit.Assert; import org.junit.Test; import org.springframework.http.ResponseEntity; public class ExceptionAdviceTest { private ExceptionAdvice advice = new ExceptionAdvice(); @Test public void testHandleUnSupportedInputException() { UnsupportedInputException inputException = new UnsupportedInputException(-5l); ResponseEntity<String> adviceResponse = advice.handleUnSupportedInputException(inputException); Assert.assertNotNull(adviceResponse); Assert.assertEquals("Input value '-5' is not in the range of accepted values {1 - 2200000000}", adviceResponse.getBody()); } }
package top.yinjinbiao.video.admin.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import top.yinjinbiao.video.admin.service.SysUserService; import top.yinjinbiao.video.common.dto.ResponseResult; import top.yinjinbiao.video.common.enums.ResponseCode; import top.yinjinbiao.video.domain.SysUser; /** * @Description 用户相关 * @Author yin.jinbiao * @Date 2021/3/28 10:05 * @Version 1.0 */ @RestController @RequestMapping("/sysuser") public class SysUserController { @Autowired private SysUserService sysUserService; @PostMapping public ResponseResult<SysUser> add(@Validated @RequestBody SysUser sysUser){ return new ResponseResult(ResponseCode.SUCCESS.code(),ResponseCode.SUCCESS.message(),sysUserService.save(sysUser)); } /** * @param id * @return */ @GetMapping("/{id}") public ResponseResult<SysUser> get(@PathVariable(value="id") Long id){ return new ResponseResult(ResponseCode.SUCCESS.code(),ResponseCode.SUCCESS.message(),sysUserService.findByUserId(id)); } }
class Twofer { String twofer(String name) { if (name == null || name == "") { return "One for you, one for me."; } return "One for " + name + ", one for me."; } }
/** * Created by computerito on 6/9/15. */ public class Square extends SimpleShape{ private float width; public Square(float width){ this.width = width; } public float area(){ return width*width; } }
/* * 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.kylin.invertedindex.invertedindex; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.dict.Dictionary; import org.apache.kylin.invertedindex.IIDescManager; import org.apache.kylin.invertedindex.IIInstance; import org.apache.kylin.invertedindex.IIManager; import org.apache.kylin.invertedindex.model.IIDesc; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; /** * Created by shaoshi on 2/5/15. */ public class IIInstanceTest extends LocalFileMetadataTestCase { @Before public void setup() { createTestMetadata(); } @After public void clean() { cleanupTestMetadata(); } @Test public void testGetIIsByDesc() throws IOException { IIManager mgr = IIManager.getInstance(getTestConfig()); List<IIInstance> iiInstances = mgr.getIIsByDesc("test_kylin_ii_desc"); Assert.assertTrue(iiInstances.size() > 0); IIInstance instance = iiInstances.get(0); Dictionary dict = mgr.getDictionary(instance.getFirstSegment(), instance.getDescriptor().findColumnRef("DEFAULT.TEST_KYLIN_FACT", "LSTG_SITE_ID")); Assert.assertNotNull(dict); } @Test public void testCreateIIInstance() throws IOException { IIDesc iiDesc = IIDescManager.getInstance(getTestConfig()).getIIDesc("test_kylin_ii_desc"); IIInstance ii = IIInstance.create("new ii", "default", iiDesc); IIManager iiMgr = IIManager.getInstance(getTestConfig()); List<IIInstance> allIIList = iiMgr.listAllIIs(); iiMgr.createII(ii); Assert.assertNotNull(iiMgr.getII("new ii")); } }
package jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class ExcluirPessoa { public static void main(String[] args) throws SQLException{ Scanner entrada = new Scanner(System.in); System.out.println("Informe o codigo:"); int codigo = entrada.nextInt(); Connection conexao = FabricaConexao.getConexao(); String sql = "DELETE FROM pessoas WHERE codigo > ?"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setInt(1,codigo); int contador = stmt.executeUpdate(); if(contador > 0) { System.out.println("Pessoa excluida com sucesso"); System.out.println("Linhas afetadas " + contador); }else { System.out.println("Nada feito"); } conexao.close(); entrada.close(); } }
/* * Copyright (C) 2016 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.internal.codegen; /** Allows options to control how features in component processing are enabled. */ enum FeatureStatus { ENABLED, DISABLED; }
/* * Copyright (c) 2020, Zoinkwiz * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.questhelper.quests.ghostsahoy; import com.questhelper.Zone; import com.questhelper.requirements.ItemRequirement; import com.questhelper.questhelpers.QuestHelper; import com.questhelper.steps.DetailedOwnerStep; import com.questhelper.steps.DetailedQuestStep; import com.questhelper.steps.NpcStep; import com.questhelper.steps.ObjectStep; import com.questhelper.steps.QuestStep; import com.questhelper.requirements.conditional.ConditionForStep; import com.questhelper.requirements.conditional.ZoneCondition; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import net.runelite.api.ItemID; import net.runelite.api.NpcID; import net.runelite.api.ObjectID; import net.runelite.api.coords.WorldPoint; import net.runelite.api.events.GameTick; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.eventbus.Subscribe; public class DyeShipSteps extends DetailedOwnerStep { boolean coloursKnown = false; HashMap<String, FlagColour> shapeColours = new HashMap<>(); HashMap<String, FlagColour> currentColours = new HashMap<>(); DetailedQuestStep searchMast, dyeTop, dyeSkull, dyeBottom, goDownToMan, talkToMan, goUpToMan, goUpToDeckForMast, goUpToMast; ConditionForStep onTopOfShip, onDeck; Zone topOfShip, deck; ItemRequirement modelShip; public DyeShipSteps(QuestHelper questHelper) { super(questHelper); topOfShip = new Zone(new WorldPoint(3616, 3541, 2), new WorldPoint(3622, 3545, 2)); deck = new Zone(new WorldPoint(3600, 3541, 1), new WorldPoint(3623, 3545, 1)); onTopOfShip = new ZoneCondition(topOfShip); onDeck = new ZoneCondition(deck); shapeColours.put("skull", FlagColour.WHITE); shapeColours.put("top", FlagColour.WHITE); shapeColours.put("bottom", FlagColour.WHITE); currentColours.put("skull", FlagColour.WHITE); currentColours.put("top", FlagColour.WHITE); currentColours.put("bottom", FlagColour.WHITE); } @Subscribe public void onGameTick(GameTick event) { updateSteps(); } private void updateCurrentColours() { Widget dyed = client.getWidget(WidgetInfo.DIALOG_SPRITE_TEXT); if (dyed == null) { return; } String text = dyed.getText(); if (text.isEmpty()) { return; } String[] splitOnNewLines = text.split("<br>"); if (splitOnNewLines.length > 1) { for (String splitOnNewLine : splitOnNewLines) { updateCurrentColoursFromString(splitOnNewLine); } } String[] splitText = text.split("dye the "); if (splitText.length < 2) { return; } updateCurrentColoursFromString(splitText[1]); } private void updateCurrentColoursFromString(String text) { String[] shapeAndColour = text.split(" (emblem|of the flag) "); if (shapeAndColour.length < 2) { return; } String shape = shapeAndColour[0]; String colour = shapeAndColour[1]; shape = shape.replace("The ", ""); colour = colour.replace("is ", ""); currentColours.put(shape, FlagColour.findByKey(colour)); } public void updateSteps() { updateCurrentColours(); updateColours(); FlagColour topColour = shapeColours.get("top"); FlagColour bottomColour = shapeColours.get("bottom"); FlagColour skullColour = shapeColours.get("skull"); FlagColour currentTopColour = currentColours.get("top"); FlagColour currentBottomColour = currentColours.get("bottom"); FlagColour currentSkullColour = currentColours.get("skull"); if (!coloursKnown && topColour != FlagColour.WHITE && skullColour != FlagColour.WHITE && bottomColour != FlagColour.WHITE) { coloursKnown = true; dyeTop.setRequirements(Arrays.asList(topColour.getItem(), modelShip)); dyeTop.setText("Dye the top of the model ship's flag " + topColour.getColourText() + " If you already have, inspect the ship."); dyeTop.addDialogStep("Top half"); dyeBottom.setRequirements(Arrays.asList(bottomColour.getItem(), modelShip)); dyeBottom.setText("Dye the bottom of the model ship's flag " + bottomColour.getColourText() + " If you already have, inspect the ship."); dyeBottom.addDialogStep("Bottom half"); dyeSkull.setRequirements(Arrays.asList(skullColour.getItem(), modelShip)); dyeSkull.addDialogStep("Skull emblem"); dyeSkull.setText("Dye the skull on the model ship's flag " + skullColour.getColourText() + " If you already have, inspect the ship."); } if (!coloursKnown) { if (onDeck.check(client)) { startUpStep(goUpToMast); } else if (onTopOfShip.check(client)) { startUpStep(searchMast); } else { startUpStep(goUpToDeckForMast); } return; } if (topColour != currentTopColour) { startUpStep(dyeTop); } else if (bottomColour != currentBottomColour) { startUpStep(dyeBottom); } else if (skullColour != currentSkullColour) { startUpStep(dyeSkull); } else if (onTopOfShip.check(client)) { startUpStep(goDownToMan); } else if (onDeck.check(client)) { startUpStep(talkToMan); } else { startUpStep(goUpToMan); } } public void updateColours() { Widget textWidget = client.getWidget(229, 1); if (textWidget != null) { String text = textWidget.getText(); if (text.isEmpty()) { return; } String[] splitText = text.split("The "); if (splitText.length < 2) { return; } String mainText = splitText[1]; if (!mainText.contains("coloured")) { return; } String[] shapeAndColour = mainText.split(" (emblem|half of the flag) is coloured "); if (shapeAndColour.length < 2) { return; } String shape = shapeAndColour[0]; String colour = shapeAndColour[1]; shapeColours.put(shape, FlagColour.findByKey(colour)); } } @Override protected void setupSteps() { modelShip = new ItemRequirement("Model ship", ItemID.MODEL_SHIP_4254); modelShip.setHighlightInInventory(true); searchMast = new ObjectStep(getQuestHelper(), ObjectID.MAST_16640, new WorldPoint(3619, 3543, 2), "Search the Mast repeatedly until you've found out all the colours for the toy boat."); dyeTop = new DetailedQuestStep(getQuestHelper(), "Dye the top of the model ship's flag to match the real ship.", modelShip); dyeBottom = new DetailedQuestStep(getQuestHelper(), "Dye the bottom of the model ship's flag to match the real ship.", modelShip); dyeSkull = new DetailedQuestStep(getQuestHelper(), "Dye the skull of the model ship's flag to match the real ship.", modelShip); talkToMan = new NpcStep(getQuestHelper(), NpcID.OLD_MAN, new WorldPoint(3616, 3543, 1), "Talk to the Old Man with the model ship to get a key."); talkToMan.addDialogStep("Is this your toy boat?"); goDownToMan = new ObjectStep(getQuestHelper(), ObjectID.SHIPS_LADDER_16112, new WorldPoint(3615, 3541, 2), "Go to the main deck of the ship."); goUpToMan = new ObjectStep(getQuestHelper(), ObjectID.SHIPS_LADDER_16111, new WorldPoint(3613, 3543, 0), "Go up the ladder in the ship west of Port Phasmatys."); goDownToMan.addSubSteps(goUpToMan); goUpToDeckForMast = new ObjectStep(getQuestHelper(), ObjectID.SHIPS_LADDER_16111, new WorldPoint(3613, 3543, 0), "Go up the ladder in the ship west of Port Phasmatys."); goUpToMast = new ObjectStep(getQuestHelper(), ObjectID.SHIPS_LADDER_16111, new WorldPoint(3615, 3541, 1), "Go up to the mast of the ship."); } @Override public Collection<QuestStep> getSteps() { return Arrays.asList(searchMast, dyeTop, dyeBottom, dyeSkull, talkToMan, goDownToMan, goUpToMan, goUpToDeckForMast, goUpToMast); } public List<QuestStep> getDisplaySteps() { return Arrays.asList(goUpToDeckForMast, goUpToMast, searchMast, dyeTop, dyeBottom, dyeSkull, goDownToMan, talkToMan); } private enum FlagColour { RED("red.", new ItemRequirement("Red dye", ItemID.RED_DYE)), BLUE("blue.", new ItemRequirement("Blue dye", ItemID.BLUE_DYE)), YELLOW("yellow.", new ItemRequirement("Yellow dye", ItemID.YELLOW_DYE)), GREEN("green.", new ItemRequirement("Green dye", ItemID.GREEN_DYE)), PURPLE("purple.", new ItemRequirement("Purple dye", ItemID.PURPLE_DYE)), ORANGE("orange.", new ItemRequirement("Orange dye", ItemID.ORANGE_DYE)), WHITE("white.", new ItemRequirement("White", -1, -1)); private final String colourText; private final ItemRequirement item; FlagColour(String colourText, ItemRequirement item) { this.colourText = colourText; item.setHighlightInInventory(true); this.item = item; } public String getColourText() { return colourText; } public ItemRequirement getItem() { return item; } public static FlagColour findByKey(String colour) { FlagColour[] flagColours = FlagColour.values(); for (FlagColour flagColour : flagColours) { if (flagColour.colourText.equals(colour)) { return flagColour; } } return null; } } }
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID 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.opensaml.saml2.core.validator; import javax.xml.namespace.QName; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.ArtifactResponse; /** * */ public class ArtifactResponseSchemaTest extends StatusResponseSchemaTestBase { /** * Constructor * */ public ArtifactResponseSchemaTest() { super(); targetQName = new QName(SAMLConstants.SAML20P_NS, ArtifactResponse.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); validator = new ArtifactResponseSchemaValidator(); } // All requirements are tested in the superclasses. }
package ru.napadovskiub.store; /** * Class extends Base. */ public class User extends Base { /** * user id. */ private String id; /** * Method return user id. * @returnuser id. */ @Override public String getId() { return this.id; } /** * Method set user id. * @param id base id. */ @Override public void setId(String id) { this.id = id; } }
/* * Copyright (c) 2017 Strapdata (http://www.strapdata.com) * Contains some code from Elasticsearch (http://www.elastic.co) * * 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.elassandra; import org.apache.cassandra.db.ConsistencyLevel; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ESSingleNodeTestCase; import org.junit.Test; import java.util.Locale; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.equalTo; /** * @author vroyer * */ //gradle :server:test -Dtests.seed=65E2CF27F286CC89 -Dtests.class=org.elassandra.ExplainTests -Dtests.security.manager=false -Dtests.locale=en-PH -Dtests.timezone=America/Coral_Harbour public class ExplainTests extends ESSingleNodeTestCase { @Test public void testExplain() throws Exception { XContentBuilder mapping = XContentFactory.jsonBuilder() .startObject() .startObject("properties") .startObject("id") .field("type", "keyword") .field("cql_collection", "singleton") .field("cql_primary_key_order", 0) .field("cql_partition_key", true) .endObject() .startObject("f1") .field("type", "integer") .field("cql_collection", "singleton") .endObject() .endObject() .endObject(); assertAcked(client().admin().indices().prepareCreate("test").addMapping("t1", mapping)); ensureGreen("test"); long N = 10; for(int i=0; i < N; i++) process(ConsistencyLevel.ONE, String.format(Locale.ROOT, "INSERT INTO test.t1 (id, f1) VALUES ('%d',%d)", i,i)); assertThat(client().prepareSearch().setIndices("test").setQuery(QueryBuilders.termQuery("f1", 1)).get().getHits().getTotalHits(), equalTo(1L)); assertThat(client().prepareExplain("test", "t1", "1").setQuery(QueryBuilders.termQuery("f1", 1)).get().hasExplanation(), equalTo(true)); } }
/* * All GTAS code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP). * * Please see LICENSE.txt for details. */ package gov.gtas.services; import static gov.gtas.constant.GtasSecurityConstants.PRIVILEGES_ADMIN_AND_VIEW_PASSENGER; import static gov.gtas.constant.GtasSecurityConstants.PRIVILEGES_ADMIN_AND_MANAGE_RULES_AND_MANAGE_WATCH_LIST_AND_MANAGE_QUERIES; import gov.gtas.model.*; import gov.gtas.model.lookup.DispositionStatus; import gov.gtas.services.dto.PassengersPageDto; import gov.gtas.services.dto.PassengersRequestDto; import gov.gtas.vo.passenger.CaseVo; import gov.gtas.vo.passenger.PassengerVo; import java.util.Date; import java.util.List; import java.util.Set; import org.springframework.security.access.prepost.PreAuthorize; public interface PassengerService { Passenger create(Passenger passenger); Passenger update(Passenger passenger); @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) Passenger findById(Long id); @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) Passenger findByIdWithFlightPaxAndDocuments(Long paxId); /* List<Passenger> getPassengersByLastName(String lastName); */ @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) List<Disposition> getPassengerDispositionHistory(Long passengerId, Long flightId); @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) void createDisposition(DispositionData disposition, User user); void createDisposition(HitsSummary hit); void createDisposition(List<HitsSummary> hit); @PreAuthorize(PRIVILEGES_ADMIN_AND_MANAGE_RULES_AND_MANAGE_WATCH_LIST_AND_MANAGE_QUERIES) List<DispositionStatus> getDispositionStatuses(); @PreAuthorize(PRIVILEGES_ADMIN_AND_MANAGE_RULES_AND_MANAGE_WATCH_LIST_AND_MANAGE_QUERIES) List<CaseVo> getAllDispositions(); void createOrEditDispositionStatus(DispositionStatus ds); void deleteDispositionStatus(DispositionStatus ds); /** * Gets the passengers by criteria. * * @param flightId optional * @param request the request * @return the passengers by criteria */ @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) PassengersPageDto getPassengersByCriteria(Long flightId, PassengersRequestDto request); void fillWithHitsInfo(PassengerVo vo, Long flightId, Long passengerId); /** * Gets the travel history. * * @param pId the id * @param docNum the doc num * @param docIssuCountry the doc issu country * @param docExpirationDate the doc expiration date * @return the travel history */ @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) List<Flight> getTravelHistory(Long pId, String docNum, String docIssuCountry, Date docExpDate); @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) List<Flight> getTravelHistoryByItinerary(Long pnrId, String pnrRef); @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) List<Flight> getTravelHistoryNotByItinerary(Long pId, Long pnrId, String pnrRef); @PreAuthorize(PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) List<Passenger> getBookingDetailHistoryByPaxID(Long pId); Set<Flight> getAllFlights(Long id); Set<FlightPax> findFlightPaxFromPassengerIds(List<Long> passengerIdList); List<Passenger> getPaxByPaxIdList(List<Long> passengerIdList); void setAllFlights(Set<Flight> flights, Long id); void SetSingleFlight(Flight f, Long id); List<Flight> getFlightsByIdList(List<Long> flightIdList); Set<Passenger> getPassengersForFuzzyMatching(List<MessageStatus> messageIds); }
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE.txt in the project root for license information. *----------------------------------------------------------------*/ package com.thoughtworks.gauge.reference; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiReferenceBase; import com.thoughtworks.gauge.language.psi.ConceptStep; import com.thoughtworks.gauge.language.psi.impl.SpecStepImpl; import com.thoughtworks.gauge.util.StepUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.thoughtworks.gauge.util.GaugeUtil.moduleForPsiElement; public class ConceptReference extends PsiReferenceBase<ConceptStep> { public ConceptReference(@NotNull ConceptStep element) { super(element); } @Nullable @Override public PsiElement resolve() { SpecStepImpl step = new SpecStepImpl(this.myElement.getNode()); step.setConcept(true); return StepUtil.findStepImpl(step, moduleForPsiElement(this.myElement)); } @NotNull @Override public Object[] getVariants() { return new Object[0]; } @Override public TextRange getRangeInElement() { return new TextRange(0, myElement.getTextLength()); } @Override public boolean isReferenceTo(PsiElement element) { if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod) element; return StepUtil.isMatch(method, this.myElement.getStepValue().getStepText(), moduleForPsiElement(element)); } else { return false; } } }
/* * Copyright 2014-2019 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 com.webank.webase.front.situation; import com.webank.webase.front.situation.entity.Situation; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import javax.transaction.Transactional; import java.util.List; public interface SituationRepository extends CrudRepository<Situation, Long> { @Query(value="select s from Situation s where s.groupId = ?1 and s.timestamp between ?2 and ?3 order by s.timestamp") public List<Situation> findByTimeBetween(int groupId, Long startTime, Long endTime); @Query(value="select s from Situation s where s.groupId = ?1 order by s.timestamp desc") public List<Situation> findSituationDataNow(int groupId); @Modifying @Transactional @Query(value="delete from Situation s where s.timestamp< ?1",nativeQuery = true) public int deleteTimeAgo(Long time); }
/* * Copyright 2016 The original 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 io.sundr.dsl.internal.element.functions; import io.sundr.Function; import io.sundr.dsl.annotations.Keyword; import io.sundr.dsl.annotations.Option; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; public class ToClasses implements Function<Element, Set<String>> { private final TypeElement OPTION; public ToClasses(Elements elements) { OPTION = elements.getTypeElement(Option.class.getCanonicalName()); } public Set<String> apply(Element element) { Set<String> classes = new HashSet<String>(); for (AnnotationMirror mirror : element.getAnnotationMirrors()) { for (AnnotationMirror innerMirror : mirror.getAnnotationType().asElement().getAnnotationMirrors()) { if (innerMirror.getAnnotationType().asElement().equals(OPTION)) { classes.add(mirror.getAnnotationType().asElement().toString()); continue; } } } return classes; } }
package ua.gov.dp.econtact.gallery.databinders; /** * Created by Yalantis * 2015/08/04. * * @author Artem Kh. */ public class FolderData { private int mPreviewImageId; private String mPreviewPath; private int mCount; private int mType = -1; private String mDisplayName; private String mThumbnailPath; public void increaseCount() { mCount++; } public void decreaseCount() { mCount--; } public int getCount() { return mCount; } public int getPreviewImageId() { return mPreviewImageId; } public void setPreviewImageId(final int previewImageId) { mPreviewImageId = previewImageId; } public String getPreviewPath() { return mPreviewPath; } public void setPreviewPath(final String previewPath) { mPreviewPath = previewPath; } public int getType() { return mType; } public String getDisplayName() { return mDisplayName; } public void setDisplayName(final String displayName) { mDisplayName = displayName; } public void setType(final int type) { mType = type; } public String getThumbnailPath() { return mThumbnailPath; } public void setThumbnailPath(final String thumbnailPath) { mThumbnailPath = thumbnailPath; } }
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.postgresql.snapshot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AlwaysSnapshotter extends QueryingSnapshotter { private final static Logger LOGGER = LoggerFactory.getLogger(AlwaysSnapshotter.class); @Override public boolean shouldStream() { return true; } @Override public boolean shouldSnapshot() { LOGGER.info("Taking a new snapshot as per configuration"); return true; } }
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.modules.internal.messages; import java.util.ArrayList; import java.util.List; import im.actor.core.entity.Avatar; import im.actor.core.entity.ContentDescription; import im.actor.core.entity.ContentType; import im.actor.core.entity.Dialog; import im.actor.core.entity.DialogBuilder; import im.actor.core.entity.Group; import im.actor.core.entity.Message; import im.actor.core.entity.MessageState; import im.actor.core.entity.Peer; import im.actor.core.entity.User; import im.actor.core.entity.content.AbsContent; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.internal.messages.entity.DialogHistory; import im.actor.core.modules.utils.ModuleActor; import im.actor.runtime.Log; import im.actor.runtime.Runtime; import im.actor.runtime.annotations.Verified; import im.actor.runtime.storage.ListEngine; import static im.actor.core.util.JavaUtil.equalsE; public class DialogsActor extends ModuleActor { private ListEngine<Dialog> dialogs; private Boolean isEmpty; private Boolean emptyNotified; public DialogsActor(ModuleContext context) { super(context); } @Override public void preStart() { super.preStart(); this.dialogs = context().getMessagesModule().getDialogsEngine(); notifyState(true); } @Verified private void onMessage(Peer peer, Message message, boolean forceWrite, int counter) { long start = im.actor.runtime.Runtime.getCurrentTime(); PeerDesc peerDesc = buildPeerDesc(peer); if (peerDesc == null) { Log.d("DialogsActor", "unknown peer desk"); return; } if (message == null) { // Ignore empty message if not forcing write if (!forceWrite) { Log.d("DialogsActor", "not force"); return; } // Else perform chat clear onChatClear(peer); } else { Dialog dialog = dialogs.getValue(peer.getUnuqueId()); ContentDescription contentDescription = ContentDescription.fromContent(message.getContent()); DialogBuilder builder = new DialogBuilder() .setRid(message.getRid()) .setTime(message.getDate()) .setMessageType(contentDescription.getContentType()) .setText(contentDescription.getText()) .setRelatedUid(contentDescription.getRelatedUser()) .setStatus(message.getMessageState()) .setSenderId(message.getSenderId()) .setUnreadCount(counter); boolean forceUpdate = false; if (dialog != null) { // Ignore old messages if no force if (!forceWrite && dialog.getSortDate() > message.getSortDate()) { Log.d("DialogsActor", "too old"); return; } builder.setPeer(dialog.getPeer()) .setDialogTitle(dialog.getDialogTitle()) .setDialogAvatar(dialog.getDialogAvatar()) .setSortKey(dialog.getSortDate()); // Do not push up dialogs for silent messages if (!contentDescription.isSilent()) { builder.setSortKey(message.getSortDate()); } } else { // Do not create dialogs for silent messages if (contentDescription.isSilent()) { Log.d("DialogsActor", "is silent in"); return; } builder.setPeer(peer) .setDialogTitle(peerDesc.getTitle()) .setDialogAvatar(peerDesc.getAvatar()) .setSortKey(message.getSortDate()); forceUpdate = true; } addOrUpdateItem(builder.createDialog()); notifyState(forceUpdate); } Log.d("DialogsActor", "onMessage in " + (Runtime.getCurrentTime() - start) + " ms"); } @Verified private void onUserChanged(User user) { Dialog dialog = dialogs.getValue(user.peer().getUnuqueId()); if (dialog != null) { // Ignore if nothing changed if (dialog.getDialogTitle().equals(user.getName()) && equalsE(dialog.getDialogAvatar(), user.getAvatar())) { return; } // Update dialog peer info Dialog updated = dialog.editPeerInfo(user.getName(), user.getAvatar()); addOrUpdateItem(updated); updateSearch(updated); } } @Verified private void onGroupChanged(Group group) { Dialog dialog = dialogs.getValue(group.peer().getUnuqueId()); if (dialog != null) { // Ignore if nothing changed if (dialog.getDialogTitle().equals(group.getTitle()) && equalsE(dialog.getDialogAvatar(), group.getAvatar())) { return; } // Update dialog peer info Dialog updated = dialog.editPeerInfo(group.getTitle(), group.getAvatar()); addOrUpdateItem(updated); updateSearch(updated); } } @Verified private void onChatDeleted(Peer peer) { // Removing dialog dialogs.removeItem(peer.getUnuqueId()); notifyState(true); } @Verified private void onChatClear(Peer peer) { Dialog dialog = dialogs.getValue(peer.getUnuqueId()); // If we have dialog for this peer if (dialog != null) { // Update dialog addOrUpdateItem(new DialogBuilder(dialog) .setMessageType(ContentType.EMPTY) .setText("") .setTime(0) .setUnreadCount(0) .setRid(0) .setSenderId(0) .setStatus(MessageState.UNKNOWN) .createDialog()); } } @Verified private void onMessageStatusChanged(Peer peer, long rid, MessageState state) { Dialog dialog = dialogs.getValue(peer.getUnuqueId()); // If message is on top if (dialog != null && dialog.getRid() == rid) { // Update dialog addOrUpdateItem(new DialogBuilder(dialog) .setStatus(state) .createDialog()); } } @Verified private void onMessageContentChanged(Peer peer, long rid, AbsContent content) { Dialog dialog = dialogs.getValue(peer.getUnuqueId()); // If message is on top if (dialog != null && dialog.getRid() == rid) { // Update dialog ContentDescription description = ContentDescription.fromContent(content); addOrUpdateItem(new DialogBuilder(dialog) .setText(description.getText()) .setRelatedUid(description.getRelatedUser()) .setMessageType(description.getContentType()) .createDialog()); } } @Verified private void onCounterChanged(Peer peer, int count) { Dialog dialog = dialogs.getValue(peer.getUnuqueId()); // If we have dialog for this peer if (dialog != null) { // Counter not actually changed if (dialog.getUnreadCount() == count) { return; } // Update dialog addOrUpdateItem(new DialogBuilder(dialog) .setUnreadCount(count) .createDialog()); } } @Verified private void onHistoryLoaded(List<DialogHistory> history) { ArrayList<Dialog> updated = new ArrayList<Dialog>(); for (DialogHistory dialogHistory : history) { // Ignore already available dialogs if (dialogs.getValue(dialogHistory.getPeer().getUnuqueId()) != null) { continue; } PeerDesc peerDesc = buildPeerDesc(dialogHistory.getPeer()); if (peerDesc == null) { continue; } ContentDescription description = ContentDescription.fromContent(dialogHistory.getContent()); updated.add(new Dialog(dialogHistory.getPeer(), dialogHistory.getSortDate(), peerDesc.getTitle(), peerDesc.getAvatar(), dialogHistory.getUnreadCount(), dialogHistory.getRid(), description.getContentType(), description.getText(), dialogHistory.getStatus(), dialogHistory.getSenderId(), dialogHistory.getDate(), description.getRelatedUser())); } addOrUpdateItems(updated); updateSearch(updated); context().getAppStateModule().onDialogsLoaded(); notifyState(true); } // Utils private void addOrUpdateItems(List<Dialog> updated) { dialogs.addOrUpdateItems(updated); } private void addOrUpdateItem(Dialog dialog) { dialogs.addOrUpdateItem(dialog); } private void updateSearch(Dialog dialog) { ArrayList<Dialog> d = new ArrayList<Dialog>(); d.add(dialog); context().getSearchModule().onDialogsChanged(d); } private void updateSearch(List<Dialog> updated) { context().getSearchModule().onDialogsChanged(updated); } private void notifyState(boolean force) { if (isEmpty == null || force) { isEmpty = this.dialogs.isEmpty(); } if (!isEmpty.equals(emptyNotified)) { emptyNotified = isEmpty; context().getAppStateModule().onDialogsUpdate(isEmpty); } } @Verified private PeerDesc buildPeerDesc(Peer peer) { switch (peer.getPeerType()) { case PRIVATE: User u = getUser(peer.getPeerId()); return new PeerDesc(u.getName(), u.getAvatar()); case GROUP: Group g = getGroup(peer.getPeerId()); return new PeerDesc(g.getTitle(), g.getAvatar()); default: return null; } } private class PeerDesc { private String title; private Avatar avatar; private PeerDesc(String title, Avatar avatar) { this.title = title; this.avatar = avatar; } public String getTitle() { return title; } public Avatar getAvatar() { return avatar; } } // Messages @Override public void onReceive(Object message) { if (message instanceof InMessage) { InMessage inMessage = (InMessage) message; onMessage(inMessage.getPeer(), inMessage.getMessage(), false, inMessage.getCounter()); } else if (message instanceof UserChanged) { UserChanged userChanged = (UserChanged) message; onUserChanged(userChanged.getUser()); } else if (message instanceof ChatClear) { onChatClear(((ChatClear) message).getPeer()); } else if (message instanceof ChatDelete) { onChatDeleted(((ChatDelete) message).getPeer()); } else if (message instanceof MessageStateChanged) { MessageStateChanged messageStateChanged = (MessageStateChanged) message; onMessageStatusChanged(messageStateChanged.getPeer(), messageStateChanged.getRid(), messageStateChanged.getState()); } else if (message instanceof MessageDeleted) { MessageDeleted deleted = (MessageDeleted) message; onMessage(deleted.getPeer(), deleted.getTopMessage(), true, -1); } else if (message instanceof HistoryLoaded) { HistoryLoaded historyLoaded = (HistoryLoaded) message; onHistoryLoaded(historyLoaded.getHistory()); } else if (message instanceof GroupChanged) { GroupChanged groupChanged = (GroupChanged) message; onGroupChanged(groupChanged.getGroup()); } else if (message instanceof MessageContentChanged) { MessageContentChanged contentChanged = (MessageContentChanged) message; onMessageContentChanged(contentChanged.getPeer(), contentChanged.getRid(), contentChanged.getContent()); } else if (message instanceof CounterChanged) { CounterChanged counterChanged = (CounterChanged) message; onCounterChanged(counterChanged.getPeer(), counterChanged.getCounter()); } else { drop(message); } } public static class InMessage { private Peer peer; private Message message; private int counter; public InMessage(Peer peer, Message message, int counter) { this.peer = peer; this.message = message; this.counter = counter; } public Peer getPeer() { return peer; } public Message getMessage() { return message; } public int getCounter() { return counter; } } public static class CounterChanged { private Peer peer; private int counter; public CounterChanged(Peer peer, int counter) { this.peer = peer; this.counter = counter; } public Peer getPeer() { return peer; } public int getCounter() { return counter; } } public static class UserChanged { private User user; public UserChanged(User user) { this.user = user; } public User getUser() { return user; } } public static class GroupChanged { private Group group; public GroupChanged(Group group) { this.group = group; } public Group getGroup() { return group; } } public static class ChatClear { private Peer peer; public ChatClear(Peer peer) { this.peer = peer; } public Peer getPeer() { return peer; } } public static class ChatDelete { private Peer peer; public ChatDelete(Peer peer) { this.peer = peer; } public Peer getPeer() { return peer; } } public static class MessageStateChanged { private Peer peer; private long rid; private MessageState state; public MessageStateChanged(Peer peer, long rid, MessageState state) { this.peer = peer; this.rid = rid; this.state = state; } public Peer getPeer() { return peer; } public long getRid() { return rid; } public MessageState getState() { return state; } } public static class MessageContentChanged { private Peer peer; private long rid; private AbsContent content; public MessageContentChanged(Peer peer, long rid, AbsContent content) { this.peer = peer; this.rid = rid; this.content = content; } public Peer getPeer() { return peer; } public long getRid() { return rid; } public AbsContent getContent() { return content; } } public static class MessageDeleted { private Peer peer; private Message topMessage; public MessageDeleted(Peer peer, Message topMessage) { this.peer = peer; this.topMessage = topMessage; } public Peer getPeer() { return peer; } public Message getTopMessage() { return topMessage; } } public static class HistoryLoaded { private List<DialogHistory> history; public HistoryLoaded(List<DialogHistory> history) { this.history = history; } public List<DialogHistory> getHistory() { return history; } } }
/* * Copyright 2014 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.service.manager; import edu.usu.sdl.openstorefront.util.Convert; import edu.usu.sdl.openstorefront.util.OpenStorefrontConstant; import java.text.MessageFormat; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import org.codemonkey.simplejavamail.Email; import org.codemonkey.simplejavamail.Mailer; import org.codemonkey.simplejavamail.Recipient; import org.codemonkey.simplejavamail.TransportStrategy; /** * Used for Handling Email * * @author dshurtleff */ public class MailManager implements Initializable { private static final Logger log = Logger.getLogger(MailManager.class.getName()); private static Mailer mailer; public static void init() { //pull properties String server = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_SERVER); String serverPort = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_SERVER_PORT); String serverUser = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_SERVER_USER); String serverPW = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_SERVER_PW); String useSSL = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_USE_SSL); String useTLS = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_USE_TLS); if (StringUtils.isNotBlank(server)) { TransportStrategy transportStrategy = TransportStrategy.SMTP_PLAIN; if (Convert.toBoolean(useSSL)) { transportStrategy = TransportStrategy.SMTP_SSL; } else if (Convert.toBoolean(useTLS)) { transportStrategy = TransportStrategy.SMTP_TLS; } mailer = new Mailer(server, Convert.toInteger(serverPort), serverUser, serverPW, transportStrategy); } else { log.log(Level.WARNING, "No mail server is set up. See application properties file to configure."); } } public static void cleanup() { //nothing needed for now } public static Email newEmail() { String fromName = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_FROM_NAME, OpenStorefrontConstant.NOT_AVAILABLE); String fromAddress = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_FROM_ADDRESS, OpenStorefrontConstant.DEFAULT_FROM_ADDRESS); String fromReply = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_REPLY_NAME); String fromReplyAddress = PropertiesManager.getValue(PropertiesManager.KEY_MAIL_REPLY_ADDRESS); Email email = new Email(); email.setFromAddress(fromName, fromAddress); if (StringUtils.isNotBlank(fromReplyAddress)) { email.setReplyToAddress(fromReply, fromReplyAddress); } return email; } public static void send(Email email) { if (email != null) { if (mailer != null) { mailer.sendMail(email); } else { StringBuilder sb = new StringBuilder(); for (Recipient recipient : email.getRecipients()) { sb.append(recipient.getType()).append(": "); sb.append(recipient.getAddress()).append(", "); } log.log(Level.FINE, MessageFormat.format("(Mock Email Handler) Sending Message Subject: {0} To {1}", new Object[]{email.getSubject(), sb.toString()})); } } else { log.log(Level.FINE, "Unable to send NULL email message. No message to send."); } } @Override public void initialize() { MailManager.init(); } @Override public void shutdown() { MailManager.cleanup(); } }
package tetris.game; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; import tetris.game.Shape.Shapes; public class Board extends JPanel implements ActionListener { Timer timer; JLabel statusbar; Shape curPiece; Shapes[] board; final int BoardWidth = 10; final int BoardHeight = 22; int numLinesRemoved = 0; int curX = 0; int curY = 0; boolean isFallingFinished = false; boolean isStarted = false; boolean isPaused = false; public Board(App parent){ setFocusable(true); curPiece = new Shape(); timer = new Timer(400, this); timer.start(); statusbar = parent.getStatusBar(); board = new Shapes[BoardWidth * BoardHeight]; addKeyListener(new TAdapter()); clearBoard(); } public void actionPerformed(ActionEvent e) { if (isFallingFinished) { isFallingFinished = false; newPiece(); } else { oneLineDown(); } } int squareWidth() { return (int) getSize().getWidth() / BoardWidth; } int squareHeight() { return (int) getSize().getHeight() / BoardHeight; } Shapes shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; } public void start(){ if (isPaused) return; isStarted = true; isFallingFinished = false; numLinesRemoved = 0; clearBoard(); newPiece(); timer.start(); } private void pause() { if (!isStarted) return; isPaused = !isPaused; if (isPaused) { timer.stop(); statusbar.setText("paused"); } else { timer.start(); statusbar.setText(String.valueOf(numLinesRemoved)); } repaint(); } public void paint(Graphics g){ super.paint(g); Dimension size = getSize(); int boardTop = (int) size.getHeight() - BoardHeight * squareHeight(); for (int i = 0; i < BoardHeight; ++i) { for (int j = 0; j < BoardWidth; ++j) { Shapes shape = shapeAt(j, BoardHeight - i - 1); if (shape != Shapes.no) drawSquare(g, 0 + j * squareWidth(), boardTop + i * squareHeight(), shape); } } if (curPiece.getShape() != Shapes.no) { for (int i = 0; i < 4; ++i) { int x = curX + curPiece.x(i); int y = curY - curPiece.y(i); drawSquare(g, 0 + x * squareWidth(), boardTop + (BoardHeight - y - 1) * squareHeight(), curPiece.getShape()); } } } private void dropDown() { int newY = curY; while (newY > 0) { if (!tryMove(curPiece, curX, newY - 1)){ break;} //--newY;} } pieceDropped(); } private void oneLineDown() { if (!tryMove(curPiece, curX, curY - 1)){ pieceDropped();} } private void clearBoard() { for (int i = 0; i < BoardHeight * BoardWidth; ++i){ board[i] = Shapes.no;} } private void pieceDropped(){ for (int i = 0; i < 4; ++i) { int x = curX + curPiece.x(i); int y = curY - curPiece.y(i); board[(y * BoardWidth) + x] = curPiece.getShape(); } removeFullLines(); if (!isFallingFinished){ newPiece();} } private void newPiece(){ curPiece.setRandomShape(); curX = BoardWidth / 2 + 1; curY = BoardHeight - 1 + curPiece.minY(); if (!tryMove(curPiece, curX, curY)) { String str = "Game Over \n Point: " + numLinesRemoved; curPiece.setShape(Shapes.no); timer.stop(); isStarted = false; JOptionPane.showMessageDialog(null, str); statusbar.setText("game over"); } } private boolean tryMove(Shape newPiece, int newX, int newY){ for (int i = 0; i < 4; ++i) { int x = newX + newPiece.x(i); int y = newY - newPiece.y(i); if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight){ return false;} if (shapeAt(x, y) != Shapes.no){ return false;} } curPiece = newPiece; curX = newX; curY = newY; repaint(); return true; } private void removeFullLines(){ int numFullLines = 0; for (int i = BoardHeight - 1; i >= 0; --i) { boolean lineIsFull = true; for (int j = 0; j < BoardWidth; ++j) { if (shapeAt(j, i) == Shapes.no) { lineIsFull = false; break; } } if (lineIsFull) { ++numFullLines; for (int k = i; k < BoardHeight - 1; ++k) { for (int j = 0; j < BoardWidth; ++j){ board[(k * BoardWidth) + j] = shapeAt(j, k + 1);} } } } if (numFullLines > 0) { numLinesRemoved += numFullLines; statusbar.setText(String.valueOf(numLinesRemoved)); isFallingFinished = true; curPiece.setShape(Shapes.no); repaint(); } } private void drawSquare(Graphics g, int x, int y, Shapes shape){ Color colors[] = { new Color(200, 200, 200), new Color(210, 0, 0), new Color(0, 210, 0), new Color(0, 0, 210), new Color(210, 210, 0), new Color(210, 0, 210), new Color(0, 210, 210), new Color(220, 150, 0) }; Color color = colors[shape.ordinal()]; g.setColor(color); g.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2); g.setColor(color.brighter()); g.drawLine(x, y + squareHeight() - 1, x, y); g.drawLine(x, y, x + squareWidth() - 1, y); g.setColor(color.darker()); g.drawLine(x + 1, y + squareHeight() - 1, x + squareWidth() - 1, y + squareHeight() - 1); g.drawLine(x + squareWidth() - 1, y + squareHeight() - 1, x + squareWidth() - 1, y + 1); } class TAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { if (!isStarted || curPiece.getShape() == Shapes.no) { return; } int keycode = e.getKeyCode(); if (keycode == 'p' || keycode == 'P') { pause(); return; } if (isPaused) return; switch (keycode) { case KeyEvent.VK_LEFT: tryMove(curPiece, curX - 1, curY); break; case KeyEvent.VK_RIGHT: tryMove(curPiece, curX + 1, curY); break; case KeyEvent.VK_DOWN: tryMove(curPiece.rotateRight(), curX, curY); break; case KeyEvent.VK_UP: tryMove(curPiece.rotateLeft(), curX, curY); break; case KeyEvent.VK_SPACE: dropDown(); break; case 'd': oneLineDown(); break; case 'D': oneLineDown(); break; } } } }
// Copyright 2015-2020 SWIM.AI 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 swim.api.warp.function; import swim.api.auth.Identity; import swim.concurrent.Preemptive; @FunctionalInterface public interface WillLeave extends Preemptive { void willLeave(Identity identity); }
package utils; import android.os.Handler; import android.os.Looper; import net.BaseCallback; import net.Myapplication; import com.google.gson.Gson; import com.google.gson.JsonParseException; import java.io.IOException; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by xuchichi on 2017/12/13. */ public class MyOkHttpHelper { private OkHttpClient okHttpClient = Myapplication.okHttpClient; private Gson gson; Handler handler; public MyOkHttpHelper() { gson=new Gson(); handler=new Handler(Looper.getMainLooper()); } public static MyOkHttpHelper getInstance(){ return new MyOkHttpHelper(); } public void get(String url,BaseCallback baseCallback){ Request request=buildRequest(url,null,OkHttpMethodType.GET); doRequest(request,baseCallback); } public void post(String url, Map<String,String> params,BaseCallback baseCallback){ Request request=buildRequest(url,params,OkHttpMethodType.POST); doRequest(request,baseCallback); } public void doRequest( final Request request,final BaseCallback callback){ callback.onRequestBefore(request); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(e); } @Override public void onResponse(Call call, Response response) throws IOException { callback.onResponse(response); if (response.isSuccessful()){ String string=response.body().string(); if(callback.mType==String.class){ callBackSuccess(callback,response,string); }else{ try { Object object= gson.fromJson(string,callback.mType); callBackSuccess(callback,response,object); }catch (JsonParseException ex){ ex.printStackTrace(); callBackError(callback,response,ex); } } }else{ callBackError(callback,response,null); } } }); } private void callBackSuccess(final BaseCallback callback, final Response response, final Object object){ handler.post(new Runnable() { @Override public void run() { callback.onResponseSuccess(response,object); } }); } private void callBackError(final BaseCallback callback, final Response response,final Exception e){ handler.post(new Runnable() { @Override public void run() { callback.onResponseError(response,response.code(),e); } }); } private Request buildRequest(String url,Map<String,String> params,OkHttpMethodType type){ Request.Builder builder=new Request.Builder(); builder.tag(this); builder.url(url); if (type==OkHttpMethodType.GET){ builder.get(); }else if(type==OkHttpMethodType.POST){ RequestBody requestBody= buildFormData(params); builder.post(requestBody); } return builder.build(); } public RequestBody buildFormData(Map<String,String> params){ FormBody.Builder builder=new FormBody.Builder(); if(params!=null){ for (Map.Entry<String,String> a:params.entrySet()) { builder.add(a.getKey(),a.getValue()); } } return builder.build(); } enum OkHttpMethodType { GET, POST } }
package io.smallrye.reactive.messaging.kafka; import static io.smallrye.reactive.messaging.kafka.KafkaConnector.CONNECTOR_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.awaitility.Awaitility.await; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.enterprise.context.ApplicationScoped; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.IntegerDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Metadata; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.junit.jupiter.api.Test; import io.smallrye.mutiny.Multi; import io.smallrye.reactive.messaging.kafka.base.KafkaMapBasedConfig; import io.smallrye.reactive.messaging.kafka.base.KafkaTestBase; public class MetadataPropagationTest extends KafkaTestBase { @Test public void testFromAppToKafka() { List<Map.Entry<String, String>> messages = new CopyOnWriteArrayList<>(); usage.consumeStrings("some-topic-testFromAppToKafka", 10, 1, TimeUnit.MINUTES, null, (key, value) -> messages.add(entry(key, value))); runApplication(getKafkaSinkConfigForMyAppGeneratingData(), MyAppGeneratingData.class); await().until(() -> messages.size() == 10); assertThat(messages).allSatisfy(entry -> { assertThat(entry.getKey()).isEqualTo("my-key"); assertThat(entry.getValue()).isNotNull(); }); } @Test public void testFromKafkaToAppToKafka() { String topicIn = UUID.randomUUID().toString(); List<Map.Entry<String, String>> messages = new CopyOnWriteArrayList<>(); usage.consumeStrings(topic, 10, 1, TimeUnit.MINUTES, null, (key, value) -> messages.add(entry(key, value))); runApplication(getKafkaSinkConfigForMyAppProcessingData(topic, topicIn), MyAppProcessingData.class); AtomicInteger count = new AtomicInteger(); usage.produceIntegers(10, null, () -> new ProducerRecord<>(topicIn, "a-key", count.getAndIncrement())); await().until(() -> messages.size() >= 10); assertThat(messages).allSatisfy(entry -> { assertThat(entry.getKey()).isEqualTo("my-key"); assertThat(entry.getValue()).isNotNull(); }); } @SuppressWarnings("rawtypes") @Test public void testFromKafkaToAppWithMetadata() { runApplication(getKafkaSourceConfigForMyAppWithKafkaMetadata(topic), MyAppWithKafkaMetadata.class); AtomicInteger value = new AtomicInteger(); usage.produceIntegers(10, null, () -> new ProducerRecord<>(topic, "a-key", value.getAndIncrement())); MyAppWithKafkaMetadata bean = get(MyAppWithKafkaMetadata.class); await().atMost(2, TimeUnit.MINUTES).until(() -> bean.list().size() >= 10); assertThat(bean.list()).contains(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); assertThat(bean.getMetadata()).isNotNull(); assertThat(bean.getMetadata()).contains(bean.getOriginal()); AtomicBoolean foundMetadata = new AtomicBoolean(false); for (Object object : bean.getMetadata()) { if (object instanceof IncomingKafkaRecordMetadata) { IncomingKafkaRecordMetadata incomingMetadata = (IncomingKafkaRecordMetadata) object; assertThat(incomingMetadata.getKey()).isEqualTo("a-key"); assertThat(incomingMetadata.getTopic()).isEqualTo(topic); foundMetadata.compareAndSet(false, true); } } assertThat(foundMetadata.get()).isTrue(); } private KafkaMapBasedConfig getKafkaSinkConfigForMyAppGeneratingData() { KafkaMapBasedConfig.Builder builder = KafkaMapBasedConfig.builder("mp.messaging.outgoing.kafka"); builder.put("value.serializer", StringSerializer.class.getName()); builder.put("topic", "should-not-be-used"); return builder.build(); } private KafkaMapBasedConfig getKafkaSinkConfigForMyAppProcessingData(String topicOut, String topicIn) { KafkaMapBasedConfig.Builder builder = KafkaMapBasedConfig.builder(); builder.put("mp.messaging.outgoing.kafka.value.serializer", StringSerializer.class.getName()); builder.put("mp.messaging.outgoing.kafka.connector", CONNECTOR_NAME); builder.put("mp.messaging.outgoing.kafka.bootstrap.servers", getBootstrapServers()); builder.put("mp.messaging.outgoing.kafka.topic", topicOut); builder.put("mp.messaging.incoming.source.value.deserializer", IntegerDeserializer.class.getName()); builder.put("mp.messaging.incoming.source.key.deserializer", StringDeserializer.class.getName()); builder.put("mp.messaging.incoming.source.auto.offset.reset", "earliest"); builder.put("mp.messaging.incoming.source.bootstrap.servers", getBootstrapServers()); builder.put("mp.messaging.incoming.source.connector", CONNECTOR_NAME); builder.put("mp.messaging.incoming.source.graceful-shutdown", false); builder.put("mp.messaging.incoming.source.topic", topicIn); builder.put("mp.messaging.incoming.source.commit-strategy", "latest"); return builder.build(); } private KafkaMapBasedConfig getKafkaSourceConfigForMyAppWithKafkaMetadata(String topic) { KafkaMapBasedConfig.Builder builder = KafkaMapBasedConfig.builder("mp.messaging.incoming.kafka"); builder.put("value.deserializer", IntegerDeserializer.class.getName()); builder.put("key.deserializer", StringDeserializer.class.getName()); builder.put("auto.offset.reset", "earliest"); builder.put("topic", topic); builder.put("commit-strategy", "latest"); return builder.build(); } @SuppressWarnings("deprecation") @ApplicationScoped public static class MyAppGeneratingData { @Outgoing("source") public Multi<Integer> source() { return Multi.createFrom().range(0, 10); } @Incoming("source") @Outgoing("p1") public Message<Integer> processMessage(Message<Integer> input) { return KafkaMessage.of("some-topic-testFromAppToKafka", "my-key", input.getPayload()); } @Incoming("p1") @Outgoing("kafka") public String processPayload(int payload) { return Integer.toString(payload); } } @SuppressWarnings("deprecation") @ApplicationScoped public static class MyAppProcessingData { @Incoming("source") @Outgoing("p1") public Message<Integer> processMessage(Message<Integer> input) { return KafkaMessage.of("my-key", input.getPayload()); } @Incoming("p1") @Outgoing("kafka") public String processPayload(int payload) { return Integer.toString(payload); } } @ApplicationScoped public static class MyAppWithKafkaMetadata { private final List<Integer> received = new CopyOnWriteArrayList<>(); private Metadata metadata; private final MetadataValue original = new MetadataValue("important"); @Incoming("kafka") @Outgoing("source") public Message<Integer> source(Message<Integer> input) { return input.addMetadata(original); } @Incoming("source") @Outgoing("output") public Message<Integer> processMessage(Message<Integer> input) { return KafkaRecord.from(input); } @Incoming("output") public CompletionStage<Void> verify(Message<Integer> record) { received.add(record.getPayload()); metadata = record.getMetadata(); return CompletableFuture.completedFuture(null); } public List<Integer> list() { return received; } public Metadata getMetadata() { return metadata; } public MetadataValue getOriginal() { return original; } } public static class MetadataValue { private final String value; public MetadataValue(String value) { this.value = value; } public String getValue() { return value; } } }
package com.prowidesoftware.swift.model.mx.dic; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Details of the transaction in the authorisation response contained in a batch. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CardPaymentTransactionDetails32", propOrder = { "ccy", "ttlAmt", "dtldAmt", "invcAmt", "vldtyDt", "acctTp", "iccRltdData" }) public class CardPaymentTransactionDetails32 { @XmlElement(name = "Ccy") protected String ccy; @XmlElement(name = "TtlAmt", required = true) protected BigDecimal ttlAmt; @XmlElement(name = "DtldAmt") protected DetailedAmount15 dtldAmt; @XmlElement(name = "InvcAmt") protected BigDecimal invcAmt; @XmlElement(name = "VldtyDt") @XmlSchemaType(name = "date") protected XMLGregorianCalendar vldtyDt; @XmlElement(name = "AcctTp") @XmlSchemaType(name = "string") protected CardAccountType3Code acctTp; @XmlElement(name = "ICCRltdData") protected byte[] iccRltdData; /** * Gets the value of the ccy property. * * @return * possible object is * {@link String } * */ public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public CardPaymentTransactionDetails32 setCcy(String value) { this.ccy = value; return this; } /** * Gets the value of the ttlAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTtlAmt() { return ttlAmt; } /** * Sets the value of the ttlAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public CardPaymentTransactionDetails32 setTtlAmt(BigDecimal value) { this.ttlAmt = value; return this; } /** * Gets the value of the dtldAmt property. * * @return * possible object is * {@link DetailedAmount15 } * */ public DetailedAmount15 getDtldAmt() { return dtldAmt; } /** * Sets the value of the dtldAmt property. * * @param value * allowed object is * {@link DetailedAmount15 } * */ public CardPaymentTransactionDetails32 setDtldAmt(DetailedAmount15 value) { this.dtldAmt = value; return this; } /** * Gets the value of the invcAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getInvcAmt() { return invcAmt; } /** * Sets the value of the invcAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public CardPaymentTransactionDetails32 setInvcAmt(BigDecimal value) { this.invcAmt = value; return this; } /** * Gets the value of the vldtyDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getVldtyDt() { return vldtyDt; } /** * Sets the value of the vldtyDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public CardPaymentTransactionDetails32 setVldtyDt(XMLGregorianCalendar value) { this.vldtyDt = value; return this; } /** * Gets the value of the acctTp property. * * @return * possible object is * {@link CardAccountType3Code } * */ public CardAccountType3Code getAcctTp() { return acctTp; } /** * Sets the value of the acctTp property. * * @param value * allowed object is * {@link CardAccountType3Code } * */ public CardPaymentTransactionDetails32 setAcctTp(CardAccountType3Code value) { this.acctTp = value; return this; } /** * Gets the value of the iccRltdData property. * * @return * possible object is * byte[] */ public byte[] getICCRltdData() { return iccRltdData; } /** * Sets the value of the iccRltdData property. * * @param value * allowed object is * byte[] */ public CardPaymentTransactionDetails32 setICCRltdData(byte[] value) { this.iccRltdData = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
package org.jgroups.tests; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.protocols.DISCARD_PAYLOAD; import org.jgroups.protocols.pbcast.NAKACK; import org.jgroups.protocols.pbcast.NAKACK2; import org.jgroups.stack.ProtocolStack; import org.jgroups.util.Util; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Collection; import java.util.concurrent.ConcurrentLinkedQueue; /** * Tests the NAKACK protocol for OOB and regular msgs, tests http://jira.jboss.com/jira/browse/JGRP-379 * @author Bela Ban */ @Test(groups=Global.STACK_DEPENDENT,sequential=true) public class NAKACK_Test extends ChannelTestBase { JChannel c1, c2, c3; @BeforeMethod void setUp() throws Exception { c1=createChannel(true, 3); c2=createChannel(c1); c3=createChannel(c1); } @AfterMethod void tearDown() throws Exception { Util.close(c3, c2, c1); } /** * Tests http://jira.jboss.com/jira/browse/JGRP-379: we send 1, 2, 3, 4(OOB) and 5 to the cluster. * Message with seqno 3 is discarded two times, so retransmission will make the receivers receive it *after* 4. * Note that OOB messages *destroys* FIFO ordering (or whatever ordering properties are set) ! * @throws Exception */ @Test @SuppressWarnings("unchecked") public void testOutOfBandMessages() throws Exception { NAKACK_Test.MyReceiver receiver1=new NAKACK_Test.MyReceiver(); NAKACK_Test.MyReceiver receiver2=new NAKACK_Test.MyReceiver(); NAKACK_Test.MyReceiver receiver3=new NAKACK_Test.MyReceiver(); c1.setReceiver(receiver1); c2.setReceiver(receiver2); c3.setReceiver(receiver3); c1.getProtocolStack().insertProtocol(new DISCARD_PAYLOAD(),ProtocolStack.BELOW,NAKACK.class,NAKACK2.class); c1.connect("NAKACK_OOB_Test"); c2.connect("NAKACK_OOB_Test"); c3.connect("NAKACK_OOB_Test"); assert c3.getView().getMembers().size() == 3 : "view is " + c3.getView() + ", expected view of 3 members"; for(int i=1; i <=5; i++) { Message msg=new Message(null, null,(long)i); if(i == 4) msg.setFlag(Message.Flag.OOB); System.out.println("-- sending message #" + i); c1.send(msg); Util.sleep(100); } Collection<Long> seqnos1=receiver1.getSeqnos(); Collection<Long> seqnos2=receiver2.getSeqnos(); Collection<Long> seqnos3=receiver3.getSeqnos(); // wait until retransmission of seqno #3 happens, so that 4 and 5 are received as well long target_time=System.currentTimeMillis() + 20000; do { if(seqnos1.size() >= 5 && seqnos2.size() >= 5 && seqnos3.size() >= 5) break; Util.sleep(500); } while(target_time > System.currentTimeMillis()); System.out.println("sequence numbers:"); System.out.println("c1: " + seqnos1); System.out.println("c2: " + seqnos2); System.out.println("c3: " + seqnos3); checkOrder(seqnos1, seqnos2, seqnos3); } /** * Checks whether the numbers are in order *after* removing 4: the latter is OOB and can therefore appear anywhere * in the sequence * @param lists */ private static void checkOrder(Collection<Long> ... lists) throws Exception { for(Collection<Long> list: lists) { list.remove(4L); long prev_val=0; for(long val: list) { if(val <= prev_val) throw new Exception("elements are not ordered in list: " + list); prev_val=val; } } } public static class MyReceiver extends ReceiverAdapter { /** List<Long> of unicast sequence numbers */ Collection<Long> seqnos=new ConcurrentLinkedQueue<Long>(); public MyReceiver() { } public Collection<Long> getSeqnos() { return seqnos; } public void receive(Message msg) { if(msg != null) { Long num=(Long)msg.getObject(); seqnos.add(num); } } public int size() {return seqnos.size();} } }
package com.funsonli.springbootdemo400rabbitmq.controller; import com.funsonli.springbootdemo400rabbitmq.constant.RabbitmqConstant; import com.funsonli.springbootdemo400rabbitmq.vo.Message; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.atomic.AtomicInteger; /** * Student Controller * * @author Funson * @date 2019/10/12 */ @Slf4j @RestController public class ProducerController { AtomicInteger id = new AtomicInteger(); @Autowired private RabbitTemplate rabbitTemplate; /** * fanout 一个入,一个出 1:1 * @author Funsonli * @date 2019/10/3 */ @GetMapping("/direct") public String direct() { rabbitTemplate.convertAndSend(RabbitmqConstant.DIRECT_QUEUE, new Message(id.getAndIncrement(), "direct")); return "direct success"; } /** * fanout 一个入,多个出 1:N * @author Funsonli * @date 2019/10/3 */ @GetMapping("/fanout") public String fanout() { rabbitTemplate.convertAndSend(RabbitmqConstant.FANOUT_EXCHANGE, "", new Message(id.getAndIncrement(), "fanout")); return "fanout success"; } /** * fanout 一个入,多个出 根据规则匹配 * 规则1 fanout.# 可以把fanout交换机绑定进来 * 规则2 绑定单个队列 * 规则3 绑定 * 符号“#”匹配一个或多个词 比如“hello.#”能够匹配到“hello.123.456” * 符号“*”匹配一个词 “hello.*”只能匹配到“hello.123” * @author Funsonli * @date 2019/10/3 */ @GetMapping("/topic1") public String topic1() { rabbitTemplate.convertAndSend(RabbitmqConstant.TOPIC_EXCHANGE, "fanout.queue.k", new Message(id.getAndIncrement(), "topic1")); return "topic1 success"; } @GetMapping("/topic2") public String topic2() { rabbitTemplate.convertAndSend(RabbitmqConstant.TOPIC_EXCHANGE, "fanout.queue.2.2", new Message(id.getAndIncrement(), "topic2")); return "topic2 success"; } @GetMapping("/topic3") public String topic3() { rabbitTemplate.convertAndSend(RabbitmqConstant.TOPIC_EXCHANGE, "abc.queue.1", new Message(id.getAndIncrement(), "topic3")); return "topic3 success"; } }
/* * Copyright (c) 2008-2021, Hazelcast, Inc. 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.hazelcast.config; import com.hazelcast.internal.config.ConfigDataSerializerHook; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; import java.io.Serializable; import static com.hazelcast.internal.util.Preconditions.checkNotNull; import static com.hazelcast.internal.util.Preconditions.checkPositive; /** * Configuration for storing and pre-loading Near Cache keys. * * Preloader re-populates Near Cache after client/server restart to provide * fast access. * * @since 3.8 */ @SuppressWarnings("WeakerAccess") public class NearCachePreloaderConfig implements IdentifiedDataSerializable, Serializable { /** * Default initial delay for the Near Cache key storage. */ public static final int DEFAULT_STORE_INITIAL_DELAY_SECONDS = 600; /** * Default interval for the Near Cache key storage (in seconds). */ public static final int DEFAULT_STORE_INTERVAL_SECONDS = 600; private boolean enabled; private String directory = ""; private int storeInitialDelaySeconds = DEFAULT_STORE_INITIAL_DELAY_SECONDS; private int storeIntervalSeconds = DEFAULT_STORE_INTERVAL_SECONDS; public NearCachePreloaderConfig() { } public NearCachePreloaderConfig(NearCachePreloaderConfig nearCachePreloaderConfig) { this(nearCachePreloaderConfig.enabled, nearCachePreloaderConfig.directory); this.storeInitialDelaySeconds = nearCachePreloaderConfig.storeInitialDelaySeconds; this.storeIntervalSeconds = nearCachePreloaderConfig.storeIntervalSeconds; } public NearCachePreloaderConfig(String directory) { this(true, directory); } public NearCachePreloaderConfig(boolean enabled, String directory) { this.enabled = enabled; this.directory = checkNotNull(directory, "directory cannot be null!"); } public boolean isEnabled() { return enabled; } public NearCachePreloaderConfig setEnabled(boolean isEnabled) { this.enabled = isEnabled; return this; } public NearCachePreloaderConfig setDirectory(String directory) { this.directory = checkNotNull(directory, "directory cannot be null!"); return this; } public String getDirectory() { return directory; } public int getStoreInitialDelaySeconds() { return storeInitialDelaySeconds; } public NearCachePreloaderConfig setStoreInitialDelaySeconds(int storeInitialDelaySeconds) { this.storeInitialDelaySeconds = checkPositive("storeInitialDelaySeconds", storeInitialDelaySeconds); return this; } public int getStoreIntervalSeconds() { return storeIntervalSeconds; } public NearCachePreloaderConfig setStoreIntervalSeconds(int storeIntervalSeconds) { this.storeIntervalSeconds = checkPositive("storeIntervalSeconds", storeIntervalSeconds); return this; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getClassId() { return ConfigDataSerializerHook.NEAR_CACHE_PRELOADER_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeBoolean(enabled); out.writeUTF(directory); out.writeInt(storeInitialDelaySeconds); out.writeInt(storeIntervalSeconds); } @Override public void readData(ObjectDataInput in) throws IOException { enabled = in.readBoolean(); directory = in.readUTF(); storeInitialDelaySeconds = in.readInt(); storeIntervalSeconds = in.readInt(); } @Override public String toString() { return "NearCachePreloaderConfig{" + "enabled=" + enabled + ", directory=" + directory + ", storeInitialDelaySeconds=" + storeInitialDelaySeconds + ", storeIntervalSeconds=" + storeIntervalSeconds + '}'; } @Override @SuppressWarnings("checkstyle:npathcomplexity") public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NearCachePreloaderConfig that = (NearCachePreloaderConfig) o; if (enabled != that.enabled) { return false; } if (storeInitialDelaySeconds != that.storeInitialDelaySeconds) { return false; } if (storeIntervalSeconds != that.storeIntervalSeconds) { return false; } return directory != null ? directory.equals(that.directory) : that.directory == null; } @Override public int hashCode() { int result = (enabled ? 1 : 0); result = 31 * result + (directory != null ? directory.hashCode() : 0); result = 31 * result + storeInitialDelaySeconds; result = 31 * result + storeIntervalSeconds; return result; } }
package com.google.api.ads.dfp.jaxws.v201311; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for createUsersResponse element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="createUsersResponse"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="rval" type="{https://www.google.com/apis/ads/publisher/v201311}User" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "rval" }) @XmlRootElement(name = "createUsersResponse") public class UserServiceInterfacecreateUsersResponse { protected List<User> rval; /** * Gets the value of the rval property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rval property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRval().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link User } * * */ public List<User> getRval() { if (rval == null) { rval = new ArrayList<User>(); } return this.rval; } }
package com.lab4.junit; import com.lab4.bank.Client; import com.lab4.bank.Purse; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; public class ClientTest { @Test public void testGetID() throws Exception { Client client=new Client(1,null,null); Assert.assertTrue(client.GetID()==1); } @Test public void testGetAmount() throws Exception { Client client=new Client(1,null,new Purse(10,1)); Assert.assertTrue(client.GetAmount()==10); } }
/* * 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 gobblin.broker; import org.testng.Assert; import org.testng.annotations.Test; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import gobblin.broker.gobblin_scopes.GobblinScopeInstance; import gobblin.broker.gobblin_scopes.GobblinScopeTypes; import gobblin.broker.gobblin_scopes.JobScopeInstance; import gobblin.broker.gobblin_scopes.TaskScopeInstance; public class GobblinBrokerCreationTest { @Test public void testCreationOfBrokers() throws Exception { // Correct creation behavior Config config = ConfigFactory.empty(); SharedResourcesBrokerImpl<GobblinScopeTypes> topBroker = SharedResourcesBrokerFactory.createDefaultTopLevelBroker(config, new SimpleScope<GobblinScopeTypes>(GobblinScopeTypes.GLOBAL, "myGlobalScope")); SharedResourcesBrokerImpl<GobblinScopeTypes> jobBroker = topBroker.newSubscopedBuilder(new JobScopeInstance("myJob", "job123")).build(); SharedResourcesBrokerImpl<GobblinScopeTypes> containerBroker = topBroker.newSubscopedBuilder(GobblinScopeTypes.CONTAINER.defaultScopeInstance()).build(); SharedResourcesBrokerImpl<GobblinScopeTypes> taskBroker = jobBroker.newSubscopedBuilder(new TaskScopeInstance("taskabc")) .withAdditionalParentBroker(containerBroker).build(); Assert.assertEquals(taskBroker.selfScope().getType(), GobblinScopeTypes.TASK); Assert.assertEquals(((TaskScopeInstance) taskBroker.selfScope()).getTaskId(), "taskabc"); Assert.assertEquals(taskBroker.getScope(GobblinScopeTypes.CONTAINER).getType(), GobblinScopeTypes.CONTAINER); Assert.assertEquals(((GobblinScopeInstance) taskBroker.getScope(GobblinScopeTypes.CONTAINER)).getScopeId(), "container"); } @Test public void testFailIfSubBrokerAtHigherScope() throws Exception { Config config = ConfigFactory.empty(); SharedResourcesBrokerImpl<GobblinScopeTypes> topBroker = SharedResourcesBrokerFactory.createDefaultTopLevelBroker(config, GobblinScopeTypes.GLOBAL.defaultScopeInstance()); SharedResourcesBrokerImpl<GobblinScopeTypes> jobBroker = topBroker.newSubscopedBuilder(new JobScopeInstance("myJob", "job123")).build(); try { jobBroker.newSubscopedBuilder(new GobblinScopeInstance(GobblinScopeTypes.INSTANCE, "instance")).build(); Assert.fail(); } catch (IllegalArgumentException iae) { // expected } } @Test public void testFailIfIntermediateScopeHasNoDefault() throws Exception { Config config = ConfigFactory.empty(); SharedResourcesBrokerImpl<GobblinScopeTypes> topBroker = SharedResourcesBrokerFactory.createDefaultTopLevelBroker(config, GobblinScopeTypes.GLOBAL.defaultScopeInstance()); // should trow error if an intermediate scope does not have a default try { topBroker.newSubscopedBuilder(new TaskScopeInstance("taskxyz")).build(); Assert.fail(); } catch (IllegalArgumentException iae) { // expected } } @Test public void testFailIfDifferentAncestors() throws Exception { // Correct creation behavior Config config = ConfigFactory.empty(); SharedResourcesBrokerImpl<GobblinScopeTypes> topBroker = SharedResourcesBrokerFactory.createDefaultTopLevelBroker(config, GobblinScopeTypes.GLOBAL.defaultScopeInstance()); SharedResourcesBrokerImpl<GobblinScopeTypes> jobBroker = topBroker.newSubscopedBuilder(new JobScopeInstance("myJob", "job123")).build(); SharedResourcesBrokerImpl<GobblinScopeTypes> topBroker2 = SharedResourcesBrokerFactory.createDefaultTopLevelBroker(config, GobblinScopeTypes.GLOBAL.defaultScopeInstance()); SharedResourcesBrokerImpl<GobblinScopeTypes> containerBroker = topBroker2.newSubscopedBuilder(GobblinScopeTypes.CONTAINER.defaultScopeInstance()).build(); try { jobBroker.newSubscopedBuilder(new TaskScopeInstance("taskxyz")).withAdditionalParentBroker(containerBroker).build(); Assert.fail(); } catch (IllegalArgumentException iae) { // expected } } }
package com.afollestad.materialdialogs.simplelist; import android.graphics.PorterDuff; 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 com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.commons.R; import com.afollestad.materialdialogs.internal.MDAdapter; import java.util.ArrayList; import java.util.List; /** * See the sample project to understand how this is used. Mimics the Simple List dialog style * displayed on Google's guidelines site: https://www.google.com/design/spec/components/dialogs.html#dialogs-simple-dialogs * * @author Aidan Follestad (afollestad) */ public class MaterialSimpleListAdapter extends RecyclerView.Adapter<MaterialSimpleListAdapter.SimpleListVH> implements MDAdapter { public interface Callback { void onMaterialListItemSelected(int index, MaterialSimpleListItem item); } private MaterialDialog dialog; private List<MaterialSimpleListItem> mItems; private Callback mCallback; public MaterialSimpleListAdapter(Callback callback) { mItems = new ArrayList<>(4); mCallback = callback; } public void add(MaterialSimpleListItem item) { mItems.add(item); notifyItemInserted(mItems.size() - 1); } public void clear() { mItems.clear(); notifyDataSetChanged(); } public MaterialSimpleListItem getItem(int index) { return mItems.get(index); } @Override public void setDialog(MaterialDialog dialog) { this.dialog = dialog; } @Override public SimpleListVH onCreateViewHolder(ViewGroup parent, int viewType) { final View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.md_simplelist_item, parent, false); return new SimpleListVH(view, this); } @Override public void onBindViewHolder(SimpleListVH holder, int position) { if (dialog != null) { final MaterialSimpleListItem item = mItems.get(position); if (item.getIcon() != null) { holder.icon.setImageDrawable(item.getIcon()); holder.icon.setPadding(item.getIconPadding(), item.getIconPadding(), item.getIconPadding(), item.getIconPadding()); holder.icon.getBackground().setColorFilter(item.getBackgroundColor(), PorterDuff.Mode.SRC_ATOP); } else { holder.icon.setVisibility(View.GONE); } holder.title.setTextColor(dialog.getBuilder().getItemColor()); holder.title.setText(item.getContent()); dialog.setTypeface(holder.title, dialog.getBuilder().getRegularFont()); } } @Override public int getItemCount() { return mItems.size(); } public static class SimpleListVH extends RecyclerView.ViewHolder implements View.OnClickListener { final ImageView icon; final TextView title; final MaterialSimpleListAdapter adapter; public SimpleListVH(View itemView, MaterialSimpleListAdapter adapter) { super(itemView); icon = (ImageView) itemView.findViewById(android.R.id.icon); title = (TextView) itemView.findViewById(android.R.id.title); this.adapter = adapter; itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (adapter.mCallback != null) adapter.mCallback.onMaterialListItemSelected(getAdapterPosition(), adapter.getItem(getAdapterPosition())); } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.org 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 co.theengine.loomplayer; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxEditText; import org.cocos2dx.lib.Cocos2dxRenderer; import android.app.ActivityManager; import android.content.Context; import android.content.res.Configuration; import android.content.pm.ConfigurationInfo; import android.os.Bundle; import android.util.Log; import android.widget.FrameLayout; import android.widget.RelativeLayout; import android.view.ViewGroup; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.content.Intent; import co.theengine.loomplayer.OuyaGLSurfaceView; public class LoomPlayer extends Cocos2dxActivity{ private OuyaGLSurfaceView mGLView; public static LoomPlayer instance = null; public static void triggerGenericEvent(String type, String payload) { // Submit callback on proper thread. final String fType = type; final String fPayload = payload; OuyaGLSurfaceView.mainView.queueEvent(new Runnable() { @Override public void run() { internalTriggerGenericEvent(fType, fPayload); } }); } private static native void internalTriggerGenericEvent(String type, String payload); public static void handleGenericEvent(String type, String payload) { Log.d("Loom", "Saw generic event " + type + " " + payload); if(type.equals("cameraRequest")) { logError("Camera not supported on OUYA."); } } protected void onCreate(Bundle savedInstanceState) { instance = this; super.onCreate(savedInstanceState); if (!detectOpenGLES20()) { Log.d("Loom", "Sorry - this device doesn't support gles2.0"); finish(); } // get the packageName,it's used to set the resource path String packageName = getApplication().getPackageName(); super.setPackageName(packageName); // FrameLayout ViewGroup.LayoutParams framelayout_params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); FrameLayout framelayout = new FrameLayout(this); framelayout.setLayoutParams(framelayout_params); // Cocos2dxEditText layout ViewGroup.LayoutParams edittext_layout_params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); Cocos2dxEditText edittext = new Cocos2dxEditText(this); edittext.setLayoutParams(edittext_layout_params); ViewGroup webViewGroup = new RelativeLayout(this); // ...add to FrameLayout framelayout.addView(edittext); // OuyaGLSurfaceView mGLView = new OuyaGLSurfaceView(this); // ...add to FrameLayout framelayout.addView(mGLView); framelayout.addView(webViewGroup); mGLView.setEGLContextClientVersion(2); mGLView.setCocos2dxRenderer(new Cocos2dxRenderer()); mGLView.setTextField(edittext); // Set framelayout as the content view setContentView(framelayout); // give the webview class our layout LoomWebView.setRootLayout(webViewGroup); LoomAdMob.setRootLayout(webViewGroup); // Listen for IME-initiated resizes. // Thanks to http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android final View activityRootView = framelayout; Log.d("Loom", "Registering for global layout listener!"); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Log.d("Loom", "keyboardResize " + activityRootView.getHeight()); // Convert the dps to pixels final float scale = activityRootView.getContext().getResources().getDisplayMetrics().density; final float scaledThreshold = (int) (100 * scale + 0.5f); int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); if (heightDiff > scaledThreshold) { // if more than 100 points, its probably a keyboard... triggerGenericEvent("keyboardResize", "" + activityRootView.getHeight()); } } }); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) nativeSetOrientation("landscape"); else nativeSetOrientation("portrait"); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private boolean detectOpenGLES20() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo info = am.getDeviceConfigurationInfo(); return (info.reqGlEsVersion >= 0x20000); } public static native void log(String message); public static native void logWarn(String message); public static native void logError(String message); public static native void logDebug(String message); public static void logInfo(String message) { log(message); } static { System.loadLibrary("LoomPlayer"); } }
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2017 Adobe ~ ~ 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.adobe.cq.wcm.core.components.models; import java.util.Calendar; import org.apache.sling.api.resource.Resource; import org.jetbrains.annotations.Nullable; import org.osgi.annotation.versioning.ConsumerType; import com.adobe.cq.wcm.core.components.commons.link.Link; /** * Interface for a generic list item, used by the {@link List} and {@link Search} models. * * @since com.adobe.cq.wcm.core.components.models 12.2.0 */ @ConsumerType public interface ListItem extends Component { /** * Returns the link of this {@code ListItem}. * * @return the link of this list item. * @since com.adobe.cq.wcm.core.components.models 12.20.0 */ @Nullable default Link getLink() { return null; } /** * Returns the URL of this {@code ListItem}. * * @return the URL of this list item or {@code null} * @since com.adobe.cq.wcm.core.components.models 12.2.0 * @deprecated Please use {@link #getLink()} */ @Deprecated @Nullable default String getURL() { return null; } /** * Returns the title of this {@code ListItem}. * * @return the title of this list item or {@code null} * @since com.adobe.cq.wcm.core.components.models 12.2.0 */ @Nullable default String getTitle() { return null; } /** * Returns the description of this {@code ListItem}. * * @return the description of this list item or {@code null} * @since com.adobe.cq.wcm.core.components.models 12.2.0 */ @Nullable default String getDescription() { return null; } /** * Returns the date when this {@code ListItem} was last modified. * * @return the last modified date of this list item or {@code null} * @since com.adobe.cq.wcm.core.components.models 12.2.0 */ @Nullable default Calendar getLastModified() { return null; } /** * Returns the path of this {@code ListItem}. * * @return the list item path or {@code null} * @since com.adobe.cq.wcm.core.components.models 12.2.0 */ @Nullable default String getPath() { return null; } /** * Returns the name of this {@code ListItem}. * * @return the list item name or {@code null} * @since com.adobe.cq.wcm.core.components.models 12.6.0 */ @Nullable default String getName() { return null; } /** * Returns a wrapped resource of the item which is used to render the item as a Teaser component. * * The wrapped resource is either: * - the featured image of the item page, if it exists * - the content node of the item page, if it exists * - null otherwise * * @return wrapped resource of the item which can be rendered as a Teaser component * @since com.adobe.cq.wcm.core.components.models 12.21.0 */ @Nullable default Resource getTeaserResource() { return null;} }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/spanner/v1/spanner.proto package com.google.spanner.v1; /** * * * <pre> * The request for [GetSession][google.spanner.v1.Spanner.GetSession]. * </pre> * * Protobuf type {@code google.spanner.v1.GetSessionRequest} */ public final class GetSessionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.spanner.v1.GetSessionRequest) GetSessionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetSessionRequest.newBuilder() to construct. private GetSessionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetSessionRequest() { name_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private GetSessionRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } 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; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } default: { if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { done = true; } 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 com.google.spanner.v1.SpannerProto .internal_static_google_spanner_v1_GetSessionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.spanner.v1.SpannerProto .internal_static_google_spanner_v1_GetSessionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.spanner.v1.GetSessionRequest.class, com.google.spanner.v1.GetSessionRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; 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(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } 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 com.google.spanner.v1.GetSessionRequest)) { return super.equals(obj); } com.google.spanner.v1.GetSessionRequest other = (com.google.spanner.v1.GetSessionRequest) obj; boolean result = true; result = result && getName().equals(other.getName()); 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(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.spanner.v1.GetSessionRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.spanner.v1.GetSessionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.spanner.v1.GetSessionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.spanner.v1.GetSessionRequest 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.spanner.v1.GetSessionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.spanner.v1.GetSessionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.spanner.v1.GetSessionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.spanner.v1.GetSessionRequest 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.spanner.v1.GetSessionRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.spanner.v1.GetSessionRequest 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.spanner.v1.GetSessionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.spanner.v1.GetSessionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.spanner.v1.GetSessionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override 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> * The request for [GetSession][google.spanner.v1.Spanner.GetSession]. * </pre> * * Protobuf type {@code google.spanner.v1.GetSessionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.spanner.v1.GetSessionRequest) com.google.spanner.v1.GetSessionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.spanner.v1.SpannerProto .internal_static_google_spanner_v1_GetSessionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.spanner.v1.SpannerProto .internal_static_google_spanner_v1_GetSessionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.spanner.v1.GetSessionRequest.class, com.google.spanner.v1.GetSessionRequest.Builder.class); } // Construct using com.google.spanner.v1.GetSessionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.spanner.v1.SpannerProto .internal_static_google_spanner_v1_GetSessionRequest_descriptor; } @java.lang.Override public com.google.spanner.v1.GetSessionRequest getDefaultInstanceForType() { return com.google.spanner.v1.GetSessionRequest.getDefaultInstance(); } @java.lang.Override public com.google.spanner.v1.GetSessionRequest build() { com.google.spanner.v1.GetSessionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.spanner.v1.GetSessionRequest buildPartial() { com.google.spanner.v1.GetSessionRequest result = new com.google.spanner.v1.GetSessionRequest(this); result.name_ = name_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.spanner.v1.GetSessionRequest) { return mergeFrom((com.google.spanner.v1.GetSessionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.spanner.v1.GetSessionRequest other) { if (other == com.google.spanner.v1.GetSessionRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.spanner.v1.GetSessionRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.spanner.v1.GetSessionRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * * * <pre> * Required. The name of the session to retrieve. * </pre> * * <code>string name = 1;</code> */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.spanner.v1.GetSessionRequest) } // @@protoc_insertion_point(class_scope:google.spanner.v1.GetSessionRequest) private static final com.google.spanner.v1.GetSessionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.spanner.v1.GetSessionRequest(); } public static com.google.spanner.v1.GetSessionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetSessionRequest> PARSER = new com.google.protobuf.AbstractParser<GetSessionRequest>() { @java.lang.Override public GetSessionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new GetSessionRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<GetSessionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetSessionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.spanner.v1.GetSessionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package org.hisp.dhis.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; /* * Copyright (c) 2004-2015, 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. */ public class ObjectUtils { /** * Returns the first non-null argument. Returns null if all arguments are null. * * @param objects the objects. * @return the first non-null argument. */ @SafeVarargs public static final <T> T firstNonNull( T... objects ) { if ( objects != null ) { for ( T object : objects ) { if ( object != null ) { return object; } } } return null; } /** * Returns a list of strings, where the strings are the result of calling * String.valueOf( Object ) of each object in the given collection. * * @param objects the collection of objects. * @return a list of strings. */ public static List<String> asStringList( Collection<? extends Object> objects ) { List<String> list = new ArrayList<>(); for ( Object object : objects ) { list.add( String.valueOf( object ) ); } return list; } }
/** * Copyright &copy; 2012-2014 <a href="http://www.kszhineng.cn">OA</a> All rights reserved. */ package com.szcxsl.oa.common.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import org.apache.commons.lang3.StringUtils; /** * 对象操作工具类, 继承org.apache.commons.lang3.ObjectUtils类 * @author Shi Lei * @version 2014-6-29 */ public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils { /** * 注解到对象复制,只复制能匹配上的方法。 * @param annotation * @param object */ public static void annotationToObject(Object annotation, Object object){ if (annotation != null){ Class<?> annotationClass = annotation.getClass(); Class<?> objectClass = object.getClass(); for (Method m : objectClass.getMethods()){ if (StringUtils.startsWith(m.getName(), "set")){ try { String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3)); Object obj = annotationClass.getMethod(s).invoke(annotation); if (obj != null && !"".equals(obj.toString())){ if (object == null){ object = objectClass.newInstance(); } m.invoke(object, obj); } } catch (Exception e) { // 忽略所有设置失败方法 } } } } } /** * 序列化对象 * @param object * @return */ public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { if (object != null){ baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); return baos.toByteArray(); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 反序列化对象 * @param bytes * @return */ public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { if (bytes != null && bytes.length > 0){ bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } } catch (Exception e) { e.printStackTrace(); } return null; } }
package com.atguigu.gmall.ums.dao; import com.atguigu.gmall.ums.entity.MemberEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 会员 * * @author lzc * @email lzc@atguigu.com * @date 2019-12-16 19:16:53 */ @Mapper public interface MemberDao extends BaseMapper<MemberEntity> { }
package ws.soap.security.socketserver; import java.io.OutputStream; import com.sun.net.httpserver.HttpExchange; public class MyIService implements IService { @Override public void get(HttpExchange arg0){ try { arg0.sendResponseHeaders(200, 0); // 0 == as many bytes as there are OutputStream out = arg0.getResponseBody(); out.write("GETResponse".getBytes()); out.close(); } catch (Exception e) { System.err.println("Error in get MyIservice"); } } }
/** * */ package de.unirostock.sems.bives.cellml.parser; import java.util.ArrayList; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Namespace; import de.unirostock.sems.bives.ds.rdf.RDF; import de.unirostock.sems.bives.ds.rdf.RDFDescription; import de.unirostock.sems.bives.exception.BivesLogicalException; import de.unirostock.sems.bives.markup.MarkupElement; import de.unirostock.sems.xmlutils.ds.DocumentNode; import de.unirostock.sems.xmlutils.ds.TreeNode; /** * The Class CellMLEntity representing an entity in a CellML model. * * @author Martin Scharm */ public abstract class CellMLEntity { /** The model. */ protected CellMLModel model; /** The RDF descriptions. */ private List<RDF> rdfBlocks; /** The document node. */ private DocumentNode node; /** The rdf descriptions. */ private List<RDFDescription> rdfDescriptions; /** * Instantiates a new CellML entity. * * @param node the corresponding node in the XML document * @param model the model * @throws BivesLogicalException */ public CellMLEntity (DocumentNode node, CellMLModel model) throws BivesLogicalException { this.model = model; this.node = node; rdfBlocks = new ArrayList<RDF> (); rdfDescriptions = new ArrayList<RDFDescription> (); if (model != null) { model.mapNode (node, this); String metaId = getMetaId (); if (metaId != null) model.registerMetaId (metaId, this); } if (node != null) { List<TreeNode> kids= node.getChildrenWithTag ("RDF"); for (TreeNode kid : kids) { if (kid.getType () != TreeNode.DOC_NODE) continue; RDF rdf = new RDF ((DocumentNode) kid); rdfBlocks.add (rdf); if (model != null) model.registerRdfBlock (rdf); } } } /** * Flags occuring modifcations of the meta information (notes, annotations) to the given MarkupElement. * * @param me the MarkupElement that should be flagged * @return true, if flagged */ public boolean flagMetaModifcations (MarkupElement me) { for (RDF rdf : rdfBlocks) if (rdf.getNode ().getModification () != TreeNode.UNCHANGED) { me.flagInvisibleModification (); return true; } return false; } /** * Gets the document node. * * @return the document node */ public DocumentNode getDocumentNode () { return node; } /** * Gets the RDF descriptions, if there are any rooted in this entity. * * @return the RDF descriptions */ public List<RDF> getRdfBlocks () { return rdfBlocks; } /** * Gets the corresponding model. * * @return the model */ public CellMLModel getModel () { return model; } /** * Sets the model. * * @param model the new model * @throws BivesLogicalException */ public void setModel (CellMLModel model) throws BivesLogicalException { model.mapNode (node, this); String metaId = getMetaId (); if (metaId != null) model.registerMetaId (metaId, this); } /** * Sets the meta id of this entity. Must be unique in this model and * * @param metaId the meta id * @return true, if successful * @throws BivesLogicalException */ public boolean setMetaId (String metaId) throws BivesLogicalException { if (metaId == null || metaId.length () < 1) return false; if (getMetaId () != null) model.unregisterMetaId (getMetaId ()); if (model.getEntityByMetaId (metaId) != null) return false; node.setAttribute (new Attribute ("id", metaId, Namespace.getNamespace ("cmeta", "http://www.cellml.org/metadata/1.0#"))); model.registerMetaId (metaId, this); return true; } /** * Gets the CellML meta id of this entity. Might return null if not defined. * * @return the meta id */ public String getMetaId () { if (node != null) return node.getAttributeValue ("id", "cellml.org/metadata"); else return null; } /** * Associate an rdf description. * * @param descr the description */ public void associateRdfDescription (RDFDescription descr) { rdfDescriptions.add (descr); } /** * Gets the rdf descriptions. * * @return the rdf descriptions */ public List<RDFDescription> getRdfDescriptions () { return rdfDescriptions; } }
package com.gakes.util.encrypt; import android.util.Base64; import android.util.Log; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public final class AESCrypt { private static final String TAG = "AESCrypt"; //AESCrypt-ObjC uses CBC and PKCS7Padding private static final String AES_MODE = "AES/CBC/PKCS7Padding"; private static final String CHARSET = "UTF-8"; //AESCrypt-ObjC uses SHA-256 (and so a 256-bit key) private static final String HASH_ALGORITHM = "SHA-256"; //AESCrypt-ObjC uses blank IV (not the best security, but the aim here is compatibility) private static final byte[] ivBytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; //togglable log option (please turn off in live!) public static boolean DEBUG_LOG_ENABLED = false; /** * Generates SHA256 hash of the password which is used as key * * @param password used to generated key * @return SHA256 of the password */ private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM); byte[] bytes = password.getBytes("UTF-8"); digest.update(bytes, 0, bytes.length); byte[] key = digest.digest(); log("SHA-256 key ", key); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); return secretKeySpec; } /** * Encrypt and encode message using 256-bit AES with key generated from password. * * @param password used to generated key * @param message the thing you want to encrypt assumed String UTF-8 * @return Base64 encoded CipherText * @throws GeneralSecurityException if problems occur during encryption */ public static String encrypt(final String password, String message) throws GeneralSecurityException { try { final SecretKeySpec key = generateKey(password); log("message", message); byte[] cipherText = encrypt(key, ivBytes, message.getBytes(CHARSET)); //NO_WRAP is important as was getting \n at the end String encoded = Base64.encodeToString(cipherText, Base64.NO_WRAP); log("Base64.NO_WRAP", encoded); return encoded; } catch (UnsupportedEncodingException e) { if (DEBUG_LOG_ENABLED) Log.e(TAG, "UnsupportedEncodingException ", e); throw new GeneralSecurityException(e); } } /** * More flexible AES encrypt that doesn't encode * * @param key AES key typically 128, 192 or 256 bit * @param iv Initiation Vector * @param message in bytes (assumed it's already been decoded) * @return Encrypted cipher text (not encoded) * @throws GeneralSecurityException if something goes wrong during encryption */ public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message) throws GeneralSecurityException { final Cipher cipher = Cipher.getInstance(AES_MODE); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] cipherText = cipher.doFinal(message); log("cipherText", cipherText); return cipherText; } /** * Decrypt and decode ciphertext using 256-bit AES with key generated from password * * @param password used to generated key * @param base64EncodedCipherText the encrpyted message encoded with base64 * @return message in Plain text (String UTF-8) * @throws GeneralSecurityException if there's an issue decrypting */ public static String decrypt(final String password, String base64EncodedCipherText) throws GeneralSecurityException { try { final SecretKeySpec key = generateKey(password); log("base64EncodedCipherText", base64EncodedCipherText); byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP); log("decodedCipherText", decodedCipherText); byte[] decryptedBytes = decrypt(key, ivBytes, decodedCipherText); log("decryptedBytes", decryptedBytes); String message = new String(decryptedBytes, CHARSET); log("message", message); return message; } catch (UnsupportedEncodingException e) { if (DEBUG_LOG_ENABLED) Log.e(TAG, "UnsupportedEncodingException ", e); throw new GeneralSecurityException(e); } } /** * More flexible AES decrypt that doesn't encode * * @param key AES key typically 128, 192 or 256 bit * @param iv Initiation Vector * @param decodedCipherText in bytes (assumed it's already been decoded) * @return Decrypted message cipher text (not encoded) * @throws GeneralSecurityException if something goes wrong during encryption */ public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText) throws GeneralSecurityException { final Cipher cipher = Cipher.getInstance(AES_MODE); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] decryptedBytes = cipher.doFinal(decodedCipherText); log("decryptedBytes", decryptedBytes); return decryptedBytes; } private static void log(String what, byte[] bytes) { if (DEBUG_LOG_ENABLED) Log.d(TAG, what + "[" + bytes.length + "] [" + bytesToHex(bytes) + "]"); } private static void log(String what, String value) { if (DEBUG_LOG_ENABLED) Log.d(TAG, what + "[" + value.length() + "] [" + value + "]"); } /** * Converts byte array to hexidecimal useful for logging and fault finding * * @param bytes * @return */ private static String bytesToHex(byte[] bytes) { final char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } private AESCrypt() { } }
/* * * * Copyright (c) 2021. - TinyZ. * * 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.struct.core.converter; /** * The instance type converter. */ public interface Converter { /** * Covert origin value to target field's type. * * @param originValue the origin value. * @param targetType the convert to field type. * @return return the converted value */ Object convert(Object originValue, Class<?> targetType); }
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * 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.deleidos.rtws.core.framework.parser; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.util.ArrayList; import net.sf.json.JSONObject; import org.junit.Test; import com.deleidos.rtws.core.framework.parser.JSONParser; import com.deleidos.rtws.core.framework.parser.ParsePipelineException; public class JSONParserTest { @Test public void testParse() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red\", id: \"545\", animal: \"cat\"}"); lines.add("{color: \"blue\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); for (String i : lines) expected.add(JSONObject.fromObject(i)); assertTrue(results.equals(expected)); } @Test public void testParseWithQuotedEndBrace() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red\", id: \"545\", animal: \"cat\"}"); lines.add("{color: \"blue}\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); for (String i : lines) expected.add(JSONObject.fromObject(i)); assertTrue(results.equals(expected)); } @Test public void testParseWithQuotedOpenBrace() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red\", id: \"545\", animal: \"cat\"}"); lines.add("{color: \"blue{\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); for (String i : lines) expected.add(JSONObject.fromObject(i)); assertTrue(results.equals(expected)); } @Test public void testParseWithSplitRecord() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red\", "); lines.add("id: \"545\", animal: \"cat\"}"); lines.add("{color: \"blue\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); expected.add(JSONObject.fromObject("{color: \"red\", id: \"545\", animal: \"cat\"}")); expected.add(JSONObject.fromObject("{color: \"blue\", id: \"546\", animal: \"dog\"}")); assertTrue(results.equals(expected)); } @Test public void testParseWithSplitQuotedString() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red"); lines.add("\", id: \"545\", animal: \"cat\"}"); lines.add("{color: \"blue\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); expected.add(JSONObject.fromObject("{color: \"red\", id: \"545\", animal: \"cat\"}")); expected.add(JSONObject.fromObject("{color: \"blue\", id: \"546\", animal: \"dog\"}")); assertTrue(results.equals(expected)); } @Test public void testWorstCaseSplitQuotedStringWithBrace() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red}"); lines.add("\", id: \"545\", animal: \"cat\"}"); lines.add("{color: \"blue\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); expected.add(JSONObject.fromObject("{color: \"red}\", id: \"545\", animal: \"cat\"}")); expected.add(JSONObject.fromObject("{color: \"blue\", id: \"546\", animal: \"dog\"}")); assertTrue(results.equals(expected)); } @Test public void testParseWithUnevenEscapedJSONQuotes() throws ParsePipelineException { JSONParser tempParser = new JSONParser("UTF-8"); ArrayList<String> lines = new ArrayList<String>(); ArrayList<JSONObject> results = new ArrayList<JSONObject>(), expected = new ArrayList<JSONObject>(); lines.add("{color: \"red\", id: \"545\", animal: \"c\\\"at\"}"); lines.add("{color: \"blue\", id: \"546\", animal: \"dog\"}"); String input = ""; JSONObject temp; for (String i : lines) input += "\n" + i; input = input.substring(1); tempParser.setInputStream(new ByteArrayInputStream(input.getBytes())); while ((temp = tempParser.parse()) != null) results.add(temp); for (String i : lines) expected.add(JSONObject.fromObject(i)); assertTrue(results.equals(expected)); } }
public interface Bar { public int baz(); public String axa(); }
package com.sap.cloud.lm.sl.mta.parsers; import static com.sap.cloud.lm.sl.mta.handlers.v2.Schemas.PLATFORM; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.sap.cloud.lm.sl.common.ParsingException; import com.sap.cloud.lm.sl.mta.model.ModuleType; import com.sap.cloud.lm.sl.mta.model.Platform; import com.sap.cloud.lm.sl.mta.model.ResourceType; import com.sap.cloud.lm.sl.mta.schema.MapElement; public class PlatformParser extends ModelParser<Platform> { protected static final String PROCESSED_OBJECT_NAME = "MTA platform type"; public static final String NAME = "name"; public static final String MODULE_TYPES = "module-types"; public static final String RESOURCE_TYPES = "resource-types"; public static final String PARAMETERS = "parameters"; protected final Set<String> usedModuleTypeNames = new HashSet<>(); protected final Set<String> usedResourceTypeNames = new HashSet<>(); public PlatformParser(Map<String, Object> source) { this(PLATFORM, source); } protected PlatformParser(MapElement schema, Map<String, Object> source) { super(PROCESSED_OBJECT_NAME, schema, source); } @Override public Platform parse() throws ParsingException { return new Platform().setName(getName()) .setModuleTypes(getModuleTypes()) .setResourceTypes(getResourceTypes()) .setParameters(getParameters()); } protected String getName() { return getStringElement(NAME); } protected List<ModuleType> getModuleTypes() { return getListElement(MODULE_TYPES, new ListParser<ModuleType>() { @Override protected ModuleType parseItem(Map<String, Object> map) { return getModuleTypeParser(map).setUsedValues(usedModuleTypeNames) .parse(); } }); } protected ModuleTypeParser getModuleTypeParser(Map<String, Object> source) { return new ModuleTypeParser(source); } protected List<ResourceType> getResourceTypes() { return getListElement(RESOURCE_TYPES, new ListParser<ResourceType>() { @Override protected ResourceType parseItem(Map<String, Object> map) { return getResourceTypeParser(map).setUsedValues(usedResourceTypeNames) .parse(); } }); } protected ResourceTypeParser getResourceTypeParser(Map<String, Object> source) { return new ResourceTypeParser(source); } protected Map<String, Object> getParameters() { return getMapElement(PARAMETERS); } }
package com.cloudburst.storify; import com.cloudburst.storify.examples.CompositeKeyEntity; import com.cloudburst.storify.examples.BasicEntity; import org.junit.Assert; import org.junit.Test; /** * Created by ajchesney on 23/08/2016. */ public class EntityTests { @Test public void testBasicPutAndThenLoadThenDelete() { BasicEntity entity = new BasicEntity().setName("testkey").setValue("testvalue").setLongValue(123); Storify.sfy().put(entity); BasicEntity test = Storify.sfy().load(BasicEntity.class,"testkey").get(); Assert.assertEquals("testkey", test.getName()); Assert.assertEquals("testvalue", test.getValue()); Assert.assertEquals(123, test.getLongValue()); Storify.sfy().delete(BasicEntity.class,"testkey"); } @Test public void testCompositeKeyPutAndThenLoad() { CompositeKeyEntity entity = new CompositeKeyEntity().setOne("one").setTwo("two").setValue("testvalue"); Storify.sfy().put(entity); CompositeKeyEntity test = Storify.sfy().load(CompositeKeyEntity.class,"one:two").get(); Assert.assertEquals("one", test.getOne()); Assert.assertEquals("two", test.getTwo()); Assert.assertEquals("testvalue", test.getValue()); Storify.sfy().delete(CompositeKeyEntity.class,"one:two"); } }
package com.instagram; import expo.modules.ReactActivityDelegateWrapper; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ @Override protected String getMainComponentName() { return "instagram"; } @Override protected ReactActivityDelegate createReactActivityDelegate() { return new ReactActivityDelegateWrapper(this, new ReactActivityDelegate(this, getMainComponentName()) ); } }
package com.openrest.v1_1; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonIgnoreProperties(ignoreUnknown = true) public class AffiliateFullInfo extends OpenrestObject { public static final String TYPE = "affiliate_full"; private static final long serialVersionUID = 1L; /** Default constructor for JSON deserialization. */ public AffiliateFullInfo() {} public AffiliateFullInfo(Affiliate affiliate, Distributor distributor) { this.affiliate = affiliate; this.distributor = distributor; } /** The affiliate. */ @JsonInclude(Include.NON_NULL) public Affiliate affiliate; /** The distributor. */ @JsonInclude(Include.NON_NULL) public Distributor distributor; }
/* * Copyright 2015 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. */ /** * Classes and interfaces for managing client sessions. * <p> * Sessions represent the context in which clients communicate with a Raft cluster. Sessions allow clusters * to process requests according to client state. For instance, sessions are responsible for ensuring operations * are executed in the order specified by the client (sequential consistency) and operations are only applied * to the replicated state machine once (linearizability). * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ package io.atomix.copycat.session;
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hystrix.strategy.properties; import java.util.concurrent.ConcurrentHashMap; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPool; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.strategy.HystrixPlugins; /** * Factory for retrieving properties implementations. * <p> * This uses given {@link HystrixPropertiesStrategy} implementations to construct Properties instances and caches each instance according to the cache key provided. * * @ExcludeFromJavadoc */ public class HystrixPropertiesFactory { /** * Clears all the defaults in the static property cache. This makes it possible for property defaults to not persist for * an entire JVM lifetime. May be invoked directly, and also gets invoked by <code>Hystrix.reset()</code> */ public static void reset() { commandProperties.clear(); threadPoolProperties.clear(); collapserProperties.clear(); } // String is CommandKey.name() (we can't use CommandKey directly as we can't guarantee it implements hashcode/equals correctly) private static final ConcurrentHashMap<String, HystrixCommandProperties> commandProperties = new ConcurrentHashMap<String, HystrixCommandProperties>(); /** * Get an instance of {@link HystrixCommandProperties} with the given factory {@link HystrixPropertiesStrategy} implementation for each {@link HystrixCommand} instance. * * @param key * Pass-thru to {@link HystrixPropertiesStrategy#getCommandProperties} implementation. * @param builder * Pass-thru to {@link HystrixPropertiesStrategy#getCommandProperties} implementation. * @return {@link HystrixCommandProperties} instance */ public static HystrixCommandProperties getCommandProperties(HystrixCommandKey key, HystrixCommandProperties.Setter builder) { HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy(); String cacheKey = hystrixPropertiesStrategy.getCommandPropertiesCacheKey(key, builder); if (cacheKey != null) { HystrixCommandProperties properties = commandProperties.get(cacheKey); if (properties != null) { return properties; } else { if (builder == null) { builder = HystrixCommandProperties.Setter(); } // create new instance properties = hystrixPropertiesStrategy.getCommandProperties(key, builder); // cache and return HystrixCommandProperties existing = commandProperties.putIfAbsent(cacheKey, properties); if (existing == null) { return properties; } else { return existing; } } } else { // no cacheKey so we generate it with caching return hystrixPropertiesStrategy.getCommandProperties(key, builder); } } // String is ThreadPoolKey.name() (we can't use ThreadPoolKey directly as we can't guarantee it implements hashcode/equals correctly) private static final ConcurrentHashMap<String, HystrixThreadPoolProperties> threadPoolProperties = new ConcurrentHashMap<String, HystrixThreadPoolProperties>(); /** * Get an instance of {@link HystrixThreadPoolProperties} with the given factory {@link HystrixPropertiesStrategy} implementation for each {@link HystrixThreadPool} instance. * * @param key * Pass-thru to {@link HystrixPropertiesStrategy#getThreadPoolProperties} implementation. * @param builder * Pass-thru to {@link HystrixPropertiesStrategy#getThreadPoolProperties} implementation. * @return {@link HystrixThreadPoolProperties} instance */ public static HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey key, HystrixThreadPoolProperties.Setter builder) { HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy(); String cacheKey = hystrixPropertiesStrategy.getThreadPoolPropertiesCacheKey(key, builder); if (cacheKey != null) { HystrixThreadPoolProperties properties = threadPoolProperties.get(cacheKey); if (properties != null) { return properties; } else { if (builder == null) { builder = HystrixThreadPoolProperties.Setter(); } // create new instance properties = hystrixPropertiesStrategy.getThreadPoolProperties(key, builder); // cache and return HystrixThreadPoolProperties existing = threadPoolProperties.putIfAbsent(cacheKey, properties); if (existing == null) { return properties; } else { return existing; } } } else { // no cacheKey so we generate it with caching return hystrixPropertiesStrategy.getThreadPoolProperties(key, builder); } } // String is CollapserKey.name() (we can't use CollapserKey directly as we can't guarantee it implements hashcode/equals correctly) private static final ConcurrentHashMap<String, HystrixCollapserProperties> collapserProperties = new ConcurrentHashMap<String, HystrixCollapserProperties>(); /** * Get an instance of {@link HystrixCollapserProperties} with the given factory {@link HystrixPropertiesStrategy} implementation for each {@link HystrixCollapserKey} instance. * * @param key * Pass-thru to {@link HystrixPropertiesStrategy#getCollapserProperties} implementation. * @param builder * Pass-thru to {@link HystrixPropertiesStrategy#getCollapserProperties} implementation. * @return {@link HystrixCollapserProperties} instance */ public static HystrixCollapserProperties getCollapserProperties(HystrixCollapserKey key, HystrixCollapserProperties.Setter builder) { HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy(); String cacheKey = hystrixPropertiesStrategy.getCollapserPropertiesCacheKey(key, builder); if (cacheKey != null) { HystrixCollapserProperties properties = collapserProperties.get(cacheKey); if (properties != null) { return properties; } else { if (builder == null) { builder = HystrixCollapserProperties.Setter(); } // create new instance properties = hystrixPropertiesStrategy.getCollapserProperties(key, builder); // cache and return HystrixCollapserProperties existing = collapserProperties.putIfAbsent(cacheKey, properties); if (existing == null) { return properties; } else { return existing; } } } else { // no cacheKey so we generate it with caching return hystrixPropertiesStrategy.getCollapserProperties(key, builder); } } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|cxf operator|. name|common operator|. name|annotation package|; end_package begin_class specifier|public class|class name|Base block|{ specifier|public name|Base parameter_list|() block|{ } block|} end_class end_unit
package ro.pub.cs.systems.eim.lab05.startedserviceactivity.view; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.TextView; import ro.pub.cs.systems.eim.lab05.startedserviceactivity.general.Constants; public class StartedServiceBroadcastReceiver extends BroadcastReceiver { private TextView messageTextView; // TODO: exercise 9 - default constructor public StartedServiceBroadcastReceiver(){ this.messageTextView = null; } public StartedServiceBroadcastReceiver(TextView messageTextView) { this.messageTextView = messageTextView; } @Override public void onReceive(Context context, Intent intent) { // TODO: exercise 7 - get the action and the extra information from the intent // and set the text on the messageTextView String action = intent.getAction(); String data = null; if (Constants.ACTION_STRING.equals(action)) { data = intent.getStringExtra(Constants.DATA); } if (Constants.ACTION_INTEGER.equals(action)) { data = String.valueOf(intent.getIntExtra(Constants.DATA, -1)); } if (Constants.ACTION_ARRAY_LIST.equals(action)) { data = intent.getStringArrayListExtra(Constants.DATA).toString(); } if (messageTextView != null) { messageTextView.setText(messageTextView.getText().toString() + "\n" + data); } // TODO: exercise 9 - restart the activity through an intent // if the messageTextView is not available Intent startedServiceActivityIntent = new Intent(context, StartedServiceActivity.class); startedServiceActivityIntent.putExtra(Constants.MESSAGE, data); startedServiceActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(startedServiceActivityIntent); } }
package essentials.tuple; import essentials.collections.IterableList; import essentials.datastructure.Lazy; import essentials.util.HashGenerator; import org.jetbrains.annotations.NotNull; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.function.Supplier; /** * @author Patrick * @since 16.11.2016 */ @SuppressWarnings("WeakerAccess") class UnitImpl<A> implements Serializable, IterableList<Object>, Unit<A> { protected A A; protected final Lazy<List<Object>> _values; protected final Lazy<Integer> _hashCode; // =============== // Constructors // =============== public UnitImpl(Unit<A> a){ this(a.getA()); } public UnitImpl(A a) { A = a; _values = Lazy.of(makeArray()); _hashCode = Lazy.of(this::makeHash); } // =============== // Properties // =============== public A getA() { return A; } public void setA(A a) { A = a; } // =============== // Methods // =============== protected Supplier<List<Object>> makeArray(){ return () -> Collections.singletonList(A); } /** * Part for the equals * @apiNote Must be overridden by all subclasses * @param obj the * @return */ protected boolean equalClass(Object obj){ return obj instanceof Unit; } @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object obj) { return equalClass(obj) && hashCode() == obj.hashCode(); } @Override public int hashCode() { return _hashCode.get(); } public int makeHash() { return new HashGenerator(getClass()) .appendAll(_values.get()) .toHashCode(); } @NotNull @Override public ListIterator<Object> iterator() { return _values.get().listIterator(); } @NotNull @Override public ListIterator<Object> listIterator() { return iterator(); } @Override public String toString() { StringBuilder builder = new StringBuilder("[ "); int count = 0; for (Iterator<Object> iter = _values.get().iterator(); iter.hasNext(); ){ Object cur = iter.next(); builder.append("Val").append(count++).append(": ").append(cur); if (iter.hasNext()){ builder.append(" | "); } else { builder.append("]"); } } return builder.toString(); } }
/********************************************************************************** * * Copyright (c) 2006, 2008, 2013 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.sakaiproject.tasks.impl.test; import static org.junit.runners.MethodSorters.NAME_ASCENDING; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.sakaiproject.tasks.api.Priorities; import org.sakaiproject.tasks.api.TaskService; import org.sakaiproject.tasks.api.Task; import org.sakaiproject.tasks.api.UserTaskAdapterBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TaskServiceTestConfiguration.class}) @FixMethodOrder(NAME_ASCENDING) public class TaskServiceTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private TaskService taskService; private Task createTask(String reference) { String siteId = "python101"; String description = "This is my task"; Set<String> userIds = new HashSet<>(); userIds.add("abcde"); userIds.add("earle"); Task task = new Task(); task.setSiteId(siteId); task.setReference(reference); task.setSystem(false); task.setDescription(description); return taskService.createTask(task, userIds, Priorities.HIGH); } @Test public void testCanCreateSingleUserTask() { String description = "Description about my task"; String notes = "Notes about my task"; int priority = Priorities.QUITE_HIGH; UserTaskAdapterBean bean = new UserTaskAdapterBean(); bean.setDescription(description); bean.setNotes(notes); bean.setPriority(priority); taskService.createSingleUserTask(bean); Optional<UserTaskAdapterBean> optionalUserTask = taskService.getAllTasksForCurrentUser().stream().findFirst(); Assert.isTrue(optionalUserTask.isPresent(), "getAllTasksForCurrentUser did not return our new task"); UserTaskAdapterBean userTask = optionalUserTask.get(); assertEquals("task.description were not the same", description, userTask.getDescription()); assertEquals("usertask.notes were not the same", notes, userTask.getNotes()); Assert.isTrue(userTask.getPriority() == priority, "task.priority were not the same"); } @Test public void testCanCreateTask() { String reference = "/a/xyz"; Task task = createTask(reference); Assert.isTrue(task.getId() != null, "The saved task should now have an id"); Assert.isTrue(taskService.getAllTasksForCurrentUser().stream().findFirst().isPresent(), "getAllTasksForCurrentUser did not return our new task"); } @Test public void testCanSaveUserTask() { String reference = "/a/xyz"; createTask(reference); List<UserTaskAdapterBean> userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 1, "There should be one user task after creating"); UserTaskAdapterBean userTask = userTasks.get(0); String newNotes = "New notes"; String newDescription = "New description"; userTask.setNotes(newNotes); userTask.setPriority(3); userTask.setComplete(true); userTask.setDescription(newDescription); taskService.saveUserTask(userTask); userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 1, "There should be one user task after updating"); userTask = userTasks.get(0); assertEquals("Newly saved notes doesn't match", newNotes, userTask.getNotes()); assertEquals("Newly saved description doesn't match", newDescription, userTask.getDescription()); Assert.isTrue(userTask.getPriority() == 3, "Newly saved priority doesn't match"); Assert.isTrue(userTask.getComplete(), "Newly saved task should be complete"); } @Test public void testCanRemoveUserTask() { String reference = "/a/xyz"; createTask(reference); List<UserTaskAdapterBean> userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 1, "There should be one user task after creating"); UserTaskAdapterBean userTask = userTasks.get(0); taskService.removeUserTask(userTask.getUserTaskId()); userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 0, "There should be zero user task after removing"); } @Test public void testCanDeleteTask() { String reference = "/a/xyz"; Task task = createTask(reference); Assert.isTrue(task.getId() != null, "The saved task should now have an id"); taskService.removeTask(task); List<UserTaskAdapterBean> userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 0, "Deleting a Task should delete the user tasks"); } @Test public void testCanSoftDeleteTask() { String reference = "/a/xyz"; Task task = createTask(reference); List<UserTaskAdapterBean> userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 1, "There should only be one task"); UserTaskAdapterBean userTask = userTasks.get(0); userTask.setSoftDeleted(true); taskService.saveUserTask(userTask); userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 1, "There should only be one task"); userTask = userTasks.get(0); Assert.isTrue(userTask.getSoftDeleted(), "The task should be soft deleted"); } @Test public void testCanDeleteTaskByReference() { String reference = "/a/xyz"; Task task = createTask(reference); Assert.isTrue(task.getId() != null, "The saved task should now have an id"); taskService.removeTaskByReference(reference); List<UserTaskAdapterBean> userTasks = taskService.getAllTasksForCurrentUser(); Assert.isTrue(userTasks.size() == 0, "Deleting a Task by reference should delete the user tasks"); } }
package pogrebenko.labfive.controller.initialization; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.TextField; import javafx.stage.FileChooser; import javafx.stage.Stage; import pogrebenko.labfive.controller.Main; import pogrebenko.labfive.controller.main.MainController; import pogrebenko.labfive.util.CommonUtil; import pogrebenko.labfive.util.JavaFxUtil; import pogrebenko.labfive.view.ViewRoutes; import pogrebenko.loggerwrapper.LoggerWrapper; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; public class InitializationController { private static final Logger LOGGER = LoggerWrapper.getLogger(); // Settings for log file browse window. private final static String[] extensionsLogFile = {"*.txt", "*.log"}; private final static String filterLabelLogFile = "Choose or create *.txt or *.log file"; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="tfLogFilePath" private TextField tfLogFilePath; // Value injected by FXMLLoader @FXML // fx:id="tfFTPHost" private TextField tfFTPHost; // Value injected by FXMLLoader @FXML // fx:id="tfFTPPort" private TextField tfFTPPort; // Value injected by FXMLLoader @FXML // fx:id="tfFTPUsername" private TextField tfFTPUsername; // Value injected by FXMLLoader @FXML // fx:id="tfFTPPassword" private TextField pfFTPPassword; // Value injected by FXMLLoader /** * On log file browse event. Chooses log file to load in the app. * * @param event browse event. */ @FXML void onBrowseLogFile(ActionEvent event) { LOGGER.info("Browsing for log file..."); FileChooser fc = JavaFxUtil.browseForFile(filterLabelLogFile, extensionsLogFile); File logFile = fc.showOpenDialog(new Stage()); // Check if any file has been selected. if (logFile == null) { LOGGER.info("No log file chosen..."); return; } // Get path to the selected file. String absPath = logFile.getAbsolutePath(); tfLogFilePath.setText(logFile.getAbsolutePath()); LOGGER.info("Chosen log file is: " + absPath); } /** * On continue button press event. Initializes the app, and opens the main window with loaded data. * * @param event browse event. */ @FXML void onContinuePressed(ActionEvent event) { LOGGER.info("Continue button pressed, validating input..."); // Check if the selected files exist. if (!CommonUtil.isFileExists(getLogFilePath())) { LOGGER.severe("Given log file path is invalid: " + getLogFilePath()); new Alert(Alert.AlertType.ERROR, "Invalid log file path!", ButtonType.YES).showAndWait(); return; } try { getFTPPort(); } catch (NumberFormatException e) { LOGGER.severe("Given DB port is invalid: " + getFTPPort()); new Alert(Alert.AlertType.ERROR, "Invalid DB port provided!", ButtonType.YES).showAndWait(); return; } // Open main page, and load data to it. try { prepareMainController(event); } catch (IOException e) { LOGGER.log(Level.INFO, e.getMessage(), e); new Alert(Alert.AlertType.ERROR, "Cannot start app! " + e.getMessage(), ButtonType.YES).showAndWait(); } } private void prepareMainController(ActionEvent event) throws IOException { LOGGER.info("Switching to the new window, loading scene..."); FXMLLoader loader = JavaFxUtil.getSceneLoader(ViewRoutes.APP_MAIN_SCREEN); Parent root = loader.load(); LOGGER.info("Retrieving main controller and setting the init values..."); MainController mainController = loader.getController(); LOGGER.info("Setting main controller params..."); setMainControllerParams(mainController); LOGGER.info("Preparing main controller..."); mainController.prepareController(); LOGGER.info("Opening new window..."); Stage mainStage = JavaFxUtil.getNewStage(root, Main.MAIN_SCREEN_TITLE); mainStage.setOnHiding(mainController::onStageClosing); mainStage.show(); LOGGER.info("Closing old window..."); JavaFxUtil.closeWindow(event); } private void setMainControllerParams(MainController mainController) { LOGGER.info("Setting the init values for the main controller..."); mainController.setLogPath(getLogFilePath()); mainController.setFTPHost(getFTPHost()); mainController.setFTPPort(getFTPPort()); mainController.setFTPUsername(getFTPUsername()); mainController.setFTPPassword(getFTPPassword()); } /** * Exits the window when the "close" button is pressed. * * @param event browse event. */ @FXML void onExitPressed(ActionEvent event) { // Alternatively i could use: Stage stage = (Stage)btnExit.getScene().getWindow(); stage.close(); LOGGER.info("Exit button on init page pressed..."); JavaFxUtil.closeWindow(event); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { LOGGER.info("Initialization..."); } /** * Return the path to the selected log file. * * @return path to the selected log file. */ public String getLogFilePath() { LOGGER.finest("Retrieving log file path..."); return tfLogFilePath.getText(); } public String getFTPHost() { LOGGER.finest("Retrieving FTP connection host..."); return tfFTPHost.getText(); } public int getFTPPort() throws NumberFormatException { LOGGER.finest("Retrieving FTP connection port..."); return Integer.parseInt(tfFTPPort.getText()); } public String getFTPUsername() { LOGGER.finest("Retrieving FTP connection username..."); return tfFTPUsername.getText(); } public String getFTPPassword() { LOGGER.finest("Retrieving FTP connection password..."); return pfFTPPassword.getText(); } }
package module552packageJava0; import java.lang.Integer; public class Foo253 { Integer int0; Integer int1; public void foo0() { new module552packageJava0.Foo252().foo5(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } }
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.jdbc.thin; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.sql.Array; import java.sql.BatchUpdateException; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLPermission; import java.sql.SQLTimeoutException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.binary.BinaryObjectException; import org.apache.ignite.binary.BinaryType; import org.apache.ignite.client.ClientException; import org.apache.ignite.configuration.BinaryConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.MarshallerPlatformIds; import org.apache.ignite.internal.binary.BinaryCachingMetadataHandler; import org.apache.ignite.internal.binary.BinaryContext; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.BinaryMetadata; import org.apache.ignite.internal.binary.BinaryMetadataHandler; import org.apache.ignite.internal.binary.BinaryTypeImpl; import org.apache.ignite.internal.jdbc2.JdbcUtils; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.GridCacheUtils; import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode; import org.apache.ignite.internal.processors.odbc.ClientListenerResponse; import org.apache.ignite.internal.processors.odbc.SqlStateCode; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBinaryTypeGetRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBinaryTypeGetResult; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBinaryTypeNameGetRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBinaryTypeNameGetResult; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBinaryTypeNamePutRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBinaryTypePutRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcBulkLoadBatchRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcCachePartitionsRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcCachePartitionsResult; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcOrderedBatchExecuteRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcOrderedBatchExecuteResult; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcQuery; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcQueryCancelRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcQueryExecuteRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcQueryExecuteResult; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcResponse; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcResult; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcResultWithIo; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcStatementType; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcUpdateBinarySchemaResult; import org.apache.ignite.internal.sql.command.SqlCommand; import org.apache.ignite.internal.sql.command.SqlSetStreamingCommand; import org.apache.ignite.internal.sql.optimizer.affinity.PartitionClientContext; import org.apache.ignite.internal.sql.optimizer.affinity.PartitionResult; import org.apache.ignite.internal.util.HostAndPortRange; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.logger.NullLogger; import org.apache.ignite.marshaller.MarshallerContext; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.thread.IgniteThreadFactory; import org.jetbrains.annotations.Nullable; import static java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT; import static java.sql.ResultSet.CONCUR_READ_ONLY; import static java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT; import static java.sql.ResultSet.TYPE_FORWARD_ONLY; import static org.apache.ignite.internal.processors.odbc.SqlStateCode.CLIENT_CONNECTION_FAILED; import static org.apache.ignite.internal.processors.odbc.SqlStateCode.CONNECTION_CLOSED; import static org.apache.ignite.internal.processors.odbc.SqlStateCode.CONNECTION_FAILURE; import static org.apache.ignite.internal.processors.odbc.SqlStateCode.INTERNAL_ERROR; import static org.apache.ignite.marshaller.MarshallerUtils.processSystemClasses; /** * JDBC connection implementation. * * See documentation of {@link org.apache.ignite.IgniteJdbcThinDriver} for details. */ public class JdbcThinConnection implements Connection { /** Logger. */ private static final Logger LOG = Logger.getLogger(JdbcThinConnection.class.getName()); /** Request timeout period. */ private static final int REQUEST_TIMEOUT_PERIOD = 1_000; /** Reconnection period. */ public static final int RECONNECTION_DELAY = 200; /** Reconnection maximum period. */ private static final int RECONNECTION_MAX_DELAY = 300_000; /** Network timeout permission */ private static final String SET_NETWORK_TIMEOUT_PERM = "setNetworkTimeout"; /** Zero timeout as query timeout means no timeout. */ static final int NO_TIMEOUT = 0; /** Index generator. */ private static final AtomicLong IDX_GEN = new AtomicLong(); /** Default retires count. */ public static final int DFLT_RETRIES_CNT = 4; /** No retries. */ public static final int NO_RETRIES = 0; /** Partition awareness enabled flag. */ private final boolean partitionAwareness; /** Statements modification mutex. */ private final Object stmtsMux = new Object(); /** Schema name. */ private String schema; /** Closed flag. */ private volatile boolean closed; /** Current transaction isolation. */ private int txIsolation; /** Auto-commit flag. */ private boolean autoCommit; /** Read-only flag. */ private boolean readOnly; /** Streaming flag. */ private volatile StreamState streamState; /** Current transaction holdability. */ private int holdability; /** Jdbc metadata. Cache the JDBC object on the first access */ private JdbcThinDatabaseMetadata metadata; /** Connection properties. */ private final ConnectionProperties connProps; /** The amount of potentially alive {@code JdbcThinTcpIo} instances - connections to server nodes. */ private final AtomicInteger connCnt = new AtomicInteger(); /** Tracked statements to close on disconnect. */ private final Set<JdbcThinStatement> stmts = Collections.newSetFromMap(new IdentityHashMap<>()); /** Affinity cache. */ private AffinityCache affinityCache; /** Ignite endpoint. */ private volatile JdbcThinTcpIo singleIo; /** Node Ids tp ignite endpoints. */ private final ConcurrentSkipListMap<UUID, JdbcThinTcpIo> ios = new ConcurrentSkipListMap<>(); /** Server index. */ private int srvIdx; /** Ignite server version. */ private Thread ownThread; /** Mutex. */ private final Object mux = new Object(); /** Ignite endpoint to use within transactional context. */ private volatile JdbcThinTcpIo txIo; /** Random generator. */ private static final Random RND = new Random(System.currentTimeMillis()); /** Network timeout. */ private int netTimeout; /** Query timeout. */ private final @Nullable Integer qryTimeout; /** Background periodical maintenance: query timeouts and reconnection handler. */ private final ScheduledExecutorService maintenanceExecutor; /** Cancelable future for query timeout task. */ private ScheduledFuture<?> qryTimeoutScheduledFut; /** Cancelable future for connections handler task. */ private ScheduledFuture<?> connectionsHndScheduledFut; /** Connections handler timer. */ private final IgniteProductVersion baseEndpointVer; /** Binary context. */ private volatile BinaryContext ctx; /** Binary metadata handler. */ private volatile JdbcBinaryMetadataHandler metaHnd; /** Marshaller context. */ private final JdbcMarshallerContext marshCtx; /** * Creates new connection. * * @param connProps Connection properties. * @throws SQLException In case Ignite client failed to start. */ public JdbcThinConnection(ConnectionProperties connProps) throws SQLException { this.connProps = connProps; metaHnd = new JdbcBinaryMetadataHandler(); marshCtx = new JdbcMarshallerContext(); ctx = createBinaryCtx(metaHnd, marshCtx); holdability = HOLD_CURSORS_OVER_COMMIT; autoCommit = true; txIsolation = Connection.TRANSACTION_NONE; netTimeout = connProps.getConnectionTimeout(); qryTimeout = connProps.getQueryTimeout(); maintenanceExecutor = Executors.newScheduledThreadPool(2, new IgniteThreadFactory(ctx.configuration().getIgniteInstanceName(), "jdbc-maintenance")); schema = JdbcUtils.normalizeSchema(connProps.getSchema()); partitionAwareness = connProps.isPartitionAwareness(); if (partitionAwareness) { baseEndpointVer = connectInBestEffortAffinityMode(null); connectionsHndScheduledFut = maintenanceExecutor.scheduleWithFixedDelay(new ConnectionHandlerTask(), 0, RECONNECTION_DELAY, TimeUnit.MILLISECONDS); } else { connectInCommonMode(); baseEndpointVer = null; } } /** Create new binary context. */ private BinaryContext createBinaryCtx(JdbcBinaryMetadataHandler metaHnd, JdbcMarshallerContext marshCtx) { BinaryMarshaller marsh = new BinaryMarshaller(); marsh.setContext(marshCtx); BinaryConfiguration binCfg = new BinaryConfiguration().setCompactFooter(true); BinaryContext ctx = new BinaryContext(metaHnd, new IgniteConfiguration(), new NullLogger()); ctx.configure(marsh, binCfg); ctx.registerUserTypesSchema(); return ctx; } /** * @throws SQLException On connection error. */ private void ensureConnected() throws SQLException { if (connCnt.get() > 0) return; assert !closed; assert ios.isEmpty(); if (partitionAwareness) connectInBestEffortAffinityMode(baseEndpointVer); else connectInCommonMode(); } /** * @return Whether this connection is streamed or not. */ boolean isStream() { return streamState != null; } /** * @param sql Statement. * @param cmd Parsed form of {@code sql}. * @param stmt Jdbc thin statement. * @throws SQLException if failed. */ void executeNative(String sql, SqlCommand cmd, JdbcThinStatement stmt) throws SQLException { if (cmd instanceof SqlSetStreamingCommand) { SqlSetStreamingCommand cmd0 = (SqlSetStreamingCommand)cmd; // If streaming is already on, we have to close it first. if (streamState != null) { streamState.close(); streamState = null; } boolean newVal = ((SqlSetStreamingCommand)cmd).isTurnOn(); ensureConnected(); JdbcThinTcpIo cliIo = cliIo(null); // Actual ON, if needed. if (newVal) { if (!cmd0.isOrdered() && !cliIo.isUnorderedStreamSupported()) { throw new SQLException("Streaming without order doesn't supported by server [remoteNodeVer=" + cliIo.igniteVersion() + ']', INTERNAL_ERROR); } streamState = new StreamState((SqlSetStreamingCommand)cmd, cliIo); sendRequest(new JdbcQueryExecuteRequest(JdbcStatementType.ANY_STATEMENT_TYPE, schema, 1, 1, autoCommit, stmt.explicitTimeout, sql, null), stmt, cliIo); streamState.start(); } } else throw IgniteQueryErrorCode.createJdbcSqlException("Unsupported native statement: " + sql, IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } /** * Add another query for batched execution. * * @param sql Query. * @param args Arguments. * @throws SQLException On error. */ void addBatch(String sql, List<Object> args) throws SQLException { assert isStream(); streamState.addBatch(sql, args); } /** {@inheritDoc} */ @Override public Statement createStatement() throws SQLException { return createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, HOLD_CURSORS_OVER_COMMIT); } /** {@inheritDoc} */ @Override public Statement createStatement(int resSetType, int resSetConcurrency) throws SQLException { return createStatement(resSetType, resSetConcurrency, HOLD_CURSORS_OVER_COMMIT); } /** {@inheritDoc} */ @Override public Statement createStatement(int resSetType, int resSetConcurrency, int resSetHoldability) throws SQLException { ensureNotClosed(); checkCursorOptions(resSetType, resSetConcurrency); JdbcThinStatement stmt = new JdbcThinStatement(this, resSetHoldability, schema); if (qryTimeout != null) stmt.setQueryTimeout(qryTimeout); synchronized (stmtsMux) { stmts.add(stmt); } return stmt; } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, HOLD_CURSORS_OVER_COMMIT); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int resSetType, int resSetConcurrency) throws SQLException { return prepareStatement(sql, resSetType, resSetConcurrency, HOLD_CURSORS_OVER_COMMIT); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int resSetType, int resSetConcurrency, int resSetHoldability) throws SQLException { ensureNotClosed(); checkCursorOptions(resSetType, resSetConcurrency); if (sql == null) throw new SQLException("SQL string cannot be null."); JdbcThinPreparedStatement stmt = new JdbcThinPreparedStatement(this, sql, resSetHoldability, schema); synchronized (stmtsMux) { stmts.add(stmt); } return stmt; } /** * @param resSetType Cursor option. * @param resSetConcurrency Cursor option. * @throws SQLException If options unsupported. */ private void checkCursorOptions(int resSetType, int resSetConcurrency) throws SQLException { if (resSetType != TYPE_FORWARD_ONLY) throw new SQLFeatureNotSupportedException("Invalid result set type (only forward is supported)."); if (resSetConcurrency != CONCUR_READ_ONLY) throw new SQLFeatureNotSupportedException("Invalid concurrency (updates are not supported)."); } /** {@inheritDoc} */ @Override public CallableStatement prepareCall(String sql) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Callable functions are not supported."); } /** {@inheritDoc} */ @Override public CallableStatement prepareCall(String sql, int resSetType, int resSetConcurrency) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Callable functions are not supported."); } /** {@inheritDoc} */ @Override public String nativeSQL(String sql) throws SQLException { ensureNotClosed(); if (sql == null) throw new SQLException("SQL string cannot be null."); return sql; } /** {@inheritDoc} */ @Override public void setAutoCommit(boolean autoCommit) throws SQLException { ensureNotClosed(); // Do nothing if resulting value doesn't actually change. if (autoCommit != this.autoCommit) { doCommit(); this.autoCommit = autoCommit; } } /** {@inheritDoc} */ @Override public boolean getAutoCommit() throws SQLException { ensureNotClosed(); return autoCommit; } /** {@inheritDoc} */ @Override public void commit() throws SQLException { ensureNotClosed(); if (autoCommit) throw new SQLException("Transaction cannot be committed explicitly in auto-commit mode."); doCommit(); } /** {@inheritDoc} */ @Override public void rollback() throws SQLException { ensureNotClosed(); if (autoCommit) throw new SQLException("Transaction cannot be rolled back explicitly in auto-commit mode."); try (Statement s = createStatement()) { s.execute("ROLLBACK"); } } /** * Send to the server {@code COMMIT} command. * * @throws SQLException if failed. */ private void doCommit() throws SQLException { try (Statement s = createStatement()) { s.execute("COMMIT"); } } /** {@inheritDoc} */ @Override public void close() throws SQLException { if (isClosed()) return; closed = true; maintenanceExecutor.shutdown(); if (streamState != null) { streamState.close(); streamState = null; } synchronized (stmtsMux) { stmts.clear(); } SQLException err = null; if (partitionAwareness) { for (JdbcThinTcpIo clioIo : ios.values()) clioIo.close(); ios.clear(); } else { if (singleIo != null) singleIo.close(); } if (err != null) throw err; } /** {@inheritDoc} */ @Override public boolean isClosed() { return closed; } /** {@inheritDoc} */ @Override public DatabaseMetaData getMetaData() throws SQLException { ensureNotClosed(); if (metadata == null) metadata = new JdbcThinDatabaseMetadata(this); return metadata; } /** {@inheritDoc} */ @Override public void setReadOnly(boolean readOnly) throws SQLException { ensureNotClosed(); this.readOnly = readOnly; } /** {@inheritDoc} */ @Override public boolean isReadOnly() throws SQLException { ensureNotClosed(); return readOnly; } /** {@inheritDoc} */ @Override public void setCatalog(String catalog) throws SQLException { ensureNotClosed(); } /** {@inheritDoc} */ @Override public String getCatalog() throws SQLException { ensureNotClosed(); return null; } /** {@inheritDoc} */ @Override public void setTransactionIsolation(int level) throws SQLException { ensureNotClosed(); switch (level) { case Connection.TRANSACTION_READ_UNCOMMITTED: case Connection.TRANSACTION_READ_COMMITTED: case Connection.TRANSACTION_REPEATABLE_READ: case Connection.TRANSACTION_SERIALIZABLE: case Connection.TRANSACTION_NONE: break; default: throw new SQLException("Invalid transaction isolation level.", SqlStateCode.INVALID_TRANSACTION_LEVEL); } txIsolation = level; } /** {@inheritDoc} */ @Override public int getTransactionIsolation() throws SQLException { ensureNotClosed(); return txIsolation; } /** {@inheritDoc} */ @Override public SQLWarning getWarnings() throws SQLException { ensureNotClosed(); return null; } /** {@inheritDoc} */ @Override public void clearWarnings() throws SQLException { ensureNotClosed(); } /** {@inheritDoc} */ @Override public Map<String, Class<?>> getTypeMap() throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Types mapping is not supported."); } /** {@inheritDoc} */ @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Types mapping is not supported."); } /** {@inheritDoc} */ @Override public void setHoldability(int holdability) throws SQLException { ensureNotClosed(); if (holdability != HOLD_CURSORS_OVER_COMMIT && holdability != CLOSE_CURSORS_AT_COMMIT) throw new SQLException("Invalid result set holdability value."); this.holdability = holdability; } /** {@inheritDoc} */ @Override public int getHoldability() throws SQLException { ensureNotClosed(); return holdability; } /** {@inheritDoc} */ @Override public Savepoint setSavepoint() throws SQLException { ensureNotClosed(); if (autoCommit) throw new SQLException("Savepoint cannot be set in auto-commit mode."); throw new SQLFeatureNotSupportedException("Savepoints are not supported."); } /** {@inheritDoc} */ @Override public Savepoint setSavepoint(String name) throws SQLException { ensureNotClosed(); if (name == null) throw new SQLException("Savepoint name cannot be null."); if (autoCommit) throw new SQLException("Savepoint cannot be set in auto-commit mode."); throw new SQLFeatureNotSupportedException("Savepoints are not supported."); } /** {@inheritDoc} */ @Override public void rollback(Savepoint savepoint) throws SQLException { ensureNotClosed(); if (savepoint == null) throw new SQLException("Invalid savepoint."); if (autoCommit) throw new SQLException("Auto-commit mode."); throw new SQLFeatureNotSupportedException("Savepoints are not supported."); } /** {@inheritDoc} */ @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { ensureNotClosed(); if (savepoint == null) throw new SQLException("Savepoint cannot be null."); throw new SQLFeatureNotSupportedException("Savepoints are not supported."); } /** {@inheritDoc} */ @Override public CallableStatement prepareCall(String sql, int resSetType, int resSetConcurrency, int resSetHoldability) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Callable functions are not supported."); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Auto generated keys are not supported."); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int[] colIndexes) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Auto generated keys are not supported."); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, String[] colNames) throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("Auto generated keys are not supported."); } /** {@inheritDoc} */ @Override public Clob createClob() throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("SQL-specific types are not supported."); } /** {@inheritDoc} */ @Override public Blob createBlob() throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("SQL-specific types are not supported."); } /** {@inheritDoc} */ @Override public NClob createNClob() throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("SQL-specific types are not supported."); } /** {@inheritDoc} */ @Override public SQLXML createSQLXML() throws SQLException { ensureNotClosed(); throw new SQLFeatureNotSupportedException("SQL-specific types are not supported."); } /** {@inheritDoc} */ @Override public boolean isValid(int timeout) throws SQLException { if (timeout < 0) throw new SQLException("Invalid timeout: " + timeout); return !closed; } /** {@inheritDoc} */ @Override public void setClientInfo(String name, String val) throws SQLClientInfoException { if (closed) throw new SQLClientInfoException("Connection is closed.", null); } /** {@inheritDoc} */ @Override public void setClientInfo(Properties props) throws SQLClientInfoException { if (closed) throw new SQLClientInfoException("Connection is closed.", null); } /** {@inheritDoc} */ @Override public String getClientInfo(String name) throws SQLException { ensureNotClosed(); return null; } /** {@inheritDoc} */ @Override public Properties getClientInfo() throws SQLException { ensureNotClosed(); return new Properties(); } /** {@inheritDoc} */ @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { ensureNotClosed(); if (typeName == null) throw new SQLException("Type name cannot be null."); throw new SQLFeatureNotSupportedException("SQL-specific types are not supported."); } /** {@inheritDoc} */ @Override public Struct createStruct(String typeName, Object[] attrs) throws SQLException { ensureNotClosed(); if (typeName == null) throw new SQLException("Type name cannot be null."); throw new SQLFeatureNotSupportedException("SQL-specific types are not supported."); } /** {@inheritDoc} */ @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (!isWrapperFor(iface)) throw new SQLException("Connection is not a wrapper for " + iface.getName()); return (T)this; } /** {@inheritDoc} */ @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface != null && iface.isAssignableFrom(JdbcThinConnection.class); } /** {@inheritDoc} */ @Override public void setSchema(String schema) throws SQLException { ensureNotClosed(); this.schema = JdbcUtils.normalizeSchema(schema); } /** {@inheritDoc} */ @Override public String getSchema() throws SQLException { ensureNotClosed(); return schema; } /** {@inheritDoc} */ @Override public void abort(Executor executor) throws SQLException { if (executor == null) throw new SQLException("Executor cannot be null."); close(); } /** {@inheritDoc} */ @Override public void setNetworkTimeout(Executor executor, int ms) throws SQLException { ensureNotClosed(); if (ms < 0) throw new SQLException("Network timeout cannot be negative."); SecurityManager secMgr = System.getSecurityManager(); if (secMgr != null) secMgr.checkPermission(new SQLPermission(SET_NETWORK_TIMEOUT_PERM)); netTimeout = ms; if (partitionAwareness) { for (JdbcThinTcpIo clioIo : ios.values()) clioIo.timeout(ms); } else singleIo.timeout(ms); } /** {@inheritDoc} */ @Override public int getNetworkTimeout() throws SQLException { ensureNotClosed(); return netTimeout; } /** * Ensures that connection is not closed. * * @throws SQLException If connection is closed. */ public void ensureNotClosed() throws SQLException { if (closed) throw new SQLException("Connection is closed.", CONNECTION_CLOSED); } /** * @return Ignite server version. */ public IgniteProductVersion igniteVersion() { if (partitionAwareness) { return ios.values().stream().map(JdbcThinTcpIo::igniteVersion).min(IgniteProductVersion::compareTo). orElse(baseEndpointVer); } else return singleIo.igniteVersion(); } /** * @return node UUID */ public UUID nodeId() { if (singleIo != null) return singleIo.nodeId(); return null; } /** * @return Auto close server cursors flag. */ boolean autoCloseServerCursor() { return connProps.isAutoCloseServerCursor(); } /** * Send request for execution via corresponding singleIo from {@link #ios}. * * @param req Request. * @return Server response. * @throws SQLException On any error. */ JdbcResultWithIo sendRequest(JdbcRequest req) throws SQLException { return sendRequest(req, null, null); } /** * Send request for execution via corresponding singleIo from {@link #ios} or sticky singleIo. * * @param req Request. * @param stmt Jdbc thin statement. * @param stickyIo Sticky ignite endpoint. * @return Server response. * @throws SQLException On any error. */ JdbcResultWithIo sendRequest(JdbcRequest req, JdbcThinStatement stmt, @Nullable JdbcThinTcpIo stickyIo) throws SQLException { RequestTimeoutTask reqTimeoutTask = null; acquireMutex(); try { int retryAttemptsLeft = 1; Exception lastE = null; while (retryAttemptsLeft > 0) { JdbcThinTcpIo cliIo = null; ensureConnected(); try { cliIo = (stickyIo == null || !stickyIo.connected()) ? cliIo(calculateNodeIds(req)) : stickyIo; if (stmt != null && stmt.requestTimeout() != NO_TIMEOUT) { reqTimeoutTask = new RequestTimeoutTask( req instanceof JdbcBulkLoadBatchRequest ? stmt.currentRequestId() : req.requestId(), cliIo, stmt.requestTimeout()); qryTimeoutScheduledFut = maintenanceExecutor.scheduleAtFixedRate(reqTimeoutTask, 0, REQUEST_TIMEOUT_PERIOD, TimeUnit.MILLISECONDS); } JdbcQueryExecuteRequest qryReq = null; if (req instanceof JdbcQueryExecuteRequest) qryReq = (JdbcQueryExecuteRequest)req; JdbcResponse res = cliIo.sendRequest(req, stmt); txIo = res.activeTransaction() ? cliIo : null; if (res.status() == IgniteQueryErrorCode.QUERY_CANCELED && stmt != null && stmt.requestTimeout() != NO_TIMEOUT && reqTimeoutTask != null && reqTimeoutTask.expired.get()) { int qryTimeout = stmt.getQueryTimeout(); throw new SQLTimeoutException(getTimeoutDescription(qryTimeout, cliIo), SqlStateCode.QUERY_CANCELLED, IgniteQueryErrorCode.QUERY_CANCELED); } else if (res.status() != ClientListenerResponse.STATUS_SUCCESS) throw new SQLException(res.error(), IgniteQueryErrorCode.codeToSqlState(res.status()), res.status()); updateAffinityCache(qryReq, res); return new JdbcResultWithIo(res.response(), cliIo); } catch (SQLException e) { if (LOG.isLoggable(Level.FINE)) LOG.log(Level.FINE, "Exception during sending an sql request.", e); throw e; } catch (Exception e) { if (LOG.isLoggable(Level.FINE)) LOG.log(Level.FINE, "Exception during sending an sql request.", e); // We reuse the same connection when deals with binary objects to synchronize the binary schema, // so if any error occurred during synchronization, we close the underlying IO when handling problem // for the first time and should skip it during next processing if (cliIo != null && cliIo.connected()) onDisconnect(cliIo); if (e instanceof SocketTimeoutException) throw new SQLException("Connection timed out.", CONNECTION_FAILURE, e); else { if (lastE == null) { retryAttemptsLeft = calculateRetryAttemptsCount(stickyIo, req); lastE = e; } else retryAttemptsLeft--; } } } throw new SQLException("Failed to communicate with Ignite cluster.", CONNECTION_FAILURE, lastE); } finally { if (stmt != null && stmt.requestTimeout() != NO_TIMEOUT && reqTimeoutTask != null) qryTimeoutScheduledFut.cancel(false); releaseMutex(); } } /** * Get timeout and node information * @param timeout - timeout * @param cliIo - ignite endpoint * @return Error description */ private String getTimeoutDescription(int timeout, JdbcThinTcpIo cliIo) { String cliIoInfo = ""; if (cliIo != null) { cliIoInfo = " ["; if (cliIo.nodeId() != null) cliIoInfo = cliIoInfo + "[Node UUID: " + cliIo.nodeId().toString() + "]"; if (cliIo.igniteVersion() != null) cliIoInfo = cliIoInfo + "[Ignite version: " + cliIo.igniteVersion().toString() + "]"; cliIoInfo += "]"; } return "The query was cancelled while executing due to timeout. Query timeout was : " + timeout + "." + cliIoInfo; } /** * Calculate node UUIDs. * * @param req Jdbc request for which we'll try to calculate node id. * @return node UUID or null if failed to calculate. * @throws IOException If Exception occurred during the network partition distribution retrieval. * @throws SQLException If Failed to calculate derived partitions. */ @Nullable private List<UUID> calculateNodeIds(JdbcRequest req) throws IOException, SQLException { if (!partitionAwareness || !(req instanceof JdbcQueryExecuteRequest)) return null; JdbcQueryExecuteRequest qry = (JdbcQueryExecuteRequest)req; if (affinityCache == null) { qry.partitionResponseRequest(true); return null; } JdbcThinPartitionResultDescriptor partResDesc = affinityCache.partitionResult( new QualifiedSQLQuery(qry.schemaName(), qry.sqlQuery())); // Value is empty. if (partResDesc == JdbcThinPartitionResultDescriptor.EMPTY_DESCRIPTOR) return null; // Key is missing. if (partResDesc == null) { qry.partitionResponseRequest(true); return null; } Collection<Integer> parts = calculatePartitions(partResDesc, qry.arguments()); if (parts == null || parts.isEmpty()) return null; UUID[] cacheDistr = retrieveCacheDistribution(partResDesc.cacheId(), partResDesc.partitionResult().partitionsCount()); if (parts.size() == 1) return Collections.singletonList(cacheDistr[parts.iterator().next()]); else { List<UUID> partitionAwarenessNodeIds = new ArrayList<>(); for (int part : parts) partitionAwarenessNodeIds.add(cacheDistr[part]); return partitionAwarenessNodeIds; } } /** * Retrieve cache distribution for specified cache Id. * * @param cacheId Cache Id. * @param partCnt Partitions count. * @return Partitions cache distribution. * @throws IOException If Exception occurred during the network partition distribution retrieval. */ private UUID[] retrieveCacheDistribution(int cacheId, int partCnt) throws IOException { UUID[] cacheDistr = affinityCache.cacheDistribution(cacheId); if (cacheDistr != null) return cacheDistr; JdbcResponse res; res = cliIo(null).sendRequest(new JdbcCachePartitionsRequest(Collections.singleton(cacheId)), null); assert res.status() == ClientListenerResponse.STATUS_SUCCESS; AffinityTopologyVersion resAffinityVer = res.affinityVersion(); if (affinityCache.version().compareTo(resAffinityVer) < 0) { affinityCache = new AffinityCache( resAffinityVer, connProps.getPartitionAwarenessPartitionDistributionsCacheSize(), connProps.getPartitionAwarenessSqlCacheSize()); } else if (affinityCache.version().compareTo(resAffinityVer) > 0) { // Jdbc thin affinity cache is binded to the newer affinity topology version, so we should ignore retrieved // partition distribution. Given situation might occur in case of concurrent race and is not // possible in single-threaded jdbc thin client, so it's a reserve for the future. return null; } List<JdbcThinPartitionAwarenessMappingGroup> mappings = ((JdbcCachePartitionsResult)res.response()).getMappings(); // Despite the fact that, at this moment, we request partition distribution only for one cache, // we might retrieve multiple caches but exactly with same distribution. assert mappings.size() == 1; JdbcThinPartitionAwarenessMappingGroup mappingGrp = mappings.get(0); cacheDistr = mappingGrp.revertMappings(partCnt); for (int mpCacheId : mappingGrp.cacheIds()) affinityCache.addCacheDistribution(mpCacheId, cacheDistr); return cacheDistr; } /** * Calculate partitions for the query. * * @param partResDesc Partition result descriptor. * @param args Arguments. * @return Calculated partitions or {@code null} if failed to calculate and there should be a broadcast. * @throws SQLException If Failed to calculate derived partitions. */ public static Collection<Integer> calculatePartitions(JdbcThinPartitionResultDescriptor partResDesc, Object[] args) throws SQLException { PartitionResult derivedParts = partResDesc.partitionResult(); if (derivedParts != null) { try { return derivedParts.tree().apply(partResDesc.partitionClientContext(), args); } catch (IgniteCheckedException e) { throw new SQLException("Failed to calculate derived partitions for query.", INTERNAL_ERROR); } } return null; } /** * Send request for execution via corresponding singleIo from {@link #ios} or sticky singleIo. * Response is waited at the separate thread (see {@link StreamState#asyncRespReaderThread}). * * @param req Request. * @throws SQLException On any error. */ void sendQueryCancelRequest(JdbcQueryCancelRequest req, JdbcThinTcpIo cliIo) throws SQLException { if (connCnt.get() == 0) throw new SQLException("Failed to communicate with Ignite cluster.", CONNECTION_FAILURE); assert cliIo != null; try { cliIo.sendCancelRequest(req); } catch (Exception e) { throw new SQLException("Failed to communicate with Ignite cluster.", CONNECTION_FAILURE, e); } } /** * Send request for execution via corresponding singleIo from {@link #ios} or sticky singleIo. * Response is waited at the separate thread (see {@link StreamState#asyncRespReaderThread}). * * @param req Request. * @param stickyIO Sticky ignite endpoint. * @throws SQLException On any error. */ private void sendRequestNotWaitResponse(JdbcRequest req, JdbcThinTcpIo stickyIO) throws SQLException { ensureConnected(); acquireMutex(); try { stickyIO.sendRequestNoWaitResponse(req); } catch (SQLException e) { throw e; } catch (Exception e) { onDisconnect(stickyIO); if (e instanceof SocketTimeoutException) throw new SQLException("Connection timed out.", CONNECTION_FAILURE, e); else throw new SQLException("Failed to communicate with Ignite cluster.", CONNECTION_FAILURE, e); } finally { releaseMutex(); } } /** * Acquire mutex. Allows subsequent acquire by the same thread. * <p> * How to use: * <pre> * acquireMutex(); * * try { * // do some work here * } * finally { * releaseMutex(); * } * * </pre> * * @throws SQLException If mutex already acquired by another thread. * @see JdbcThinConnection#releaseMutex() */ private void acquireMutex() throws SQLException { synchronized (mux) { Thread curr = Thread.currentThread(); if (ownThread != null && ownThread != curr) { throw new SQLException("Concurrent access to JDBC connection is not allowed" + " [ownThread=" + ownThread.getName() + ", curThread=" + curr.getName(), CONNECTION_FAILURE); } ownThread = curr; } } /** * Release mutex. Does nothing if nobody own the mutex. * <p> * How to use: * <pre> * acquireMutex(); * * try { * // do some work here * } * finally { * releaseMutex(); * } * * </pre> * * @throws IllegalStateException If mutex is owned by another thread. * @see JdbcThinConnection#acquireMutex() */ private void releaseMutex() { synchronized (mux) { Thread curr = Thread.currentThread(); if (ownThread != null && ownThread != curr) throw new IllegalStateException("Mutex is owned by another thread"); ownThread = null; } } /** * @return Connection URL. */ public String url() { return connProps.getUrl(); } /** * Called on IO disconnect: close the client IO and opened statements. */ private void onDisconnect(JdbcThinTcpIo cliIo) { assert connCnt.get() > 0; if (partitionAwareness) { cliIo.close(); ios.remove(cliIo.nodeId()); } else { if (singleIo != null) singleIo.close(); } connCnt.decrementAndGet(); if (streamState != null) { streamState.close0(); streamState = null; } synchronized (stmtsMux) { for (JdbcThinStatement s : stmts) s.closeOnDisconnect(); stmts.clear(); } // Clear local metadata cache on disconnect. metaHnd = new JdbcBinaryMetadataHandler(); ctx = createBinaryCtx(metaHnd, marshCtx); } /** * @param stmt Statement to close. */ void closeStatement(JdbcThinStatement stmt) { synchronized (stmtsMux) { stmts.remove(stmt); } } /** * Streamer state and */ private class StreamState { /** Maximum requests count that may be sent before any responses. */ private static final int MAX_REQUESTS_BEFORE_RESPONSE = 10; /** Batch size for streaming. */ private int streamBatchSize; /** Batch for streaming. */ private List<JdbcQuery> streamBatch; /** Last added query to recognize batches. */ private String lastStreamQry; /** Keep request order on execution. */ private long order; /** Async response reader thread. */ private Thread asyncRespReaderThread; /** Async response error. */ private volatile Exception err; /** The order of the last batch request at the stream. */ private long lastRespOrder = -1; /** Last response future. */ private final GridFutureAdapter<Void> lastRespFut = new GridFutureAdapter<>(); /** Response semaphore sem. */ private Semaphore respSem = new Semaphore(MAX_REQUESTS_BEFORE_RESPONSE); /** Streaming sticky ignite endpoint. */ private final JdbcThinTcpIo streamingStickyIo; /** * @param cmd Stream cmd. * @param stickyIo Sticky ignite endpoint. */ StreamState(SqlSetStreamingCommand cmd, JdbcThinTcpIo stickyIo) { streamBatchSize = cmd.batchSize(); asyncRespReaderThread = new Thread(this::readResponses); streamingStickyIo = stickyIo; } /** * Start reader. */ void start() { asyncRespReaderThread.start(); } /** * Add another query for batched execution. * * @param sql Query. * @param args Arguments. * @throws SQLException On error. */ void addBatch(String sql, List<Object> args) throws SQLException { checkError(); boolean newQry = (args == null || !F.eq(lastStreamQry, sql)); // Providing null as SQL here allows for recognizing subbatches on server and handling them more efficiently. JdbcQuery q = new JdbcQuery(newQry ? sql : null, args != null ? args.toArray() : null); if (streamBatch == null) streamBatch = new ArrayList<>(streamBatchSize); streamBatch.add(q); // Null args means "addBatch(String)" was called on non-prepared Statement, // we don't want to remember its query string. lastStreamQry = (args != null ? sql : null); if (streamBatch.size() == streamBatchSize) executeBatch(false); } /** * @param lastBatch Whether open data streamers must be flushed and closed after this batch. * @throws SQLException if failed. */ private void executeBatch(boolean lastBatch) throws SQLException { checkError(); if (lastBatch) lastRespOrder = order; try { respSem.acquire(); sendRequestNotWaitResponse( new JdbcOrderedBatchExecuteRequest(schema, streamBatch, autoCommit, lastBatch, order), streamingStickyIo); streamBatch = null; lastStreamQry = null; if (lastBatch) { try { lastRespFut.get(); } catch (IgniteCheckedException ignored) { // No-op. // No exceptions are expected here. } checkError(); } else order++; } catch (InterruptedException e) { throw new SQLException("Streaming operation was interrupted", INTERNAL_ERROR, e); } } /** * Throws at the user thread exception that was thrown at the {@link #asyncRespReaderThread} thread. * * @throws SQLException Saved exception. */ void checkError() throws SQLException { if (err != null) { Exception err0 = err; err = null; if (err0 instanceof SQLException) throw (SQLException)err0; else { onDisconnect(streamingStickyIo); if (err0 instanceof SocketTimeoutException) throw new SQLException("Connection timed out.", CONNECTION_FAILURE, err0); throw new SQLException("Failed to communicate with Ignite cluster on JDBC streaming.", CONNECTION_FAILURE, err0); } } } /** * @throws SQLException On error. */ void close() throws SQLException { close0(); checkError(); } /** */ void close0() { if (connCnt.get() > 0) { try { executeBatch(true); } catch (SQLException e) { err = e; LOG.log(Level.WARNING, "Exception during batch send on streamed connection close", e); } } if (asyncRespReaderThread != null) asyncRespReaderThread.interrupt(); } /** */ void readResponses() { try { while (true) { JdbcResponse resp = streamingStickyIo.readResponse(); if (resp.response() instanceof JdbcOrderedBatchExecuteResult) { JdbcOrderedBatchExecuteResult res = (JdbcOrderedBatchExecuteResult)resp.response(); respSem.release(); if (res.errorCode() != ClientListenerResponse.STATUS_SUCCESS) { err = new BatchUpdateException(res.errorMessage(), IgniteQueryErrorCode.codeToSqlState(res.errorCode()), res.errorCode(), res.updateCounts()); } // Receive the response for the last request. if (res.order() == lastRespOrder) { lastRespFut.onDone(); break; } } else if (resp.response() instanceof JdbcBinaryTypeGetResult) metaHnd.handleResult((JdbcBinaryTypeGetResult)resp.response()); else if (resp.response() instanceof JdbcBinaryTypeNameGetResult) marshCtx.handleResult((JdbcBinaryTypeNameGetResult)resp.response()); else if (resp.response() instanceof JdbcUpdateBinarySchemaResult) { JdbcUpdateBinarySchemaResult binarySchemaRes = (JdbcUpdateBinarySchemaResult)resp.response(); if (!marshCtx.handleResult(binarySchemaRes) && !metaHnd.handleResult(binarySchemaRes)) LOG.log(Level.WARNING, "Neither marshaller context nor metadata handler" + " wait for update binary schema result (req=" + binarySchemaRes + ")"); } else if (resp.status() != ClientListenerResponse.STATUS_SUCCESS) err = new SQLException(resp.error(), IgniteQueryErrorCode.codeToSqlState(resp.status())); else assert false : "Invalid response: " + resp; } } catch (Exception e) { err = e; } } } /** * @return True if query cancellation supported, false otherwise. */ boolean isQueryCancellationSupported() { return partitionAwareness || singleIo.isQueryCancellationSupported(); } /** * Whether custom objects are supported or not. * * @return True if custom objects are supported, false otherwise. */ boolean isCustomObjectSupported() { return singleIo.isCustomObjectSupported(); } /** * @param nodeIds Set of node's UUIDs. * @return Ignite endpoint to use for request/response transferring. */ private JdbcThinTcpIo cliIo(List<UUID> nodeIds) { if (!partitionAwareness) return singleIo; if (txIo != null) return txIo; if (nodeIds == null || nodeIds.isEmpty()) return randomIo(); JdbcThinTcpIo io = null; if (nodeIds.size() == 1) io = ios.get(nodeIds.get(0)); else { int initNodeId = RND.nextInt(nodeIds.size()); int iterCnt = 0; while (io == null) { io = ios.get(nodeIds.get(initNodeId)); initNodeId = initNodeId == nodeIds.size() ? 0 : initNodeId + 1; iterCnt++; if (iterCnt == nodeIds.size()) break; } } return io != null ? io : randomIo(); } /** * Returns random tcpIo, based on random UUID, generated in a custom way * with the help of {@code Random} instead of {@code SecureRandom}. It's * valid, cause cryptographically strong pseudo random number generator is * not required in this particular case. {@code Random} is much faster * than {@code SecureRandom}. * * @return random tcpIo */ private JdbcThinTcpIo randomIo() { byte[] randomBytes = new byte[16]; RND.nextBytes(randomBytes); randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] |= 0x80; /* set to IETF variant */ long msb = 0; long lsb = 0; for (int i = 0; i < 8; i++) msb = (msb << 8) | (randomBytes[i] & 0xff); for (int i = 8; i < 16; i++) lsb = (lsb << 8) | (randomBytes[i] & 0xff); UUID randomUUID = new UUID(msb, lsb); Map.Entry<UUID, JdbcThinTcpIo> entry = ios.ceilingEntry(randomUUID); return entry != null ? entry.getValue() : ios.floorEntry(randomUUID).getValue(); } /** * @return Current server index. */ public int serverIndex() { return srvIdx; } /** * Get next server index. * * @param len Number of servers. * @return Index of the next server to connect to. */ private static int nextServerIndex(int len) { if (len == 1) return 0; else { long nextIdx = IDX_GEN.getAndIncrement(); return (int)(nextIdx % len); } } /** * Establishes a connection to ignite endpoint, trying all specified hosts and ports one by one. * Stops as soon as any connection is established. * * @throws SQLException If failed to connect to ignite cluster. */ private void connectInCommonMode() throws SQLException { HostAndPortRange[] srvs = connProps.getAddresses(); List<Exception> exceptions = null; for (int i = 0; i < srvs.length; i++) { srvIdx = nextServerIndex(srvs.length); HostAndPortRange srv = srvs[srvIdx]; try { InetAddress[] addrs = InetAddress.getAllByName(srv.host()); for (InetAddress addr : addrs) { for (int port = srv.portFrom(); port <= srv.portTo(); ++port) { try { JdbcThinTcpIo cliIo = new JdbcThinTcpIo(connProps, new InetSocketAddress(addr, port), ctx, 0); cliIo.timeout(netTimeout); singleIo = cliIo; connCnt.incrementAndGet(); return; } catch (Exception exception) { if (exceptions == null) exceptions = new ArrayList<>(); exceptions.add(exception); } } } } catch (Exception exception) { if (exceptions == null) exceptions = new ArrayList<>(); exceptions.add(exception); } } handleConnectExceptions(exceptions); } /** * Prepare and throw general {@code SQLException} with all specified exceptions as suppressed items. * * @param exceptions Exceptions list. * @throws SQLException Umbrella exception. */ private void handleConnectExceptions(List<Exception> exceptions) throws SQLException { if (connCnt.get() == 0 && exceptions != null) { close(); if (exceptions.size() == 1) { Exception ex = exceptions.get(0); if (ex instanceof SQLException) throw (SQLException)ex; else if (ex instanceof IOException) throw new SQLException("Failed to connect to Ignite cluster [url=" + connProps.getUrl() + ']', CLIENT_CONNECTION_FAILED, ex); } SQLException e = new SQLException("Failed to connect to server [url=" + connProps.getUrl() + ']', CLIENT_CONNECTION_FAILED); for (Exception ex : exceptions) e.addSuppressed(ex); throw e; } } /** * Establishes a connection to ignite endpoint, trying all specified hosts * and ports one by one. * * Stops as soon as all iosArr are established. * * @param baseEndpointVer Base endpoint version. * @return last connected endpoint version. * @throws SQLException If failed to connect to at least one ignite * endpoint, or if endpoints versions are less than base endpoint version. */ private IgniteProductVersion connectInBestEffortAffinityMode( IgniteProductVersion baseEndpointVer) throws SQLException { List<Exception> exceptions = null; for (int i = 0; i < connProps.getAddresses().length; i++) { HostAndPortRange srv = connProps.getAddresses()[i]; try { InetAddress[] addrs = InetAddress.getAllByName(srv.host()); for (InetAddress addr : addrs) { for (int port = srv.portFrom(); port <= srv.portTo(); ++port) { try { JdbcThinTcpIo cliIo = new JdbcThinTcpIo(connProps, new InetSocketAddress(addr, port), ctx, 0); if (!cliIo.isPartitionAwarenessSupported()) { cliIo.close(); throw new SQLException("Failed to connect to Ignite node [url=" + connProps.getUrl() + "]. address = [" + addr + ':' + port + "]." + "Node doesn't support Partition Awareness mode.", INTERNAL_ERROR); } IgniteProductVersion endpointVer = cliIo.igniteVersion(); if (baseEndpointVer != null && baseEndpointVer.compareTo(endpointVer) > 0) { cliIo.close(); throw new SQLException("Failed to connect to Ignite node [url=" + connProps.getUrl() + "], address = [" + addr + ':' + port + "]," + "the node version [" + endpointVer + "] " + "is smaller than the base one [" + baseEndpointVer + "].", INTERNAL_ERROR); } cliIo.timeout(netTimeout); JdbcThinTcpIo ioToSameNode = ios.putIfAbsent(cliIo.nodeId(), cliIo); // This can happen if the same node has several IPs or if connection manager background // timer task runs concurrently. if (ioToSameNode != null) cliIo.close(); else connCnt.incrementAndGet(); return cliIo.igniteVersion(); } catch (Exception exception) { if (exceptions == null) exceptions = new ArrayList<>(); exceptions.add(exception); } } } } catch (Exception exception) { if (exceptions == null) exceptions = new ArrayList<>(); exceptions.add(exception); } } handleConnectExceptions(exceptions); return null; } /** * Recreates affinity cache if affinity topology version was changed and adds partition result to sql cache. * * @param qryReq Query request. * @param res Jdbc Response. */ private void updateAffinityCache(JdbcQueryExecuteRequest qryReq, JdbcResponse res) { if (partitionAwareness) { AffinityTopologyVersion resAffVer = res.affinityVersion(); if (resAffVer != null && (affinityCache == null || affinityCache.version().compareTo(resAffVer) < 0)) { affinityCache = new AffinityCache( resAffVer, connProps.getPartitionAwarenessPartitionDistributionsCacheSize(), connProps.getPartitionAwarenessSqlCacheSize()); } // Partition result was requested. if (res.response() instanceof JdbcQueryExecuteResult && qryReq.partitionResponseRequest()) { PartitionResult partRes = ((JdbcQueryExecuteResult)res.response()).partitionResult(); if (partRes == null || affinityCache.version().equals(partRes.topologyVersion())) { int cacheId = (partRes != null && partRes.tree() != null) ? GridCacheUtils.cacheId(partRes.cacheName()) : -1; PartitionClientContext partClientCtx = partRes != null ? new PartitionClientContext(partRes.partitionsCount()) : null; QualifiedSQLQuery qry = new QualifiedSQLQuery(qryReq.schemaName(), qryReq.sqlQuery()); JdbcThinPartitionResultDescriptor partResDescr = new JdbcThinPartitionResultDescriptor(partRes, cacheId, partClientCtx); affinityCache.addSqlQuery(qry, partResDescr); } } } } /** * Calculates query retries count for given {@param req}. * * @param stickyIo sticky connection, if any. * @param req Jdbc request. * @return retries count. */ private int calculateRetryAttemptsCount(JdbcThinTcpIo stickyIo, JdbcRequest req) { if (!partitionAwareness) return NO_RETRIES; if (stickyIo != null) return NO_RETRIES; if (req.type() == JdbcRequest.META_TABLES || req.type() == JdbcRequest.META_COLUMNS || req.type() == JdbcRequest.META_INDEXES || req.type() == JdbcRequest.META_PARAMS || req.type() == JdbcRequest.META_PRIMARY_KEYS || req.type() == JdbcRequest.META_SCHEMAS || req.type() == JdbcRequest.CACHE_PARTITIONS) return DFLT_RETRIES_CNT; if (req.type() == JdbcRequest.QRY_EXEC) { JdbcQueryExecuteRequest qryExecReq = (JdbcQueryExecuteRequest)req; String trimmedQry = qryExecReq.sqlQuery().trim(); // Last symbol is ignored. for (int i = 0; i < trimmedQry.length() - 1; i++) { if (trimmedQry.charAt(i) == ';') return NO_RETRIES; } return trimmedQry.toUpperCase().startsWith("SELECT") ? DFLT_RETRIES_CNT : NO_RETRIES; } return NO_RETRIES; } /** * Request Timeout Task */ private class RequestTimeoutTask implements Runnable { /** Request id. */ private final long reqId; /** Sticky singleIo. */ private final JdbcThinTcpIo stickyIO; /** Remaining query timeout. */ private int remainingQryTimeout; /** Flag that shows whether TimerTask was expired or not. */ private AtomicBoolean expired; /** * @param reqId Request Id to cancel in case of timeout * @param initReqTimeout Initial request timeout */ RequestTimeoutTask(long reqId, JdbcThinTcpIo stickyIO, int initReqTimeout) { this.reqId = reqId; this.stickyIO = stickyIO; remainingQryTimeout = initReqTimeout; expired = new AtomicBoolean(false); } /** {@inheritDoc} */ @Override public void run() { try { if (remainingQryTimeout <= 0) { expired.set(true); sendQueryCancelRequest(new JdbcQueryCancelRequest(reqId), stickyIO); qryTimeoutScheduledFut.cancel(false); return; } remainingQryTimeout -= REQUEST_TIMEOUT_PERIOD; } catch (SQLException e) { LOG.log(Level.WARNING, "Request timeout processing failure: unable to cancel request [reqId=" + reqId + ']', e); qryTimeoutScheduledFut.cancel(false); } } } /** * Connection Handler Task */ private class ConnectionHandlerTask implements Runnable { /** Map with reconnection delays. */ private Map<InetSocketAddress, Integer> reconnectionDelays = new HashMap<>(); /** Map with reconnection delays remainder. */ private Map<InetSocketAddress, Integer> reconnectionDelaysRemainder = new HashMap<>(); /** {@inheritDoc} */ @Override public void run() { try { for (Map.Entry<InetSocketAddress, Integer> delayEntry : reconnectionDelaysRemainder.entrySet()) reconnectionDelaysRemainder.put(delayEntry.getKey(), delayEntry.getValue() - RECONNECTION_DELAY); Set<InetSocketAddress> aliveSockAddrs = ios.values().stream().map(JdbcThinTcpIo::socketAddress).collect(Collectors.toSet()); IgniteProductVersion prevIgniteEndpointVer = null; for (int i = 0; i < connProps.getAddresses().length; i++) { HostAndPortRange srv = connProps.getAddresses()[i]; try { InetAddress[] addrs = InetAddress.getAllByName(srv.host()); for (InetAddress addr : addrs) { for (int port = srv.portFrom(); port <= srv.portTo(); ++port) { InetSocketAddress sockAddr = null; try { sockAddr = new InetSocketAddress(addr, port); if (aliveSockAddrs.contains(sockAddr)) { reconnectionDelaysRemainder.remove(sockAddr); reconnectionDelays.remove(sockAddr); continue; } Integer delayRemainder = reconnectionDelaysRemainder.get(sockAddr); if (delayRemainder != null && delayRemainder != 0) continue; if (closed) { maintenanceExecutor.shutdown(); return; } JdbcThinTcpIo cliIo = new JdbcThinTcpIo(connProps, new InetSocketAddress(addr, port), ctx, 0); if (!cliIo.isPartitionAwarenessSupported()) { processDelay(sockAddr); LOG.log(Level.WARNING, "Failed to connect to Ignite node [url=" + connProps.getUrl() + "]. address = [" + addr + ':' + port + "]." + "Node doesn't support best effort affinity mode."); cliIo.close(); continue; } if (prevIgniteEndpointVer != null && !prevIgniteEndpointVer.equals(cliIo.igniteVersion())) { processDelay(sockAddr); LOG.log(Level.WARNING, "Failed to connect to Ignite node [url=" + connProps.getUrl() + "]. address = [" + addr + ':' + port + "]." + "Different versions of nodes are not supported in best " + "effort affinity mode."); cliIo.close(); continue; } cliIo.timeout(netTimeout); JdbcThinTcpIo ioToSameNode = ios.putIfAbsent(cliIo.nodeId(), cliIo); // This can happen if the same node has several IPs or if ensureConnected() runs // concurrently if (ioToSameNode != null) cliIo.close(); else connCnt.incrementAndGet(); prevIgniteEndpointVer = cliIo.igniteVersion(); if (closed) { maintenanceExecutor.shutdown(); cliIo.close(); ios.remove(cliIo.nodeId()); return; } } catch (Exception exception) { if (sockAddr != null) processDelay(sockAddr); LOG.log(Level.WARNING, "Failed to connect to Ignite node [url=" + connProps.getUrl() + "]. address = [" + addr + ':' + port + "]."); } } } } catch (Exception exception) { LOG.log(Level.WARNING, "Failed to connect to Ignite node [url=" + connProps.getUrl() + "]. server = [" + srv + "]."); } } } catch (Exception e) { LOG.log(Level.WARNING, "Connection handler processing failure. Reconnection processes was stopped.", e); connectionsHndScheduledFut.cancel(false); } } /** * Increase reconnection delay if needed and store it to corresponding maps. * * @param sockAddr Socket address. */ private void processDelay(InetSocketAddress sockAddr) { Integer delay = reconnectionDelays.get(sockAddr); delay = delay == null ? RECONNECTION_DELAY : delay * 2; if (delay > RECONNECTION_MAX_DELAY) delay = RECONNECTION_MAX_DELAY; reconnectionDelays.put(sockAddr, delay); reconnectionDelaysRemainder.put(sockAddr, delay); } } /** * JDBC implementation of {@link MarshallerContext}. */ private class JdbcMarshallerContext extends BlockingJdbcChannel implements MarshallerContext { /** Type ID -> class name map. */ private final Map<Integer, String> cache = new ConcurrentHashMap<>(); /** */ private final Set<String> sysTypes = new HashSet<>(); /** * Default constructor. */ public JdbcMarshallerContext() { try { processSystemClasses(U.gridClassLoader(), null, sysTypes::add); } catch (IOException e) { throw new IgniteException("Unable to initialize marshaller context", e); } } /** {@inheritDoc} */ @Override public boolean registerClassName( byte platformId, int typeId, String clsName, boolean failIfUnregistered ) throws IgniteCheckedException { assert platformId == MarshallerPlatformIds.JAVA_ID : String.format("Only Java platform is supported [expPlatformId=%d, actualPlatformId=%d].", MarshallerPlatformIds.JAVA_ID, platformId); boolean res = true; if (!cache.containsKey(typeId)) { try { JdbcUpdateBinarySchemaResult updateRes = doRequest( new JdbcBinaryTypeNamePutRequest(typeId, platformId, clsName)); res = updateRes.success(); } catch (ExecutionException | InterruptedException | ClientException | SQLException e) { throw new IgniteCheckedException(e); } if (res) cache.put(typeId, clsName); } return res; } /** {@inheritDoc} */ @Deprecated @Override public boolean registerClassName(byte platformId, int typeId, String clsName) throws IgniteCheckedException { return registerClassName(platformId, typeId, clsName, false); } /** {@inheritDoc} */ @Override public boolean registerClassNameLocally(byte platformId, int typeId, String clsName) { throw new UnsupportedOperationException("registerClassNameLocally not supported by " + this.getClass().getSimpleName()); } /** {@inheritDoc} */ @Override public Class getClass(int typeId, ClassLoader ldr) throws ClassNotFoundException, IgniteCheckedException { return U.forName(getClassName(MarshallerPlatformIds.JAVA_ID, typeId), ldr, null); } /** {@inheritDoc} */ @Override public String getClassName(byte platformId, int typeId) throws ClassNotFoundException, IgniteCheckedException { assert platformId == MarshallerPlatformIds.JAVA_ID : String.format("Only Java platform is supported [expPlatformId=%d, actualPlatformId=%d].", MarshallerPlatformIds.JAVA_ID, platformId); String clsName = cache.get(typeId); if (clsName == null) { try { JdbcBinaryTypeNameGetResult res = doRequest(new JdbcBinaryTypeNameGetRequest(typeId, platformId)); clsName = res.typeName(); } catch (ExecutionException | InterruptedException | ClientException | SQLException e) { throw new IgniteCheckedException(e); } } if (clsName == null) throw new ClassNotFoundException(String.format("Unknown type id [%s]", typeId)); return clsName; } /** * Handle update binary schema result. * * @param res Result. * @return {@code true} if marshaller was waiting for result with given request ID. */ public boolean handleResult(JdbcUpdateBinarySchemaResult res) { return handleResult(res.reqId(), res); } /** * Handle binary type name result. * * @param res Result. * @return {@code true} if marshaller was waiting for result with given request ID. */ public boolean handleResult(JdbcBinaryTypeNameGetResult res) { return handleResult(res.reqId(), res); } /** {@inheritDoc} */ @Override public boolean isSystemType(String typeName) { return sysTypes.contains(typeName); } /** {@inheritDoc} */ @Override public IgnitePredicate<String> classNameFilter() { return null; } /** {@inheritDoc} */ @Override public JdkMarshaller jdkMarshaller() { return new JdkMarshaller(); } } /** * JDBC implementation of {@link BinaryMetadataHandler}. */ private class JdbcBinaryMetadataHandler extends BlockingJdbcChannel implements BinaryMetadataHandler { /** In-memory metadata cache. */ private final BinaryMetadataHandler cache = BinaryCachingMetadataHandler.create(); /** {@inheritDoc} */ @Override public void addMeta(int typeId, BinaryType meta, boolean failIfUnregistered) throws BinaryObjectException { try { doRequest(new JdbcBinaryTypePutRequest(((BinaryTypeImpl)meta).metadata())); } catch (ExecutionException | InterruptedException | ClientException | SQLException e) { throw new BinaryObjectException(e); } cache.addMeta(typeId, meta, failIfUnregistered); // merge } /** {@inheritDoc} */ @Override public void addMetaLocally(int typeId, BinaryType meta, boolean failIfUnregistered) throws BinaryObjectException { throw new UnsupportedOperationException("Can't register metadata locally for thin client."); } /** {@inheritDoc} */ @Override public BinaryType metadata(int typeId) throws BinaryObjectException { BinaryType meta = cache.metadata(typeId); if (meta == null) meta = getBinaryType(typeId); return meta; } /** {@inheritDoc} */ @Override public BinaryMetadata metadata0(int typeId) throws BinaryObjectException { BinaryMetadata meta = cache.metadata0(typeId); if (meta == null) { BinaryTypeImpl binType = (BinaryTypeImpl)getBinaryType(typeId); if (binType != null) meta = binType.metadata(); } return meta; } /** * Request binary type from grid. * * @param typeId Type ID. * @return Binary type. */ private @Nullable BinaryType getBinaryType(int typeId) throws BinaryObjectException { BinaryType binType = null; try { JdbcBinaryTypeGetResult res = doRequest(new JdbcBinaryTypeGetRequest(typeId)); BinaryMetadata meta = res.meta(); if (meta != null) { binType = new BinaryTypeImpl(ctx, meta); cache.addMeta(typeId, binType, false); } } catch (ExecutionException | InterruptedException | ClientException | SQLException e) { throw new BinaryObjectException(e); } return binType; } /** * Handle update binary schema result. * * @param res Result. * @return {@code true} if handler was waiting for result with given * request ID. */ public boolean handleResult(JdbcUpdateBinarySchemaResult res) { return handleResult(res.reqId(), res); } /** * Handle binary type schema result. * * @param res Result. * @return {@code true} if handler was waiting for result with given * request ID. */ public boolean handleResult(JdbcBinaryTypeGetResult res) { return handleResult(res.reqId(), res); } /** {@inheritDoc} */ @Override public BinaryType metadata(int typeId, int schemaId) throws BinaryObjectException { BinaryType type = metadata(typeId); return type != null && ((BinaryTypeImpl)type).metadata().hasSchema(schemaId) ? type : null; } /** {@inheritDoc} */ @Override public Collection<BinaryType> metadata() throws BinaryObjectException { return cache.metadata(); } } /** * Jdbc channel to communicate in blocking style, regardless of whether * streaming mode is enabled or not. */ private abstract class BlockingJdbcChannel { /** Request ID -> Jdbc result map. */ private Map<Long, CompletableFuture<JdbcResult>> results = new ConcurrentHashMap<>(); /** * Do request in blocking style. It just call * {@link JdbcThinConnection#sendRequest(JdbcRequest)} for non-streaming * mode and creates future and waits it completion when streaming is * enabled. * * @param req Request. * @return Result for given request. */ <R extends JdbcResult> R doRequest(JdbcRequest req) throws SQLException, InterruptedException, ExecutionException { R res; if (isStream()) { CompletableFuture<JdbcResult> resFut = new CompletableFuture<>(); CompletableFuture<JdbcResult> oldFut = results.put(req.requestId(), resFut); assert oldFut == null : "Another request with the same id is waiting for result."; sendRequestNotWaitResponse(req, streamState.streamingStickyIo); res = (R)resFut.get(); } else res = sendRequest(req).response(); return res; } /** * Handles result for specified request ID. * * @param reqId Request id. * @param res Result. */ boolean handleResult(long reqId, JdbcResult res) { boolean handled = false; CompletableFuture<JdbcResult> fut = results.remove(reqId); if (fut != null) { fut.complete(res); handled = true; } return handled; } } }
/* Copyright (c) 2012 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* $Id$ */ package com.linkedin.data; import com.fasterxml.jackson.core.async.ByteArrayFeeder; import com.linkedin.data.parser.NonBlockingDataParser; import com.linkedin.data.protobuf.ProtoReader; import com.linkedin.data.protobuf.ProtoWriter; import com.linkedin.data.protobuf.Utf8Utils; import com.linkedin.util.ArgumentUtil; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * An immutable sequence of bytes. * * Extra effort is taken to avoid extra copying during streaming when there is a need to assemble multiple ByteStrings * into on ByteString (e.g. receiving request/responses via chunked transfer encoding). * When constructing the new larger ByteString with {@link Builder}, we don't actually do the copy but simply keep * reference to backing data of the smaller ByteStrings. As a result, for some important use cases, * e.g. asInputStream(), the extra copy can be avoided. * However, for some other use cases such as asString(), we still need to do the copy due to the fact that a single * byte array is required to construct those values. * * @author Chris Pettitt * @author Zhenkai Zhu * @version $Revision$ */ public final class ByteString { private static final ByteString EMPTY = new ByteString(new byte[0]); // backing data structure private final ByteArrayVector _byteArrays; /** * Returns an empty {@link ByteString}. * * @return an empty {@link ByteString} */ public static ByteString empty() { return EMPTY; } /** * Returns a new {@link ByteString} that wraps the supplied bytes. Changes to the supplied bytes will be reflected * in the returned {@link ByteString}. * * WARNING: Please exercise caution when using this. Care must be taken to ensure that bytes are not changed * after construction. * * @param bytes the bytes to back the ByteString. * @return a {@link ByteString} that wraps the supplied bytes. * @throws NullPointerException if {@code bytes} is {@code null}. */ public static ByteString unsafeWrap(byte[] bytes) { ArgumentUtil.notNull(bytes, "bytes"); return bytes.length == 0 ? empty() : new ByteString(bytes); } /** * Returns a new {@link ByteString} that wraps the supplied bytes. Changes to the supplied bytes will be reflected * in the returned {@link ByteString}. * * WARNING: Please exercise caution when using this. Care must be taken to ensure that bytes are not changed * after construction. * * @param bytes the bytes to back the ByteString. * @param offset the offset of the actual data. * @param length the length of the actual data. * @return a {@link ByteString} that wraps the supplied bytes. * @throws NullPointerException if {@code bytes} is {@code null}. */ public static ByteString unsafeWrap(byte[] bytes, int offset, int length) { ArgumentUtil.notNull(bytes, "bytes"); return bytes.length == 0 ? empty() : new ByteString(bytes, offset, length); } /** * Returns a new {@link ByteString} that wraps a copy of the supplied bytes. Changes to the supplied bytes * will not be reflected in the returned {@link ByteString}. * * @param bytes the bytes to copy * @return a {@link ByteString} that wraps a copy of the supplied bytes * @throws NullPointerException if {@code bytes} is {@code null}. */ public static ByteString copy(byte[] bytes) { ArgumentUtil.notNull(bytes, "bytes"); return bytes.length == 0 ? empty() : new ByteString(Arrays.copyOf(bytes, bytes.length)); } /** * Returns a new {@link ByteString} that wraps a copy of the desired region of supplied bytes. Changes to the supplied * bytes will not be reflected in the returned {@link ByteString}. * * @param bytes the bytes to copy * @param offset the starting point of region to be copied * @param length the length of the region to be copied * @return a {@link ByteString} that wraps a copy of the desired region of supplied bytes * @throws NullPointerException if {@code bytes} is {@code null}. * @throws IndexOutOfBoundsException if offset or length is negative, or offset + length is larger than the length * of the bytes */ public static ByteString copy(byte[] bytes, int offset, int length) { ArgumentUtil.notNull(bytes, "bytes"); ArgumentUtil.checkBounds(bytes.length, offset, length); return length == 0 ? empty() : new ByteString(Arrays.copyOfRange(bytes, offset, offset + length)); } /** * Returns a new {@link ByteString} that wraps a copy of the bytes in the supplied {@link ByteBuffer}. * Changes to the supplied bytes will not be reflected in the returned {@link ByteString}. * * @param byteBuffer the {@link ByteBuffer} to copy bytes from. * @return a {@link ByteString} that wraps a copy of the bytes in the supplied {@link ByteBuffer}. * @throws NullPointerException if {@code byteBuffer} is {@code null}. */ public static ByteString copy(ByteBuffer byteBuffer) { ArgumentUtil.notNull(byteBuffer, "byteBuffer"); int size = byteBuffer.remaining(); if (size == 0) { return empty(); } byte[] bytes = new byte[size]; byteBuffer.get(bytes); return new ByteString(bytes); } /** * Returns a new {@link ByteString} that wraps the bytes generated from the supplied string with the * given charset. * * @param str the string to copy * @param charsetName the name of the charset used to encode the bytes * @return a {@link ByteString} that wraps a copy of the supplied bytes */ public static ByteString copyString(String str, String charsetName) { return copyString(str, Charset.forName(charsetName)); } /** * Returns a new {@link ByteString} that wraps the bytes generated from the supplied string with the * given charset. * * @param str the string to copy * @param charset the charset used to encode the bytes * @return a {@link ByteString} that wraps a copy of the supplied bytes */ public static ByteString copyString(String str, Charset charset) { ArgumentUtil.notNull(str, "str"); return copy(str.getBytes(charset)); } /** * Returns a new {@link ByteString} that wraps the bytes generated from the supplied string * using {@link Data#stringToBytes(String, boolean)}. * * @param string that will be used to generate the bytes. * @param validate indicates whether validation is enabled, validation is enabled if true. * @return a {@link ByteString} that wraps a copy of the supplied bytes, if validation fails return null. * @throws NullPointerException if {@code string} is {@code null}. */ public static ByteString copyAvroString(String string, boolean validate) { ArgumentUtil.notNull(string, "string"); if (string.length() == 0) { return empty(); } byte[] bytes = Data.stringToBytes(string, validate); if (bytes == null) { return null; } else { return new ByteString(bytes); } } /** * Returns a new {@link ByteString} with bytes read from an {@link InputStream}. * * If size is zero, then this method will always return the {@link ByteString#empty()}, * and no bytes will be read from the {@link InputStream}. * If size is less than zero, then {@link NegativeArraySizeException} will be thrown * when this method attempt to create an array of negative size. * * @param inputStream that will provide the bytes. * @param size provides the number of bytes to read. * @return a ByteString that contains the read bytes. * @throws IOException from InputStream if requested number of bytes * cannot be read. */ public static ByteString read(InputStream inputStream, int size) throws IOException { if (size == 0) { return empty(); } final byte[] buf = new byte[size]; int bytesRead, bufIdx = 0; while (bufIdx < size && (bytesRead = inputStream.read(buf, bufIdx, size - bufIdx)) != -1) { bufIdx += bytesRead; } if (bufIdx != size) { throw new IOException("Insufficient data in InputStream, requested size " + size + ", read " + bufIdx); } return new ByteString(buf); } /** * Returns a new {@link ByteString} with bytes read from an {@link InputStream} with unknown size. * * @param inputStream that will provide the bytes. * @return a ByteString that contains the read bytes. */ public static ByteString read(InputStream inputStream) throws IOException { NoCopyByteArrayOutputStream bos = new NoCopyByteArrayOutputStream(); byte[] buf = new byte[4096]; int bytesRead; while((bytesRead = inputStream.read(buf, 0, buf.length)) != -1) { bos.write(buf, 0, bytesRead); } return new ByteString(bos.getBytes(), 0, bos.getBytesCount()); } private ByteString(byte[] bytes) { this(ArgumentUtil.ensureNotNull(bytes, "bytes"), 0, bytes.length); } /** * This is internally used to create slice or copySlice of ByteString. */ private ByteString(byte[] bytes, int offset, int length) { ArgumentUtil.notNull(bytes, "bytes"); ByteArray[] byteArrays = new ByteArray[1]; byteArrays[0] = new ByteArray(bytes, offset, length); _byteArrays = new ByteArrayVector(byteArrays); } /** * This is internally used to create a new ByteString with existing backing byte arrays * * @param byteArrays ByteArrayVector constructed with existing backing byte arrays */ private ByteString(ByteArrayVector byteArrays) { ArgumentUtil.notNull(byteArrays, "byteArrays"); _byteArrays = byteArrays; } /** * Returns the number of bytes in this {@link ByteString}. * * @return the number of bytes in this {@link ByteString} */ public int length() { return _byteArrays.getBytesNum(); } /** * Checks whether this {@link ByteString} is empty or not. * @return true for an empty {@link ByteString}, false otherwise */ public boolean isEmpty() { return _byteArrays.getBytesNum() == 0; } /** * Returns a copy of the bytes in this {@link ByteString}. Changes to the returned byte[] will not be * reflected in this {@link ByteString}.<p> * * Where possible prefer other methods for accessing the underlying bytes, such as * {@link #asByteBuffer()}, {@link #write(java.io.OutputStream)}, or {@link #asString(Charset)}. * The first two make no copy of the byte array, while the last minimizes the amount of copying * (constructing a String from a byte[] always involves copying). * * @return a copy of the bytes in this {@link ByteString} */ public byte[] copyBytes() { byte[] result = new byte[_byteArrays.getBytesNum()]; copyBytes(result, 0); return result; } /** * Copy the bytes in this {@link ByteString} to the provided byte[] starting at the specified offset. * * Where possible prefer other methods for accessing the underlying bytes, such as * {@link #asByteBuffer()}, {@link #write(java.io.OutputStream)}, or {@link #asString(Charset)}. * The first two make no copy of the byte array, while the last minimizes the amount of copying * (constructing a String from a byte[] always involves copying). * * @param dest is the destination to copy the bytes in this {@link ByteString} to. * @param offset is the starting offset in the destination to receive the copy. */ public void copyBytes(byte[] dest, int offset) { int position = offset; for (int i = 0; i < _byteArrays.getArraySize(); i ++) { ByteArray byteArray = _byteArrays.get(i); System.arraycopy(byteArray.getArray(), byteArray.getOffset(), dest, position, byteArray.getLength()); position += byteArray.getLength(); } } /** * Returns a read only {@link ByteBuffer} view of this {@link ByteString}. This method makes no copy. * * @return read only {@link ByteBuffer} view of this {@link ByteString}. */ public ByteBuffer asByteBuffer() { // we cannot supply an array of byte array to ByteBuffer, so we have to copy to a new larger continuous byte array // if needed ByteArray byteArray = assembleIfNeeded(); return ByteBuffer.wrap(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength()).asReadOnlyBuffer(); } /** * Return a String representation of the bytes in this {@link ByteString}, decoded using the supplied * charset. * * @param charsetName the name of the charset to use to decode the bytes * @return the String representation of this {@link ByteString} */ public String asString(String charsetName) { return asString(Charset.forName(charsetName)); } /** * Return a String representation of the bytes in this {@link ByteString}, decoded using the supplied * charset. * * @param charset the charset to use to decode the bytes * @return the String representation of this {@link ByteString} */ public String asString(Charset charset) { // we cannot supply an array of byte array to String, so we have to copy to a new larger continuous byte array // if needed ByteArray byteArray = assembleIfNeeded(); return new String(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength(), charset); } /** * Return an Avro representation of the bytes in this {@link ByteString}. * * @return the String representation of this {@link ByteString} */ public String asAvroString() { return new String(asAvroCharArray()); } /** * Return an Avro representation of the bytes in this {@link ByteString}. * * @return the character array representation of this {@link ByteString} */ public char[] asAvroCharArray() { char[] charArray = new char[_byteArrays.getBytesNum()]; int charArrayOffset = 0; for (ByteArray byteArray : _byteArrays._byteArrays) { Data.bytesToCharArray(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength(), charArray, charArrayOffset); charArrayOffset += byteArray.getLength(); } return charArray; } /** * Return an {@link InputStream} view of the bytes in this {@link ByteString}. * * @return an {@link InputStream} view of the bytes in this {@link ByteString} */ public InputStream asInputStream() { return new ByteArrayVectorInputStream(_byteArrays); } /** * Return a {@link ProtoReader} to read the bytes in this {@link ByteString}. * * @return a {@link ProtoReader} to read the bytes in this {@link ByteString} */ public ProtoReader asProtoReader() { // Shortcut to using the byte array reader if we have just 1 segment. if (_byteArrays.getArraySize() == 1) { ByteArray byteArray = _byteArrays.get(0); return ProtoReader.newInstance(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength()); } return new ByteStringProtoReader(_byteArrays); } /** * Feeds a chunk of this {@link ByteString} to a {@link ByteArrayFeeder} without copying the underlying byte[]. * * @param feeder the feeder to feed the bytes to * @param index the index of the chunk to feed * * @throws IOException if an error occurs while writing to the feeder * * @return The next index to feed or -1 if no more indices are left to feed. */ public int feed(ByteArrayFeeder feeder, int index) throws IOException { if (feeder.needMoreInput()) { ByteArray byteArray = _byteArrays.get(index); // Note that jackson ByteArrayFeeder API takes in end and NOT length. int end = byteArray.getOffset() + byteArray.getLength(); feeder.feedInput(byteArray.getArray(), byteArray.getOffset(), end); } else { throw new IOException("Byte Array Feeder is not ok to feed more data."); } int returnIndex = index + 1; return returnIndex < _byteArrays.getArraySize() ? returnIndex : -1; } /** * Feeds a chunk of this {@link ByteString} to a {@link NonBlockingDataParser} * without copying the underlying byte[]. * * @param parser the feeder to feed the bytes to * @param index the index of the chunk to feed * * @throws IOException if an error occurs while writing to the feeder * * @return The next index to feed or -1 if no more indices are left to feed. */ public int feed(NonBlockingDataParser parser, int index) throws IOException { ByteArray byteArray = _byteArrays.get(index); parser.feedInput(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength()); int returnIndex = index + 1; return returnIndex < _byteArrays.getArraySize() ? returnIndex : -1; } /** * Writes this {@link ByteString} to a stream without copying the underlying byte[]. * * @param out the stream to write the bytes to * * @throws IOException if an error occurs while writing to the stream */ public void write(OutputStream out) throws IOException { for (int i = 0; i < _byteArrays.getArraySize(); i++) { ByteArray byteArray = _byteArrays.get(i); out.write(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength()); } } /** * Writes this {@link ByteString} to a {@link ProtoWriter} without copying the underlying byte[]. * * @param writer the ProtoWriter to write the bytes to * * @throws IOException if an error occurs while writing to the stream */ public void write(ProtoWriter writer) throws IOException { writer.writeUInt32(length()); for (int i = 0; i < _byteArrays.getArraySize(); i++) { ByteArray byteArray = _byteArrays.get(i); writer.writeBytes(byteArray.getArray(), byteArray.getOffset(), byteArray.getLength()); } } /** * Decomposes this ByteString into a {@link java.util.List} of the original underlying ByteString(s). * * If this ByteString was constructed using multiple ByteStrings, then those ByteStrings are returned in a * {@link java.util.List}. If this ByteString was constructed as a result of a copy, i.e {@link #copySlice} or * {@link #copy}, then a {@link java.util.List} is returned with a single ByteString. * * If this ByteString is empty, then a {@link java.util.List} is returned with an empty ByteString. * * @return a {@link java.util.List} of 1 or more ByteStrings that compose this ByteString. */ public List<ByteString> decompose() { final List<ByteString> decomposedList = new ArrayList<ByteString>(); //Note that if this is the empty ByteString, there is still one byte array that exists. for (int i = 0; i < _byteArrays.getArraySize(); i++) { final ByteArray[] byteArrays = new ByteArray[1]; byteArrays[0] = _byteArrays.get(i); decomposedList.add(new ByteString(new ByteArrayVector(byteArrays))); } return decomposedList; } /** * Returns a slice of ByteString. * This create a "view" of this ByteString, which holds the entire content of the original ByteString. If your code * only needs a small portion of a large ByteString and is not interested in the rest of that ByteString, it is better * to use {@link #copySlice} method. * * @param offset the starting point of the slice * @param length the length of the slice * @return a slice of ByteString backed by the same backing byte array * @throws IndexOutOfBoundsException if offset or length is negative, or offset + length is larger than the length * of this ByteString */ public ByteString slice(int offset, int length) { ArgumentUtil.checkBounds(_byteArrays.getBytesNum(), offset, length); return new ByteString(_byteArrays.slice(offset, length)); } /** * Returns a slice of ByteString backed by a new byte array. * This copies the content from the desired portion of the original ByteString and does not hold reference to the * original ByteString. * * @param offset the starting point of the slice * @param length the length of the slice * @return a slice of ByteString backed by a new byte array * @throws IndexOutOfBoundsException if offset or length is negative, or offset + length is larger than the length * of this ByteString */ public ByteString copySlice(int offset, int length) { ArgumentUtil.checkBounds(_byteArrays.getBytesNum(), offset, length); return new ByteString(slice(offset, length).copyBytes()); } /** * Tests if this ByteString starts with the specified byte array prefix. * * @param prefixBytes the byte array prefix. * @return <code>true</code> if the byte array sequence represented by the argument is a prefix of the byte sequence * represented by this ByteString; <code>false</code> otherwise. * Note also that <code>true</code> will be returned if the argument is an empty byte array or is equal to this * ByteString object as determined by the {@link #equals(Object)} method. */ public boolean startsWith(byte[] prefixBytes) { if (prefixBytes.length == 0) { return true; } if (prefixBytes.length > _byteArrays._totalLength) { return false; } return slice(0, prefixBytes.length).equals(new ByteString(prefixBytes)); } //Private class to abstract away iteration over bytes in a compound ByteString. Note that we don't implement //the Iterator interface so that we can avoid autoboxing. private class ByteIterator { private int _currentByteArray; private int _currentByteIndex; private boolean _finished; private ByteIterator() { _currentByteArray = 0; _currentByteIndex = 0; _finished = false; //Note that there is no need to skip any empty ByteArrays at the beginning (or even while traversing) since the //builder in ByteString skips empty ByteStrings upon construction. This means that we can be sure that each and //every ByteString inside of this (potentially) compound ByteString is non-empty. } private ByteIterator(final ByteIterator byteIterator) { _currentByteArray = byteIterator._currentByteArray; _currentByteIndex = byteIterator._currentByteIndex; _finished = byteIterator._finished; } private ByteIterator copy() { return new ByteIterator(this); } private void next() { //Shift the internal pointer to the next byte. _currentByteIndex++; if(_currentByteIndex == _byteArrays.get(_currentByteArray)._length) { //Check to see if we are finished. if(_currentByteArray + 1 == _byteArrays.getArraySize()) { _finished = true; return; } //Move to the next ByteArray. _currentByteArray++; _currentByteIndex = 0; } } private byte getCurrentByte() { return _byteArrays.get(_currentByteArray).get(_currentByteIndex); } private boolean isFinished() { return _finished; } private int currentIndex() { int totalLengthCovered = 0; for (int m = 0; m < _currentByteArray; m++) { totalLengthCovered += _byteArrays.get(m)._length; } totalLengthCovered += _currentByteIndex; return totalLengthCovered; } } /** * Returns the starting position (index) of the first occurrence of the specified target byte array within this ByteString or * -1 if there is no such occurrence. If the targetBytes are larger then this ByteString, -1 is returned. If the * targetBytes are empty, then 0 is returned. * * @param targetBytes the byte array to search for as a sub array within this ByteString. * @return the starting position of the first occurrence of the specified target byte array within this ByteString, * or -1 if there is no such occurrence. */ public int indexOfBytes(byte[] targetBytes) { if (targetBytes.length == 0) { return 0; } if (targetBytes.length > _byteArrays._totalLength) { return -1; } //Used to abstract away the iteration of all the bytes represented by this compound ByteString. ByteIterator byteIterator = new ByteIterator(); //This is a reference on where to resume in case we get a mismatch. ByteIterator resumeByteIterator = byteIterator.copy(); //We skip the first since byteIterator will begin there. resumeByteIterator.next(); for (int i = 0; i < targetBytes.length;) { //If we have exhausted everything in the ByteString, then we return -1. if (byteIterator.isFinished()) { return -1; } final byte b = byteIterator.getCurrentByte(); if (b != targetBytes[i]) { //There was a mismatch so we reset i and prepare to start over. i = 0; //Update byteIterator to point to the next byte where our comparison will begin. byteIterator = resumeByteIterator; //Keep track of where to resume in the future. resumeByteIterator = resumeByteIterator.copy(); //Skip the next since byteIterator will begin there. resumeByteIterator.next(); continue; } i++; byteIterator.next(); } //We found a match. Calculate where it started. return byteIterator.currentIndex() - targetBytes.length; } /** * Returns the byte located at the specified offset within this ByteString. This is a constant time operation. * * If this ByteString is a compound ByteString, meaning it was composed of multiple ByteStrings, then this operation * becomes log(n) where n is the number of ByteStrings in the compound ByteString. * * @param offset the index specifying the target byte's location * @return the resulting byte */ public byte getByte(int offset) { return _byteArrays.getByte(offset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ByteString that = (ByteString) o; int length = length(); if (length != that.length()) { return false; } // compare bytes one by one to determine whether the contents are equivalent int arrayIndex = 0; int arrayOffset = 0; int thatArrayIndex = 0; int thatArrayOffset = 0; int pos = 0; while(pos < length) { if (_byteArrays.get(arrayIndex).get(arrayOffset) != that._byteArrays.get(thatArrayIndex).get(thatArrayOffset)) { return false; } arrayOffset++; thatArrayOffset++; if (arrayOffset == _byteArrays.get(arrayIndex).getLength()) { arrayIndex++; arrayOffset = 0; } if (thatArrayOffset == that._byteArrays.get(thatArrayIndex).getLength()) { thatArrayIndex++; thatArrayOffset = 0; } pos++; } return true; } @Override public int hashCode() { int result = 1; for (int index = 0; index < _byteArrays.getArraySize(); index++) { for (int offset = 0; offset < _byteArrays.get(index).getLength(); offset++) { result = result * 31 + _byteArrays.get(index).get(offset); } } return result; } /** * Return a summary of the contents of this {@link ByteString}. This summary is of reasonable size, * regardless of the length of this {@link ByteString}. * * @return a summary representation of this {@link ByteString} */ @Override public String toString() { final int NUM_BYTES = 4; StringBuilder sb = new StringBuilder(); sb.append("ByteString(length="); sb.append(length()); if (length() > 0) { sb.append(",bytes="); for (int i = 0; i < Math.min(length(), NUM_BYTES); i++) { sb.append(String.format("%02x", (int) _byteArrays.getByte(i) & 0xff)); } if (length() > NUM_BYTES * 2) { sb.append("..."); } for (int i = Math.max(NUM_BYTES, length() - NUM_BYTES); i < length(); i++) { sb.append(String.format("%02x", (int)_byteArrays.getByte(i) & 0xff)); } } sb.append(")"); return sb.toString(); } /** * A builder to assemble multiple ByteStrings into one ByteString without copying the backing byte arrays. * * This class is not thread safe */ public static class Builder { private final List<ByteString> _chunks; public Builder() { _chunks = new ArrayList<ByteString>(); } public Builder append(ByteString dataChunk) { ArgumentUtil.notNull(dataChunk, "dataChunk"); if (!EMPTY.equals(dataChunk)) { _chunks.add(dataChunk); } return this; } public ByteString build() { if (_chunks.isEmpty()) { return empty(); } else if (_chunks.size() == 1) // return the ByteString directly if there is only one to be assembled { return _chunks.get(0); } else { // each ByteString could have multiple backing arrays, so we first count the number of backing arrays int totalByteArraySize = 0; for (ByteString chunk: _chunks) { totalByteArraySize += chunk._byteArrays.getArraySize(); } ByteArray[] byteArrays = new ByteArray[totalByteArraySize]; int index = 0; for (ByteString chunk: _chunks) { for (int i = 0; i < chunk._byteArrays.getArraySize(); i++) { byteArrays[index] = chunk._byteArrays.get(i); index++; } } return new ByteString(new ByteArrayVector(byteArrays)); } } } private ByteArray assembleIfNeeded() { if (_byteArrays.getArraySize() == 1) { return _byteArrays.get(0); } else { return new ByteArray(copyBytes(), 0, _byteArrays.getBytesNum()); } } /** * This class is intended for internal use only. The output stream should not be passed around after * the construction; otherwise the internal representation of the ByteString would change, voiding the * immutability guarantee. */ private static class NoCopyByteArrayOutputStream extends ByteArrayOutputStream { byte[] getBytes() { return super.buf; } int getBytesCount() { return super.count; } } /** * This is a convenient class to hold a byte array and keep the offset & effective length to refer to * a visible portion of the original byte array */ private static class ByteArray { private final byte[] _bytes; private final int _offset; private final int _length; /** * * @param bytes the backing byte array * @param offset the offset in the byte array for the visible range * @param length the length of the visible range in the byte array */ ByteArray(byte[] bytes, int offset, int length) { ArgumentUtil.notNull(bytes, "bytes"); ArgumentUtil.checkBounds(bytes.length, offset, length); _bytes = bytes; _offset = offset; _length = length; } /** * Returns the backing array as quite a few APIs require raw byte array * @return the backing byte array */ byte[] getArray() { return _bytes; } /** * @return the offset of the visible portion */ int getOffset() { return _offset; } /** * * @return the length of the visible portion */ int getLength() { return _length; } /** * @param i the index of the byte (relative to _offset) * @return the ith byte in the visible portion of byte array */ byte get(int i) { if (i >= _length || i < 0) { throw new IndexOutOfBoundsException("i: " + i); } return _bytes[_offset + i]; } /** * Creat a slice of this ByteArray using the same backing array * @param offset the start point of the slice * @param length the length of the slice * @return a slice of this ByteArray starting at offset with specified length */ ByteArray slice(int offset, int length) { ArgumentUtil.checkBounds(_length, offset, length); return new ByteArray(_bytes, _offset + offset, length); } /** * Create a slice of this ByteArray using the same backing array * @param offset the start point of the slice * @return a slice of this ByteArray starting at offset til the end */ ByteArray slice(int offset) { if (offset > _length || offset < 0) { throw new IndexOutOfBoundsException("offset: " + offset); } return new ByteArray(_bytes, _offset + offset, _length - offset); } } /** * This is a convenient class to hold an array of ByteArray. */ private static class ByteArrayVector { // the backing array of ByteArray private final ByteArray[] _byteArrays; /** * This is an array to record the accumulated bytes at each position. E.g. _accumulatedLens[i] * is the number of bytes held in ByteArrays from 0 to i-1. It's like an index so that we can * quickly locate which ByteArray contains the byte in a desired position. */ private final int[] _accumulatedLens; // the total number of bytes held private final int _totalLength; ByteArrayVector(ByteArray[] byteArrays) { _byteArrays = byteArrays; int arrayNum = _byteArrays.length; _accumulatedLens = new int[arrayNum]; int accuLen = 0; for (int i = 0; i < arrayNum; i++) { _accumulatedLens[i] = accuLen; accuLen += _byteArrays[i].getLength(); } _totalLength = accuLen; } /** * Get the ith ByteArray * @param i the index of the desired ByteArray * @return the ByteArray */ ByteArray get(int i) { if (i >= _byteArrays.length || i < 0) { throw new IndexOutOfBoundsException("i: " + i); } return _byteArrays[i]; } /** * Get the desired byte from the ByteArrayVector. * This is not the efficient way to access bytes sequentially. * * @param offset the offset in terms of bytes num of the desired byte * @return the byte */ byte getByte(int offset) { if (offset >= _totalLength || offset < 0) { throw new IndexOutOfBoundsException("offset: " + offset); } // get the index of the ByteArray that contains this byte int index = locate(offset, 0, _byteArrays.length - 1); return _byteArrays[index].get(offset - _accumulatedLens[index]); } /** * Create a slice of this ByteArrayVector * @param offset the offset in terms of the bytes num * @param length the length of the slice * @return a ByteArrayVector that is a slice of the current ByteArrayVector */ ByteArrayVector slice(int offset, int length) { ArgumentUtil.checkBounds(_totalLength, offset, length); int startIndex = locate(offset, 0, _byteArrays.length - 1); int endIndex = locate(offset + length, startIndex, _byteArrays.length - 1); ByteArray[] byteArrays; if (startIndex == endIndex) { byteArrays = new ByteArray[1]; byteArrays[0] = _byteArrays[startIndex].slice(offset - _accumulatedLens[startIndex], length); } else { int arrayLen = endIndex - startIndex + 1; byteArrays = new ByteArray[arrayLen]; byteArrays[0] = _byteArrays[startIndex].slice(offset - _accumulatedLens[startIndex]); byteArrays[arrayLen - 1] = _byteArrays[endIndex].slice(0, offset + length - _accumulatedLens[endIndex]); for (int i = 1; i < arrayLen - 1; i ++) { byteArrays[i] = _byteArrays[startIndex + i]; } } return new ByteArrayVector(byteArrays); } int getBytesNum() { return _totalLength; } int getArraySize() { return _byteArrays.length; } /** * Locate the ByteArray where the ith byte is located * @param i the ith byte * @param startIndex the index of the first ByteArray to look at * @param endIndex the index of the last ByteArray to look at * @return the index of the target ByteArray */ private int locate(int i, int startIndex, int endIndex) { if (startIndex > endIndex) { throw new IllegalArgumentException("location " + i + " is out of bound"); } int mid = (startIndex + endIndex) / 2; if (_accumulatedLens[mid] > i) { return locate(i, startIndex, mid - 1); } else if (_accumulatedLens[mid] == i) { return mid; } else if (mid == endIndex || _accumulatedLens[mid + 1] > i) { return mid; } else { return locate(i, mid + 1, endIndex); } } } /** * An inputstream backed by a ByteArrayVector. * Unlike ByteArrayInputStream, this inputstream does not synchronize on methods. */ private static class ByteArrayVectorInputStream extends InputStream { private final ByteArrayVector _byteArrays; private int _pos; private int _arrayIndex; private int _arrayOffset; private int _mark; private int _count; ByteArrayVectorInputStream(ByteArrayVector byteArrays) { _byteArrays = byteArrays; _count = _byteArrays.getBytesNum(); _pos = 0; _mark = _pos; _arrayIndex = 0; _arrayOffset = 0; } @Override public int available() { return _count - _pos; } @Override public void mark(int readLimit) { // readLimit is ignored per Java class Lib. book, p.220. _mark = _pos; } @Override public boolean markSupported() { return true; } @Override public int read() { if (_pos < _count) { _pos++; byte result= _byteArrays.get(_arrayIndex).get(_arrayOffset); _arrayOffset++; if (_arrayOffset == _byteArrays.get(_arrayIndex).getLength()) { _arrayIndex++; _arrayOffset = 0; } return ((int) result) & 0xFF; } return -1; } @Override public int read(byte[] buffer, int offset, int length) { if (_pos >= _count) { return -1; } int numBytes = Math.min(_count - _pos, length); int copiedBytesNum = 0; while (copiedBytesNum < numBytes) { ByteArray byteArray = _byteArrays.get(_arrayIndex); int len = Math.min(byteArray.getLength() - _arrayOffset, numBytes - copiedBytesNum); System.arraycopy(byteArray.getArray(), byteArray.getOffset() + _arrayOffset, buffer, offset + copiedBytesNum, len); copiedBytesNum += len; if (len == byteArray.getLength() - _arrayOffset) { _arrayIndex++; _arrayOffset = 0; } else { _arrayOffset += len; } } _pos += numBytes; return numBytes; } @Override public void reset() { _pos = _mark; _arrayIndex = _byteArrays.locate(_pos, 0, _byteArrays.getArraySize()); _arrayOffset = _pos - _byteArrays._accumulatedLens[_arrayIndex]; } @Override public long skip(long num) { long numBytes = Math.min((long)(_count - _pos), num < 0 ? 0L : num); _pos += numBytes; _arrayIndex = _byteArrays.locate(_pos, 0, _byteArrays.getArraySize()); _arrayOffset = _pos - _byteArrays._accumulatedLens[_arrayIndex]; return numBytes; } } /** * A {@link ProtoReader} that can read the contents of this ByteString. */ private static class ByteStringProtoReader extends ProtoReader { private final ByteArrayVector _byteArrays; private int _currentArrayOffset; private int _currentIndex; private ByteArray _currentSegment; private ByteStringProtoReader(ByteArrayVector byteArrays) { _byteArrays = byteArrays; // It is safe to call .get(0) without worrying about getting an ArrayIndexOutOfBoundsException, since every // ByteString (even empty) is guaranteed to have at least one segment. _currentSegment = byteArrays.get(0); _currentArrayOffset = _currentSegment.getOffset(); } @Override public String readASCIIString() throws IOException { final int size = readInt32(); if (size > 0) { if (size <= getCurrentRemaining()) { // If we can read from the current chunk, read directly. String value = Utf8Utils.decodeASCII(_currentSegment.getArray(), _currentArrayOffset, size, _textBuffer); _currentArrayOffset += size; return value; } else { ByteStringLongDecoderState state = new ByteStringLongDecoderState(_byteArrays, _currentIndex, _currentArrayOffset); String value = Utf8Utils.decodeLongASCII(state, size, _textBuffer); _currentIndex = state.getCurrentIndex(); _currentSegment = _byteArrays.get(_currentIndex); _currentArrayOffset = state.getPosition(); return value; } } else if (size == 0) { return ""; } else { throw new IOException("Read negative size: " + size + ". Invalid string"); } } @Override public String readString() throws IOException { final int size = readInt32(); if (size > 0) { if (size <= getCurrentRemaining()) { // If we can read from the current chunk, read directly. String value = Utf8Utils.decode(_currentSegment.getArray(), _currentArrayOffset, size, _textBuffer); _currentArrayOffset += size; return value; } else { ByteStringLongDecoderState state = new ByteStringLongDecoderState(_byteArrays, _currentIndex, _currentArrayOffset); String value = Utf8Utils.decodeLong(state, size, _textBuffer); _currentIndex = state.getCurrentIndex(); _currentSegment = _byteArrays.get(_currentIndex); _currentArrayOffset = state.getPosition(); return value; } } else if (size == 0) { return ""; } else { throw new IOException("Read negative size: " + size + ". Invalid string"); } } @Override public byte[] readByteArray() throws IOException { final int size = readInt32(); if (size < 0) { throw new IOException("Read negative size: " + size + ". Invalid byte array"); } else if (size <= getCurrentRemaining()) { // Fast path: We already have the bytes in a contiguous buffer, so just copy directly from it. final byte[] result = Arrays.copyOfRange(_currentSegment.getArray(), _currentArrayOffset, _currentArrayOffset + size); _currentArrayOffset += size; return result; } else { // Slow path: Build a byte array first then copy it. return readRawBytesSlowPath(size); } } @Override public int readInt32() throws IOException { // See implementation notes for readInt64 fastpath: { int tempOffset = _currentArrayOffset; if (getCurrentRemaining() == 0) { break fastpath; } final byte[] buffer = _currentSegment.getArray(); int x; if ((x = buffer[tempOffset++]) >= 0) { _currentArrayOffset = tempOffset; return x; } else if (_currentSegment.getLength() - (tempOffset - _currentSegment.getOffset()) < 9) { break fastpath; } else if ((x ^= (buffer[tempOffset++] << 7)) < 0) { x ^= (~0 << 7); } else if ((x ^= (buffer[tempOffset++] << 14)) >= 0) { x ^= (~0 << 7) ^ (~0 << 14); } else if ((x ^= (buffer[tempOffset++] << 21)) < 0) { x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); } else { int y = buffer[tempOffset++]; x ^= y << 28; x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); if (y < 0 && buffer[tempOffset++] < 0 && buffer[tempOffset++] < 0 && buffer[tempOffset++] < 0 && buffer[tempOffset++] < 0 && buffer[tempOffset++] < 0) { break fastpath; // Will throw malformedVarint() } } _currentArrayOffset = tempOffset; return x; } return (int) readRawVarint64SlowPath(); } @Override public long readInt64() throws IOException { // Implementation notes: // // Optimized for one-byte values, expected to be common. // The particular code below was selected from various candidates // empirically, by winning VarintBenchmark. // // Sign extension of (signed) Java bytes is usually a nuisance, but // we exploit it here to more easily obtain the sign of bytes read. // Instead of cleaning up the sign extension bits by masking eagerly, // we delay until we find the final (positive) byte, when we clear all // accumulated bits with one xor. We depend on javac to constant fold. fastpath: { int tempOffset = _currentArrayOffset; if (getCurrentRemaining() == 0) { break fastpath; } final byte[] buffer = _currentSegment.getArray(); long x; int y; if ((y = buffer[tempOffset++]) >= 0) { _currentArrayOffset = tempOffset; return y; } else if (_currentSegment.getLength() - (tempOffset - _currentSegment.getOffset()) < 9) { break fastpath; } else if ((y ^= (buffer[tempOffset++] << 7)) < 0) { x = y ^ (~0 << 7); } else if ((y ^= (buffer[tempOffset++] << 14)) >= 0) { x = y ^ ((~0 << 7) ^ (~0 << 14)); } else if ((y ^= (buffer[tempOffset++] << 21)) < 0) { x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); } else if ((x = y ^ ((long) buffer[tempOffset++] << 28)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); } else if ((x ^= ((long) buffer[tempOffset++] << 35)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); } else if ((x ^= ((long) buffer[tempOffset++] << 42)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); } else if ((x ^= ((long) buffer[tempOffset++] << 49)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49); } else { x ^= ((long) buffer[tempOffset++] << 56); x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49) ^ (~0L << 56); if (x < 0L) { if (buffer[tempOffset++] < 0L) { break fastpath; // Will throw malformedVarint() } } } _currentArrayOffset = tempOffset; return x; } return readRawVarint64SlowPath(); } @Override public int readFixedInt32() throws IOException { if (getCurrentRemaining() < ProtoWriter.FIXED32_SIZE) { return (((readRawByte() & 0xff)) | ((readRawByte() & 0xff) << 8) | ((readRawByte() & 0xff) << 16) | ((readRawByte() & 0xff) << 24)); } final byte[] buffer = _currentSegment.getArray(); return (((buffer[_currentArrayOffset++] & 0xff)) | ((buffer[_currentArrayOffset++] & 0xff) << 8) | ((buffer[_currentArrayOffset++] & 0xff) << 16) | ((buffer[_currentArrayOffset++] & 0xff) << 24)); } @Override public long readFixedInt64() throws IOException { if (getCurrentRemaining() < ProtoWriter.FIXED64_SIZE) { return (((readRawByte() & 0xffL)) | ((readRawByte() & 0xffL) << 8) | ((readRawByte() & 0xffL) << 16) | ((readRawByte() & 0xffL) << 24) | ((readRawByte() & 0xffL) << 32) | ((readRawByte() & 0xffL) << 40) | ((readRawByte() & 0xffL) << 48) | ((readRawByte() & 0xffL) << 56)); } final byte[] buffer = _currentSegment.getArray(); return (((buffer[_currentArrayOffset++] & 0xffL)) | ((buffer[_currentArrayOffset++] & 0xffL) << 8) | ((buffer[_currentArrayOffset++] & 0xffL) << 16) | ((buffer[_currentArrayOffset++] & 0xffL) << 24) | ((buffer[_currentArrayOffset++] & 0xffL) << 32) | ((buffer[_currentArrayOffset++] & 0xffL) << 40) | ((buffer[_currentArrayOffset++] & 0xffL) << 48) | ((buffer[_currentArrayOffset++] & 0xffL) << 56)); } @Override public byte readRawByte() throws IOException { if (getCurrentRemaining() == 0) { readNextBuffer(); } return _currentSegment.getArray()[_currentArrayOffset++]; } private void readNextBuffer() throws IOException { if (_currentIndex >= _byteArrays.getArraySize()) { throw new EOFException(); } _currentSegment = _byteArrays.get(++_currentIndex); _currentArrayOffset = _currentSegment.getOffset(); } private long readRawVarint64SlowPath() throws IOException { long result = 0; for (int shift = 0; shift < 64; shift += 7) { final byte b = readRawByte(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } } throw new IOException("Malformed VarInt"); } private byte[] readRawBytesSlowPath(int size) throws IOException { byte[] bytes = new byte[size]; int offset = 0; // Copy over remaining bytes from current segment if any. int length = getCurrentRemaining(); if (length > 0) { System.arraycopy(_currentSegment.getArray(), _currentArrayOffset, bytes, offset, length); size -= length; offset += length; _currentArrayOffset += length; } while (size > 0) { readNextBuffer(); length = Math.min(size, _currentSegment.getLength()); System.arraycopy(_currentSegment.getArray(), _currentArrayOffset, bytes, offset, length); size -= length; offset += length; _currentArrayOffset += length; } return bytes; } private int getCurrentRemaining() { return _currentSegment.getOffset() + _currentSegment.getLength() - _currentArrayOffset; } } /** * Maintains the current state of the decoder when parsing a {@link String} across * multiple {@link ByteArray} instances. */ private static class ByteStringLongDecoderState extends Utf8Utils.LongDecoderState { private final ByteArrayVector _byteArrays; private int _currentIndex; ByteStringLongDecoderState(ByteArrayVector byteArrays, int currentIndex, int currentArrayOffset) { _byteArrays = byteArrays; _currentIndex = currentIndex; updateState(); _position = currentArrayOffset; } @Override public void readNextChunk() throws IOException { if (++_currentIndex >= _byteArrays.getArraySize()) { throw new EOFException(); } updateState(); } int getCurrentIndex() { return _currentIndex; } private void updateState() { ByteArray array = _byteArrays.get(_currentIndex); _buffer = array.getArray(); _offset = array.getOffset(); _position = array.getOffset(); _bufferSize = array.getLength(); } } }
package models; import com.avaje.ebean.Ebean; import com.avaje.ebean.Model; import play.data.validation.Constraints; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; //import java.sql.Blob; /** * Represents a Picture - Work in progress * Created by nathancheek on 6/24/16. */ @Entity @Table(name = "pictures") public class Picture extends Model { /** * Find a Picture by its id * @param id Id of Picture * @return Picture if it exists */ public static Picture findById(int id) { return Ebean.find(Picture.class).where().eq("id", id).findUnique(); } @Id public int id; @Constraints.Required @Lob public byte[] image; /** * Create an instance of Picture * @param image Picture as byte array */ public Picture(byte[] image) { this.image = image; this.save(); } }
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.models.bigbad; import org.eclipse.persistence.sessions.*; import org.eclipse.persistence.mappings.converters.*; import org.eclipse.persistence.mappings.*; import org.eclipse.persistence.descriptors.RelationalDescriptor; /** * This class was generated by the TopLink project class generator. * It stores the meta-data (descriptors) that define the TopLink mappings. * @see org.eclipse.persistence.sessions.factories.ProjectClassGenerator */ public class BigBadProject extends org.eclipse.persistence.sessions.Project { public BigBadProject() { setName("BigBad"); applyLogin(); addDescriptor(buildBigBadObjectDescriptor()); addDescriptor(buildBigBadAggregateDescriptor()); addDescriptor(buildBigBadReferenceDataDescriptor()); } public void applyLogin() { DatabaseLogin login = new DatabaseLogin(); setLogin(login); } public RelationalDescriptor buildBigBadObjectDescriptor() { RelationalDescriptor descriptor = new RelationalDescriptor(); descriptor.setJavaClass(org.eclipse.persistence.testing.models.bigbad.BigBadObject.class); descriptor.addTableName("BIG_BAD_OBJ"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID01"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID02"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID03"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID04"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID05"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID06"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID07"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID08"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID09"); descriptor.addPrimaryKeyFieldName("BIG_BAD_OBJ.ID10"); // Mappings. // strings for (int index = 0; index < 20; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("string" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.STRING_DATA" + indexString); descriptor.addMapping(directMapping); } // ids (after to check indexing) for (int index = 0; index < 10; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("id" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.ID" + indexString); descriptor.addMapping(directMapping); } // calendar for (int index = 0; index < 10; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("calendar" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.CALENDAR_DATA" + indexString); descriptor.addMapping(directMapping); } // date for (int index = 0; index < 10; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("date" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.DATE_DATA" + indexString); descriptor.addMapping(directMapping); } // time for (int index = 0; index < 10; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("time" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.TIME_DATA" + indexString); descriptor.addMapping(directMapping); } // timestamp for (int index = 0; index < 10; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("timestamp" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.TIMESTAMP_DATA" + indexString); descriptor.addMapping(directMapping); } // largestring for (int index = 0; index < 3; index++) { DirectToFieldMapping directMapping = new DirectToFieldMapping(); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } directMapping.setAttributeName("largeString" + indexString); directMapping.setFieldName("BIG_BAD_OBJ.LSTRING_DATA" + indexString); descriptor.addMapping(directMapping); } // blob DirectToFieldMapping directMapping = new DirectToFieldMapping(); directMapping.setAttributeName("blob"); directMapping.setFieldName("BIG_BAD_OBJ.BLOB_DATA"); descriptor.addMapping(directMapping); // serialized blob directMapping = new DirectToFieldMapping(); directMapping.setAttributeName("serializedBlob"); directMapping.setFieldName("BIG_BAD_OBJ.SER_DATA"); directMapping.setConverter(new SerializedObjectConverter()); descriptor.addMapping(directMapping); // numbers directMapping = new DirectToFieldMapping(); directMapping.setAttributeName("number01"); directMapping.setFieldName("BIG_BAD_OBJ.NUM_DATA01"); descriptor.addMapping(directMapping); directMapping = new DirectToFieldMapping(); directMapping.setAttributeName("number02"); directMapping.setFieldName("BIG_BAD_OBJ.NUM_DATA02"); descriptor.addMapping(directMapping); // aggregates for (int index = 0; index < 3; index++) { AggregateObjectMapping aggMapping = new AggregateObjectMapping(); aggMapping.setReferenceClass(BigBadAggregate.class); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } aggMapping.setAttributeName("agg" + indexString); aggMapping.addFieldNameTranslation("BIG_BAD_OBJ.AGG_STRING" + indexString, "string"); aggMapping.addFieldNameTranslation("BIG_BAD_OBJ.AGG_NUM" + indexString, "number"); descriptor.addMapping(aggMapping); } // 1-1 for (int index = 0; index < 3; index++) { OneToOneMapping oneToOneMapping = new OneToOneMapping(); oneToOneMapping.setReferenceClass(BigBadReferenceData.class); String indexString = String.valueOf(index + 1); if (indexString.length() == 1) { indexString = "0" + indexString; } oneToOneMapping.setAttributeName("ref" + indexString); oneToOneMapping.addForeignKeyFieldName("BIG_BAD_OBJ.REF_FK" + indexString, "BIG_BAD_DATA.ID"); descriptor.addMapping(oneToOneMapping); } return descriptor; } public RelationalDescriptor buildBigBadReferenceDataDescriptor() { RelationalDescriptor descriptor = new RelationalDescriptor(); descriptor.setJavaClass(org.eclipse.persistence.testing.models.bigbad.BigBadReferenceData.class); descriptor.addTableName("BIG_BAD_DATA"); descriptor.addPrimaryKeyFieldName("BIG_BAD_DATA.ID"); // Mappings. DirectToFieldMapping idMapping = new DirectToFieldMapping(); idMapping.setAttributeName("id"); idMapping.setFieldName("BIG_BAD_DATA.ID"); descriptor.addMapping(idMapping); DirectToFieldMapping dataMapping = new DirectToFieldMapping(); dataMapping.setAttributeName("data"); dataMapping.setFieldName("BIG_BAD_DATA.DATA"); descriptor.addMapping(dataMapping); return descriptor; } public RelationalDescriptor buildBigBadAggregateDescriptor() { RelationalDescriptor descriptor = new RelationalDescriptor(); descriptor.descriptorIsAggregate(); descriptor.setJavaClass(org.eclipse.persistence.testing.models.bigbad.BigBadAggregate.class); // Mappings. DirectToFieldMapping idMapping = new DirectToFieldMapping(); idMapping.setAttributeName("number"); idMapping.setFieldName("number"); descriptor.addMapping(idMapping); DirectToFieldMapping dataMapping = new DirectToFieldMapping(); dataMapping.setAttributeName("string"); dataMapping.setFieldName("string"); descriptor.addMapping(dataMapping); return descriptor; } }
package org.tourgune.egistour.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Service; /** * AppTrack * * Created by CICtourGUNE on 10/04/13. * Copyright (c) 2013 CICtourGUNE. All rights reserved. * */ @Service public class AppTrackUtils { public static String DOMAIN = Configuration.getInstance().getProperty( Configuration.IP); public static String PORT = Configuration.getInstance().getProperty( Configuration.PORT); public static String ROOT = Configuration.getInstance().getProperty( Configuration.ROOT); public static String BASEURL = "http://" + DOMAIN + ":" + PORT + "/" + ROOT; public static String APIURL = BASEURL + "/api"; public static String API_USER = APIURL + "/user"; public static String API_QR = "/open"; /** * Este método convierte un String separado por ";" en una lista de valores * * @param values Valores separados por ";" * @return Lista de valores resultante */ public List<String> stringToArray(String values) { String[] arrayValues = values.split(";"); List<String> array = new ArrayList<String>(); // En este momento tenemos un array en el que cada elemento es una // opcion. for (int i = 0; i < arrayValues.length; i++) { String y = arrayValues[i].trim();// para quitar los primeros y // �ltimos espacios if (y.length() > 0) { array.add(y); } } return array; } /** * Este método convierte un texto en formato fecha, en un objeto de tipo Date * * @param fecha Valor en formato texto de la fecha * @return Objeto Date resultante */ public Date convertStringToDate(String fecha) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date fechaData = null; try { fechaData = df.parse(fecha); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fechaData; } }
package io.techery.analytics.sample.event; import org.junit.Test; import java.util.Calendar; import io.techery.analytics.sample.BaseTest; import io.techery.analytics.sample.utils.MapMatcher; import io.techery.analytics.sample_common.entity.PetEntity; import io.techery.analytics.sample_common.entity.PetType; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; public class BuyPetEventKtTest extends BaseTest { @Test public void eventKotlinSentWithCorrectData() { Calendar petBirthDate = Calendar.getInstance(); petBirthDate.set(2015, 4, 13); // formatted date will be "May 13, 2015" PetEntity pet = new PetEntity(PetType.DOG, "Moohtar", petBirthDate); BuyPetEventKt event = new BuyPetEventKt(pet); analyticsPipe.send(event); verify(tracker).trackEvent(eq("user_bought_pet:dog:mall"), argThat(MapMatcher.builder() .with("pet_birth_date", "May 13, 2015") .with("pet_name", "Moohtar") .with("pet_gender", "female") .without("nullable_attribute") .build() )); } }
package org.egov.pt.calculator.web.models.propertyV2; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; import org.egov.pt.calculator.web.models.property.AuditDetails; import javax.validation.Valid; import javax.validation.constraints.Digits; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import java.math.BigDecimal; /** * UnitV2 */ @ToString @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode(of = { "id" }) public class UnitV2 { @JsonProperty("id") private String id; @JsonProperty("tenantId") private String tenantId; @Max(value = 500) @JsonProperty("floorNo") private Integer floorNo; @JsonProperty("unitType") private String unitType; @JsonProperty("usageCategory") @NotNull private String usageCategory; @JsonProperty("occupancyType") private String occupancyType; @JsonProperty("active") private Boolean active; @JsonProperty("occupancyDate") private Long occupancyDate; @Valid @NotNull @JsonProperty("constructionDetail") private ConstructionDetail constructionDetail; @JsonProperty("additionalDetails") private Object additionalDetails; @JsonProperty("auditDetails") private AuditDetails auditDetails; @Digits(integer = 10, fraction = 2) @JsonProperty("arv") private BigDecimal arv; }
/* * Copyright 2016 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 com.github.alexfalappa.nbspringboot.prefs; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.MalformedURLException; import java.net.URL; import java.util.prefs.Preferences; import javax.swing.DefaultComboBoxModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.openide.util.NbPreferences; import com.github.alexfalappa.nbspringboot.PrefConstants; import com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService; /** * Plugin options panel. * <p> * It is shown under the Java category in Tools/Options dialog. * * @author Alessandro Falappa */ final class BootPrefsPanel extends javax.swing.JPanel implements DocumentListener, ChangeListener, ActionListener { private final BootPrefsOptionsPanelController controller; private static final String[] SEVERITY_LEVELS = new String[]{"None", "Warning", "Error"}; BootPrefsPanel(BootPrefsOptionsPanelController controller) { this.controller = controller; initComponents(); } /** This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of * this method is always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lInitializr = new javax.swing.JLabel(); sep1 = new javax.swing.JSeparator(); lInitializrUrl = new javax.swing.JLabel(); txInitializrUrl = new javax.swing.JTextField(); lInitializrTimeout = new javax.swing.JLabel(); spInitializrTimeout = new javax.swing.JSpinner(); lSeconds = new javax.swing.JLabel(); lLaunch = new javax.swing.JLabel(); sep2 = new javax.swing.JSeparator(); chDevtoolsTrigger = new javax.swing.JCheckBox(); chColorOutput = new javax.swing.JCheckBox(); lVmOpts = new javax.swing.JLabel(); txVmOpts = new javax.swing.JTextField(); chVmOptsLaunch = new javax.swing.JCheckBox(); lCfgProps = new javax.swing.JLabel(); sep3 = new javax.swing.JSeparator(); lLists = new javax.swing.JLabel(); chDeprSortLast = new javax.swing.JCheckBox(); chDeprErrorShow = new javax.swing.JCheckBox(); lErrHighl = new javax.swing.JLabel(); lSynErr = new javax.swing.JLabel(); cbSynErr = new javax.swing.JComboBox<>(); lDupl = new javax.swing.JLabel(); cbDupl = new javax.swing.JComboBox<>(); lDtMismatch = new javax.swing.JLabel(); cbDtMismatch = new javax.swing.JComboBox<>(); lUnknown = new javax.swing.JLabel(); cbUnknown = new javax.swing.JComboBox<>(); lDeprecated = new javax.swing.JLabel(); cbDeprecated = new javax.swing.JComboBox<>(); lCompletion = new javax.swing.JLabel(); chArrayNotation = new javax.swing.JCheckBox(); org.openide.awt.Mnemonics.setLocalizedText(lInitializr, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.lInitializr.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lInitializrUrl, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.lInitializrUrl.text")); // NOI18N txInitializrUrl.setColumns(20); org.openide.awt.Mnemonics.setLocalizedText(lInitializrTimeout, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.lInitializrTimeout.text")); // NOI18N spInitializrTimeout.setModel(new javax.swing.SpinnerNumberModel(30, 5, 999, 5)); org.openide.awt.Mnemonics.setLocalizedText(lSeconds, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.lSeconds.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lLaunch, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lLaunch.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(chDevtoolsTrigger, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.chDevtoolsTrigger.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(chColorOutput, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.chColorOutput.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lVmOpts, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lVmOpts.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(chVmOptsLaunch, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.chVmOptsLaunch.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lCfgProps, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.lCfgProps.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lLists, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lLists.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(chDeprSortLast, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.chDeprSortLast.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(chDeprErrorShow, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.chDeprErrorShow.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lErrHighl, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lErrHighl.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(lSynErr, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lSynErr.text")); // NOI18N cbSynErr.setModel(new DefaultComboBoxModel<>(SEVERITY_LEVELS)); org.openide.awt.Mnemonics.setLocalizedText(lDupl, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lDupl.text")); // NOI18N cbDupl.setModel(new DefaultComboBoxModel<>(SEVERITY_LEVELS)); org.openide.awt.Mnemonics.setLocalizedText(lDtMismatch, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lDtMismatch.text")); // NOI18N cbDtMismatch.setModel(new DefaultComboBoxModel<>(SEVERITY_LEVELS)); org.openide.awt.Mnemonics.setLocalizedText(lUnknown, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lUnknown.text")); // NOI18N cbUnknown.setModel(new DefaultComboBoxModel<>(SEVERITY_LEVELS)); org.openide.awt.Mnemonics.setLocalizedText(lDeprecated, org.openide.util.NbBundle.getBundle(BootPrefsPanel.class).getString("BootPrefsPanel.lDeprecated.text")); // NOI18N cbDeprecated.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "None", "Highlight" })); org.openide.awt.Mnemonics.setLocalizedText(lCompletion, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.lCompletion.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(chArrayNotation, org.openide.util.NbBundle.getMessage(BootPrefsPanel.class, "BootPrefsPanel.chArrayNotation.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lLaunch) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sep2)) .addGroup(layout.createSequentialGroup() .addComponent(lInitializr) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sep1)) .addGroup(layout.createSequentialGroup() .addComponent(lCfgProps) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sep3)) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lInitializrTimeout) .addComponent(lInitializrUrl)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(spInitializrTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lSeconds) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txInitializrUrl))) .addGroup(layout.createSequentialGroup() .addComponent(lVmOpts) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(chVmOptsLaunch) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txVmOpts))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chColorOutput) .addComponent(chDevtoolsTrigger) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lLists) .addComponent(chDeprErrorShow) .addComponent(lCompletion) .addComponent(chArrayNotation) .addComponent(chDeprSortLast)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lErrHighl) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lSynErr) .addComponent(lDupl) .addComponent(lDtMismatch) .addComponent(lUnknown) .addComponent(lDeprecated)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cbSynErr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbDupl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbDtMismatch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbUnknown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbDeprecated, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addGap(0, 0, Short.MAX_VALUE))))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lInitializr) .addComponent(sep1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lInitializrUrl) .addComponent(txInitializrUrl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lInitializrTimeout) .addComponent(spInitializrTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lSeconds)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lLaunch) .addComponent(sep2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chDevtoolsTrigger) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chColorOutput) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lVmOpts) .addComponent(txVmOpts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chVmOptsLaunch) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lCfgProps) .addComponent(sep3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lErrHighl) .addComponent(lLists)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lSynErr) .addComponent(cbSynErr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chDeprSortLast)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lDupl) .addComponent(cbDupl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(chDeprErrorShow))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lDtMismatch) .addComponent(cbDtMismatch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lCompletion)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lUnknown) .addComponent(cbUnknown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chArrayNotation)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lDeprecated) .addComponent(cbDeprecated, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents void load() { // read settings and initialize GUI final Preferences prefs = NbPreferences.forModule(PrefConstants.class); txInitializrUrl.setText(prefs.get(PrefConstants.PREF_INITIALIZR_URL, PrefConstants.DEFAULT_INITIALIZR_URL)); txVmOpts.setText(prefs.get(PrefConstants.PREF_VM_OPTS, "")); spInitializrTimeout.setValue(prefs.getInt(PrefConstants.PREF_INITIALIZR_TIMEOUT, 30)); chColorOutput.setSelected(prefs.getBoolean(PrefConstants.PREF_FORCE_COLOR_OUTPUT, true)); chDevtoolsTrigger.setSelected(prefs.getBoolean(PrefConstants.PREF_MANUAL_RESTART, false)); chVmOptsLaunch.setSelected(prefs.getBoolean(PrefConstants.PREF_VM_OPTS_LAUNCH, true)); chDeprSortLast.setSelected(prefs.getBoolean(PrefConstants.PREF_DEPR_SORT_LAST, true)); chDeprErrorShow.setSelected(prefs.getBoolean(PrefConstants.PREF_DEPR_ERROR_SHOW, true)); chArrayNotation.setSelected(prefs.getBoolean(PrefConstants.PREF_ARRAY_NOTATION, false)); cbDtMismatch.setSelectedIndex(prefs.getInt(PrefConstants.PREF_HLIGHT_LEV_DTMISMATCH, 2)); cbDupl.setSelectedIndex(prefs.getInt(PrefConstants.PREF_HLIGHT_LEV_DUPLICATES, 1)); cbSynErr.setSelectedIndex(prefs.getInt(PrefConstants.PREF_HLIGHT_LEV_SYNERR, 2)); cbUnknown.setSelectedIndex(prefs.getInt(PrefConstants.PREF_HLIGHT_LEV_UNKNOWN, 1)); cbDeprecated.setSelectedIndex(prefs.getInt(PrefConstants.PREF_HLIGHT_LEV_DEPRECATED, 1)); // listen to changes in form fields and call controller.changed() // Register listener on the textFields to detect changes txInitializrUrl.getDocument().addDocumentListener(this); txVmOpts.getDocument().addDocumentListener(this); spInitializrTimeout.addChangeListener(this); chColorOutput.addActionListener(this); chDevtoolsTrigger.addActionListener(this); chVmOptsLaunch.addActionListener(this); chDeprSortLast.addActionListener(this); chDeprErrorShow.addActionListener(this); cbDtMismatch.addActionListener(this); cbDupl.addActionListener(this); cbSynErr.addActionListener(this); cbUnknown.addActionListener(this); cbDeprecated.addActionListener(this); } void store() { // store modified settings final Preferences prefs = NbPreferences.forModule(PrefConstants.class); prefs.put(PrefConstants.PREF_INITIALIZR_URL, txInitializrUrl.getText()); prefs.put(PrefConstants.PREF_VM_OPTS, txVmOpts.getText()); prefs.putInt(PrefConstants.PREF_INITIALIZR_TIMEOUT, (int) spInitializrTimeout.getValue()); prefs.putBoolean(PrefConstants.PREF_FORCE_COLOR_OUTPUT, chColorOutput.isSelected()); prefs.putBoolean(PrefConstants.PREF_MANUAL_RESTART, chDevtoolsTrigger.isSelected()); prefs.putBoolean(PrefConstants.PREF_VM_OPTS_LAUNCH, chVmOptsLaunch.isSelected()); prefs.putBoolean(PrefConstants.PREF_DEPR_SORT_LAST, chDeprSortLast.isSelected()); prefs.putBoolean(PrefConstants.PREF_DEPR_ERROR_SHOW, chDeprErrorShow.isSelected()); prefs.putBoolean(PrefConstants.PREF_ARRAY_NOTATION, chArrayNotation.isSelected()); prefs.putInt(PrefConstants.PREF_HLIGHT_LEV_DTMISMATCH, cbDtMismatch.getSelectedIndex()); prefs.putInt(PrefConstants.PREF_HLIGHT_LEV_DUPLICATES, cbDupl.getSelectedIndex()); prefs.putInt(PrefConstants.PREF_HLIGHT_LEV_SYNERR, cbSynErr.getSelectedIndex()); prefs.putInt(PrefConstants.PREF_HLIGHT_LEV_UNKNOWN, cbUnknown.getSelectedIndex()); prefs.putInt(PrefConstants.PREF_HLIGHT_LEV_DEPRECATED, cbDeprecated.getSelectedIndex()); InitializrService.getInstance().clearCachedValues(); } boolean valid() { // check whether form is consistent and complete boolean ret = true; try { URL url = new URL(txInitializrUrl.getText()); } catch (MalformedURLException ex) { ret = false; } return ret; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> cbDeprecated; private javax.swing.JComboBox<String> cbDtMismatch; private javax.swing.JComboBox<String> cbDupl; private javax.swing.JComboBox<String> cbSynErr; private javax.swing.JComboBox<String> cbUnknown; private javax.swing.JCheckBox chArrayNotation; private javax.swing.JCheckBox chColorOutput; private javax.swing.JCheckBox chDeprErrorShow; private javax.swing.JCheckBox chDeprSortLast; private javax.swing.JCheckBox chDevtoolsTrigger; private javax.swing.JCheckBox chVmOptsLaunch; private javax.swing.JLabel lCfgProps; private javax.swing.JLabel lCompletion; private javax.swing.JLabel lDeprecated; private javax.swing.JLabel lDtMismatch; private javax.swing.JLabel lDupl; private javax.swing.JLabel lErrHighl; private javax.swing.JLabel lInitializr; private javax.swing.JLabel lInitializrTimeout; private javax.swing.JLabel lInitializrUrl; private javax.swing.JLabel lLaunch; private javax.swing.JLabel lLists; private javax.swing.JLabel lSeconds; private javax.swing.JLabel lSynErr; private javax.swing.JLabel lUnknown; private javax.swing.JLabel lVmOpts; private javax.swing.JSeparator sep1; private javax.swing.JSeparator sep2; private javax.swing.JSeparator sep3; private javax.swing.JSpinner spInitializrTimeout; private javax.swing.JTextField txInitializrUrl; private javax.swing.JTextField txVmOpts; // End of variables declaration//GEN-END:variables // DocumentListener interface @Override public void insertUpdate(DocumentEvent e) { controller.changed(); } // DocumentListener interface @Override public void removeUpdate(DocumentEvent e) { controller.changed(); } // DocumentListener interface @Override public void changedUpdate(DocumentEvent e) { controller.changed(); } // ChangeListener interface @Override public void stateChanged(ChangeEvent e) { controller.changed(); } // Actionistener interface @Override public void actionPerformed(ActionEvent e) { controller.changed(); } }
package datart.security.base; /** * 权限载体 */ public enum SubjectType { USER, ROLE, USER_ROLE, }
package uk.ac.ebi.fgpt.zooma.service; import uk.ac.ebi.fgpt.zooma.model.Property; import uk.ac.ebi.fgpt.zooma.model.Study; import java.net.URI; import java.util.Collection; import java.util.Map; /** * An abstract decorator of a {@link StudySearchService}. You should subclass this decorator to create different * decorations that add functionality to study searches. * * @author Tony Burdett * @date 02/08/13 */ public abstract class StudySearchServiceDecorator implements StudySearchService { private final StudySearchService _studySearchService; protected StudySearchServiceDecorator(StudySearchService studySearchService) { this._studySearchService = studySearchService; } @Override public Collection<Study> searchBySemanticTags(String... semanticTagShortnames) { return _studySearchService.searchBySemanticTags(semanticTagShortnames); } @Override public Collection<Study> searchBySemanticTags(URI... semanticTags) { return _studySearchService.searchBySemanticTags(semanticTags); } @Override public Collection<Study> searchBySemanticTags(boolean useInference, String... semanticTagShortnames) { return _studySearchService.searchBySemanticTags(useInference, semanticTagShortnames); } @Override public Collection<Study> searchBySemanticTags(boolean useInference, URI... semanticTags) { return _studySearchService.searchBySemanticTags(useInference, semanticTags); } @Override public Collection<Study> searchByProperty(Property... property) { return _studySearchService.searchByProperty(property); } @Override public Collection<Study> searchByStudyAccession(String accession) { return _studySearchService.searchByStudyAccession(accession); } }
/* * Copyright 2013 Pascal Christoph (hbz) * * 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.metafacture.xml; import static org.mockito.Mockito.inOrder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.metafacture.framework.StreamReceiver; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * Tests for class {@link XmlElementSplitter}. * * @author Christoph Böhme (rewrite) * @author Pascal Christoph (dr0i) * */ public class XmlElementSplitterTest { private static final String NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; @Rule public MockitoRule mockito = MockitoJUnit.rule(); @Mock private StreamReceiver receiver; private XmlElementSplitter xmlElementSplitter; @Before public void setup() { xmlElementSplitter = new XmlElementSplitter(); xmlElementSplitter.setReceiver(receiver); } @Test public void shouldSplitXmlAtDefinedElementName() throws SAXException { xmlElementSplitter.setElementName("Description"); xmlElementSplitter.setTopLevelElement("rdf:RDF"); xmlElementSplitter.startPrefixMapping("rdf", NAMESPACE); xmlElementSplitter.startElement(NAMESPACE, "RDF", "rdf:RDF", new AttributesImpl()); startDescription("1"); emitResourceContent("r1", "1"); xmlElementSplitter.endElement(NAMESPACE, "Description", "rdf:Description"); startDescription("2"); emitResourceContent("r2", "2"); xmlElementSplitter.endElement(NAMESPACE, "Description", "rdf:Description"); xmlElementSplitter.endElement(NAMESPACE, "RDF", "rdf:RDF"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("0"); ordered.verify(receiver).literal("Element", "<?xml version = \"1.0\" encoding = \"UTF-8\"?><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"1\"><a rdf:resource=\"r1\">1</a></rdf:Description></rdf:RDF>"); ordered.verify(receiver).endRecord(); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("Element", "<?xml version = \"1.0\" encoding = \"UTF-8\"?><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"2\"><a rdf:resource=\"r2\">2</a></rdf:Description></rdf:RDF>"); ordered.verify(receiver).endRecord(); } private void startDescription(final String id) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(NAMESPACE, "about", "rdf:about", "CDATA", id); xmlElementSplitter.startElement(NAMESPACE, "Description", "rdf:Description", attributes); } private void emitResourceContent(final String resource, final String data) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(NAMESPACE, "resource", "rdf:resource", "CDATA", resource); xmlElementSplitter.startElement(null, "a", "a", attributes); xmlElementSplitter.characters(data.toCharArray(), 0, data.length()); xmlElementSplitter.endElement(null, "a", "a"); } }
//,temp,Upgrade410to420.java,1540,1557,temp,Upgrade302to40.java,718,737 //,3 public class xxx { private void addSrxFirewall(Connection conn, long hostId, long physicalNetworkId) { s_logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); String insertSrx = "INSERT INTO `cloud`.`external_firewall_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try (PreparedStatement pstmtUpdate = conn.prepareStatement(insertSrx);) { pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setLong(2, hostId); pstmtUpdate.setString(3, "JuniperSRX"); pstmtUpdate.setString(4, "JuniperSRXFirewall"); pstmtUpdate.setLong(5, 0); pstmtUpdate.setBoolean(6, false); pstmtUpdate.setString(7, "Enabled"); pstmtUpdate.setString(8, "Shared"); pstmtUpdate.setString(9, UUID.randomUUID().toString()); pstmtUpdate.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Exception while adding SRX firewall device ", e); } } };
package com; import com.adapter.ListViewAdapter; import com.fzu.android.fdkdzs.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; public class ExpressList extends Activity{ private ListView lv_common; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_all); final String[] all_name = getResources().getStringArray(R.array.common); final String[] all_code = getResources().getStringArray(R.array.common_code); lv_common = (ListView)findViewById(R.id.lv_all); lv_common.setAdapter(new ListViewAdapter(this, all_name)); lv_common.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub Intent data = new Intent(); data.putExtra("code", all_code[position]); data.putExtra("name", all_name[position]); setResult(0, data); finish(); } }); } }
package org.codefilarete.stalactite.mapping; import org.codefilarete.stalactite.engine.EntityPersister; import org.codefilarete.stalactite.mapping.id.assembly.IdentifierAssembler; import org.codefilarete.stalactite.mapping.id.manager.IdentifierInsertionManager; /** * Contract about entity identifier mapping. * * @author Guillaume Mary * @param <C> target persisted class * @param <I> identifier class * @see SimpleIdMapping * @see ComposedIdMapping */ public interface IdMapping<C, I> { /** * Expected to indicate if given entity is persisted or not, meaning already exists in database. * Necessary at different steps of the engine, for instance : * - to distinguish SQL statement to apply : insert or update (see {@link EntityPersister#persist(Object)}), * - to prevent from deletion of an instance that's actually not present in database * * <br/><br/> * Determining if an instance is persisted or not can merely be done by testing it's id against nullity in majority of cases, that's why this * method is in this class, but we pass it the whole instance so one can use a different strategy such as checking another field of it such * as a creation date ar a simple boolean not owned by identifier. * * @param entity the entity which the engine need to know if it's persisted * @return true if the entity is persisted (exists in database), else false */ boolean isNew(C entity); IdAccessor<C, I> getIdAccessor(); IdentifierAssembler<I> getIdentifierAssembler(); IdentifierInsertionManager<C, I> getIdentifierInsertionManager(); }