text
stringlengths
7
1.01M
package ru.stqa.pft.mantis.appmanager; import org.openqa.selenium.By; public class RegistationHelper extends HelperBase{ public RegistationHelper(ApplicationManager app) { super(app); } public void start(String username, String email) { wd.get(app.getProperty("web.baseUrl") + "/signup_page.php"); type(By.name("username"), username); type(By.name("email"), email); click(By.cssSelector("input[value='Зарегистрироваться']")); } public void finish(String confirmationLink, String password) { wd.get(confirmationLink); type(By.name("password"), password); type(By.name("password_confirm"), password); click(By.cssSelector("button[type='submit']")); } }
package item; // An Item that can be purchased through the Shop-room public class PurchasableItem extends Item { private final int PRICE; // Initialize the Item with a price PurchasableItem(int PRICE) { this.PRICE = PRICE; } // Return the price of the Item public int getPrice() { return PRICE; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.requests; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.protocol.ApiKeys; import org.apache.kafka.common.protocol.ProtoUtils; import org.apache.kafka.common.protocol.types.Schema; import org.apache.kafka.common.protocol.types.Struct; import org.apache.kafka.common.utils.CollectionUtils; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ListOffsetResponse extends AbstractRequestResponse { private static final Schema CURRENT_SCHEMA = ProtoUtils.currentResponseSchema(ApiKeys.LIST_OFFSETS.id); private static final String RESPONSES_KEY_NAME = "responses"; // topic level field names private static final String TOPIC_KEY_NAME = "topic"; private static final String PARTITIONS_KEY_NAME = "partition_responses"; // partition level field names private static final String PARTITION_KEY_NAME = "partition"; private static final String ERROR_CODE_KEY_NAME = "error_code"; /** * Possible error code: * * UNKNOWN_TOPIC_OR_PARTITION (3) * NOT_LEADER_FOR_PARTITION (6) * UNKNOWN (-1) */ private static final String OFFSETS_KEY_NAME = "offsets"; private final Map<TopicPartition, PartitionData> responseData; public static final class PartitionData { public final short errorCode; public final List<Long> offsets; public PartitionData(short errorCode, List<Long> offsets) { this.errorCode = errorCode; this.offsets = offsets; } } public ListOffsetResponse(Map<TopicPartition, PartitionData> responseData) { super(new Struct(CURRENT_SCHEMA)); Map<String, Map<Integer, PartitionData>> topicsData = CollectionUtils.groupDataByTopic(responseData); List<Struct> topicArray = new ArrayList<Struct>(); for (Map.Entry<String, Map<Integer, PartitionData>> topicEntry: topicsData.entrySet()) { Struct topicData = struct.instance(RESPONSES_KEY_NAME); topicData.set(TOPIC_KEY_NAME, topicEntry.getKey()); List<Struct> partitionArray = new ArrayList<Struct>(); for (Map.Entry<Integer, PartitionData> partitionEntry : topicEntry.getValue().entrySet()) { PartitionData offsetPartitionData = partitionEntry.getValue(); Struct partitionData = topicData.instance(PARTITIONS_KEY_NAME); partitionData.set(PARTITION_KEY_NAME, partitionEntry.getKey()); partitionData.set(ERROR_CODE_KEY_NAME, offsetPartitionData.errorCode); partitionData.set(OFFSETS_KEY_NAME, offsetPartitionData.offsets.toArray()); partitionArray.add(partitionData); } topicData.set(PARTITIONS_KEY_NAME, partitionArray.toArray()); topicArray.add(topicData); } struct.set(RESPONSES_KEY_NAME, topicArray.toArray()); this.responseData = responseData; } public ListOffsetResponse(Struct struct) { super(struct); responseData = new HashMap<TopicPartition, PartitionData>(); for (Object topicResponseObj : struct.getArray(RESPONSES_KEY_NAME)) { Struct topicResponse = (Struct) topicResponseObj; String topic = topicResponse.getString(TOPIC_KEY_NAME); for (Object partitionResponseObj : topicResponse.getArray(PARTITIONS_KEY_NAME)) { Struct partitionResponse = (Struct) partitionResponseObj; int partition = partitionResponse.getInt(PARTITION_KEY_NAME); short errorCode = partitionResponse.getShort(ERROR_CODE_KEY_NAME); Object[] offsets = partitionResponse.getArray(OFFSETS_KEY_NAME); List<Long> offsetsList = new ArrayList<Long>(); for (Object offset: offsets) offsetsList.add((Long) offset); PartitionData partitionData = new PartitionData(errorCode, offsetsList); responseData.put(new TopicPartition(topic, partition), partitionData); } } } public Map<TopicPartition, PartitionData> responseData() { return responseData; } public static ListOffsetResponse parse(ByteBuffer buffer) { return new ListOffsetResponse((Struct) CURRENT_SCHEMA.read(buffer)); } }
package dream.work.modules.system.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.sql.Timestamp; import java.util.Objects; import java.util.Set; /** * 角色 * @author jie * @date 2018-11-22 */ @Entity @Table(name = "role") @Getter @Setter public class Role implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @NotNull(groups = {Update.class}) private Long id; @Column(nullable = false) @NotBlank private String name; // 数据权限类型 全部 、 本级 、 自定义 @Column(name = "data_scope") private String dataScope = "本级"; // 数值越小,级别越大 @Column(name = "level") private Integer level = 3; @Column private String remark; @JsonIgnore @ManyToMany(mappedBy = "roles") private Set<User> users; @ManyToMany @JoinTable(name = "roles_permissions", joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "permission_id",referencedColumnName = "id")}) private Set<Permission> permissions; @ManyToMany @JoinTable(name = "roles_menus", joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "menu_id",referencedColumnName = "id")}) private Set<Menu> menus; @ManyToMany @JoinTable(name = "roles_depts", joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "dept_id",referencedColumnName = "id")}) private Set<Dept> depts; @CreationTimestamp @Column(name = "create_time") private Timestamp createTime; @Override public String toString() { return "Role{" + "id=" + id + ", name='" + name + '\'' + ", remark='" + remark + '\'' + ", createDateTime=" + createTime + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Role role = (Role) o; return Objects.equals(id, role.id); } @Override public int hashCode() { return Objects.hash(id); } public interface Update{} }
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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 net.sf.farrago.test; import java.io.*; import junit.framework.*; import net.sf.farrago.query.*; import net.sf.farrago.session.*; import openjava.ptree.*; import org.eigenbase.oj.rel.*; import org.eigenbase.oj.rex.*; import org.eigenbase.rel.*; import org.eigenbase.rex.*; import org.eigenbase.sql.SqlKind; import org.eigenbase.sql2rel.*; import org.eigenbase.test.DiffRepository; import org.eigenbase.trace.EigenbaseTrace; import org.eigenbase.util.*; /** * FarragoRexToOJTranslatorTest contains unit tests for the translation code in * {@link net.sf.farrago.ojrex}. * * <p>Tests are of two forms:<ul> * * <li>Tests that call {@link #checkTranslation(String)} take a single SQL row * expression string as input, perform code generation, and then diffs the * generated Java code snippet against an expected output in * {@code FarragoRexToOJTranslatorTest.ref.xml}.</li> * * <li>Tests that call {@link #checkQueryTranslation(String)} take a whole * query and generate a whole Java class. These tests can focus on the nuances * of common-subexpression elimination, for instance, when it is safe to reuse * the value of an expression computed for the WHERE clause in a SELECT * expression.</li> * * </ul> * * @author John V. Sichi * @version $Id$ */ public class FarragoRexToOJTranslatorTest extends FarragoSqlToRelTestBase { private boolean full; //~ Constructors ----------------------------------------------------------- /** * Creates a FarragoRexToOJTranslatorTest. * * @param testName Test case name * * @throws Exception on error */ public FarragoRexToOJTranslatorTest(String testName) throws Exception { super(testName); } //~ Methods ---------------------------------------------------------------- // implement TestCase public static Test suite() { return wrappedSuite(FarragoRexToOJTranslatorTest.class); } // override FarragoTestCase protected boolean shouldDiff() { // this test should always work regardless of Fennel availability return true; } protected DiffRepository getDiffRepos() { return DiffRepository.lookup(FarragoRexToOJTranslatorTest.class); } /** * Tests translation of a single row expression. * * @param rowExpression the text of the row expression to test (this is used * as the single select item in a constructed EXPLAIN PLAN statement) * @param tableExpression the table to use in the FROM clause (don't use * anything fancy here like a nested query because the optimizer used for * this test has its hands tied) */ private void checkTranslation( String rowExpression, String tableExpression) throws Exception { final String query = "SELECT " + rowExpression + " FROM " + tableExpression; final String query2 = getDiffRepos().expand("query", query); final String explainQuery = "EXPLAIN PLAN FOR " + query2; full = false; checkQuery(explainQuery); } /** * Tests the translation of a whole query. * * @param query SELECT statement * @throws Exception */ protected void checkQueryTranslation( String query) throws Exception { final String query2 = getDiffRepos().expand("query", query); final String explainQuery = "EXPLAIN PLAN FOR " + query2; full = true; checkQuery(explainQuery); } protected void checkAbstract( FarragoPreparingStmt stmt, RelNode topRel) throws Exception { assert (topRel instanceof IterCalcRel) : topRel.getClass().getName(); IterCalcRel calcRel = (IterCalcRel) topRel; String actual; if (full) { actual = getJavaSourceForQuery(stmt, calcRel); } else { actual = getJavaSourceForRowExpr(stmt, calcRel); } // OJ formats 'finally' wrong. actual = actual.replaceAll(" finally \n\\{", " finally {\n"); actual = actual.replaceAll(" finally \r\n\\{", " finally {\r\n"); // OJ has a nasty habit of creating multiple blank lines. Strip 'em out. int size; do { size = actual.length(); actual = actual.replaceAll("\n *\n", "\n"); actual = actual.replaceAll("\r\n *\r\n", "\r\n"); } while (actual.length() < size); // Convert // }, "FtrsIndexScanRel.#15:364", 26, null ) ){ // to // }, "FtrsIndexScanRel.#xx:xxx", xx, null ) ){ actual = actual.replaceAll( "\"(FtrsIndexScanRel|AspenOldToIteratorConverter).#[0-9]+:[0-9]+\", [0-9]+,", "\"$1.#x:x\", x,"); actual = actual.replaceAll("stmt[0-9]+", "stmtx"); // and diff it against what we expect final DiffRepository diffRepos = getDiffRepos(); diffRepos.assertEquals( "expectedProgram", "${expectedProgram}", TestUtil.NL + actual); } private String getJavaSourceForRowExpr( FarragoPreparingStmt stmt, IterCalcRel calcRel) { // grab the RexNode corresponding to our select item final RexProgram program = calcRel.getProgram(); final RexLocalRef ref = program.getProjectList().get(0); RexNode rexNode = program.getExprList().get(ref.getIndex()); // create objects needed for codegen SqlToRelConverter sqlToRelConverter = stmt.getSqlToRelConverter(); FarragoRelImplementor relImplementor = new FarragoRelImplementor( stmt, sqlToRelConverter.getRexBuilder()); StatementList stmtList = new StatementList(); MemberDeclarationList memberList = new MemberDeclarationList(); final RexToOJTranslator translator = relImplementor.newStmtTranslator( calcRel, stmtList, memberList); Expression translatedExp; try { translator.pushProgram(program); translatedExp = translator.translateRexNode(rexNode); } finally { translator.popProgram(program); } // dump the generated code final StringWriter sw = new StringWriter(); PrintWriter printWriter = new PrintWriter(sw); if (!memberList.isEmpty()) { printWriter.println(memberList); } if (!stmtList.isEmpty()) { printWriter.println(stmtList); } printWriter.println("return " + translatedExp + ";"); printWriter.close(); return sw.toString(); } private String getJavaSourceForQuery( FarragoPreparingStmt stmt, IterCalcRel calcRel) { // Create a handler so that we can be told the java source code. final String[] source = { null }; EigenbaseTrace.getDynamicHandler().set( new Util.Function2<Void, File, String>() { public Void apply(File p0, String p1) { source[0] = p1; return null; } } ); // Note: Calling preImplement followed by implement just happens to // work. If the preparation process or FarragoPreparingStmt needs to // change, go ahead; just change this code to something else that works. stmt.preImplement(); stmt.implement(calcRel, SqlKind.SELECT, false); return source[0]; } protected void initPlanner(FarragoPreparingStmt stmt) { // TODO jvs 9-Apr-2006: Eliminate the init parameter // to newPlanner and construct a HepPlanner here. // NOTE jvs 22-June-2004: We use a very stripped-down planner // so that the optimizer doesn't decide to rewrite our // carefully constructed expressions. This also guarantees // that the Java calculator is used without having to // mess with system parameters. FarragoSessionPlanner planner = stmt.getSession().getPersonality().newPlanner(stmt, false); planner.addRule(IterRules.IterCalcRule.instance); FennelToIteratorConverter.register(planner); // Constant reduction hides what we're trying to test for. planner.setRuleDescExclusionFilter( FarragoReduceExpressionsRule.EXCLUSION_PATTERN); stmt.setPlanner(planner); } /** * Tests translation of a single row expression, using the SALES.EMPS table * for context. * * @param rowExpression the text of the row expression to test (this is used * as the single select item in a constructed EXPLAIN PLAN statement) */ private void checkTranslation(String rowExpression) throws Exception { checkTranslation(rowExpression, "SALES.EMPS"); } public void testPrimitiveEquals() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno = age"); } public void testPrimitiveEqualsNotNull() throws Exception { // NOTE: choose both not null checkTranslation("empno = empid"); } public void testPrimitiveLess() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno < age"); } public void testPrimitiveGreater() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno > age"); } public void testPrimitivePlus() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno + age"); } public void testPrimitiveMinus() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno - age"); } public void testPrimitiveTimes() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno * age"); } public void testPrimitiveDivide() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("empno / age"); } public void testDivideNullable() throws Exception { checkTranslation("1e1 / cast(null as float)"); } public void testPrimitivePrefixMinus() throws Exception { // NOTE: choose nullable checkTranslation("-age"); } public void testPrimitiveGreaterBoolean() throws Exception { // NOTE: choose one null, one not null checkTranslation("manager > slacker"); } public void testPrefixMinusCastNullTinyint() throws Exception { checkTranslation("-cast(null as tinyint)"); } public void testPlusCastNullSmallint() throws Exception { checkTranslation("cast(null as tinyint) + cast (null as smallint)"); } public void testVarcharEquals() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("name = city"); } public void testVarcharLess() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("name < city"); } public void testBooleanNot() throws Exception { // NOTE: choose nullable checkTranslation("not slacker"); } public void testBooleanOr() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("slacker or manager"); } public void testBooleanOrNullable() throws Exception { // NOTE: choose both nullable checkTranslation("(empno < age) or (name = city)"); } public void testBooleanAnd() throws Exception { // NOTE: choose one nullable and one not null checkTranslation("slacker and manager"); } public void testBooleanConjunction() throws Exception { // NOTE: choose both nullable checkTranslation("(empno < age) and (name = city)"); } public void testBooleanConjunctionNotNull() throws Exception { // NOTE: choose all not null checkTranslation("(empno = empid) and (empno = deptno)"); } public void testNullableIsTrue() throws Exception { checkTranslation("slacker is true"); } public void testNullableIsFalse() throws Exception { checkTranslation("slacker is false"); } public void testNotNullIsTrue() throws Exception { checkTranslation("manager is true"); } public void testNotNullIsFalse() throws Exception { checkTranslation("manager is false"); } public void testNullableIsNull() throws Exception { checkTranslation("age is null"); } public void testNullableIsNotNull() throws Exception { checkTranslation("age is not null"); } public void testNotNullIsNull() throws Exception { checkTranslation("empno is null"); } public void testNotNullIsNotNull() throws Exception { checkTranslation("empno is not null"); } // FIXME /* public void testDynamicParam() throws Exception { checkTranslation("empno + ?"); } */ public void testUser() throws Exception { checkTranslation("user"); } public void testCurrentUser() throws Exception { checkTranslation("current_user"); } public void testSessionUser() throws Exception { checkTranslation("session_user"); } public void testSystemUser() throws Exception { checkTranslation("system_user"); } public void testCurrentDate() throws Exception { checkTranslation("current_date"); } public void testCurrentTime() throws Exception { checkTranslation("current_time"); } public void testCurrentTimestamp() throws Exception { checkTranslation("current_timestamp"); } public void testCurrentPath() throws Exception { checkTranslation("current_path"); } public void testJavaUdfInvocation() throws Exception { checkTranslation("sales.decrypt_public_key(public_key)"); } public void testSqlUdfInvocation() throws Exception { checkTranslation("sales.maybe_female(gender)"); } // FIXME /* public void testCastNullToPrimitive() throws Exception { // FIXME: should take cast(null as int) checkTranslation("cast(null as integer)"); } */ // FIXME /* public void testCastNullToVarchar() throws Exception { checkTranslation("cast(null as varchar(10))"); } */ public void testCastToVarcharImplicitTruncate() throws Exception { checkTranslation( "cast('supercalifragilistiexpialodocious' as varchar(10))"); } public void testCastToVarchar() throws Exception { checkTranslation("cast('boo' as varchar(10))"); } // TODO (depends on dtbug 79) /* public void testCastToCharImplicitPad() throws Exception { checkTranslation( "cast('boo' as char(10))"); } */ // TODO (depends on dtbug 79) /* public void testCastToCharExact() throws Exception { checkTranslation( "cast('0123456789' as char(10))"); } */ // TODO (depends on dtbug 79) /* public void testCastToBinaryImplicitPad() throws Exception { checkTranslation( "cast(x'58797A' as binary(10))"); } */ public void testCastToVarbinaryImplicitTruncate() throws Exception { checkTranslation("cast(x'00112233445566778899AABB' as varbinary(10))"); } public void testCastIntToVarchar() throws Exception { checkTranslation("cast(cast(null as tinyint) as varchar(30))"); } // TODO jvs 22-June-2004: figure out a way to test codegen for // assignment of nullable value to NOT NULL field // // start Case test cases. // // public void testCaseNotNullableCondWithElse() throws Exception { checkTranslation( "case manager when true then 'Yes' when false then 'No' else 'Other' end"); } public void testCaseNotNullableCondWithoutElse() throws Exception { checkTranslation("case deptno when 10 then 'Yes' end"); } public void testCaseNullableCondWithElse() throws Exception { checkTranslation( "case age when 50 then 'fifty' when 25 then 'twenty-five' end"); } public void testCaseNullableCondWithoutElse() throws Exception { checkTranslation("case gender when 'M' then 'Yes' end"); } public void testCaseNotNullableCondWithElsePrimitive() throws Exception { checkTranslation("case empno when 120 then 1 else 2 end"); } public void testCaseNotNullableCondWithoutElsePrimitive() throws Exception { checkTranslation( "case name when 'Fred' then 1 when 'Eric' then 2 when 'Wilma' then 3 when 'John' then 4 end"); } public void testCaseNullableCondWithElsePrimitive() throws Exception { checkTranslation( "case deptno when 10 then 1 when 20 then 2 when 40 then 3 else 4 end"); } public void testCaseNullableCondWithoutElsePrimitive() throws Exception { checkTranslation("case slacker when true then 1 end"); } public void testCommonReusePreviousWhen() throws Exception { // At the second occurrence of 'empid * 2', the first occurrence has // definitely been evaluated, so it is safe to re-use it. checkTranslation( "case\n" + " when empid > 50 then 1\n" + " when empid * 2 > 50 then 2\n" + " when empid + 3 > 50 then 3\n" + " when 1 + empid * 2 > 40 then 4\n" + " else 5\n" + "end"); } public void testCommonReusePrevious() throws Exception { // At the second occurrence of 'empid * 2', the first occurrence has // definitely been evaluated, so it is safe to re-use it. checkTranslation( "(empid * 2)\n" + "+\n" + "case\n" + " when empid > 50 then 1\n" + " when empid * 2 > 50 then 2\n" + " else 5\n" + "end"); } public void testCommonCannotReusePrevious() throws Exception { // At the second occurrence of 'empid * 2', the first occurrence may // or may not have been evaluated, so it is not safe to re-use it. // The third occurrence can re-use the second. checkTranslation( "case\n" + " when empid > 50 then empid * 2\n" + " else 100\n" + "end\n" + "+\n" + "case\n" + " when empid > 50 then 1\n" + " when empid * 2 > 50 then 2\n" + " else empid * 2\n" + "end"); } public void testCommonReusePreviousFirstWhen() throws Exception { // At the second occurrence of 'empid * 2', the first occurrence has // definitely been evaluated, because it was in the first WHEN clause of // a CASE, so it is not safe to re-use it. // The third occurrence can re-use the second. checkTranslation( "case\n" + " when empid * 2 > 50 then 2\n" + " else 100\n" + "end\n" + "+\n" + "case\n" + " when empid > 50 then 1\n" + " when empid * 2 > 50 then 2\n" + " else empid * 2\n" + "end"); } public void testCommonCannotReuseThen() throws Exception { // At the second and third occurrences of 'empid * 2', the first // occurrence has definitely not been evaluated. The fourth and fifth // can re-use the third. checkTranslation( "case\n" + " when empid > 50 then empid * 2\n" + " when empid > 70 then 1 + empid * 2\n" + " when empid * 2 > 70 then 2 + empid * 2\n" + " else 3 + empid * 2\n" + "end"); } public void testSubstringNullableLength() throws Exception { checkTranslation("substring(city, 2, age/10)"); } public void testSubstringNullablePosition() throws Exception { checkTranslation("substring(city, age/20, empid)"); } public void testSubstringNoLength() throws Exception { checkTranslation("substring(city, 3)"); } public void testSubstringPositionLessThanZero() throws Exception { checkTranslation("substring(city, -1, 4)"); } public void testSubstringPositionZero() throws Exception { checkTranslation("substring(city, 0, 4)"); } public void testSubstringNegativeLength() throws Exception { checkTranslation("substring(city, 1, empid - 2)"); } public void testSubstringNothingNullable() throws Exception { checkTranslation("substring(name, 2, empid)"); } public void testConcatNoNullable() throws Exception { checkTranslation("name||name"); } public void testConcatWithOneNullable() throws Exception { checkTranslation("city||name"); } public void testConcatBothNullable() throws Exception { checkTranslation("city||city"); } public void testOverlayNoLength() throws Exception { checkTranslation("overlay(city placing 'MIDDLE' from 2)"); } public void testOverlayNullable() throws Exception { checkTranslation("overlay(city placing 'MIDDLE' from 2 for 3)"); } public void testOverlayNoNullable() throws Exception { checkTranslation("overlay(name placing 'MIDDLE' from 2 for 3)"); } public void testOverlayThreeNullable() throws Exception { checkTranslation("overlay(city placing name from age for age)"); } public void testOverlayAllNullable() throws Exception { checkTranslation("overlay(city placing gender from age for age)"); } public void testPower() throws Exception { checkTranslation("power(2, empid)"); } public void testMod() throws Exception { checkTranslation("mod(age, 3)"); } public void testTrimBoth() throws Exception { checkTranslation("trim(both 'S' from city)"); } public void testTrimLeading() throws Exception { checkTranslation("trim(leading 'W' from name)"); } public void testTrimTrailing() throws Exception { checkTranslation("trim(trailing 'c' from name)"); } public void testUpper() throws Exception { checkTranslation("upper(city)"); } public void testLower() throws Exception { checkTranslation("Lower(city)"); } public void testInitcap() throws Exception { checkTranslation("initcap(city)"); } public void testCharLength() throws Exception { checkTranslation("char_length(city)"); } public void testCharacterLength() throws Exception { checkTranslation("character_length(city)"); } public void testPosition() throws Exception { checkTranslation("position('Fran' in city)"); } public void testLikeLiteral() throws Exception { checkTranslation("City like 'San%'"); } public void testLikeRuntime() throws Exception { checkTranslation("City like Name"); } public void testLikeLiteralWithEscape() throws Exception { checkTranslation("City like 'San%' escape 'n'"); } public void testLikeRuntimeWithEscape() throws Exception { checkTranslation("City like Name escape 'n'"); } public void testSimilarLiteral() throws Exception { checkTranslation("City similar to '[S][[:ALPHA:]]n%'"); } public void testSimilarRuntime() throws Exception { checkTranslation("City similar to Name"); } public void testSimilarLiteralWithEscape() throws Exception { checkTranslation("City similar to 'San%' escape 'n'"); } public void testSimilarRuntimeWithEscape() throws Exception { checkTranslation("City similar to Name escape 'n'"); } public void testQuery() throws Exception { // Check the translation to make sure that: // 'deptno + 4' from WHERE clause is re-used in B and D; // 'empid * 3' from A is reused in D; // 'deptno * 7' from C is NOT reused in D (it's not computed on all // paths). // // Since 'deptno * 7' is always used, it would be better if we always // computed it. But we don't currently. checkQueryTranslation( "select empid * 3 * 2 as a,\n" + " deptno + 4 + 6 as b,\n" + " case when 1 = 1 then deptno * 7 else 0 end as c,\n" + " deptno + 4 + empid * 3 + 1 + deptno * 7 as d\n" + "from sales.emps\n" + "where deptno + 4 > 10"); } public void testQueryOr() throws Exception { // Check that: // 'deptno + 1' is re-used later in WHERE and also in A // 'empno + 2' is NOT re-used in B // '100 / (deptno + 1)' is not evaluated if 'deptno + 1 = 0' has // previously evaluated true // // Some bad things we're living with: // * 'oj_var6.value / 10.0d' occurs mulitple times; // * the sqrt ('oj_var7 = pow ...') occurs unconditionally. checkQueryTranslation( "select deptno + 1 as a,\n" + " empno + 2 as b\n" + "from sales.emps\n" + "where deptno + 1 < 0\n" + " or 100 / (deptno + 1) < 5 / sqrt(deptno + 1)"); } } // End FarragoRexToOJTranslatorTest.java
/* * Copyright 2015-2020 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.pinpoint.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.pinpoint.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetCampaignsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetCampaignsRequestProtocolMarshaller implements Marshaller<Request<GetCampaignsRequest>, GetCampaignsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/v1/apps/{application-id}/campaigns").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false) .serviceName("AmazonPinpoint").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetCampaignsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetCampaignsRequest> marshall(GetCampaignsRequest getCampaignsRequest) { if (getCampaignsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetCampaignsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, getCampaignsRequest); protocolMarshaller.startMarshalling(); GetCampaignsRequestMarshaller.getInstance().marshall(getCampaignsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
// Copyright 2016 Google 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. /** * PolicyViolationErrorPart.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201609.cm; /** * Points to a substring within an ad field or criterion. */ public class PolicyViolationErrorPart implements java.io.Serializable { /* Index of the starting position of the violating text within * the line. */ private java.lang.Integer index; /* The length of the violating text. */ private java.lang.Integer length; public PolicyViolationErrorPart() { } public PolicyViolationErrorPart( java.lang.Integer index, java.lang.Integer length) { this.index = index; this.length = length; } @Override public String toString() { return com.google.common.base.MoreObjects.toStringHelper(this.getClass()) .omitNullValues() .add("index", getIndex()) .add("length", getLength()) .toString(); } /** * Gets the index value for this PolicyViolationErrorPart. * * @return index * Index of the starting position of the violating text within * the line. */ public java.lang.Integer getIndex() { return index; } /** * Sets the index value for this PolicyViolationErrorPart. * * @param index * Index of the starting position of the violating text within * the line. */ public void setIndex(java.lang.Integer index) { this.index = index; } /** * Gets the length value for this PolicyViolationErrorPart. * * @return length * The length of the violating text. */ public java.lang.Integer getLength() { return length; } /** * Sets the length value for this PolicyViolationErrorPart. * * @param length * The length of the violating text. */ public void setLength(java.lang.Integer length) { this.length = length; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof PolicyViolationErrorPart)) return false; PolicyViolationErrorPart other = (PolicyViolationErrorPart) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.index==null && other.getIndex()==null) || (this.index!=null && this.index.equals(other.getIndex()))) && ((this.length==null && other.getLength()==null) || (this.length!=null && this.length.equals(other.getLength()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getIndex() != null) { _hashCode += getIndex().hashCode(); } if (getLength() != null) { _hashCode += getLength().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(PolicyViolationErrorPart.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201609", "PolicyViolationError.Part")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("index"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201609", "index")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("length"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201609", "length")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
/** * Copyright (C) 2010-2012, FuseSource Corp. All rights reserved. * * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.mqtt.android.codec; import org.fusesource.mqtt.android.codec.MessageSupport.Message; import java.net.ProtocolException; /** * <p> * </p> * * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ public class PINGREQ extends MessageSupport.EmptyBase implements Message { public static final byte TYPE = 12; public byte messageType() { return TYPE; } @Override public PINGREQ decode(MQTTFrame frame) throws ProtocolException { return (PINGREQ) super.decode(frame); } @Override public String toString() { return "PINGREQ"; } }
package com.example.android.miwok; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class FamilyActivity extends AppCompatActivity { MediaPlayer mediaPlayer = null; private AudioManager audioManager; private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener(){ @Override public void onAudioFocusChange(int focusChange){ if (focusChange==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT||focusChange==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){ setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer.release(); }else if (focusChange == AudioManager.AUDIOFOCUS_GAIN){ mediaPlayer.start(); }else if (focusChange == AudioManager.AUDIOFOCUS_LOSS){ mediaPlayer.release(); mediaPlayer = null; } } }; private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { releaseMediaPlayer(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); final ArrayList<Word> words = new ArrayList<>(); words.add(new Word("father","epe",R.drawable.family_father,R.raw.family_father)); words.add(new Word("mother","eta",R.drawable.family_mother,R.raw.family_mother)); words.add(new Word("son","angsi",R.drawable.family_son,R.raw.family_son)); words.add(new Word("daughter","tune",R.drawable.family_daughter,R.raw.family_daughter)); words.add(new Word("older brother","taachi",R.drawable.family_older_brother,R.raw.family_older_brother)); words.add(new Word("younger brother","chalitti",R.drawable.family_younger_brother,R.raw.family_younger_brother)); words.add(new Word("older sister","tete",R.drawable.family_older_sister,R.raw.family_older_sister)); words.add(new Word("younger sister","kolliti",R.drawable.family_younger_sister,R.raw.family_younger_sister)); words.add(new Word("grandmother","ama",R.drawable.family_grandmother,R.raw.family_grandmother)); words.add(new Word("grandfather","paapa",R.drawable.family_grandfather,R.raw.family_grandfather)); WordAdapter adapter = new WordAdapter (this, words,R.color.category_family); ListView listView = (ListView) findViewById(R.id.list); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Word word = words.get(i); releaseMediaPlayer(); int result = audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaPlayer = MediaPlayer.create(FamilyActivity.this, word.getSoundId()); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(mCompletionListener); } } }); } @Override protected void onStop() { super.onStop(); releaseMediaPlayer(); } private void releaseMediaPlayer() { if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; audioManager.abandonAudioFocus(audioFocusChangeListener); } } }
package de.dytanic.cloudnet.ext.bridge.velocity; import com.google.inject.Inject; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.event.proxy.ProxyShutdownEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.server.ServerInfo; import de.dytanic.cloudnet.driver.CloudNetDriver; import de.dytanic.cloudnet.driver.service.ServiceInfoSnapshot; import de.dytanic.cloudnet.driver.service.ServiceLifeCycle; import de.dytanic.cloudnet.ext.bridge.BridgePlayerManager; import de.dytanic.cloudnet.ext.bridge.listener.BridgeCustomChannelMessageListener; import de.dytanic.cloudnet.ext.bridge.player.IPlayerManager; import de.dytanic.cloudnet.ext.bridge.proxy.BridgeProxyHelper; import de.dytanic.cloudnet.ext.bridge.velocity.command.CommandCloudNet; import de.dytanic.cloudnet.ext.bridge.velocity.command.CommandHub; import de.dytanic.cloudnet.ext.bridge.velocity.listener.VelocityCloudNetListener; import de.dytanic.cloudnet.ext.bridge.velocity.listener.VelocityPlayerListener; import de.dytanic.cloudnet.wrapper.Wrapper; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; @Plugin(id = "cloudnet_bridge_velocity") public final class VelocityCloudNetBridgePlugin { private static VelocityCloudNetBridgePlugin instance; private final ProxyServer proxyServer; @Inject public VelocityCloudNetBridgePlugin(ProxyServer proxyServer) { CloudNetDriver.getInstance().getServicesRegistry().registerService(IPlayerManager.class, "BridgePlayerManager", new BridgePlayerManager()); instance = this; this.proxyServer = proxyServer; VelocityCloudNetHelper.setProxyServer(proxyServer); } public static VelocityCloudNetBridgePlugin getInstance() { return VelocityCloudNetBridgePlugin.instance; } @Subscribe public void handleProxyInit(ProxyInitializeEvent event) { this.initListeners(); this.registerCommands(); this.initServers(); this.runPlayerDisconnectTask(); } @Subscribe public void handleShutdown(ProxyShutdownEvent event) { CloudNetDriver.getInstance().getEventManager().unregisterListeners(this.getClass().getClassLoader()); Wrapper.getInstance().unregisterPacketListenersByClassLoader(this.getClass().getClassLoader()); } private void runPlayerDisconnectTask() { this.proxyServer.getScheduler().buildTask(this, () -> { if (VelocityCloudNetHelper.getLastOnlineCount() != -1 && this.proxyServer.getPlayerCount() != VelocityCloudNetHelper.getLastOnlineCount()) { Wrapper.getInstance().publishServiceInfoUpdate(); } }).repeat(500, TimeUnit.MILLISECONDS).schedule(); } private void initListeners() { //Velocity API this.proxyServer.getEventManager().register(this, new VelocityPlayerListener(this)); //CloudNet CloudNetDriver.getInstance().getEventManager().registerListener(new VelocityCloudNetListener()); CloudNetDriver.getInstance().getEventManager().registerListener(new BridgeCustomChannelMessageListener()); } private void registerCommands() { this.proxyServer.getCommandManager().register(new CommandCloudNet(), "cloudnet", "cloud", "cl"); this.proxyServer.getCommandManager().register(new CommandHub(), "hub", "l", "leave", "lobby"); } private void initServers() { for (ServiceInfoSnapshot serviceInfoSnapshot : CloudNetDriver.getInstance().getCloudServiceProvider().getCloudServices()) { if (serviceInfoSnapshot.getServiceId().getEnvironment().isMinecraftJavaServer()) { if ((serviceInfoSnapshot.getProperties().contains("Online-Mode") && serviceInfoSnapshot.getProperties().getBoolean("Online-Mode")) || serviceInfoSnapshot.getLifeCycle() != ServiceLifeCycle.RUNNING) { continue; } String name = serviceInfoSnapshot.getServiceId().getName(); proxyServer.registerServer(new ServerInfo(name, new InetSocketAddress( serviceInfoSnapshot.getAddress().getHost(), serviceInfoSnapshot.getAddress().getPort() ))); BridgeProxyHelper.cacheServiceInfoSnapshot(serviceInfoSnapshot); VelocityCloudNetHelper.addServerToVelocityPrioritySystemConfiguration(serviceInfoSnapshot, name); } } } public ProxyServer getProxyServer() { return this.proxyServer; } }
/* * Copyright (c) 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.encrypt; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.ArrayList; import java.util.List; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import oracle.weblogic.deploy.logging.PlatformLogger; import oracle.weblogic.deploy.logging.WLSDeployLogFactory; import oracle.weblogic.deploy.util.StringUtils; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; /** * This class provides basic encryption/decryption capabilities. */ public final class EncryptionUtils { private static final String CLASS = EncryptionUtils.class.getName(); private static final PlatformLogger LOGGER = WLSDeployLogFactory.getLogger("wlsdeploy.encrypt"); private static final String SECRET_KEY_FACTORY_ALGORITHM = "PBKDF2WithHmacSHA256"; private static final String SECRET_KEY_SPEC_ALGORITHM = "AES"; private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding"; private static final String CIPHER_TEXT_PREFIX = "{AES}"; private static final String SEP = ":"; private static final int ITERATIONS = 65536; private static final int AES_KEY_SIZE = 128; private static final int GCM_NONCE_LENGTH = 12; private static final int GCM_TAG_LENGTH = 16; private static final int SALT_SIZE = 8; private static final int BITS_PER_BYTE = 8; private static final int CIPHER_SECTIONS = 3; private static final int PWD_POS = 0; private static final int NONCE_POS = 1; private static final int SALT_POS = 2; private static final SecureRandom RANDOM = new SecureRandom(); private EncryptionUtils() { // hide the constructor for this utility class } /** * Determines whether or not a string is already encrypted. * * @param text the string to check * @return whether or not the string is already encrypted, * false is always returned for zero length or null strings */ public static boolean isEncryptedString(String text) { return !StringUtils.isEmpty(text) && text.startsWith(CIPHER_TEXT_PREFIX); } /** * Get the unencrypted characters from an encrypted string. * * @param cipherText the encrypted string * @param userPassphrase the passphrase used to encrypt the string * @return the unencrypted characters * @throws EncryptionException if an error occurs while decrypting the string */ public static char[] decryptString(String cipherText, final char[] userPassphrase) throws EncryptionException { final String METHOD = "decryptString"; if (userPassphrase == null || userPassphrase.length == 0) { EncryptionException ee = new EncryptionException("WLSDPLY-04000"); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } char[] result = null; if (!StringUtils.isEmpty(cipherText)) { List<byte[]> parts = getCipherComponents(cipherText); if (parts.size() == CIPHER_SECTIONS) { byte[] cipherFodder = parts.remove(0); byte[] nonce = parts.remove(0); byte[] salt = parts.remove(0); SecretKey key = getKey(userPassphrase, salt); Cipher cipher = getCipher(); try { cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_LENGTH * BITS_PER_BYTE, nonce)); result = new String(cipher.doFinal(cipherFodder), UTF_8).toCharArray(); } catch (InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { EncryptionException ee = new EncryptionException("WLSDPLY-04001", ex, ex.getLocalizedMessage()); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } } } return result; } /** * Get the encrypted string for the specified characters. * * @param clearText the characters to encrypt * @param userPassphrase the passphrase to use for encryption/decryption * @return the encrypted string * @throws EncryptionException if an error occurs while encrypting the characters */ public static String encryptString(String clearText, final char[] userPassphrase) throws EncryptionException { final String METHOD = "encryptString"; if (userPassphrase == null || userPassphrase.length == 0) { EncryptionException ee = new EncryptionException("WLSDPLY-04000"); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } String result = clearText; if (!StringUtils.isEmpty(clearText)) { final byte[] salt = new byte[SALT_SIZE]; RANDOM.nextBytes(salt); SecretKey key = getKey(userPassphrase, salt); Cipher cipher = getCipher(); try { final byte[] nonce = new byte[GCM_NONCE_LENGTH]; RANDOM.nextBytes(nonce); GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * BITS_PER_BYTE, nonce); cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] encrypted = cipher.doFinal(clearText.getBytes(UTF_8)); result = getEncryptedString(encrypted, nonce, salt); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) { EncryptionException ee = new EncryptionException("WLSDPLY-04002", ex, ex.getLocalizedMessage()); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } } return result; } private static SecretKey getKey(final char[] userPassphrase, byte[] saltBytes) throws EncryptionException { final String METHOD = "getKey"; SecretKeyFactory factory; try { factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM); } catch (NoSuchAlgorithmException nsae) { EncryptionException ee = new EncryptionException("WLSDPLY-04003", nsae, nsae.getLocalizedMessage()); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } SecretKey result; KeySpec spec = new PBEKeySpec(userPassphrase, saltBytes, ITERATIONS, AES_KEY_SIZE); try { SecretKey tmp = factory.generateSecret(spec); result = new SecretKeySpec(tmp.getEncoded(), SECRET_KEY_SPEC_ALGORITHM); } catch (InvalidKeySpecException ikse) { EncryptionException ee = new EncryptionException("WLSDPLY-04004", ikse, ikse.getLocalizedMessage()); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } return result; } private static Cipher getCipher() throws EncryptionException { final String METHOD = "getCipher"; Cipher cipher; try { cipher = Cipher.getInstance(CIPHER_ALGORITHM); } catch (NoSuchPaddingException | NoSuchAlgorithmException ex) { EncryptionException ee = new EncryptionException("WLSDPLY-04005", ex, ex.getLocalizedMessage()); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } return cipher; } private static String getEncryptedString(byte[] cipher, byte[] nonce, byte[] salt) { String cipherEncoded = DatatypeConverter.printBase64Binary(cipher); String nonceEncoded = DatatypeConverter.printBase64Binary(nonce); String saltEncoded = DatatypeConverter.printBase64Binary(salt); String all = cipherEncoded + SEP + nonceEncoded + SEP + saltEncoded; String allEncoded = DatatypeConverter.printBase64Binary(all.getBytes(US_ASCII)); return CIPHER_TEXT_PREFIX + allEncoded; } private static List<byte[]> getCipherComponents(String text) throws EncryptionException { final String METHOD = "getCipherComponents"; List<byte[]> result = new ArrayList<>(); if (text.startsWith(CIPHER_TEXT_PREFIX) && text.length() > CIPHER_TEXT_PREFIX.length()) { String all = text.substring(CIPHER_TEXT_PREFIX.length()); String allDecoded = new String(DatatypeConverter.parseBase64Binary(all), US_ASCII); String[] parts = allDecoded.split(SEP); if (parts.length != CIPHER_SECTIONS) { EncryptionException ee = new EncryptionException("WLSDPLY-04006", parts.length); LOGGER.throwing(CLASS, METHOD, ee); throw ee; } result.add(DatatypeConverter.parseBase64Binary(parts[PWD_POS])); result.add(DatatypeConverter.parseBase64Binary(parts[NONCE_POS])); result.add(DatatypeConverter.parseBase64Binary(parts[SALT_POS])); } return result; } }
package company.tap.gosellapi.internal.interfaces; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import company.tap.gosellapi.internal.api.enums.TransactionMode; import company.tap.gosellapi.internal.api.models.AuthorizeAction; import company.tap.gosellapi.internal.api.models.Receipt; import company.tap.gosellapi.internal.api.models.Reference; import company.tap.gosellapi.internal.api.models.Shipping; import company.tap.gosellapi.internal.api.models.Tax; import company.tap.gosellapi.open.models.Customer; import company.tap.gosellapi.open.models.PaymentItem; /** * The interface Go sell payment data source. */ public interface GoSellPaymentDataSource { /** * Transaction currency. @return the currency */ @NonNull String getCurrency(); /** * Customer. @return the customer */ @NonNull Customer getCustomer(); /** * Amount. Either amount or items should return nonnull value. If both return nonnull, then items is preferred. @return the amount */ @Nullable BigDecimal getAmount(); /** * List of items to pay for. Either amount or items should return nonnull value. If both return nonnull, then items is preferred. @return the items */ @Nullable ArrayList<PaymentItem> getItems(); /** * Transaction mode. If you return null in this method, it will be treated as PURCHASE. @return the transaction mode */ @Nullable TransactionMode getTransactionMode(); /** * List of taxes. Optional. Note: specifying taxes will affect total payment amount. @return the taxes */ @Nullable ArrayList<Tax> getTaxes(); /** * Shipping list. Optional. Note: specifying shipping will affect total payment amount. @return the shipping */ @Nullable ArrayList<Shipping> getShipping(); /** * Tap will post to this URL after transaction finishes. Optional. @return the post url */ @Nullable String getPostURL(); /** * Description of the payment. @return the payment description */ @Nullable String getPaymentDescription(); /** * If you would like to pass additional information with the payment, pass it here. @return the payment metadata */ @Nullable HashMap<String, String> getPaymentMetadata(); /** * Payment reference. Implement this property to keep a reference to the transaction on your backend. @return the payment reference */ @Nullable Reference getPaymentReference(); /** * Payment statement descriptor. @return the payment statement descriptor */ @Nullable String getPaymentStatementDescriptor(); /** * Defines if 3D secure check is required. @return the requires 3 d secure */ @Nullable boolean getRequires3DSecure(); /** * Receipt dispatch settings. @return the receipt settings */ @Nullable Receipt getReceiptSettings(); /** * Action to perform after authorization succeeds. Used only if transaction mode is AUTHORIZE_CAPTURE. @return the authorize action */ @Nullable AuthorizeAction getAuthorizeAction(); }
package org.opencb.hpg.bigdata.analysis.variant.statistics; public class FisherTestResult { private double oddRatio; private double pValue; public FisherTestResult(double pValue, double oddRatio) { this.pValue = pValue; this.oddRatio = oddRatio; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(pValue).append("\t").append(oddRatio).append("\t"); return sb.toString(); } public void setOddRatio(double oddRatio) { this.oddRatio = oddRatio; } public double getOddRatio() { return oddRatio; } public void setPValue(double pValue) { this.pValue = pValue; } public double getPValue() { return pValue; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.query; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.metrics2.sink.timeline.Precision; import org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.aggregators.Function; import static org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.query.PhoenixTransactSQL.NATIVE_TIME_RANGE_DELTA; import java.util.List; public class TopNCondition extends DefaultCondition{ private Integer topN; private boolean isBottomN; private Function topNFunction; private static final Log LOG = LogFactory.getLog(TopNCondition.class); public TopNCondition(List<String> metricNames, List<String> hostnames, String appId, String instanceId, Long startTime, Long endTime, Precision precision, Integer limit, boolean grouped, Integer topN, Function topNFunction, boolean isBottomN) { super(metricNames, hostnames, appId, instanceId, startTime, endTime, precision, limit, grouped); this.topN = topN; this.isBottomN = isBottomN; this.topNFunction = topNFunction; } @Override public StringBuilder getConditionClause() { StringBuilder sb = new StringBuilder(); boolean appendConjunction = false; if (isTopNHostCondition(metricNames, hostnames)) { appendConjunction = appendMetricNameClause(sb); StringBuilder hostnamesCondition = new StringBuilder(); hostnamesCondition.append(" HOSTNAME IN ("); hostnamesCondition.append(getTopNInnerQuery()); hostnamesCondition.append(")"); appendConjunction = append(sb, appendConjunction, getHostnames(), hostnamesCondition.toString()); } else if (isTopNMetricCondition(metricNames, hostnames)) { StringBuilder metricNamesCondition = new StringBuilder(); metricNamesCondition.append(" METRIC_NAME IN ("); metricNamesCondition.append(getTopNInnerQuery()); metricNamesCondition.append(")"); appendConjunction = append(sb, appendConjunction, getMetricNames(), metricNamesCondition.toString()); appendConjunction = appendHostnameClause(sb, appendConjunction); } else { LOG.error("Unsupported TopN Operation requested. Query can have either multiple hosts or multiple metric names " + "but not both."); return null; } appendConjunction = append(sb, appendConjunction, getAppId(), " APP_ID = ?"); appendConjunction = append(sb, appendConjunction, getInstanceId(), " INSTANCE_ID = ?"); appendConjunction = append(sb, appendConjunction, getStartTime(), " SERVER_TIME >= ?"); append(sb, appendConjunction, getEndTime(), " SERVER_TIME < ?"); return sb; } public String getTopNInnerQuery() { String innerQuery = null; if (isTopNHostCondition(metricNames, hostnames)) { String groupByClause = "METRIC_NAME, HOSTNAME, APP_ID"; String orderByClause = getTopNOrderByClause(); innerQuery = String.format(PhoenixTransactSQL.TOP_N_INNER_SQL, PhoenixTransactSQL.getNaiveTimeRangeHint(getStartTime(), NATIVE_TIME_RANGE_DELTA), "HOSTNAME", PhoenixTransactSQL.getTargetTableUsingPrecision(precision, true), super.getConditionClause().toString(), groupByClause, orderByClause, topN); } else if (isTopNMetricCondition(metricNames, hostnames)) { String groupByClause = "METRIC_NAME, APP_ID"; String orderByClause = getTopNOrderByClause(); innerQuery = String.format(PhoenixTransactSQL.TOP_N_INNER_SQL, PhoenixTransactSQL.getNaiveTimeRangeHint(getStartTime(), NATIVE_TIME_RANGE_DELTA), "METRIC_NAME", PhoenixTransactSQL.getTargetTableUsingPrecision(precision, (hostnames != null && hostnames.size() == 1)), super.getConditionClause().toString(), groupByClause, orderByClause, topN); } return innerQuery; } private String getTopNOrderByClause() { String orderByClause = null; if (topNFunction != null) { switch (topNFunction.getReadFunction()) { case AVG: orderByClause = "ROUND(AVG(METRIC_SUM),2)"; break; case SUM: orderByClause = "SUM(METRIC_SUM)"; break; default: orderByClause = "MAX(METRIC_MAX)"; break; } } if (orderByClause == null) { orderByClause = "MAX(METRIC_MAX)"; } if (!isBottomN) { orderByClause += " DESC"; } return orderByClause; } public boolean isTopNHostCondition() { return isTopNHostCondition(metricNames, hostnames); } public boolean isTopNMetricCondition() { return isTopNMetricCondition(metricNames, hostnames); } /** * Check if this is a case of Top N hosts condition * @param metricNames A list of Strings. * @param hostnames A list of Strings. * @return True if it is a Case of Top N Hosts (1 Metric and H hosts). */ public static boolean isTopNHostCondition(List<String> metricNames, List<String> hostnames) { // Case 1 : 1 Metric, H hosts // Select Top N or Bottom N host series based on 1 metric (max/avg/sum) // Hostnames cannot be empty // Only 1 metric allowed, without wildcards return (CollectionUtils.isNotEmpty(hostnames) && metricNames.size() == 1 && !metricNamesHaveWildcard(metricNames)); } /** * Check if this is a case of Top N metrics condition * @param metricNames A list of Strings. * @param hostnames A list of Strings. * @return True if it is a Case of Top N Metrics (M Metric and 1 or 0 host). */ public static boolean isTopNMetricCondition(List<String> metricNames, List<String> hostnames) { // Case 2 : M Metric names or Regex, 1 or No host // Select Top N or Bottom N metric series based on metric values(max/avg/sum) // MetricNames cannot be empty // No host (aggregate) or 1 host allowed, without wildcards return (CollectionUtils.isNotEmpty(metricNames) && (hostnames == null || hostnames.size() <= 1) && !hostNamesHaveWildcard(hostnames)); } public Integer getTopN() { return topN; } public void setTopN(Integer topN) { this.topN = topN; } public boolean isBottomN() { return isBottomN; } public void setIsBottomN(boolean isBottomN) { this.isBottomN = isBottomN; } public Function getTopNFunction() { return topNFunction; } public void setTopNFunction(Function topNFunction) { this.topNFunction = topNFunction; } }
package io.subutai.common.util; import org.junit.Test; import org.apache.commons.net.util.SubnetUtils; import static junit.framework.TestCase.assertEquals; public class SubnetUtilsTest { @Test public void testIp() { SubnetUtils utils = new SubnetUtils( "10.12.0.1/24" ); final SubnetUtils.SubnetInfo info = utils.getInfo(); assertEquals( "10.12.0.1", info.getAddress() ); assertEquals( "10.12.0.0", info.getNetworkAddress() ); assertEquals( "10.12.0.255", info.getBroadcastAddress() ); assertEquals( 254, info.getAddressCount() ); assertEquals( "10.12.0.1/24", info.getCidrSignature() ); assertEquals( "10.12.0.1", info.getLowAddress() ); assertEquals( "10.12.0.254", info.getHighAddress() ); assertEquals( "255.255.255.0", info.getNetmask() ); assertEquals( true, info.isInRange( "10.12.0.100" ) ); assertEquals( false, info.isInRange( "10.11.0.1" ) ); } }
/* Copyright 2002-2021 CS GROUP * Licensed to CS GROUP (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.estimation.measurements.gnss; import org.hipparchus.util.FastMath; import org.orekit.gnss.Frequency; import org.orekit.gnss.MeasurementType; import org.orekit.gnss.SatelliteSystem; /** * Geometry-free combination. * <p> * This combination removes the geometry part of the measurement. * It can be used to estimate the ionospheric electron content or to detect * cycle slips in the carrier phase, as well. * </p> * <pre> * mGF = m2 - m1 * </pre> * With: * <ul> * <li>mGF: Geometry-free measurement.</li> * <li>m1 : First measurement.</li> * <li>m2 : Second measurement.</li> * </ul> * <p> * Geometry-Free combination is a dual frequency combination. * The two measurements shall have different frequencies but they must have the same {@link MeasurementType}. * </p> * @author Bryan Cazabonne * @since 10.1 */ public class GeometryFreeCombination extends AbstractDualFrequencyCombination { /** * Package private constructor for the factory. * @param system satellite system for which the combination is applied */ GeometryFreeCombination(final SatelliteSystem system) { super(CombinationType.GEOMETRY_FREE, system); } /** {@inheritDoc} */ @Override protected double getCombinedValue(final double obs1, final Frequency f1, final double obs2, final Frequency f2) { // Combined observed value does not depend on frequency for the Geometry-Free combination return FastMath.abs(obs2 - obs1); } /** {@inheritDoc} */ @Override protected double getCombinedFrequency(final Frequency f1, final Frequency f2) { // There is not combined frequency for the Geometry-Free combination return Double.NaN; } }
package com.alyrow.gdx.particle.physics; import com.badlogic.gdx.math.Vector2; /** * @author alyrow * Linear force */ public class LinearForce extends PhysicForce { /** * Linear force * @param vx x axis intensity * @param vy y axis intensity */ public LinearForce(float vx, float vy) { this.vx = vx; this.vy = vy; force = new Vector2(vx, vy); } }
package com.arcare.oauth.po; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the client_type database table. * */ @Entity @Table(name="client_type") @NamedQuery(name="ClientType.findAll", query="SELECT c FROM ClientType c") public class ClientType implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(unique=true, nullable=false) private Integer id; @Column(name="client_name", length=50) private String clientName; @Column(name="client_type", length=50) private String clientType; public ClientType() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getClientName() { return this.clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public String getClientType() { return this.clientType; } public void setClientType(String clientType) { this.clientType = clientType; } }
package net.minecraft.client.renderer.entity.model; import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.util.HandSide; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public interface IHasArm { void translateHand(HandSide sideIn, MatrixStack matrixStackIn); }
/* * ============LICENSE_START======================================================= * DCAEGEN2-SERVICES-SDK * ================================================================================ * Copyright (C) 2019 Nokia. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.dcaegen2.services.sdk.services.hvves.client.producer.ct; import static org.assertj.core.api.Assertions.assertThat; import io.netty.buffer.ByteBuf; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.onap.dcaegen2.services.sdk.services.hvves.client.producer.api.options.PayloadType; import org.onap.ves.MeasDataCollectionOuterClass; import org.onap.ves.VesEventOuterClass.CommonEventHeader; import org.onap.ves.VesEventOuterClass.VesEvent; import reactor.core.publisher.Flux; import java.time.Duration; /** * @author <a href="mailto:piotr.jaszczyk@nokia.com">Piotr Jaszczyk</a> */ class HvVesProducerIT { private static final int INFO_ID = 17; private static final long VALUE = 5l; private static final int MEAS_TYPE = 3; private static final int PERIOD = 1000; private static final String OBJECT_INSTANCE_ID = "DH-1"; private final SystemUnderTestWrapper sut = new SystemUnderTestWrapper(Duration.ofSeconds(10)); @AfterEach void tearDown() { sut.stop(); } @Test void singleMessageTest_withUnsecureConnection() throws Exception { // given final VesEvent sampleEvent = createSimpleVesEvent(); final Flux<VesEvent> input = Flux.just(sampleEvent); // when sut.start(); final ByteBuf receivedData = sut.blockingSend(input); // then WireProtocolDecoder decoded = WireProtocolDecoder.decode(receivedData); assertThat(decoded.type).isEqualTo(PayloadType.PROTOBUF.getPayloadTypeBytes().getShort()); assertThat(decoded.event).isEqualTo(sampleEvent); } @Test void singleMessageTest_withSecureConnection() throws Exception { // Note: In case of test failure check validity of certificates present in resources // given final VesEvent sampleEvent = createSimpleVesEvent(); final Flux<VesEvent> input = Flux.just(sampleEvent); // when sut.startSecure(); final ByteBuf receivedData = sut.blockingSend(input); // then WireProtocolDecoder decoded = WireProtocolDecoder.decode(receivedData); assertThat(decoded.type).isEqualTo(PayloadType.PROTOBUF.getPayloadTypeBytes().getShort()); assertThat(decoded.event).isEqualTo(sampleEvent); } private VesEvent createSimpleVesEvent() { final MeasDataCollectionOuterClass.MeasDataCollection content = MeasDataCollectionOuterClass.MeasDataCollection .newBuilder() .addMeasInfo(MeasDataCollectionOuterClass.MeasInfo.newBuilder() .addMeasValues(MeasDataCollectionOuterClass.MeasValue.newBuilder() .addMeasResults(MeasDataCollectionOuterClass.MeasResult.newBuilder() .setIValue(VALUE).build()) .build()) .setIMeasInfoId(INFO_ID) .setIMeasTypes(MeasDataCollectionOuterClass.MeasInfo.IMeasTypes.newBuilder() .addIMeasType(MEAS_TYPE)) .build()) .setGranularityPeriod(PERIOD) .addMeasObjInstIdList(OBJECT_INSTANCE_ID) .build(); return VesEvent.newBuilder() .setCommonEventHeader(CommonEventHeader.newBuilder() .setDomain("RTPM") .build()) .setEventFields(content.toByteString()) .build(); } }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; /** * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean * constants. This class should not be used for any other purpose. All constants should be declared * globally (i.e. public static). Do not put anything functional in this class. * * <p>It is advised to statically import this class (or one of its inner classes) wherever the * constants are needed, to reduce verbosity. */ public final class Constants { public static final class DriveConstants { //ports public static final int dtFrontLeftPort = 1; public static final int dtBackLeftPort = 2; public static final int dtFrontRightPort = 3; public static final int dtBackRightPort = 4; public static final boolean kCurrentLimitingEnabled = true; // True/False to enable/disable limit feature. public static final int kPeakCurrentAmps = 15; // The "holding" current (amperes) to limit to when feature is activated. public static final int kPeakTimeMs = 0; // How long current must exceed threshold (seconds) before limiting occurs. public static final int kContCurrentAmps = 10; // Current must exceed this threshold (amperes) before limiting occurs. public static final int kTimeoutMs = 30; // Amount of time (in milliseconds) to wait for a specified element to be found before an error is thrown public static final double kDeadband = 0.05; // Speed constants public static final double kDriveSpeed = .8; public static final double kTurnSpeed = .8; public static final double cDriveSpeed = .6; public static final double cTurnSpeed = .6; public static final double kTurnToleranceDeg = 0; public static final double kTurnRateToleranceDegPerS = 0; public static final double ksVolts = 0.663; public static final double kvVoltSecondsPerMeter = 1.802; public static final double kaVoltSecondsSquaredPerMeter = 0.28; public static final double kPDriveVel = 0.2; // Physical measurements of DT public static final double kWheelRadius = .1524; // meters public static final double kTrackWidth = .6096; // meters public static boolean kGyroReversed = true; public static final DifferentialDriveKinematics kDriveKinematics = new DifferentialDriveKinematics(kTrackWidth); } public static final class ShooterConstants { public static final int shooterFirstPort = 9; public static final int shooterSecondPort = 4; public static final double kNeoRPM = 5880; public static final double kMotorRadius = 0 * UnitConversionConstants.distanceConversionFactor; public static final double kShooterAngle = 0 * UnitConversionConstants.angleConversionFactor; public static final double kShooterHeight = 0 * UnitConversionConstants.distanceConversionFactor; } public static class UnitConversionConstants { public static final double angleConversionFactor = (Math.PI / 180); // angles to radians public static final double distanceConversionFactor = 39.37; // inches to meters } public static final class PhysicsConstants { public static final double gAcceleration = 386.09; // in inches per second squared } public static final class FieldConstants { // All measurements are in inches public static final double kInitiationLine = 120.0; public static final double kTrenchToDriverStation = 200.0; public static final double kInitiationLineToTrench = 80.0; public static final double kTargetHeight = 98.25; public static final double kOuterToInnerTarget = 29.25; } public static final class IntakeConstants { public static final double kIntakeSpeed = 0.20; public static final int intakePort = 11; public static final int intakeSolenoidRight = 1; public static final int intakeSolenoidLeft = 2; } public static final class XboxConstants { public static final int intakeValue = 0; } public static final class HopperConstants { public static final double kHopperSpeed = 0.20; // SparkMAX CAN ports public static final int hopperPort = 4; // Solenoid ports public static final int hopperSolenoid = 3; } public static final class AutoConstants { public static final double kMaxSpeedMetersPerSecond = 1.5; public static final double kMaxAccelerationMetersPerSecondSquared = 1.5; public static final double kRamseteB = 2; public static final double kRamseteZeta = 0.7; } }
package com.jd.blockchain.ledger.core; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.jd.blockchain.ledger.LedgerDataStructure; import com.jd.blockchain.ledger.Operation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jd.binaryproto.BinaryProtocol; import com.jd.blockchain.crypto.Crypto; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.BlockBody; import com.jd.blockchain.ledger.BlockRollbackException; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.IllegalTransactionException; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerDataSnapshot; import com.jd.blockchain.ledger.LedgerInitSetting; import com.jd.blockchain.ledger.LedgerSettings; import com.jd.blockchain.ledger.OperationResult; import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionResult; import com.jd.blockchain.ledger.TransactionState; import com.jd.blockchain.storage.service.ExPolicyKVStorage; import com.jd.blockchain.storage.service.VersioningKVStorage; import com.jd.blockchain.storage.service.utils.BufferedKVStorage; import utils.Bytes; import utils.codec.Base58Utils; import utils.io.BytesUtils; public class LedgerTransactionalEditor implements LedgerEditor { private static final boolean PARALLEL_DB_WRITE; static { PARALLEL_DB_WRITE = Boolean.getBoolean("parallel-dbwrite"); } /** * 账本Hash,创世区块的编辑器则返回 null; */ private HashDigest ledgerHash; private final String ledgerKeyPrefix; private CryptoSetting cryptoSetting; private LedgerBlockData currentBlock; private boolean prepared = false; private boolean canceled = false; private boolean committed = false; private StagedSnapshot startingPoint; /** * 当前区块的存储; */ private BufferedKVStorage baseStorage; private final TransactionSetEditor txset; private LedgerDataStructure dataStructure; /** * 上一个交易产生的账本快照; */ private TxSnapshot previousTxSnapshot; /** * 当前交易的上下文; */ private volatile LedgerTransactionContextImpl currentTxCtx; /** * 最后提交的账本数据集; */ private volatile LedgerDataSetEditor latestLedgerDataset; private volatile BufferedKVStorage datasetStorage; // /** // * 最后提交的交易集合; // */ // private volatile TransactionSet latestTransactionSet; /** * 最后提交的事件数据集; */ private volatile LedgerEventSetEditor latestLedgerEventSet; private volatile BufferedKVStorage eventsetStorage; /** * @param ledgerHash * @param cryptoSetting * @param currentBlock * @param startingPoint * @param ledgerKeyPrefix * @param bufferedStorage * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; */ private LedgerTransactionalEditor(HashDigest ledgerHash, CryptoSetting cryptoSetting, LedgerBlockData currentBlock, StagedSnapshot startingPoint, String ledgerKeyPrefix, TransactionSetEditor txset, BufferedKVStorage bufferedStorage, LedgerDataStructure dataStructure) { this.ledgerHash = ledgerHash; this.ledgerKeyPrefix = ledgerKeyPrefix; this.cryptoSetting = cryptoSetting; this.currentBlock = currentBlock; this.baseStorage = bufferedStorage; this.startingPoint = startingPoint; this.txset = txset; this.dataStructure = dataStructure; // this.stagedSnapshots.push(startingPoint); } /** * 创建账本新区块的编辑器; * * @param ledgerHash 账本哈希; * @param ledgerSetting 账本设置; * @param previousBlock 前置区块; * @param ledgerKeyPrefix 账本数据前缀; * @param ledgerExStorage 账本数据存储; * @param ledgerVerStorage 账本数据版本化存储; * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; * @return */ public static LedgerTransactionalEditor createEditor(LedgerBlock previousBlock, LedgerSettings ledgerSetting, String ledgerKeyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, LedgerDataStructure dataStructure) { // new block; HashDigest ledgerHash = previousBlock.getLedgerHash(); if (ledgerHash == null) { ledgerHash = previousBlock.getHash(); } if (ledgerHash == null) { throw new IllegalArgumentException("Illegal previous block was specified!"); } LedgerBlockData currBlock = new LedgerBlockData(previousBlock.getHeight() + 1, ledgerHash, previousBlock.getHash()); // init storage; BufferedKVStorage txStagedStorage = new BufferedKVStorage(Crypto.getHashFunction(ledgerSetting.getCryptoSetting().getHashAlgorithm()), ledgerExStorage, ledgerVerStorage, PARALLEL_DB_WRITE); TransactionSetEditor txset = LedgerRepositoryImpl.loadTransactionSet(previousBlock.getHeight(), previousBlock.getTransactionSetHash(), ledgerSetting.getCryptoSetting(), ledgerKeyPrefix, txStagedStorage, txStagedStorage, dataStructure, false); StagedSnapshot startingPoint = new TxSnapshot(null, previousBlock); // instantiate editor; return new LedgerTransactionalEditor(ledgerHash, ledgerSetting.getCryptoSetting(), currBlock, startingPoint, ledgerKeyPrefix, txset, txStagedStorage, dataStructure); } /** * 创建创世区块的编辑器; * * @param initSetting * @param ledgerKeyPrefix * @param ledgerExStorage * @param ledgerVerStorage * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; * @return */ public static LedgerTransactionalEditor createEditor(LedgerInitSetting initSetting, String ledgerKeyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, LedgerDataStructure dataStructure) { LedgerBlockData genesisBlock = new LedgerBlockData(0, null, null); StagedSnapshot startingPoint = new GenesisSnapshot(initSetting); // init storage; BufferedKVStorage txStagedStorage = new BufferedKVStorage(Crypto.getHashFunction(initSetting.getCryptoSetting().getHashAlgorithm()), ledgerExStorage, ledgerVerStorage, false); TransactionSetEditor txset = LedgerRepositoryImpl.newTransactionSet(initSetting.getCryptoSetting(), ledgerKeyPrefix, txStagedStorage, txStagedStorage, dataStructure); return new LedgerTransactionalEditor(null, initSetting.getCryptoSetting(), genesisBlock, startingPoint, ledgerKeyPrefix, txset, txStagedStorage, dataStructure); } private void commitTxSnapshot(TxSnapshot snapshot) { previousTxSnapshot = snapshot; // latestLedgerDataset = currentTxCtx.getDataset(); // latestLedgerDataset.setReadonly(); // latestTransactionSet = currentTxCtx.getTransactionSet(); // latestTransactionSet.setReadonly(); // latestLedgerEventSet = currentTxCtx.getEventSet(); // latestLedgerEventSet.setReadonly(); currentTxCtx = null; } private void rollbackCurrentTx() { latestLedgerDataset.cancel(); datasetStorage.cancel(); latestLedgerEventSet.cancel(); eventsetStorage.cancel(); currentTxCtx = null; latestLedgerDataset = null; datasetStorage = null; latestLedgerEventSet = null; eventsetStorage = null; } @Override public LedgerBlock getCurrentBlock() { return currentBlock; } @Override public long getBlockHeight() { return currentBlock.getHeight(); } @Override public HashDigest getLedgerHash() { return ledgerHash; } @Override public LedgerDataSetEditor getLedgerDataset() { return innerGetDataset(); } private LedgerDataSetEditor innerGetDataset() { if (this.latestLedgerDataset == null) { this.datasetStorage = new BufferedKVStorage(Crypto.getHashFunction(cryptoSetting.getHashAlgorithm()), baseStorage, baseStorage, false); this.latestLedgerDataset = createDatasetFromLastestSnapshot(datasetStorage); } return this.latestLedgerDataset; } @Override public LedgerEventSetEditor getLedgerEventSet() { return innerGetEventset(); } private LedgerEventSetEditor innerGetEventset() { if (this.latestLedgerEventSet == null) { this.eventsetStorage = new BufferedKVStorage(Crypto.getHashFunction(cryptoSetting.getHashAlgorithm()), baseStorage, baseStorage, false); this.latestLedgerEventSet = createEventSetFromLastestSnapshot(eventsetStorage); } return this.latestLedgerEventSet; } @Override public TransactionSetEditor getTransactionSet() { // TODO: wrapper with readonly; return txset; } /** * 检查当前账本是否是指定交易请求的账本; * * @param txRequest * @return */ private boolean isRequestMatched(TransactionRequest txRequest) { HashDigest reqLedgerHash = txRequest.getTransactionContent().getLedgerHash(); if (ledgerHash == reqLedgerHash) { return true; } if (ledgerHash == null || reqLedgerHash == null) { return false; } return ledgerHash.equals(reqLedgerHash); } /** * 注:此方法不验证交易完整性和签名有效性,仅仅设计为进行交易记录的管理;调用者应在此方法之外进行数据完整性和签名有效性的检查; */ @Override public synchronized LedgerTransactionContext newTransaction(TransactionRequest txRequest) { // if (SettingContext.txSettings().verifyLedger() && !isRequestMatched(txRequest)) { if (!isRequestMatched(txRequest)) { throw new IllegalTransactionException("Transaction request is dispatched to a wrong ledger! --[TxHash=" + txRequest.getTransactionHash() + "]!", TransactionState.IGNORED_BY_WRONG_LEDGER); } if (currentTxCtx != null) { throw new IllegalStateException( "Unable to open another new transaction before the current transaction is completed! --[TxHash=" + txRequest.getTransactionHash() + "]!"); } // 检查状态是否允许创建新的交易请求;; checkState(); innerGetDataset(); innerGetEventset(); currentTxCtx = new LedgerTransactionContextImpl(txRequest, this); return currentTxCtx; // // init storage of new transaction; // BufferedKVStorage txBufferedStorage = new BufferedKVStorage(baseStorage, baseStorage, false); // // LedgerDataset txDataset = null; //// TransactionSet txset = null; // LedgerEventSet eventSet = null; // if (previousTxSnapshot == null) { // // load the starting point of the new transaction; // if (startingPoint instanceof GenesisSnapshot) { // // 准备生成创世区块; // GenesisSnapshot snpht = (GenesisSnapshot) startingPoint; // txDataset = LedgerRepositoryImpl.newDataSet(snpht.initSetting, ledgerKeyPrefix, txBufferedStorage, // txBufferedStorage); //// txset = LedgerRepositoryImpl.newTransactionSet(txDataset.getAdminDataset().getSettings(), //// ledgerKeyPrefix, txBufferedStorage, txBufferedStorage); // eventSet = LedgerRepositoryImpl.newEventSet(snpht.initSetting.getCryptoSetting(), ledgerKeyPrefix, txBufferedStorage, // txBufferedStorage); // } else if (startingPoint instanceof TxSnapshot) { // // 新的区块; // // TxSnapshot; reload dataset and eventset; // TxSnapshot snpht = (TxSnapshot) startingPoint; // // load dataset; // txDataset = LedgerRepositoryImpl.loadDataSet(snpht.dataSnapshot, cryptoSetting, ledgerKeyPrefix, // txBufferedStorage, txBufferedStorage, false); // //// // load txset; //// txset = LedgerRepositoryImpl.loadTransactionSet(snpht.txsetHash, cryptoSetting, ledgerKeyPrefix, //// txBufferedStorage, txBufferedStorage, false); // // // load eventset // eventSet = LedgerRepositoryImpl.loadEventSet(snpht.eventSnapshot, cryptoSetting, ledgerKeyPrefix, // txBufferedStorage, txBufferedStorage, false); // } else { // // Unreachable; // throw new IllegalStateException("Unreachable code was accidentally executed!"); // } // // } else { // // Reuse previous object to optimize performance; // // load dataset; // txDataset = LedgerRepositoryImpl.loadDataSet(previousTxSnapshot.dataSnapshot, cryptoSetting, // ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); // //// // load txset; //// txset = LedgerRepositoryImpl.loadTransactionSet(previousTxSnapshot.txsetHash, cryptoSetting, //// ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); // // // load txset; // eventSet = LedgerRepositoryImpl.loadEventSet(previousTxSnapshot.eventSnapshot, cryptoSetting, // ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); // } // // currentTxCtx = new LedgerTransactionContextImpl(txRequest, this); // // return currentTxCtx; } private LedgerDataSetEditor createDatasetFromLastestSnapshot(BufferedKVStorage txBufferedStorage) { LedgerDataSetEditor txDataset = null; if (previousTxSnapshot == null) { // load the starting point of the new transaction; if (startingPoint instanceof GenesisSnapshot) { // 准备生成创世区块; GenesisSnapshot snpht = (GenesisSnapshot) startingPoint; txDataset = LedgerRepositoryImpl.newDataSet(snpht.initSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, dataStructure); } else if (startingPoint instanceof TxSnapshot) { // 新的区块; // TxSnapshot; reload dataset and eventset; TxSnapshot snpht = (TxSnapshot) startingPoint; // load dataset; txDataset = LedgerRepositoryImpl.loadDataSet(currentBlock.getHeight() - 1, snpht.dataSnapshot, cryptoSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, dataStructure, false); } else { // Unreachable; throw new IllegalStateException("Unreachable code was accidentally executed!"); } } else { // Reuse previous object to optimize performance; // load dataset; txDataset = LedgerRepositoryImpl.loadDataSet(currentBlock.getHeight() - 1, previousTxSnapshot.dataSnapshot, cryptoSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, dataStructure,false); } return txDataset; } private LedgerEventSetEditor createEventSetFromLastestSnapshot(BufferedKVStorage txBufferedStorage) { LedgerEventSetEditor eventSet = null; if (previousTxSnapshot == null) { // load the starting point of the new transaction; if (startingPoint instanceof GenesisSnapshot) { // 准备生成创世区块; GenesisSnapshot snpht = (GenesisSnapshot) startingPoint; eventSet = LedgerRepositoryImpl.newEventSet(snpht.initSetting.getCryptoSetting(), ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, dataStructure); } else if (startingPoint instanceof TxSnapshot) { // 新的区块; // TxSnapshot; reload dataset and eventset; TxSnapshot snpht = (TxSnapshot) startingPoint; // load eventset eventSet = LedgerRepositoryImpl.loadEventSet(currentBlock.getHeight() - 1, snpht.dataSnapshot, cryptoSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, dataStructure,false); } else { // Unreachable; throw new IllegalStateException("Unreachable code was accidentally executed!"); } } else { // load eventset eventSet = LedgerRepositoryImpl.loadEventSet(currentBlock.getHeight() - 1, previousTxSnapshot.dataSnapshot, cryptoSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, dataStructure,false); } return eventSet; } @Override public LedgerBlock prepare() { checkState(); if (currentTxCtx != null) { // 有进行中的交易尚未提交或回滚; throw new IllegalStateException( "There is an ongoing transaction that has been not committed or rolled back!"); } if (previousTxSnapshot == null) { // 当前区块没有加入过交易,不允许产生空区块; throw new BlockRollbackException(TransactionState.EMPTY_BLOCK_ERROR, "There is no transaction in the current block, and no empty blocks is allowed!"); } // 生成交易集合根哈希; txset.commit(); saveTotal();// 底层结构为KV时使用:记录参与方,各类账户,以及账户下的KV总数; currentBlock.setTransactionSetHash(txset.getRootHash()); // do commit when transaction isolation level is BLOCK; currentBlock.setAdminAccountHash(previousTxSnapshot.getAdminAccountHash()); currentBlock.setUserAccountSetHash(previousTxSnapshot.getUserAccountSetHash()); currentBlock.setDataAccountSetHash(previousTxSnapshot.getDataAccountSetHash()); currentBlock.setContractAccountSetHash(previousTxSnapshot.getContractAccountSetHash()); currentBlock.setSystemEventSetHash(previousTxSnapshot.getSystemEventSetHash()); currentBlock.setUserEventSetHash(previousTxSnapshot.getUserEventSetHash()); // 根据ThreadLocal中的时间戳设置; Long timestamp = TIMESTAMP_HOLDER.get(); if (timestamp != null) { currentBlock.setTimestamp(timestamp); } // compute block hash; byte[] blockBodyBytes = BinaryProtocol.encode(currentBlock, BlockBody.class); HashDigest blockHash = Crypto.getHashFunction(cryptoSetting.getHashAlgorithm()).hash(blockBodyBytes); currentBlock.setHash(blockHash); // if (currentBlock.getLedgerHash() == null) { // // init GenesisBlock's ledger hash; // currentBlock.setLedgerHash(blockHash); // } // persist block bytes; // only one version per block; byte[] blockBytes = BinaryProtocol.encode(currentBlock, LedgerBlock.class); Bytes blockStorageKey = LedgerRepositoryImpl.encodeBlockStorageKey(currentBlock.getHash()); long v; if (dataStructure.equals(LedgerDataStructure.MERKLE_TREE)) { v = baseStorage.set(blockStorageKey, blockBytes, -1); } else { // key = BK/blockhash, value = blockheight, version = -1; v = baseStorage.set(blockStorageKey, BytesUtils.toBytes(currentBlock.getHeight()), -1); } if (v < 0) { throw new IllegalStateException( "Block already exist! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } // persist block hash to ledger index; HashDigest ledgerHash = currentBlock.getLedgerHash(); if (ledgerHash == null) { ledgerHash = blockHash; } Bytes ledgerIndexKey = LedgerRepositoryImpl.encodeLedgerIndexKey(ledgerHash); long expectedVersion = currentBlock.getHeight() - 1; if (dataStructure.equals(LedgerDataStructure.MERKLE_TREE)) { v = baseStorage.set(ledgerIndexKey, currentBlock.getHash().toBytes(), expectedVersion); } else { // key = IX/, value = blockcontent, version = blockheight v = baseStorage.set(ledgerIndexKey, blockBytes, expectedVersion); } if (v < 0) { throw new IllegalStateException( String.format("Index of BlockHash already exist! --[BlockHeight=%s][BlockHash=%s]", currentBlock.getHeight(), currentBlock.getHash())); } prepared = true; return currentBlock; } @Override public void commit() { if (committed) { throw new IllegalStateException("The current block has been committed!"); } if (canceled) { throw new IllegalStateException("The current block has been canceled!"); } if (!prepared) { // 未就绪; throw new IllegalStateException("The current block is not ready yet!"); } try { baseStorage.flush(); } catch (Exception e) { throw new BlockRollbackException(e.getMessage(), e); } clearCachedIndex(latestLedgerDataset, latestLedgerEventSet, txset); updatePreBlockHeight(latestLedgerDataset, latestLedgerEventSet, txset); committed = true; } @Override public void cancel() { if (committed) { throw new IllegalStateException("The current block has been committed!"); } if (canceled) { return; } canceled = true; baseStorage.cancel(); } private void checkState() { if (prepared) { throw new IllegalStateException("The current block is ready!"); } if (committed) { throw new IllegalStateException("The current block has been committed!"); } if (canceled) { throw new IllegalStateException("The current block has been canceled!"); } } private void clearCachedIndex(LedgerDataSetEditor latestLedgerDataset, LedgerEventSetEditor latestLedgerEventSet, TransactionSetEditor latestLedgerTxSet) { if (dataStructure.equals(LedgerDataStructure.MERKLE_TREE)) { return; } latestLedgerDataset.clearCachedIndex(); // 注意此处的实现 latestLedgerEventSet.clearCachedIndex(); latestLedgerTxSet.clearCachedIndex(); } private void updatePreBlockHeight(LedgerDataSetEditor latestLedgerDataset, LedgerEventSetEditor latestLedgerEventSet, TransactionSetEditor latestLedgerTxSet) { if (dataStructure.equals(LedgerDataStructure.MERKLE_TREE)) { return; } long currBlockHeight = currentBlock.getHeight(); latestLedgerDataset.updatePreBlockHeight(currBlockHeight); latestLedgerEventSet.updatePreBlockHeight(currBlockHeight); latestLedgerTxSet.updatePreBlockHeight(currBlockHeight); } private void saveTotal() { if (dataStructure.equals(LedgerDataStructure.MERKLE_TREE)) { return; } final Bytes DATA_PREFIX = Bytes.fromString("D/"); final Bytes LEDGER_PARTICIPANT_PREFIX = Bytes.fromString(ledgerKeyPrefix + "PAR/").concat(Bytes.fromString("T")); final Bytes ROLE_PRIVILEGE_PREFIX = Bytes.fromString(ledgerKeyPrefix + "RPV/").concat(Bytes.fromString("T")); final Bytes USER_ROLE_PREFIX = Bytes.fromString(ledgerKeyPrefix + "URO/").concat(Bytes.fromString("T")); final Bytes USER_SET_PREFIX = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("US/")).concat(Bytes.fromString("T")); final Bytes DATA_SET_PREFIX = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("DS/")).concat(Bytes.fromString("T")); final Bytes CONTRACT_SET_PREFIX = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("CS/")).concat(Bytes.fromString("T")); final Bytes SYSEVENT_SET_PREFIX = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("SE/")).concat(Bytes.fromString("T")); final Bytes USEREVENT_SET_PREFIX = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("UE/")).concat(Bytes.fromString("T")); long nv = 0; if (latestLedgerDataset.getAdminDataset().getParticipantDataset().isAddNew()) { nv = baseStorage.set(LEDGER_PARTICIPANT_PREFIX, BytesUtils.toBytes(latestLedgerDataset.getAdminDataset().getParticipantCount()), datasetStorage.getVersion(LEDGER_PARTICIPANT_PREFIX)); if (nv < 0) { throw new IllegalStateException( "Participants total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } } if (nv > -1 && latestLedgerDataset.getAdminDataset().getRolePrivileges().isAddNew()) { nv = baseStorage.set(ROLE_PRIVILEGE_PREFIX, BytesUtils.toBytes(latestLedgerDataset.getAdminDataset().getRolePrivileges().getRoleCount()), datasetStorage.getVersion(ROLE_PRIVILEGE_PREFIX)); if (nv < 0) { throw new IllegalStateException( "RolePrivis total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } } if (latestLedgerDataset.getAdminDataset().getAuthorizations().isAddNew()) { nv = baseStorage.set(USER_ROLE_PREFIX, BytesUtils.toBytes(latestLedgerDataset.getAdminDataset().getAuthorizations().getUserCount()), datasetStorage.getVersion(USER_ROLE_PREFIX)); if (nv < 0) { throw new IllegalStateException( "UserRoles total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } } nv = baseStorage.set(USER_SET_PREFIX, BytesUtils.toBytes(latestLedgerDataset.getUserAccountSet().getTotal()), (currentBlock.getHeight() - 1)); if (nv < 0) { throw new IllegalStateException( "UserAccounts total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } nv = baseStorage.set(DATA_SET_PREFIX, BytesUtils.toBytes(latestLedgerDataset.getDataAccountSet().getTotal()), (currentBlock.getHeight() - 1)); if (nv < 0) { throw new IllegalStateException( "DataAccounts total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } Map<Bytes, Long> kvNumCache = latestLedgerDataset.getDataAccountSet().getKvNumCache(); for (Bytes address : kvNumCache.keySet()) { // 首先查询账户地址对应的顺序号 byte[] indexBytes = baseStorage.get(Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("DS/")).concat(Bytes.fromString("I/").concat(address)), -1); long accountIndex = BytesUtils.toLong(indexBytes); Bytes dataKvTotalPrefix = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("DS/")).concat(Bytes.fromString(String.valueOf(accountIndex))).concat(DATA_PREFIX).concat(Bytes.fromString("T")); nv = baseStorage.set(dataKvTotalPrefix, BytesUtils.toBytes(latestLedgerDataset.getDataAccountSet().getAccount(address).getDataset().getDataCount() + kvNumCache.get(address).longValue()), baseStorage.getVersion(dataKvTotalPrefix)); if (nv < 0) { throw new IllegalStateException( "DataAccount kv total set exception! --[DataAccount address = " + Base58Utils.encode(address.toBytes()) + "]"); } } nv = baseStorage.set(CONTRACT_SET_PREFIX, BytesUtils.toBytes(latestLedgerDataset.getContractAccountSet().getTotal()), (currentBlock.getHeight() - 1)); if (nv < 0) { throw new IllegalStateException( "ContractAccounts total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } if (latestLedgerEventSet.getSystemEventGroup().isAddNew()) { nv = baseStorage.set(SYSEVENT_SET_PREFIX, BytesUtils.toBytes(latestLedgerEventSet.getSystemEventGroup().totalEventNames()), baseStorage.getVersion(SYSEVENT_SET_PREFIX)); if (nv < 0) { throw new IllegalStateException( "SystemEvent name total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } } if (latestLedgerEventSet.getEventAccountSet().isAddNew()) { nv = baseStorage.set(USEREVENT_SET_PREFIX, BytesUtils.toBytes(latestLedgerEventSet.getEventAccountSet().getTotal()), baseStorage.getVersion(USEREVENT_SET_PREFIX)); if (nv < 0) { throw new IllegalStateException( "UserEvent user total set exception! --[BlockHash=" + Base58Utils.encode(currentBlock.getHash().toBytes()) + "]"); } } Map<Bytes, Long> kvNumCacheEvent = latestLedgerEventSet.getEventAccountSet().getKvNumCache(); for (Bytes address : kvNumCacheEvent.keySet()) { // 首先查询账户地址对应的顺序号 byte[] indexBytes = baseStorage.get(Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("UE/")).concat(Bytes.fromString("I/")).concat(address), -1); long accountIndex = BytesUtils.toLong(indexBytes); Bytes eventNameTotalPrefix = Bytes.fromString(ledgerKeyPrefix + Bytes.fromString("UE/")).concat(Bytes.fromString(String.valueOf(accountIndex))).concat(DATA_PREFIX).concat(Bytes.fromString("T")); nv = baseStorage.set(eventNameTotalPrefix, BytesUtils.toBytes(latestLedgerEventSet.getEventAccountSet().getAccount(address).totalEventNames() + kvNumCacheEvent.get(address).longValue()), baseStorage.getVersion(eventNameTotalPrefix)); if (nv < 0) { throw new IllegalStateException( "EventAccount name total set exception! --[EventAccount address = " + Base58Utils.encode(address.toBytes()) + "]"); } } } // --------------------------- inner type -------------------------- /** * 用于暂存交易上下文数据的快照对象; * * @author huanghaiquan * */ private static interface StagedSnapshot { } /** * 创世区块的快照对象; * * @author huanghaiquan * */ private static class GenesisSnapshot implements StagedSnapshot { private LedgerInitSetting initSetting; public GenesisSnapshot(LedgerInitSetting initSetting) { this.initSetting = initSetting; } } /** * 交易执行完毕后的快照对象; * * @author huanghaiquan * */ private static class TxSnapshot implements StagedSnapshot { /** * 交易哈希; */ private HashDigest txHash; /** * 账本数据的快照; */ private LedgerDataSnapshot dataSnapshot; public HashDigest getAdminAccountHash() { return dataSnapshot.getAdminAccountHash(); } public HashDigest getUserAccountSetHash() { return dataSnapshot.getUserAccountSetHash(); } public HashDigest getDataAccountSetHash() { return dataSnapshot.getDataAccountSetHash(); } public HashDigest getContractAccountSetHash() { return dataSnapshot.getContractAccountSetHash(); } public HashDigest getTransactionHash() { return txHash; } public HashDigest getSystemEventSetHash() { return dataSnapshot.getSystemEventSetHash(); } public HashDigest getUserEventSetHash() { return dataSnapshot.getUserEventSetHash(); } /** * 创建指定交易的快照; * * @param txHash * @param dataSnapshot * @param eventSnapshot */ public TxSnapshot(HashDigest txHash, LedgerDataSnapshot dataSnapshot) { this.txHash = txHash; this.dataSnapshot = dataSnapshot; } } /** * 交易的上下文; * * @author huanghaiquan * */ private static class LedgerTransactionContextImpl implements LedgerTransactionContext { private static final Logger logger = LoggerFactory.getLogger(LedgerTransactionalEditor.class); private LedgerTransactionalEditor ledgerEditor; private TransactionRequest txRequest; private List<Operation> derivedOperations = new ArrayList<>(); private boolean committed = false; private boolean rollbacked = false; private LedgerTransactionContextImpl(TransactionRequest txRequest, LedgerTransactionalEditor editor) { this.txRequest = txRequest; this.ledgerEditor = editor; } @Override public long getBlockHeight() { return ledgerEditor.getBlockHeight(); } @Override public LedgerDataSetEditor getDataset() { // TODO: 控制只读; return ledgerEditor.getLedgerDataset(); } @Override public LedgerEventSetEditor getEventSet() { // TODO: 控制只读; return ledgerEditor.getLedgerEventSet(); } @Override public TransactionSet getTransactionSet() { return ledgerEditor.getTransactionSet(); } @Override public Operation[] getDerivedOperations() { return derivedOperations.toArray(new Operation[derivedOperations.size()]); } @Override public void addDerivedOperations(Operation... operations) { for(Operation operation : operations) { derivedOperations.add(operation); } } @Override public TransactionRequest getTransactionRequest() { return txRequest; } @Override public TransactionResult commit(TransactionState txResult) { return commit(txResult, null); } @Override public TransactionResult commit(TransactionState txExecState, List<OperationResult> operationResults) { checkTxState(); // capture snapshot logger.debug("before dataset.commit(),[contentHash={}]", this.getTransactionRequest().getTransactionHash()); ledgerEditor.latestLedgerDataset.commit(); ledgerEditor.latestLedgerEventSet.commit(); try { ledgerEditor.datasetStorage.commit(); ledgerEditor.eventsetStorage.commit(); logger.debug("after storage.flush(),[contentHash={}]", this.getTransactionRequest().getTransactionHash()); } catch (Exception e) { // 写入数据存储时发生错误可能会导致脏数据,因此只能触发区块回滚; throw new BlockRollbackException( "Fail to flush the data storage after transaction execution! --" + e.getMessage(), e); } logger.debug("after dataset.commit(),[contentHash={}]", this.getTransactionRequest().getTransactionHash()); TransactionStagedSnapshot txDataSnapshot = takeDataSnapshot(); TransactionResult txResult; try { txResult = new TransactionResultData(txRequest.getTransactionHash(), ledgerEditor.getBlockHeight(), txExecState, txDataSnapshot, operationResultArray(operationResults), getDerivedOperations()); logger.debug("before txset.add(),[contentHash={}]", this.getTransactionRequest().getTransactionHash()); ledgerEditor.txset.addTransaction(txRequest, txResult); logger.debug("after txset.add(),[contentHash={}]", this.getTransactionRequest().getTransactionHash()); // 不必每比交易完成后都计算交易集合的根哈希,只需要在最后生成区块时计算一次交易集合根哈希即可,如此可以优化性能; // this.txset.commit(); // logger.debug("after txset.commit(),[contentHash={}]", // this.getTransactionRequest().getTransactionHash()); } catch (Exception e) { // 当交易集合写入时发生错误的情况下,可能会导致脏数据,因此只能触发区块回滚; throw new BlockRollbackException( "Fail to add result of transaction to TransactionSet after execution! --" + e.getMessage(), e); } // put snapshot into stack; TxSnapshot snapshot = new TxSnapshot(txRequest.getTransactionHash(), txDataSnapshot); ledgerEditor.commitTxSnapshot(snapshot); committed = true; return txResult; } @Override public TransactionResult discardAndCommit(TransactionState txResult) { return discardAndCommit(txResult, null); } @Override public TransactionResult discardAndCommit(TransactionState txExecState, List<OperationResult> operationResults) { checkTxState(); // 未处理 ledgerEditor.latestLedgerDataset.cancel(); ledgerEditor.latestLedgerEventSet.cancel(); try { ledgerEditor.datasetStorage.cancel(); ledgerEditor.eventsetStorage.cancel(); } catch (Exception e) { // to reset currentTxCtx this.rollback(); // 写入数据存储时发生错误可能会导致脏数据,因此只能触发区块回滚; throw new BlockRollbackException( "Fail to flush the data storage after transaction execution! --" + e.getMessage(), e); } TransactionStagedSnapshot txDataSnapshot = takeDataSnapshot(); TransactionResult txResult; try { txResult = new TransactionResultData(txRequest.getTransactionHash(), ledgerEditor.getBlockHeight(), txExecState, txDataSnapshot, operationResultArray(operationResults), getDerivedOperations()); ledgerEditor.txset.addTransaction(txRequest, txResult); // 不必每比交易完成后都计算交易集合的根哈希,只需要在最后生成区块时计算一次交易集合根哈希即可,如此可以优化性能; // this.txset.commit(); } catch (Exception e) { // to reset currentTxCtx this.rollback(); // 当交易集合写入时发生错误的情况下,可能会导致脏数据,因此只能触发区块回滚; throw new BlockRollbackException( "Fail to add result of transaction to TransactionSet after execution! --" + e.getMessage(), e); } // put snapshot into stack; TxSnapshot snapshot = new TxSnapshot(txRequest.getTransactionHash(), txDataSnapshot); ledgerEditor.commitTxSnapshot(snapshot); committed = true; return txResult; } private TransactionStagedSnapshot takeDataSnapshot() { TransactionStagedSnapshot txDataSnapshot = new TransactionStagedSnapshot(); txDataSnapshot.setAdminAccountHash(ledgerEditor.latestLedgerDataset.getAdminDataset().getHash()); txDataSnapshot .setContractAccountSetHash(ledgerEditor.latestLedgerDataset.getContractAccountSet().getRootHash()); txDataSnapshot.setDataAccountSetHash(ledgerEditor.latestLedgerDataset.getDataAccountSet().getRootHash()); txDataSnapshot.setUserAccountSetHash(ledgerEditor.latestLedgerDataset.getUserAccountSet().getRootHash()); txDataSnapshot.setSystemEventSetHash(ledgerEditor.latestLedgerEventSet.getSystemEventGroup().getRootHash()); txDataSnapshot.setUserEventSetHash(ledgerEditor.latestLedgerEventSet.getEventAccountSet().getRootHash()); return txDataSnapshot; } private OperationResult[] operationResultArray(List<OperationResult> operationResults) { OperationResult[] operationResultArray = null; if (operationResults != null && !operationResults.isEmpty()) { operationResultArray = new OperationResult[operationResults.size()]; operationResults.toArray(operationResultArray); } return operationResultArray; } @Override public void rollback() { if (this.rollbacked) { return; } if (this.committed) { throw new IllegalStateException("This transaction had been committed!"); } ledgerEditor.rollbackCurrentTx(); rollbacked = true; } private void checkTxState() { if (this.committed) { throw new IllegalStateException("This transaction had been committed!"); } if (this.rollbacked) { throw new IllegalStateException("This transaction had been rollbacked!"); } } } }
package com.example.administrator.coolweather; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.administrator.coolweather.gson.Forecast; import com.example.administrator.coolweather.gson.Weather; import com.example.administrator.coolweather.service.AutoUpdateService; import com.example.administrator.coolweather.util.HttpUtil; import com.example.administrator.coolweather.util.ResponseUtil; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class WeatherActivty extends AppCompatActivity { private ScrollView scrollView; private TextView title; private TextView update; private TextView degree; private TextView weather_info; private TextView aqi; private TextView pm; private TextView comfort; private TextView car_wash; private TextView sport; private LinearLayout forest; private ImageView backgraoud; public SwipeRefreshLayout swipe; private String weather_id; public DrawerLayout drawerLayout; private Button home; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_weather_activty); swipe = (SwipeRefreshLayout) findViewById(R.id.swipelayout); swipe.setColorSchemeResources(R.color.colorPrimary); backgraoud = (ImageView) findViewById(R.id.background); scrollView = (ScrollView) findViewById(R.id.scroll); title = (TextView) findViewById(R.id.titlename); update = (TextView) findViewById(R.id.updatetime); degree = (TextView) findViewById(R.id.degree); weather_info = (TextView) findViewById(R.id.weather_info); aqi = (TextView) findViewById(R.id.aqi); pm = (TextView) findViewById(R.id.pm); comfort = (TextView) findViewById(R.id.comfort); car_wash = (TextView) findViewById(R.id.car_wash); sport = (TextView) findViewById(R.id.sport); forest = (LinearLayout) findViewById(R.id.forest); drawerLayout = (DrawerLayout) findViewById(R.id.drwalayout); home = (Button) findViewById(R.id.home); home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(GravityCompat.START); } }); SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String weather = defaultSharedPreferences.getString("weather", null); if (defaultSharedPreferences.getString("bing_pic", null) != null) { Glide.with(this).load(defaultSharedPreferences.getString("ping_pic", null)).into(backgraoud); } else { loadBackground(); } if (weather != null) { Weather weather1 = ResponseUtil.handleWeatherResponse(weather); weather_id = weather1.basic.id; showWeatherinfo(weather1); } else { weather_id = getIntent().getStringExtra("weather_id"); scrollView.setVisibility(View.INVISIBLE); requrestWeather(weather_id); } swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { requrestWeather(weather_id); } }); } private void loadBackground() { final String urlback = "http://guolin.tech/api/bing_pic"; Log.e("adderes", "queryProvinceFromServers: " + "#####"); HttpUtil.sendOkHttpRequest(urlback, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivty.this, "获取背景失败", Toast.LENGTH_LONG).show(); swipe.setRefreshing(false); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String result = response.body().string(); SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(WeatherActivty.this).edit(); SharedPreferences.Editor ping_pic = edit.putString("ping_pic", result); edit.apply(); runOnUiThread(new Runnable() { @Override public void run() { Log.e("adderes", "queryProvinceFromServers: " + "rrrrrr" + result); Glide.with(WeatherActivty.this).load(result).into(backgraoud); swipe.setRefreshing(false); } }); Log.e("adderes", "queryProvinceFromServers: " + "当前是省ssss"); } }); } public void requrestWeather(String weather_id) { String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weather_id + "&key=230a7be1e1ae4545b211c66d81ace031";//TODO HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { new Thread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivty.this, "联网失败", Toast.LENGTH_LONG).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String respon = response.body().string(); final Weather weather = ResponseUtil.handleWeatherResponse(respon); runOnUiThread( new Runnable() { @Override public void run() { if (weather != null && "ok".equals(weather.status)) { Intent intent = new Intent(WeatherActivty.this, AutoUpdateService.class); startService(intent); SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(WeatherActivty.this).edit(); edit.putString("weather", respon); edit.apply(); showWeatherinfo(weather); } else { Toast.makeText(WeatherActivty.this, "获取天气失败", Toast.LENGTH_LONG).show(); } } }); loadBackground(); } }); } private void showWeatherinfo(Weather weather) { String city = weather.basic.city; String updatetime = weather.basic.update.updatetime; String tmp = weather.now.tmp ; String txt = weather.now.more.txt;//多云 String comfort1 = "舒适度: " + weather.suggestion.comfort.txt;//舒适度 String carwash = "洗车建议: " + weather.suggestion.carwash.txt;//洗车 String sport1 = "运动建议: " + weather.suggestion.sport.txt;//运动 title.setText(city); update.setText(updatetime); degree.setText(tmp); weather_info.setText(txt); forest.removeAllViews(); for (Forecast fore : weather.forecastList ) { View view = LayoutInflater.from(this).inflate(R.layout.forest_item, forest, false); TextView date = (TextView) view.findViewById(R.id.date); TextView info = (TextView) view.findViewById(R.id.info); TextView max = (TextView) view.findViewById(R.id.max); TextView min = (TextView) view.findViewById(R.id.min); date.setText(fore.date); info.setText(fore.more.info); max.setText(fore.temperature.max); min.setText(fore.temperature.min); forest.addView(view); } Log.e("adderes", "queryProvinceFromServers: " + "当前是省" + weather.aqi); if (weather.aqi != null) { aqi.setText(weather.aqi.city.aqi); pm.setText(weather.aqi.city.pm25); } car_wash.setText(carwash); comfort.setText(comfort1); sport.setText(sport1); scrollView.setVisibility(View.VISIBLE); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.tableinput_new; import java.sql.ResultSet; import org.pentaho.di.core.RowSet; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.errorhandling.StreamInterface; /** * @author Matt * @since 20-jan-2005 */ public class TableInputNewData extends BaseStepData implements StepDataInterface { public Object[] nextrow; public Object[] thisrow; public Database db; public ResultSet rs; public String lookupStep; public RowMetaInterface rowMeta; public RowSet rowSet; public boolean isCanceled; public StreamInterface infoStream; public TableInputNewData() { super(); db = null; thisrow = null; nextrow = null; rs = null; lookupStep = null; } }
/*- * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.openecomp.sdnc.rm.data; import java.util.Collection; public abstract class Resource { public ResourceKey resourceKey; public ResourceType resourceType; public Collection<AllocationItem> allocationItems; public Collection<ResourceLoad> resourceLoadList; }
/* * Copyright © 2017-2018 Cask Data, 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 io.cdap.cdap.internal.app.runtime.artifact; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import io.cdap.cdap.api.artifact.ArtifactInfo; import io.cdap.cdap.api.artifact.ArtifactScope; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.cdap.common.conf.CConfiguration; import io.cdap.cdap.common.conf.Constants; import io.cdap.cdap.common.http.DefaultHttpRequestConfig; import io.cdap.cdap.common.internal.remote.RemoteClient; import io.cdap.cdap.common.io.Locations; import io.cdap.cdap.common.service.Retries; import io.cdap.cdap.common.service.RetryStrategy; import io.cdap.cdap.internal.guava.reflect.TypeToken; import io.cdap.cdap.internal.io.SchemaTypeAdapter; import io.cdap.cdap.proto.id.NamespaceId; import io.cdap.cdap.security.spi.authentication.AuthenticationContext; import io.cdap.common.http.HttpMethod; import io.cdap.common.http.HttpRequest; import io.cdap.common.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import org.apache.twill.discovery.DiscoveryServiceClient; import org.apache.twill.filesystem.Location; import org.apache.twill.filesystem.LocationFactory; import java.io.IOException; import java.lang.reflect.Type; import java.util.List; import javax.annotation.Nullable; /** * Implementation for {@link io.cdap.cdap.api.artifact.ArtifactManager} * communicating with {@link io.cdap.cdap.gateway.handlers.ArtifactHttpHandler} and returning artifact info. */ public final class RemoteArtifactManager extends AbstractArtifactManager { private static final Gson GSON = new GsonBuilder() .registerTypeAdapter(Schema.class, new SchemaTypeAdapter()) .create(); private static final Type ARTIFACT_INFO_LIST_TYPE = new TypeToken<List<ArtifactInfo>>() { }.getType(); private final LocationFactory locationFactory; private final AuthenticationContext authenticationContext; private final NamespaceId namespaceId; private final RetryStrategy retryStrategy; private final boolean authorizationEnabled; private final RemoteClient remoteClient; @Inject RemoteArtifactManager(CConfiguration cConf, DiscoveryServiceClient discoveryServiceClient, LocationFactory locationFactory, AuthenticationContext authenticationContext, @Assisted NamespaceId namespaceId, @Assisted RetryStrategy retryStrategy) { super(cConf); this.locationFactory = locationFactory; this.authenticationContext = authenticationContext; this.namespaceId = namespaceId; this.retryStrategy = retryStrategy; this.authorizationEnabled = cConf.getBoolean(Constants.Security.Authorization.ENABLED); this.remoteClient = new RemoteClient(discoveryServiceClient, Constants.Service.APP_FABRIC_HTTP, new DefaultHttpRequestConfig(false), String.format("%s", Constants.Gateway.API_VERSION_3)); } /** * For the specified namespace, return the available artifacts in the namespace and also the artifacts in system * namespace. * * If the app-fabric service is unavailable, it will be retried based on the passed in retry strategy. * * @return {@link List<ArtifactInfo>} * @throws IOException If there are any exception while retrieving artifacts */ @Override public List<ArtifactInfo> listArtifacts() throws IOException { return listArtifacts(namespaceId.getNamespace()); } /** * For the specified namespace, return the available artifacts in the namespace and also the artifacts in system * namespace. * * If the app-fabric service is unavailable, it will be retried based on the passed in retry strategy. * * @return {@link List<ArtifactInfo>} * @throws IOException If there are any exception while retrieving artifacts */ @Override public List<ArtifactInfo> listArtifacts(String namespace) throws IOException { return Retries.callWithRetries(() -> { HttpRequest.Builder requestBuilder = remoteClient.requestBuilder(HttpMethod.GET, String.format("namespaces/%s/artifact-internals/artifacts", namespace)); // add header if auth is enabled if (authorizationEnabled) { requestBuilder.addHeader(Constants.Security.Headers.USER_ID, authenticationContext.getPrincipal().getName()); } return getArtifactsList(requestBuilder.build()); }, retryStrategy); } private List<ArtifactInfo> getArtifactsList(HttpRequest httpRequest) throws IOException { HttpResponse httpResponse = remoteClient.execute(httpRequest); if (httpResponse.getResponseCode() == HttpResponseStatus.NOT_FOUND.code()) { throw new IOException("Could not list artifacts, endpoint not found"); } if (httpResponse.getResponseCode() == 200) { return GSON.fromJson(httpResponse.getResponseBodyAsString(), ARTIFACT_INFO_LIST_TYPE); } throw new IOException("Exception while getting artifacts list " + httpResponse.getResponseBodyAsString()); } @Override protected Location getArtifactLocation(ArtifactInfo artifactInfo, @Nullable String artifactNamespace) throws IOException { String namespace; if (ArtifactScope.SYSTEM.equals(artifactInfo.getScope())) { namespace = NamespaceId.SYSTEM.getNamespace(); } else if (artifactNamespace != null) { namespace = artifactNamespace; } else { namespace = namespaceId.getNamespace(); } HttpRequest.Builder requestBuilder = remoteClient.requestBuilder( HttpMethod.GET, String.format("namespaces/%s/artifact-internals/artifacts/%s/versions/%s/location", namespace, artifactInfo.getName(), artifactInfo.getVersion())); // add header if auth is enabled if (authorizationEnabled) { requestBuilder.addHeader(Constants.Security.Headers.USER_ID, authenticationContext.getPrincipal().getName()); } HttpResponse httpResponse = remoteClient.execute(requestBuilder.build()); if (httpResponse.getResponseCode() == HttpResponseStatus.NOT_FOUND.code()) { throw new IOException("Could not get artifact detail, endpoint not found"); } if (httpResponse.getResponseCode() != 200) { throw new IOException(String.format("Exception while getting artifacts list %s", httpResponse.getResponseBodyAsString())); } String path = httpResponse.getResponseBodyAsString(); Location location = Locations.getLocationFromAbsolutePath(locationFactory, path); if (!location.exists()) { throw new IOException(String.format("Artifact Location does not exist %s for artifact %s version %s", path, artifactInfo.getName(), artifactInfo.getVersion())); } return location; } }
package academy.devdojo.maratonajava.javacore.Vio.test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class BufferedReaderTest01 { public static void main(String[] args) { File file = new File("file.txt"); try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) { String linha; while ((linha = br.readLine()) != null) { System.out.println(linha); } } catch (IOException e) { e.printStackTrace(); } } }
package com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_extra_user.developer.bitdubai.version_1.exceptions; import com.bitdubai.fermat_api.FermatException; /** * Created by eze on 2015.06.25.. */ public class CantRegisterNewTransactionException extends FermatException { /** * This is the constructor that every inherited FermatException must implement * * @param message the short description of the why this exception happened, there is a public static constant called DEFAULT_MESSAGE that can be used here * @param cause the exception that triggered the throwing of the current exception, if there are no other exceptions to be declared here, the cause should be null * @param context a String that provides the values of the variables that could have affected the exception * @param possibleReason an explicative reason of why we believe this exception was most likely thrown */ public CantRegisterNewTransactionException(String message, Exception cause, String context, String possibleReason) { super(message, cause, context, possibleReason); } }
package deepboof; import boofcv.alg.color.ColorYuv; import boofcv.core.image.GConvertImage; import boofcv.gui.image.ImageGridPanel; import boofcv.gui.image.ShowImages; import boofcv.io.image.ConvertBufferedImage; import boofcv.struct.image.GrayF32; import boofcv.struct.image.GrayU8; import boofcv.struct.image.Planar; import deepboof.io.DeepBoofDataBaseOps; import deepboof.io.torch7.ParseAsciiTorch7; import deepboof.io.torch7.struct.TorchGeneric; import deepboof.io.torch7.struct.TorchObject; import deepboof.misc.DeepBoofOps; import deepboof.tensors.Tensor_U8; import org.ddogleg.struct.GrowQueue_I8; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static deepboof.io.torch7.ConvertTorchToBoofForward.convert; /** * @author Peter Abeles */ public class DataSetsCifar10 { public static DataSet loadTrainingYuv(boolean show) throws IOException { File trainingDir = DataSetsCifar10.downloadData(); System.out.println("Training data set "+trainingDir.getPath()); ParseAsciiTorch7 ascii = new ParseAsciiTorch7(); List<Planar<GrayF32>> listYuv = new ArrayList<>(); GrowQueue_I8 labels = new GrowQueue_I8(); for( File f : trainingDir.listFiles() ) { if( !f.getName().startsWith("data_")) continue; Map<Object,TorchObject> map = ((TorchGeneric)ascii.parseOne(f)).map; listYuv.addAll(DataSetsCifar10.convertToYuv(convert(map.get("data")),show)); Tensor_U8 l = convert(map.get("labels")); labels.addAll(l.d,0,l.d.length); } byte d[] = new byte[labels.size()]; System.arraycopy(labels.data,0,d,0,labels.size()); labels.data = d; Tensor_U8 l = Tensor_U8.wrap(labels.data,labels.size()); return new DataSet(listYuv,l); } public static DataSet loadTestYuv(boolean show) throws IOException { File trainingDir = DataSetsCifar10.downloadData(); ParseAsciiTorch7 ascii = new ParseAsciiTorch7(); File f = new File(trainingDir,"test_batch.t7"); Map<Object,TorchObject> map = ((TorchGeneric)ascii.parseOne(f)).map; List<Planar<GrayF32>> listYuv = DataSetsCifar10.convertToYuv(convert(map.get("data")),show); Tensor_U8 labels = convert(map.get("labels")); labels.reshape(labels.length());// it's saved with a weird shape that messes stuff up return new DataSet(listYuv,labels); } public static File downloadData() { File trainingDir = DeepBoofOps.pathData("cifar10"); // If needed, download required data sets and network model if( !trainingDir.exists() ) { System.out.println("Obtaining training and testing data. size = 175 MB"); DeepBoofDataBaseOps.download("http://torch7.s3-website-us-east-1.amazonaws.com/data/cifar-10-torch.tar.gz",trainingDir); DeepBoofDataBaseOps.decompressTGZ(new File(trainingDir,"cifar-10-torch.tar.gz"),trainingDir); DeepBoofDataBaseOps.moveInsideAndDeleteDir(new File(trainingDir,"cifar-10-batches-t7"),trainingDir); } return trainingDir; } /** * The input test set tensor is stored in a weird format. This will unroll each * image and convert it into a YUV image. */ public static List<Planar<GrayF32>> convertToYuv(Tensor_U8 raw , boolean showFirstImages ) { List<Planar<GrayF32>> output = new ArrayList<>(); int numTest = raw.length(1); Planar<GrayU8> color = new Planar<>(GrayU8.class,32,32,3); Planar<GrayF32> rgb = new Planar<>(GrayF32.class,32,32,3); ImageGridPanel gui = null; if( showFirstImages ) { gui = new ImageGridPanel(6,6); } for (int test = 0; test < numTest; test++) { // parse the ass backwards RGB format that the test image was stored in int imageIndex = 0; for (int band = 0; band < 3; band++) { GrayU8 gray = color.getBand(band); for (int y = 0; y < 32; y++) { for (int x = 0; x < 32; x++, imageIndex++) { gray.data[y * 32 + x] = raw.d[raw.idx(imageIndex, test)]; } } } if( showFirstImages && test < 36) { BufferedImage buffered = ConvertBufferedImage.convertTo(rgb,null,true); gui.setImage(test/6,test%6,buffered); } Planar<GrayF32> yuv = new Planar<>(GrayF32.class,32,32,3); GConvertImage.convert(color,rgb); ColorYuv.rgbToYuv_F32(rgb,yuv); output.add( yuv ); } if( showFirstImages ) { gui.autoSetPreferredSize(); ShowImages.showWindow(gui,"CIFAR-10 Images",false); } return output; } public static class DataSet { public List<Planar<GrayF32>> images; public Tensor_U8 labels; public DataSet(List<Planar<GrayF32>> images, Tensor_U8 labels) { this.images = images; this.labels = labels; } public DataSet() { } } }
package org.highmed.dsf.fhir.search.parameters.user; import org.highmed.dsf.fhir.authentication.User; public class NamingSystemUserFilter extends AbstractMetaTagAuthorizationRoleUserFilter { private static final String RESOURCE_COLUMN = "naming_system"; public NamingSystemUserFilter(User user) { super(user, RESOURCE_COLUMN); } public NamingSystemUserFilter(User user, String resourceColumn) { super(user, resourceColumn); } }
package edu.wpi.grip.generated.opencv_imgproc.enumeration; import org.bytedeco.javacpp.opencv_imgproc; public enum MorphTypesEnum { /** see cv::erode */ MORPH_ERODE(opencv_imgproc.MORPH_ERODE), /** see cv::dilate */ MORPH_DILATE(opencv_imgproc.MORPH_DILATE), /** an opening operation * \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] */ MORPH_OPEN(opencv_imgproc.MORPH_OPEN), /** a closing operation * \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] */ MORPH_CLOSE(opencv_imgproc.MORPH_CLOSE), /** a morphological gradient * \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] */ MORPH_GRADIENT(opencv_imgproc.MORPH_GRADIENT), /** "top hat" * \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] */ MORPH_TOPHAT(opencv_imgproc.MORPH_TOPHAT), /** "black hat" * \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] */ MORPH_BLACKHAT(opencv_imgproc.MORPH_BLACKHAT); public final int value; MorphTypesEnum(int value) { this.value = value; } }
package pers.li.rpc; import lombok.AllArgsConstructor; import lombok.Data; /** * 表示网络传输的一个端点 */ @Data @AllArgsConstructor public class Peer { private String host; private int port; }
package com.denizenscript.denizen.events.player; import com.denizenscript.denizen.objects.EntityTag; import com.denizenscript.denizen.objects.ItemTag; import com.denizenscript.denizen.objects.LocationTag; import com.denizenscript.denizen.objects.PlayerTag; import com.denizenscript.denizen.utilities.implementation.BukkitScriptEntryData; import com.denizenscript.denizen.events.BukkitScriptEvent; import com.denizenscript.denizencore.events.ScriptEvent; import com.denizenscript.denizencore.objects.ObjectTag; import com.denizenscript.denizencore.scripts.ScriptEntryData; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTakeLecternBookEvent; public class PlayerTakesFromLecternScriptEvent extends BukkitScriptEvent implements Listener { // <--[event] // @Events // player takes item from lectern // player takes <item> from lectern // // @Regex ^on player takes [^\s]+ from lectern$ // // @Group Player // // @Location true // // @Cancellable true // // @Triggers when a player takes a book from a lectern. // // @Context // <context.location> returns the LocationTag of the lectern. // <context.item> returns the book ItemTag taken out of the lectern. // // @Player Always. // // --> public PlayerTakesFromLecternScriptEvent() { instance = this; } public static PlayerTakesFromLecternScriptEvent instance; public LocationTag location; public ItemTag item; public PlayerTakeLecternBookEvent event; @Override public boolean couldMatch(ScriptPath path) { if (!path.eventLower.startsWith("player takes") || !path.eventArgsLowEqualStartingAt(3, "from", "lectern")) { return false; } if (!couldMatchItem(path.eventArgLowerAt(2))) { return false; } return true; } @Override public boolean matches(ScriptEvent.ScriptPath path) { String itemTest = path.eventArgLowerAt(2); if (!tryItem(item, itemTest)) { return false; } if (!runInCheck(path, location)) { return false; } return super.matches(path); } @Override public String getName() { return "PlayerTakesFromLectern"; } @Override public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData(PlayerTag.mirrorBukkitPlayer(event.getPlayer()), null); } @Override public ObjectTag getContext(String name) { if (name.equals("location")) { return location; } else if (name.equals("item")) { return item; } return super.getContext(name); } @EventHandler public void onPlayerTakesFromLectern(PlayerTakeLecternBookEvent event) { if (EntityTag.isNPC(event.getPlayer())) { return; } item = new ItemTag(event.getBook()); location = new LocationTag(event.getLectern().getLocation()); this.event = event; fire(event); } }
package cn.ruleengine.web.service.generalrule.impl; import cn.hutool.core.util.StrUtil; import cn.ruleengine.core.rule.GeneralRule; import cn.ruleengine.web.config.Context; import cn.ruleengine.web.enums.EnableEnum; import cn.ruleengine.web.enums.DataStatus; import cn.ruleengine.web.listener.body.GeneralRuleMessageBody; import cn.ruleengine.web.listener.event.GeneralRuleEvent; import cn.ruleengine.web.service.*; import cn.ruleengine.web.service.generalrule.GeneralRuleService; import cn.ruleengine.web.store.entity.*; import cn.ruleengine.web.store.manager.*; import cn.ruleengine.web.store.mapper.RuleEngineRuleMapper; import cn.ruleengine.web.store.mapper.RuleEngineGeneralRuleMapper; import cn.ruleengine.web.util.PageUtils; import cn.ruleengine.web.util.VersionUtils; import cn.ruleengine.web.vo.common.ViewRequest; import cn.ruleengine.web.vo.condition.*; import cn.ruleengine.web.vo.convert.BasicConversion; import cn.ruleengine.web.vo.base.PageRequest; import cn.ruleengine.web.vo.base.PageBase; import cn.ruleengine.web.vo.base.PageResult; import cn.ruleengine.web.vo.generalrule.*; import cn.ruleengine.core.condition.ConditionGroup; import cn.ruleengine.web.vo.generalrule.DefaultAction; import cn.hutool.core.lang.Validator; import cn.ruleengine.core.Engine; import cn.ruleengine.core.exception.ValidException; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import cn.ruleengine.web.vo.user.UserData; import cn.ruleengine.web.vo.workspace.Workspace; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; /** * 〈一句话功能简述〉<br> * 〈〉 * * @author dingqianwen * @date 2020/8/24 * @since 1.0.0 */ @Transactional(rollbackFor = Exception.class) @Service public class GeneralRuleServiceImpl implements GeneralRuleService { @Resource private RuleEngineRuleManager ruleEngineRuleManager; @Resource private RuleEngineGeneralRuleManager ruleEngineGeneralRuleManager; @Resource private RuleEngineGeneralRuleMapper ruleEngineGeneralRuleMapper; @Resource private RuleEngineRuleMapper ruleEngineRuleMapper; @Resource private Engine engine; @Resource private ParameterService parameterService; @Resource private RuleEngineGeneralRulePublishManager ruleEngineGeneralRulePublishManager; @Resource private ApplicationEventPublisher eventPublisher; @Resource private ValueResolve valueResolve; @Resource private RuleEngineConditionGroupService ruleEngineConditionGroupService; @Resource private ConditionSetService conditionSetService; @Resource private ReferenceDataService referenceDataService; /** * 规则列表 * * @param pageRequest 分页查询数据 * @return page */ @Override public PageResult<ListGeneralRuleResponse> list(PageRequest<ListGeneralRuleRequest> pageRequest) { List<PageRequest.OrderBy> orders = pageRequest.getOrders(); PageBase page = pageRequest.getPage(); Workspace workspace = Context.getCurrentWorkspace(); return PageUtils.page(this.ruleEngineGeneralRuleManager, page, () -> { QueryWrapper<RuleEngineGeneralRule> wrapper = new QueryWrapper<>(); wrapper.lambda().eq(RuleEngineGeneralRule::getWorkspaceId, workspace.getId()); PageUtils.defaultOrder(orders, wrapper); ListGeneralRuleRequest query = pageRequest.getQuery(); if (Validator.isNotEmpty(query.getName())) { wrapper.lambda().like(RuleEngineGeneralRule::getName, query.getName()); } if (Validator.isNotEmpty(query.getCode())) { wrapper.lambda().like(RuleEngineGeneralRule::getCode, query.getCode()); } // 遗留bug修复 if (Validator.isNotEmpty(query.getStatus())) { if (query.getStatus().equals(DataStatus.PUBLISHED.getStatus())) { wrapper.lambda().isNotNull(RuleEngineGeneralRule::getPublishVersion); } else { wrapper.lambda().eq(RuleEngineGeneralRule::getStatus, query.getStatus()); } } return wrapper; }, m -> { ListGeneralRuleResponse listRuleResponse = new ListGeneralRuleResponse(); listRuleResponse.setId(m.getId()); listRuleResponse.setName(m.getName()); listRuleResponse.setCode(m.getCode()); listRuleResponse.setCurrentVersion(m.getCurrentVersion()); listRuleResponse.setPublishVersion(m.getPublishVersion()); listRuleResponse.setCreateUserName(m.getCreateUserName()); listRuleResponse.setStatus(m.getStatus()); listRuleResponse.setCreateTime(m.getCreateTime()); return listRuleResponse; }); } /** * 规则code是否存在 * * @param code 规则code * @return true存在 */ @Override public Boolean ruleCodeIsExists(String code) { Workspace workspace = Context.getCurrentWorkspace(); Integer count = this.ruleEngineGeneralRuleManager.lambdaQuery() .eq(RuleEngineGeneralRule::getWorkspaceId, workspace.getId()) .eq(RuleEngineGeneralRule::getCode, code) .count(); return count != null && count >= 1; } /** * 更新规则信息 * * @param generalRuleBody 规则配置数据 * @return true执行成功 */ @Override public Boolean updateRule(GeneralRuleBody generalRuleBody) { RuleEngineGeneralRule ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.getById(generalRuleBody.getId()); if (ruleEngineGeneralRule == null) { throw new ValidException("不存在规则:{}", generalRuleBody.getId()); } // 如果之前是待发布,则删除原有待发布数据 if (Objects.equals(ruleEngineGeneralRule.getStatus(), DataStatus.WAIT_PUBLISH.getStatus())) { this.ruleEngineGeneralRulePublishManager.lambdaUpdate() .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.WAIT_PUBLISH.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, generalRuleBody.getId()) .remove(); } // 如果原来有条件信息,先删除原有信息 this.ruleEngineConditionGroupService.removeConditionGroupByRuleIds(Collections.singletonList(ruleEngineGeneralRule.getRuleId())); // 保存条件信息 this.ruleEngineConditionGroupService.saveConditionGroup(ruleEngineGeneralRule.getRuleId(), generalRuleBody.getConditionGroup()); // 更新规则信息 ruleEngineGeneralRule.setId(generalRuleBody.getId()); ruleEngineGeneralRule.setStatus(DataStatus.EDIT.getStatus()); // 保存规则结果 this.saveAction(ruleEngineGeneralRule.getRuleId(), generalRuleBody.getAction()); // 保存默认结果 DefaultAction defaultAction = generalRuleBody.getDefaultAction(); ruleEngineGeneralRule.setEnableDefaultAction(defaultAction.getEnableDefaultAction()); ruleEngineGeneralRule.setDefaultActionValue(defaultAction.getValue()); ruleEngineGeneralRule.setDefaultActionValueType(defaultAction.getValueType()); ruleEngineGeneralRule.setDefaultActionType(defaultAction.getType()); ruleEngineGeneralRule.setReferenceData(JSON.toJSONString(referenceDataService.countReferenceData(generalRuleBody))); this.ruleEngineGeneralRuleMapper.updateRuleById(ruleEngineGeneralRule); return true; } /** * 保存结果 * * @param ruleId 规则id * @param action 结果 */ private void saveAction(Integer ruleId, ConfigValue action) { RuleEngineRule ruleEngineRule = new RuleEngineRule(); ruleEngineRule.setId(ruleId); ruleEngineRule.setActionType(action.getType()); ruleEngineRule.setActionValueType(action.getValueType()); ruleEngineRule.setActionValue(action.getValue()); this.ruleEngineRuleMapper.updateRuleById(ruleEngineRule); } /** * 删除规则 * * @param id 规则id * @return true */ @Override public Boolean delete(Integer id) { RuleEngineGeneralRule ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.getById(id); if (ruleEngineGeneralRule == null) { return false; } // 从引擎中移除规则 if (this.engine.isExists(ruleEngineGeneralRule.getWorkspaceCode(), ruleEngineGeneralRule.getCode())) { GeneralRuleMessageBody ruleMessageBody = new GeneralRuleMessageBody(); ruleMessageBody.setType(GeneralRuleMessageBody.Type.REMOVE); ruleMessageBody.setWorkspaceId(ruleEngineGeneralRule.getWorkspaceId()); ruleMessageBody.setWorkspaceCode(ruleEngineGeneralRule.getWorkspaceCode()); ruleMessageBody.setRuleCode(ruleEngineGeneralRule.getCode()); this.eventPublisher.publishEvent(new GeneralRuleEvent(ruleMessageBody)); } this.ruleEngineRuleManager.removeById(ruleEngineGeneralRule.getRuleId()); // 删除规则发布记录 this.ruleEngineGeneralRulePublishManager.lambdaUpdate().eq(RuleEngineGeneralRulePublish::getGeneralRuleId, id).remove(); // 删除规则条件组信息 this.ruleEngineConditionGroupService.removeConditionGroupByRuleIds(Collections.singletonList(ruleEngineGeneralRule.getRuleId())); // 删除规则 return this.ruleEngineGeneralRuleManager.removeById(id); } /** * 保存或者更新规则定义信息 * * @param ruleDefinition 规则定义信息 * @return 规则id */ @Override public Integer saveOrUpdateRuleDefinition(GeneralRuleDefinition ruleDefinition) { // 创建规则 RuleEngineGeneralRule ruleEngineGeneralRule = new RuleEngineGeneralRule(); if (ruleDefinition.getId() == null) { if (this.ruleCodeIsExists(ruleDefinition.getCode())) { throw new ValidException("规则Code:{}已经存在", ruleDefinition.getCode()); } Workspace workspace = Context.getCurrentWorkspace(); UserData userData = Context.getCurrentUser(); ruleEngineGeneralRule.setCreateUserId(userData.getId()); ruleEngineGeneralRule.setCreateUserName(userData.getUsername()); ruleEngineGeneralRule.setWorkspaceId(workspace.getId()); ruleEngineGeneralRule.setWorkspaceCode(workspace.getCode()); RuleEngineRule ruleEngineRule = new RuleEngineRule(); ruleEngineRule.setName(ruleDefinition.getName()); ruleEngineRule.setCode(ruleDefinition.getCode()); ruleEngineRule.setDescription(ruleDefinition.getDescription()); ruleEngineRule.setCreateUserId(userData.getId()); ruleEngineRule.setCreateUserName(userData.getUsername()); this.ruleEngineRuleManager.save(ruleEngineRule); ruleEngineGeneralRule.setRuleId(ruleEngineRule.getId()); } else { ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.lambdaQuery() .eq(RuleEngineGeneralRule::getId, ruleDefinition.getId()) .one(); if (ruleEngineGeneralRule == null) { throw new ValidException("不存在规则:{}", ruleDefinition.getId()); } else { if (Objects.equals(ruleEngineGeneralRule.getStatus(), DataStatus.WAIT_PUBLISH.getStatus())) { // 删除原有待发布规则 this.ruleEngineGeneralRulePublishManager.lambdaUpdate() .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.WAIT_PUBLISH.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, ruleEngineGeneralRule.getId()) .remove(); } } } ruleEngineGeneralRule.setId(ruleDefinition.getId()); ruleEngineGeneralRule.setName(ruleDefinition.getName()); ruleEngineGeneralRule.setCode(ruleDefinition.getCode()); ruleEngineGeneralRule.setDescription(ruleDefinition.getDescription()); ruleEngineGeneralRule.setStatus(DataStatus.EDIT.getStatus()); this.ruleEngineGeneralRuleManager.saveOrUpdate(ruleEngineGeneralRule); return ruleEngineGeneralRule.getId(); } /** * 获取规则定义信息 * * @param id 规则id * @return 规则定义信息 */ @Override public GeneralRuleDefinition getRuleDefinition(Integer id) { RuleEngineGeneralRule engineGeneralRule = this.ruleEngineGeneralRuleManager.lambdaQuery() .eq(RuleEngineGeneralRule::getId, id) .one(); if (engineGeneralRule == null) { return null; } return BasicConversion.INSTANCE.convert(engineGeneralRule); } /** * 生成待发布版本,更新规则数据 * * @param generalRuleBody 规则配置数据 * @return true */ @Override public Boolean generationRelease(GeneralRuleBody generalRuleBody) { // 更新规则 RuleEngineGeneralRule ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.getById(generalRuleBody.getId()); if (ruleEngineGeneralRule == null) { throw new ValidException("不存在规则:{}", generalRuleBody.getId()); } // 如果开启了默认结果 DefaultAction defaultAction = generalRuleBody.getDefaultAction(); defaultAction.valid(); // 如果原来有条件信息,先删除原有信息 this.ruleEngineConditionGroupService.removeConditionGroupByRuleIds(Collections.singletonList(ruleEngineGeneralRule.getRuleId())); // 保存条件信息 this.ruleEngineConditionGroupService.saveConditionGroup(ruleEngineGeneralRule.getRuleId(), generalRuleBody.getConditionGroup()); // 更新版本 if (StrUtil.isBlank(ruleEngineGeneralRule.getCurrentVersion())) { ruleEngineGeneralRule.setCurrentVersion(VersionUtils.INIT_VERSION); } else { // 如果待发布与已经发布版本一致,则需要更新一个版本号 if (ruleEngineGeneralRule.getCurrentVersion().equals(ruleEngineGeneralRule.getPublishVersion())) { // 获取下一个版本 ruleEngineGeneralRule.setCurrentVersion(VersionUtils.getNextVersion(ruleEngineGeneralRule.getCurrentVersion())); } } // 更新规则信息 ruleEngineGeneralRule.setStatus(DataStatus.WAIT_PUBLISH.getStatus()); // 保存结果 ConfigValue action = generalRuleBody.getAction(); this.saveAction(ruleEngineGeneralRule.getRuleId(), generalRuleBody.getAction()); // 保存默认结果 ruleEngineGeneralRule.setEnableDefaultAction(defaultAction.getEnableDefaultAction()); ruleEngineGeneralRule.setDefaultActionValue(defaultAction.getValue()); ruleEngineGeneralRule.setDefaultActionValueType(defaultAction.getValueType()); ruleEngineGeneralRule.setDefaultActionType(defaultAction.getType()); String referenceData = JSON.toJSONString(referenceDataService.countReferenceData(generalRuleBody)); ruleEngineGeneralRule.setReferenceData(referenceData); this.ruleEngineGeneralRuleMapper.updateRuleById(ruleEngineGeneralRule); // 添加新的待发布数据 GeneralRule generalRule = new GeneralRule(); generalRule.setId(generalRuleBody.getId()); generalRule.setCode(ruleEngineGeneralRule.getCode()); generalRule.setName(ruleEngineGeneralRule.getName()); generalRule.setWorkspaceCode(ruleEngineGeneralRule.getWorkspaceCode()); generalRule.setWorkspaceId(ruleEngineGeneralRule.getWorkspaceId()); generalRule.setDescription(ruleEngineGeneralRule.getDescription()); generalRule.setConditionSet(this.conditionSetService.loadConditionSet(generalRuleBody.getConditionGroup())); generalRule.setActionValue(this.valueResolve.getValue(action.getType(), action.getValueType(), action.getValue())); // 如果启用了默认结果 if (EnableEnum.ENABLE.getStatus().equals(defaultAction.getEnableDefaultAction())) { generalRule.setDefaultActionValue(this.valueResolve.getValue(defaultAction.getType(), defaultAction.getValueType(), defaultAction.getValue())); } // 将不再判断是否存在待发布,直接执行删除sql this.ruleEngineGeneralRulePublishManager.lambdaUpdate() .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.WAIT_PUBLISH.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, ruleEngineGeneralRule.getId()) .remove(); // 生成待发布规则 RuleEngineGeneralRulePublish rulePublish = new RuleEngineGeneralRulePublish(); rulePublish.setGeneralRuleId(generalRule.getId()); rulePublish.setGeneralRuleCode(generalRule.getCode()); rulePublish.setData(generalRule.toJson()); rulePublish.setStatus(DataStatus.WAIT_PUBLISH.getStatus()); rulePublish.setWorkspaceId(generalRule.getWorkspaceId()); // add version rulePublish.setVersion(ruleEngineGeneralRule.getCurrentVersion()); rulePublish.setWorkspaceCode(generalRule.getWorkspaceCode()); rulePublish.setReferenceData(referenceData); this.ruleEngineGeneralRulePublishManager.save(rulePublish); return true; } /** * 规则发布 * * @param id 规则id * @return true */ @Override public Boolean publish(Integer id) { RuleEngineGeneralRule ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.getById(id); if (ruleEngineGeneralRule == null) { throw new ValidException("不存在规则:{}", id); } if (ruleEngineGeneralRule.getStatus().equals(DataStatus.EDIT.getStatus())) { throw new ValidException("该规则不可执行:{}", id); } // 如果已经是发布规则了 if (ruleEngineGeneralRule.getStatus().equals(DataStatus.PUBLISHED.getStatus())) { return true; } // 修改为已发布 this.ruleEngineGeneralRuleManager.lambdaUpdate() .set(RuleEngineGeneralRule::getStatus, DataStatus.PUBLISHED.getStatus()) // 更新发布的版本号 .set(RuleEngineGeneralRule::getPublishVersion, ruleEngineGeneralRule.getCurrentVersion()) .eq(RuleEngineGeneralRule::getId, ruleEngineGeneralRule.getId()) .update(); /* * 删除原有的已发布规则数据 * 修改为,原有已发布为历史版本,后期准备回退 */ this.ruleEngineGeneralRulePublishManager.lambdaUpdate() .set(RuleEngineGeneralRulePublish::getStatus, DataStatus.HISTORY_PUBLISHED.getStatus()) .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.PUBLISHED.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, ruleEngineGeneralRule.getId()) .update(); // 更新待发布为已发布 this.ruleEngineGeneralRulePublishManager.lambdaUpdate() .set(RuleEngineGeneralRulePublish::getStatus, DataStatus.PUBLISHED.getStatus()) .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.WAIT_PUBLISH.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, ruleEngineGeneralRule.getId()) .update(); // 加载规则 GeneralRuleMessageBody ruleMessageBody = new GeneralRuleMessageBody(); ruleMessageBody.setType(GeneralRuleMessageBody.Type.LOAD); ruleMessageBody.setRuleCode(ruleEngineGeneralRule.getCode()); ruleMessageBody.setWorkspaceId(ruleEngineGeneralRule.getWorkspaceId()); ruleMessageBody.setWorkspaceCode(ruleEngineGeneralRule.getWorkspaceCode()); this.eventPublisher.publishEvent(new GeneralRuleEvent(ruleMessageBody)); return true; } /** * 获取规则信息 * * @param id 规则id * @return 规则信息 */ @Override public GetGeneralRuleResponse getRuleConfig(Integer id) { RuleEngineGeneralRule ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.getById(id); if (ruleEngineGeneralRule == null) { return null; } GetGeneralRuleResponse ruleResponse = new GetGeneralRuleResponse(); ruleResponse.setId(ruleEngineGeneralRule.getId()); ruleResponse.setCode(ruleEngineGeneralRule.getCode()); ruleResponse.setName(ruleEngineGeneralRule.getName()); ruleResponse.setDescription(ruleEngineGeneralRule.getDescription()); ruleResponse.setConditionGroup(this.ruleEngineConditionGroupService.getConditionGroupConfig(ruleEngineGeneralRule.getRuleId())); // 结果 RuleEngineRule ruleEngineRule = this.ruleEngineRuleManager.getById(ruleEngineGeneralRule.getRuleId()); ConfigValue action = this.valueResolve.getConfigValue(ruleEngineRule.getActionValue(), ruleEngineRule.getActionType(), ruleEngineRule.getActionValueType()); ruleResponse.setAction(action); // 默认结果 ConfigValue defaultValue = this.valueResolve.getConfigValue(ruleEngineGeneralRule.getDefaultActionValue(), ruleEngineGeneralRule.getDefaultActionType(), ruleEngineGeneralRule.getDefaultActionValueType()); DefaultAction defaultAction = new DefaultAction(defaultValue); defaultAction.setEnableDefaultAction(ruleEngineGeneralRule.getEnableDefaultAction()); ruleResponse.setDefaultAction(defaultAction); return ruleResponse; } /** * 规则预览 * * @param viewRequest 规则id * @return GetRuleResponse */ @Override public ViewGeneralRuleResponse view(ViewRequest viewRequest) { Integer id = viewRequest.getId(); RuleEngineGeneralRule ruleEngineGeneralRule = this.ruleEngineGeneralRuleManager.getById(id); if (ruleEngineGeneralRule == null) { throw new ValidException("找不到预览的规则数据:{}", id); } if (ruleEngineGeneralRule.getStatus().equals(DataStatus.PUBLISHED.getStatus()) || viewRequest.getStatus().equals(DataStatus.PUBLISHED.getStatus())) { RuleEngineGeneralRulePublish engineRulePublish = this.ruleEngineGeneralRulePublishManager.lambdaQuery() .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.PUBLISHED.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, id) .one(); if (engineRulePublish == null) { throw new ValidException("找不到发布的规则:{}", id); } String data = engineRulePublish.getData(); GeneralRule rule = GeneralRule.buildRule(data); return this.getRuleResponseProcess(rule); } RuleEngineGeneralRulePublish engineRulePublish = this.ruleEngineGeneralRulePublishManager.lambdaQuery() .eq(RuleEngineGeneralRulePublish::getStatus, DataStatus.WAIT_PUBLISH.getStatus()) .eq(RuleEngineGeneralRulePublish::getGeneralRuleId, id) .one(); if (engineRulePublish == null) { throw new ValidException("找不到预览的规则数据:{}", id); } String data = engineRulePublish.getData(); GeneralRule rule = GeneralRule.buildRule(data); return this.getRuleResponseProcess(rule); } /** * 解析Rule配置信息为ViewGeneralRuleResponse * * @param rule Rule * @return ViewGeneralRuleResponse */ private ViewGeneralRuleResponse getRuleResponseProcess(GeneralRule rule) { ViewGeneralRuleResponse ruleResponse = new ViewGeneralRuleResponse(); ruleResponse.setId(rule.getId()); ruleResponse.setName(rule.getName()); ruleResponse.setCode(rule.getCode()); ruleResponse.setWorkspaceId(rule.getWorkspaceId()); ruleResponse.setWorkspaceCode(rule.getWorkspaceCode()); ruleResponse.setDescription(rule.getDescription()); List<ConditionGroup> conditionGroups = rule.getConditionSet().getConditionGroups(); ruleResponse.setConditionGroup(this.ruleEngineConditionGroupService.pressConditionGroupConfig(conditionGroups)); ruleResponse.setAction(valueResolve.getConfigValue(rule.getActionValue())); DefaultAction defaultAction; if (rule.getDefaultActionValue() != null) { defaultAction = new DefaultAction(this.valueResolve.getConfigValue(rule.getDefaultActionValue())); defaultAction.setEnableDefaultAction(EnableEnum.ENABLE.getStatus()); } else { defaultAction = new DefaultAction(); defaultAction.setEnableDefaultAction(EnableEnum.DISABLE.getStatus()); } ruleResponse.setDefaultAction(defaultAction); // 规则调用接口,以及规则入参 ruleResponse.setParameters(this.parameterService.getParameters(rule)); return ruleResponse; } }
package com.plexobject.demo.ddb.model; import com.amazonaws.services.dynamodbv2.datamodeling.*; import com.plexobject.aop.Tracer; import java.util.Set; @DynamoDBTable(tableName = "ProductCatalog") @Tracer public class CatalogItem { private String id; private String title; private String ISBN; private Set<String> bookAuthors; private String someProp; private Long version; public CatalogItem() { } public CatalogItem(String id, String title, String ISBN) { this.id = id; this.title = title; this.ISBN = ISBN; } @DynamoDBHashKey(attributeName = "Id") public String getId() { return id; } public void setId(String Id) { this.id = Id; } @DynamoDBAttribute(attributeName = "Title") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @DynamoDBAttribute(attributeName = "ISBN") public String getISBN() { return ISBN; } public void setISBN(String ISBN) { this.ISBN = ISBN; } @DynamoDBAttribute(attributeName = "Authors") public Set<String> getBookAuthors() { return bookAuthors; } public void setBookAuthors(Set<String> bookAuthors) { this.bookAuthors = bookAuthors; } @DynamoDBIgnore public String getSomeProp() { return someProp; } public void setSomeProp(String someProp) { this.someProp = someProp; } @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } }
package com.airbnb.aerosolve.core.transforms; import com.airbnb.aerosolve.core.FeatureVector; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; /** * @author Hector Yee */ public class BucketFloatTransformTest { private static final Logger log = LoggerFactory.getLogger(BucketFloatTransformTest.class); public FeatureVector makeFeatureVector() { Map<String, Set<String>> stringFeatures = new HashMap<>(); Map<String, Map<String, Double>> floatFeatures = new HashMap<>(); Set list = new HashSet<String>(); list.add("aaa"); list.add("bbb"); stringFeatures.put("strFeature1", list); Map<String, Double> map = new HashMap<>(); map.put("lat", 37.7); map.put("long", 40.4); map.put("zero", 0.0); map.put("negative", -1.5); floatFeatures.put("loc", map); FeatureVector featureVector = new FeatureVector(); featureVector.setStringFeatures(stringFeatures); featureVector.setFloatFeatures(floatFeatures); return featureVector; } public String makeConfig() { return "test_quantize {\n" + " transform : bucket_float\n" + " field1 : loc\n" + " bucket : 1.0\n" + " output : loc_quantized\n" + "}"; } @Test public void testEmptyFeatureVector() { Config config = ConfigFactory.parseString(makeConfig()); Transform transform = TransformFactory.createTransform(config, "test_quantize"); FeatureVector featureVector = new FeatureVector(); transform.doTransform(featureVector); assertTrue(featureVector.getStringFeatures() == null); } @Test public void testTransform() { Config config = ConfigFactory.parseString(makeConfig()); Transform transform = TransformFactory.createTransform(config, "test_quantize"); FeatureVector featureVector = makeFeatureVector(); transform.doTransform(featureVector); Map<String, Set<String>> stringFeatures = featureVector.getStringFeatures(); assertTrue(stringFeatures.size() == 1); Map<String, Double> out = featureVector.getFloatFeatures().get("loc_quantized"); log.info("quantize output"); for (Map.Entry<String, Double> entry : out.entrySet()) { log.info(entry.getKey() + "=" + entry.getValue()); } assertTrue(out.size() == 4); assertEquals(0.7, out.get("lat[1.0]=37.0").doubleValue(), 0.1); assertEquals(0.4, out.get("long[1.0]=40.0").doubleValue(), 0.1); assertEquals(0.0, out.get("zero[1.0]=0.0").doubleValue(), 0.1); assertEquals(-0.5, out.get("negative[1.0]=-1.0").doubleValue(), 0.1); } }
package org.jawk.jrt; import com.jagacy.totalAccess.jrt.AwkNode; /** * The AWK Variable Manager. * It provides getter/setter methods for global AWK variables. * Its purpose is to expose a variable management interface to * the JRT, even though the implementation is provided by * the AWK script at script compile-time. * <p> * The getters/setters here do not access <strong>all</strong> * special AWK variables, such as <code>RSTART</code> * and <code>ENVIRON</code>. That's because these variables * are not referred to within the JRT. * </p> * * @see JRT * @see org.jawk.backend.AwkCompiler * @see org.jawk.backend.AwkCompilerImpl * * @author Danny Daglas */ public interface VariableManager { /** Retrieve the contents of the ARGC variable. */ Object getARGC(); /** Retrieve the contents of the ARGV variable. */ Object getARGV(); /** Retrieve the contents of the CONVFMT variable. */ Object getCONVFMT(); /** Retrieve the contents of the FS variable. */ Object getFS(); /** Retrieve the contents of the RS variable. */ Object getRS(); /** Retrieve the contents of the OFS variable. */ Object getOFS(); /** Retrieve the contents of the SUBSEP variable. */ Object getSUBSEP(); // RMP Object getIT(); Object getIFS(); Object getDATEFMT(); Object getNODE(); Object getDEFPROPS(); Object getNS(); void setNODE(AwkNode n); /** Set the contents of the FILENAME variable. */ void setFILENAME(String fileName); /** Set the contents of the NF variable. */ void setNF(Integer newNf); /** Increases the NR variable by 1. */ void incNR(); /** Increases the FNR variable by 1. */ void incFNR(); /** Resets the FNR variable to 0. */ void resetFNR(); /** * Set the contents of a user-defined AWK * variable. Used when processing * <em>name=value</em> command-line arguments * (either via -v or via ARGV). * * @param name The AWK variable name. * @param value The new contents of the variable. */ void assignVariable(String name, Object value); }
package mod.azure.doom.item.weapons; import java.util.List; import io.netty.buffer.Unpooled; import mod.azure.doom.DoomMod; import mod.azure.doom.client.ClientInit; import mod.azure.doom.util.registry.DoomBlocks; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PlayerLookup; import net.minecraft.client.item.TooltipContext; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.math.Box; import net.minecraft.world.World; import software.bernie.geckolib3.core.AnimationState; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import software.bernie.geckolib3.network.GeckoLibNetwork; import software.bernie.geckolib3.network.ISyncable; import software.bernie.geckolib3.util.GeckoLibUtil; public class SwordCrucibleItem extends Item implements IAnimatable, ISyncable { public AnimationFactory factory = new AnimationFactory(this); public String controllerName = "controller"; public static final int ANIM_OPEN = 0; public SwordCrucibleItem() { super(new Item.Settings().group(DoomMod.DoomWeaponItemGroup).maxCount(1).maxDamage(5)); GeckoLibNetwork.registerSyncable(this); } @Override public void onStoppedUsing(ItemStack stack, World worldIn, LivingEntity entityLiving, int remainingUseTicks) { if (entityLiving instanceof PlayerEntity) { PlayerEntity playerentity = (PlayerEntity) entityLiving; if (stack.getDamage() < (stack.getMaxDamage() - 1)) { playerentity.getItemCooldownManager().set(this, 200); final Box aabb = new Box(entityLiving.getBlockPos().up()).expand(4D, 1D, 4D); entityLiving.getEntityWorld().getOtherEntities(entityLiving, aabb) .forEach(e -> doDamage(entityLiving, e)); stack.damage(1, entityLiving, p -> p.sendToolBreakStatus(entityLiving.getActiveHand())); if (!worldIn.isClient) { final int id = GeckoLibUtil.guaranteeIDForStack(stack, (ServerWorld) worldIn); GeckoLibNetwork.syncAnimation(playerentity, this, id, ANIM_OPEN); for (PlayerEntity otherPlayer : PlayerLookup.tracking(playerentity)) { GeckoLibNetwork.syncAnimation(otherPlayer, this, id, ANIM_OPEN); } } } } } private void doDamage(LivingEntity user, Entity target) { if (target instanceof LivingEntity) { target.timeUntilRegen = 0; target.damage(DamageSource.player((PlayerEntity) user), 200F); } } public <P extends Item & IAnimatable> PlayState predicate(AnimationEvent<P> event) { return PlayState.CONTINUE; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void registerControllers(AnimationData data) { data.addAnimationController(new AnimationController(this, controllerName, 1, this::predicate)); } @Override public AnimationFactory getFactory() { return this.factory; } @Override public void onAnimationSync(int id, int state) { if (state == ANIM_OPEN) { final AnimationController<?> controller = GeckoLibUtil.getControllerForID(this.factory, id, controllerName); if (controller.getAnimationState() == AnimationState.Stopped) { controller.markNeedsReload(); controller.setAnimation(new AnimationBuilder().addAnimation("using", false)); } } } @Override public void appendTooltip(ItemStack stack, World world, List<Text> tooltip, TooltipContext context) { tooltip.add(new TranslatableText("doom.crucible_sword.text").formatted(Formatting.RED) .formatted(Formatting.ITALIC)); tooltip.add(new TranslatableText( "Ammo: " + (stack.getMaxDamage() - stack.getDamage() - 1) + " / " + (stack.getMaxDamage() - 1)) .formatted(Formatting.ITALIC)); super.appendTooltip(stack, world, tooltip, context); } public void reload(PlayerEntity user, Hand hand) { if (user.getStackInHand(hand).getItem() instanceof SwordCrucibleItem) { while (user.getStackInHand(hand).getDamage() != 0 && user.getInventory().count(DoomBlocks.ARGENT_BLOCK.asItem()) > 0) { removeAmmo(DoomBlocks.ARGENT_BLOCK.asItem(), user); user.getStackInHand(hand).damage(-5, user, s -> user.sendToolBreakStatus(hand)); user.getStackInHand(hand).setCooldown(3); } } } @Override public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) { PlayerEntity playerentity = (PlayerEntity) entity; if (world.isClient) { if (playerentity.getMainHandStack().getItem() instanceof SwordCrucibleItem && ClientInit.reload.isPressed() && selected) { PacketByteBuf passedData = new PacketByteBuf(Unpooled.buffer()); passedData.writeBoolean(true); ClientPlayNetworking.send(DoomMod.CRUCIBLE, passedData); } } } public void removeAmmo(Item ammo, PlayerEntity playerEntity) { if (!playerEntity.isCreative()) { for (ItemStack item : playerEntity.getInventory().offHand) { if (item.getItem() == ammo) { item.decrement(1); break; } for (ItemStack item1 : playerEntity.getInventory().main) { if (item1.getItem() == ammo) { item1.decrement(1); break; } } } } } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) { ItemStack itemStack = user.getStackInHand(hand); user.setCurrentHand(hand); return TypedActionResult.consume(itemStack); } @Override public boolean hasGlint(ItemStack stack) { return false; } @Override public int getMaxUseTime(ItemStack stack) { return 72000; } }
package org.apereo.cas.util.serialization; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.PrettyPrinter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.hjson.JsonValue; import org.hjson.Stringify; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; /** * Generic class to serialize objects to/from JSON based on jackson. * * @author Misagh Moayyed * @param <T> the type parameter * @since 4.1 */ public abstract class AbstractJacksonBackedStringSerializer<T> implements StringSerializer<T> { private static final long serialVersionUID = -8415599777321259365L; private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJacksonBackedStringSerializer.class); private static final int ABBREVIATE_MAX_WIDTH = 100; private final PrettyPrinter prettyPrinter; private final ObjectMapper objectMapper; /** * Instantiates a new Registered service json serializer. * Uses the {@link com.fasterxml.jackson.core.util.DefaultPrettyPrinter} for formatting. */ public AbstractJacksonBackedStringSerializer() { this(new DefaultPrettyPrinter()); } /** * Instantiates a new Registered service json serializer. * * @param prettyPrinter the pretty printer */ public AbstractJacksonBackedStringSerializer(final PrettyPrinter prettyPrinter) { this.objectMapper = initializeObjectMapper(); this.prettyPrinter = prettyPrinter; } /** * Instantiates a new Registered service json serializer. * * @param objectMapper the object mapper * @param prettyPrinter the pretty printer */ public AbstractJacksonBackedStringSerializer(final ObjectMapper objectMapper, final PrettyPrinter prettyPrinter) { this.objectMapper = objectMapper; this.prettyPrinter = prettyPrinter; } private boolean isJsonFormat() { return !(this.objectMapper.getFactory() instanceof YAMLFactory); } @Override public T from(final String json) { try { final String jsonString = isJsonFormat() ? JsonValue.readHjson(json).toString() : json; return readObjectFromJson(jsonString); } catch (final Exception e) { throw new IllegalArgumentException(e); } } @Override public T from(final File json) { try { final String jsonString = isJsonFormat() ? JsonValue.readHjson(FileUtils.readFileToString(json, StandardCharsets.UTF_8)).toString() : FileUtils.readFileToString(json, StandardCharsets.UTF_8); return readObjectFromJson(jsonString); } catch (final Exception e) { throw new IllegalArgumentException(e); } } @Override public T from(final Reader json) { try { final String jsonString = isJsonFormat() ? JsonValue.readHjson(json).toString() : IOUtils.readLines(json).stream().collect(Collectors.joining()); return readObjectFromJson(jsonString); } catch (final Exception e) { throw new IllegalArgumentException(e); } } @Override public T from(final Writer writer) { return from(writer.toString()); } @Override public T from(final InputStream json) { try { final String jsonString = isJsonFormat() ? JsonValue.readHjson(IOUtils.toString(json, StandardCharsets.UTF_8)).toString() : IOUtils.readLines(json, StandardCharsets.UTF_8).stream().collect(Collectors.joining("\n")); return readObjectFromJson(jsonString); } catch (final Exception e) { throw new IllegalArgumentException(e); } } @Override public void to(final OutputStream out, final T object) { try (StringWriter writer = new StringWriter()) { this.objectMapper.writer(this.prettyPrinter).writeValue(writer, object); final String hjsonString = isJsonFormat() ? JsonValue.readHjson(writer.toString()).toString(Stringify.HJSON) : writer.toString(); IOUtils.write(hjsonString, out, StandardCharsets.UTF_8); } catch (final Exception e) { throw new IllegalArgumentException(e); } } @Override public void to(final Writer out, final T object) { try (StringWriter writer = new StringWriter()) { this.objectMapper.writer(this.prettyPrinter).writeValue(writer, object); if (isJsonFormat()) { final Stringify opt = this.prettyPrinter instanceof MinimalPrettyPrinter ? Stringify.FORMATTED : Stringify.FORMATTED; JsonValue.readHjson(writer.toString()).writeTo(out, opt); } else { IOUtils.write(writer.toString(), out); } } catch (final Exception e) { throw new IllegalArgumentException(e); } } @Override public void to(final File out, final T object) { try (StringWriter writer = new StringWriter()) { this.objectMapper.writer(this.prettyPrinter).writeValue(writer, object); if (isJsonFormat()) { try (FileWriter fileWriter = new FileWriter(out); BufferedWriter buffer = new BufferedWriter(fileWriter)) { JsonValue.readHjson(writer.toString()).writeTo(buffer); buffer.flush(); fileWriter.flush(); } } else { FileUtils.write(out, writer.toString(), StandardCharsets.UTF_8); } } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } /** * Initialize object mapper. * * @return the object mapper */ protected ObjectMapper initializeObjectMapper() { final ObjectMapper mapper = new ObjectMapper(getJsonFactory()); configureObjectMapper(mapper); return mapper; } /** * Configure mapper. * * @param mapper the mapper */ protected void configureObjectMapper(final ObjectMapper mapper) { mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); if (isDefaultTypingEnabled()) { mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); } mapper.findAndRegisterModules(); } protected boolean isDefaultTypingEnabled() { return true; } protected JsonFactory getJsonFactory() { return null; } /** * Gets type to serialize. * * @return the type to serialize */ protected abstract Class<T> getTypeToSerialize(); private T readObjectFromJson(final String jsonString) { try { return this.objectMapper.readValue(jsonString, getTypeToSerialize()); } catch (final Exception e) { LOGGER.error("Cannot read/parse JSON [{}] to deserialize into type [{}]. This may be caused " + "in the absence of a configuration/support module that knows how to interpret the JSON fragment, " + "specially if the fragment describes a CAS registered service definition. " + "Internal parsing error is [{}]", StringUtils.abbreviate(jsonString, ABBREVIATE_MAX_WIDTH), getTypeToSerialize(), e.getMessage()); LOGGER.trace(e.getMessage(), e); } return null; } }
package com.dao; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.entity.Enrollment; public class EnrollmentDao { public String updateEnrollment(Enrollment enrollment) { String resource = "conf.xml"; InputStream inputStream = null; SqlSession sqlSession = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); String statement = "com.mapping.SupplierMapper.updateEnrollment"; sqlSession.update(statement, enrollment); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return "SUCCESS"; } public List<Enrollment> selectAllEnrollment() { String resource = "conf.xml"; InputStream inputStream = null; SqlSession sqlSession = null; List<Enrollment> enrollList = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); String statement = "com.mapping.SupplierMapper.selectAllEnrollment"; enrollList = sqlSession.selectList(statement); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return enrollList; } public String insertEnrollment(Enrollment enrollment) { String resource = "conf.xml"; InputStream inputStream = null; SqlSession sqlSession = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); String statement = "com.mapping.SupplierMapper.insertEnrollment"; sqlSession.insert(statement, enrollment); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return "SUCCESS"; } public Enrollment selectOneEnrollment(String cellPhoneNum) { String resource = "conf.xml"; InputStream inputStream = null; SqlSession sqlSession = null; Enrollment enroll = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); String statement = "com.mapping.SupplierMapper.selectOneEnrollment"; enroll = sqlSession.selectOne(statement, cellPhoneNum); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return enroll; } public List<Enrollment> selectDinnerPartner(String dinnerDeskNum) { String resource = "conf.xml"; InputStream inputStream = null; SqlSession sqlSession = null; List<Enrollment> enrollList = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); String statement = "com.mapping.SupplierMapper.selectDinnerPartner"; enrollList = sqlSession.selectList(statement, dinnerDeskNum); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return enrollList; } public String checkIn(Enrollment enrollment) { String resource = "conf.xml"; InputStream inputStream = null; SqlSession sqlSession = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); String statement = "com.mapping.SupplierMapper.checkIn"; sqlSession.update(statement, enrollment); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return "SUCCESS"; } }
/** * */ package com.thinkbiganalytics.server.upgrade; /*- * #%L * kylo-operational-metadata-upgrade-service * %% * Copyright (C) 2017 ThinkBig Analytics * %% * 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. * #L% */ import com.thinkbiganalytics.KyloVersion; import org.springframework.core.annotation.Order; /** * Implemented by beans that should be invoked during the Kylo upgrade process. */ @Order(UpgradeAction.DEFAULT_ORDER) public interface UpgradeAction { int EARLY_ORDER = -10000; int DEFAULT_ORDER = 0; int LATE_ORDER = 10000; /** * Indicates whether this action should be invoked during a fresh install before * version migration begins. * @param currentVersion the starting version in the upgrade sequence * @return true if this action will participate in the fresh install before migration */ default boolean isTargetPreFreshInstall(KyloVersion currentVersion) { return false; } /** * Indicates whether this action should be invoked during the migration * sequence for the specified version. * @param version the current version in the migration sequence * @return true if this action will participate in the upgrade of to this version */ default boolean isTargetVersion(KyloVersion version) { return false; } /** * Indicates whether this action should be invoked during a fresh install after * the final version migration has completed. * @param initialVersion the final version in the upgrade sequence * @return true if this action will participate in the fresh install after migration */ default boolean isTargetFreshInstall(KyloVersion finalVersion) { return false; } /** * Invoke if when one of the isTarget* methods returns true during the upgrade procedure. * @param version the current target version */ void upgradeTo(KyloVersion version); }
package com.outlook.bigkun.demo1; /** * 抽象享元类:围棋棋子 * {@link com.outlook.bigkun.concepts.Flyweight} * * @author zhanghk * @since 2019/8/2 */ public abstract class IgoChessman { /** * 棋子颜色 * 内部状态 * {@link com.outlook.bigkun.concepts.IntrinsicState} * * @return */ public abstract String getColor(); public void display(Coordinates coord) { System.out.println("chessman's color:" + getColor() + ", position:" + coord); } }
package org.hisp.dhis; /* * Copyright (c) 2004-2013, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.Collection; import org.hisp.dhis.common.GenericStore; import org.junit.Test; import static org.junit.Assert.*; /** * @author Lars Helge Overland * @version $Id$ */ @SuppressWarnings( "unchecked" ) public abstract class GenericDhisSpringTest<T> extends DhisSpringTest { protected GenericStore<T> genericStore; @Override public final void setUpTest() throws Exception { genericStore = (GenericStore<T>) getBean( getGenericBeanId() ); setUpGenericTest(); } // ------------------------------------------------------------------------- // Tests // ------------------------------------------------------------------------- @Test public final void genericSaveGet() { int idA = genericStore.save( getObjects()[0] ); int idB = genericStore.save( getObjects()[1] ); int idC = genericStore.save( getObjects()[2] ); assertEquals( getObjects()[0], genericStore.get( idA ) ); assertEquals( getObjects()[1], genericStore.get( idB ) ); assertEquals( getObjects()[2], genericStore.get( idC ) ); } @Test public final void genericLoadGet() { int idA = genericStore.save( getObjects()[0] ); int idB = genericStore.save( getObjects()[1] ); int idC = genericStore.save( getObjects()[2] ); assertEquals( getObjects()[0], genericStore.get( idA ) ); assertEquals( getObjects()[1], genericStore.get( idB ) ); assertEquals( getObjects()[2], genericStore.get( idC ) ); } @Test public final void genericDelete() { int idA = genericStore.save( getObjects()[0] ); int idB = genericStore.save( getObjects()[1] ); int idC = genericStore.save( getObjects()[2] ); assertNotNull( genericStore.get( idA ) ); assertNotNull( genericStore.get( idB ) ); assertNotNull( genericStore.get( idC ) ); genericStore.delete( getObjects()[0] ); assertNull( genericStore.get( idA ) ); assertNotNull( genericStore.get( idB ) ); assertNotNull( genericStore.get( idC ) ); genericStore.delete( getObjects()[1] ); assertNull( genericStore.get( idA ) ); assertNull( genericStore.get( idB ) ); assertNotNull( genericStore.get( idC ) ); genericStore.delete( getObjects()[2] ); assertNull( genericStore.get( idA ) ); assertNull( genericStore.get( idB ) ); assertNull( genericStore.get( idC ) ); } @Test public final void genericGetAll() { genericStore.save( getObjects()[0] ); genericStore.save( getObjects()[1] ); genericStore.save( getObjects()[2] ); Collection<T> objects = genericStore.getAll(); assertNotNull( objects ); assertEquals( 3, objects.size() ); assertTrue( objects.contains( getObjects()[0] ) ); assertTrue( objects.contains( getObjects()[1] ) ); assertTrue( objects.contains( getObjects()[2] ) ); } // ------------------------------------------------------------------------- // Abstract methods // ------------------------------------------------------------------------- /** * Method to override in order to set up test fixture. */ protected void setUpGenericTest() throws Exception { } /** * Should return 3 objects of the class which is to be tested. */ protected abstract T[] getObjects(); /** * Should return the Spring bean identifier of the store which is to be tested. */ protected abstract String getGenericBeanId(); }
package com.lyf.generator.mapper; import java.util.List; import com.lyf.generator.domain.ColumnInfo; import com.lyf.generator.domain.TableInfo; /** * 代码生成 数据层 * * @author numberone */ public interface GenMapper { /** * 查询ry数据库表信息 * * @param tableInfo 表信息 * @return 数据库表列表 */ public List<TableInfo> selectTableList(TableInfo tableInfo); /** * 根据表名称查询信息 * * @param tableName 表名称 * @return 表信息 */ public TableInfo selectTableByName(String tableName); /** * 根据表名称查询列信息 * * @param tableName 表名称 * @return 列信息 */ public List<ColumnInfo> selectTableColumnsByName(String tableName); }
/* * Copyright 2020 Google LLC * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/talent/v4beta1/common.proto package com.google.cloud.talent.v4beta1; public interface RatingOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.talent.v4beta1.Rating) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Overall score. * </pre> * * <code>double overall = 1;</code> * * @return The overall. */ double getOverall(); /** * * * <pre> * The minimum value for the score. * </pre> * * <code>double min = 2;</code> * * @return The min. */ double getMin(); /** * * * <pre> * The maximum value for the score. * </pre> * * <code>double max = 3;</code> * * @return The max. */ double getMax(); /** * * * <pre> * The steps within the score (for example, interval = 1 max = 5 * min = 1 indicates that the score can be 1, 2, 3, 4, or 5) * </pre> * * <code>double interval = 4;</code> * * @return The interval. */ double getInterval(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.test; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.event.ActionEvent; /** * * @author PARAM 2000 */ @ManagedBean(name = "userTable") @SessionScoped public class UserTableBean implements Serializable { @ManagedProperty(value = "#{user}") UserBean user; private List<UserBean> allUserName = new ArrayList<>(); private List<UserBean> filterUser = new ArrayList<>(); public UserTableBean() { } public void addName(ActionEvent event) { if (user.getName() == null || user.getName().isEmpty()) { } else { UserBean tempUser = new UserBean(); tempUser.setName(user.getName()); allUserName.add(tempUser); } } public List<UserBean> getAllUserName() { return allUserName; } public void setAllUserName(List<UserBean> allUserName) { this.allUserName = allUserName; } public List<UserBean> getFilterUser() { return filterUser; } public void setFilterUser(List<UserBean> filterUser) { this.filterUser = filterUser; } public UserBean getUser() { return user; } public void setUser(UserBean user) { this.user = user; } }
package com.github.vbekiaris.jaxwsmetrics; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; import javax.xml.soap.SOAPException; /** * Echo web service interface, used for testing {@link MetricsHandler}. */ @WebService public interface EchoService { @WebMethod(operationName = "echo") String echo(@WebParam(name = "input") @XmlElement(required = true, nillable = false) String input); @WebMethod(operationName = "echoWithFault") String echoWithFault(@WebParam(name = "input") String input) throws SOAPException; }
/* * Copyright 2019 Google LLC * * 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.jenkins.plugins.k8sengine; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.google.jenkins.plugins.k8sengine.KubernetesEngineBuilder.DescriptorImpl; import hudson.util.FormValidation; import org.junit.Test; /** Tests for handling of namespaces in {@link KubernetesEngineBuilder}. */ public class KubernetesEngineBuilderNamespaceTest { @Test public void testDoCheckNamespaceOKWithNull() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckNamespace(null); assertNotNull(result); assertEquals(FormValidation.ok().getMessage(), result.getMessage()); } @Test public void testDoCheckNamespaceOKWithEmptyString() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckNamespace(""); assertNotNull(result); assertEquals(FormValidation.ok().getMessage(), result.getMessage()); } @Test public void testDoCheckNamespaceWithOKProperlyFormedString() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckNamespace("test-a-23-b"); assertNotNull(result); assertEquals(FormValidation.ok().getMessage(), result.getMessage()); } @Test public void testDoCheckNamespaceErrorWithValidCharactersMalformedString() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckNamespace("-test"); assertNotNull(result); assertEquals(Messages.KubernetesEngineBuilder_NamespaceInvalid(), result.getMessage()); } @Test public void testDoCheckNamespaceErrorWithInvalidCharacters() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckNamespace("*"); assertNotNull(result); assertEquals(Messages.KubernetesEngineBuilder_NamespaceInvalid(), result.getMessage()); } }
/** * Copyright 2008-2016 Evernote Corporation. All rights reserved. */ package com.evernote.android.data.sel; import java.util.Collection; final class Filter implements Selection { private final String column; private final Collection<String> values; public Filter(String column, Collection<String> values) { if (values == null || values.size() == 0) { throw new IllegalArgumentException("Cannot filter without values"); } this.column = column; this.values = values; } @Override public String sql() { return column + binding(); } private String binding() { final int size = values.size(); if (size == 1) { return " = ?"; } StringBuilder binding = new StringBuilder(5 + size * 2); binding.append(" IN (?"); for (int i = 1; i < size; ++i) { binding.append(",?"); } return binding.append(")").toString(); } @Override public Collection<String> params() { return values; } }
package org.intermine.api.query.codegen; /* * Copyright (C) 2002-2015 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.intermine.api.profile.Profile; import org.intermine.api.util.AnonProfile; import org.intermine.pathquery.PathQuery; import org.intermine.template.TemplateQuery; /** * Class to represent the information used to generate web service source code. * * @author Fengyuan Hu * */ public class WebserviceCodeGenInfo { private PathQuery query; private String serviceBaseURL; private String projectTitle; private String perlWSModuleVer; private boolean isPublic; private Profile user; private String resultTablesLib = null; private String baseUrl = null; private String lineBreak; private Properties properties = new Properties(); /** * Constructor. * * @param query a PathQuery to copy * @param serviceBaseURL the base url of web service * @param projectTitle the Title of a local InterMine project * @param perlWSModuleVer the perl web service module version on CPAN * @param isPubliclyAccessible whether this query can be accessed by the public * @param user the name of the user who was logged in when this info was generated * */ public WebserviceCodeGenInfo(PathQuery query, String serviceBaseURL, String projectTitle, String perlWSModuleVer, boolean isPubliclyAccessible, Profile user) { this.query = query; this.serviceBaseURL = serviceBaseURL; this.projectTitle = projectTitle; this.perlWSModuleVer = perlWSModuleVer; this.isPublic = isPubliclyAccessible; this.user = user; this.lineBreak = System.getProperty("line.separator"); } /** * @param pq a PathQuery to copy * @param serviceBaseURL the base url of web service * @param projectTitle the Title of a local InterMine project * @param perlWSModuleVer the perl web service module version on CPAN * @param pathQueryIsPublic whether this query can be accessed by the public * @param profile the profile of the user who was logged in when this info was generated * @param lineBreak which linebreak to use */ public WebserviceCodeGenInfo(PathQuery pq, String serviceBaseURL, String projectTitle, String perlWSModuleVer, boolean pathQueryIsPublic, Profile profile, String lineBreak) { this.query = pq; this.serviceBaseURL = serviceBaseURL; this.projectTitle = projectTitle; this.perlWSModuleVer = perlWSModuleVer; this.isPublic = pathQueryIsPublic; this.user = profile; this.lineBreak = lineBreak; } /** * @param props properties */ public void readWebProperties(Properties props) { this.properties.putAll(props); if (properties != null) { resultTablesLib = (String) properties.get("ws.imtables.provider"); baseUrl = properties.get("webapp.baseurl") + "/" + properties.get("webapp.path") + "/"; } } /** * Get a configured property for which an accessor does not exist. * * @param key The key for this property. * @param defaultValue The value to return if this property is not configured. * @return The value of the property. */ public String getProperty(String key, String defaultValue) { return properties.getProperty(key, defaultValue); } /** * * @return results tables */ public String getResultsTablesLib() { return resultTablesLib; } /** * * @return base URL */ public String getBaseUrl() { return baseUrl; } /** * Returns the filename that should be associated with this query. * @return a file name */ public String getFileName() { if (query instanceof TemplateQuery) { return "template_query"; } return "query"; } /** * @return the query */ public PathQuery getQuery() { return query; } /** * @return the serviceBaseURL */ public String getServiceBaseURL() { return serviceBaseURL; } /** * @return the projectTitle */ public String getProjectTitle() { return projectTitle; } /** * @return the perlWSModuleVer */ public String getPerlWSModuleVer() { return perlWSModuleVer; } /** * Returns whether this query is publicly accessible. If so, * then the webservice will not need to implement a log-in. * @return Whether the query is public. */ public boolean isPublic() { return isPublic; } /** * The name of the user logged in when this info was generated * @return The name of the user */ public String getUserName() { return user.getUsername(); } /** * @return a line break */ public String getLineBreak() { return lineBreak; } /** * A token for the user. The permanent token is preferred, but a temporary one * is generated if that is not available. * @return A token for the the user */ public String getUserToken() { if (user.getApiKey() != null) { return user.getApiKey(); } return user.getDayToken(); } /** * @return True if this user has a permanent profile. */ public boolean isLoggedIn() { return user.getUserId() != null && !( StringUtils.isBlank(user.getUsername()) || AnonProfile.USERNAME.equals(user.getUsername())); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, v2.3.0 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2021.08.06 at 04:43:18 PM BST // package org.treblereel.gwt.xml.mapper.client.tests.pmml.model.impl.v4_4; 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.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://www.dmg.org/PMML-4_4}Extension" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element ref="{http://www.dmg.org/PMML-4_4}Matrix"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType( name = "", propOrder = {"extension", "matrix"}) @XmlRootElement(name = "MeasurementMatrix") public class MeasurementMatrix { @XmlElement(name = "Extension") protected List<Extension> extension; @XmlElement(name = "Matrix", required = true) protected Matrix matrix; /** * Gets the value of the extension 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 extension property. * * <p>For example, to add a new item, do as follows: * * <pre> * getExtension().add(newItem); * </pre> * * <p>Objects of the following type(s) are allowed in the list {@link Extension } */ public List<Extension> getExtension() { if (extension == null) { extension = new ArrayList<Extension>(); } return this.extension; } /** * Gets the value of the matrix property. * * @return possible object is {@link Matrix } */ public Matrix getMatrix() { return matrix; } /** * Sets the value of the matrix property. * * @param value allowed object is {@link Matrix } */ public void setMatrix(Matrix value) { this.matrix = value; } }
package com.github.badoualy.telegram.tl.api.help; import com.github.badoualy.telegram.tl.TLContext; import com.github.badoualy.telegram.tl.core.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.github.badoualy.telegram.tl.StreamUtils.readTLString; import static com.github.badoualy.telegram.tl.StreamUtils.writeString; import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID; import static com.github.badoualy.telegram.tl.TLObjectUtils.computeTLStringSerializedSize; /** * @author Yannick Badoual yann.badoual@gmail.com * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ public class TLTermsOfService extends TLObject { public static final int CONSTRUCTOR_ID = 0xf1ee3e90; protected String text; private final String _constructor = "help.termsOfService#f1ee3e90"; public TLTermsOfService() { } public TLTermsOfService(String text) { this.text = text; } @Override public void serializeBody(OutputStream stream) throws IOException { writeString(text, stream); } @Override @SuppressWarnings("unchecked") public void deserializeBody(InputStream stream, TLContext context) throws IOException { text = readTLString(stream); } @Override public int computeSerializedSize() { int size = SIZE_CONSTRUCTOR_ID; size += computeTLStringSerializedSize(text); return size; } @Override public String toString() { return _constructor; } @Override public int getConstructorId() { return CONSTRUCTOR_ID; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
package com.muze.core.app.task.service; public class TaskB extends AbstractJob{ @Override public void doJob() { String[] a = new String[2]; a[2]="fdsfs"; } }
package application.model; import java.util.List; import java.util.UUID; public class BoshPackage { private String name; private String version; private Stemcell stemcell; private String flavor; private String description; private String vendor; private UUID uuid; private String os; private String arch; private String fileUri; private List<BoshPackage> dependencies; private long size; public BoshPackage(String name, String version, String vendor, Stemcell stemcell){ this.name = name; this.version = version; this.vendor = vendor; this.stemcell = stemcell; } public BoshPackage(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } public String getFileUri() { return fileUri; } public void setFileUri(String fileUri) { this.fileUri = fileUri; } public Stemcell getStemcell() { return stemcell; } public void setStemcell(Stemcell stemcell) { this.stemcell = stemcell; } public String getFlavor() { return flavor; } public void setFlavor(String flavor) { this.flavor = flavor; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public String getOs() { return os; } public void setOs(String os) { this.os = os; } public String getArch() { return arch; } public void setArch(String arch) { this.arch = arch; } public List<BoshPackage> getDependencies() { return dependencies; } public void setDependencies(List<BoshPackage> dependencies) { this.dependencies = dependencies; } public boolean equals(BoshPackage obj) { if(name.equals(obj.name) && version.equals(obj.version) && (stemcell == null || stemcell.equals(obj.stemcell)) && vendor.equals(obj.vendor) && (flavor == null || flavor.equals(obj.flavor)) && (os == null || os.equals(obj.os))){ return true; } return false; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } }
//Code to demonstrate Arrays Class via asList() function import java.util.*; public class ArrayClass1 { public static void main(String[] args) { int ar[] = {1,2,3,4,5,6,7,8,9,10}; System.out.println("Integer Array as List: "+Arrays.asList(ar)); } }
/* * Copyright 2021 Arcade Data Ltd * * 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. */ /* Generated By:JJTree: Do not edit this line. OAlterPropertyStatement.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_USERTYPE_VISIBILITY_PUBLIC=true */ package com.arcadedb.query.sql.parser; import com.arcadedb.exception.CommandSQLParsingException; import com.arcadedb.query.sql.executor.CommandContext; import com.arcadedb.query.sql.executor.ResultSet; import java.util.*; public class AlterPropertyStatement extends ODDLStatement { public Expression settingValue; Identifier typeName; Identifier propertyName; Identifier customPropertyName; Expression customPropertyValue; Identifier settingName; public AlterPropertyStatement(int id) { super(id); } public AlterPropertyStatement(SqlParser p, int id) { super(p, id); } @Override public ResultSet executeDDL(CommandContext ctx) { throw new UnsupportedOperationException(); // Database db = ctx.getDatabase(); // OClass typez = db.getMetadata().getSchema().getClass(className.getStringValue()); // // if (typez == null) { // throw new PCommandExecutionException("Invalid class name or class not found: " + typez); // } // // OProperty property = typez.getProperty(propertyName.getStringValue()); // if (property == null) { // throw new PCommandExecutionException("Property " + property + " not found on class " + typez); // } // // OResultInternal result = new OResultInternal(); // result.setProperty("class", className.getStringValue()); // result.setProperty("property", propertyName.getStringValue()); // // if (customPropertyName != null) { // String customName = customPropertyName.getStringValue(); // Object oldValue = property.getCustom(customName); // Object finalValue = customPropertyValue.execute((PIdentifiable) null, ctx); // property.setCustom(customName, finalValue == null ? null : "" + finalValue); // // result.setProperty("operation", "alter property custom"); // result.setProperty("customAttribute", customPropertyName.getStringValue()); // result.setProperty("oldValue", oldValue != null ? oldValue.toString() : null); // result.setProperty("newValue", finalValue != null ? finalValue.toString() : null); // } else { // String setting = settingName.getStringValue(); // Object finalValue = settingValue.execute((PIdentifiable) null, ctx); // // OProperty.ATTRIBUTES attribute; // try { // attribute = OProperty.ATTRIBUTES.valueOf(setting.toUpperCase(Locale.ENGLISH)); // } catch (IllegalArgumentException e) { // throw OException.wrapException(new PCommandExecutionException( // "Unknown property attribute '" + setting + "'. Supported attributes are: " + Arrays // .toString(OProperty.ATTRIBUTES.values())), e); // } // Object oldValue = property.get(attribute); // property.set(attribute, finalValue); // finalValue = property.get(attribute);//it makes some conversions... // // result.setProperty("operation", "alter property"); // result.setProperty("attribute", setting); // result.setProperty("oldValue", oldValue != null ? oldValue.toString() : null); // result.setProperty("newValue", finalValue != null ? finalValue.toString() : null); // } // OInternalResultSet rs = new OInternalResultSet(); // rs.add(result); // return rs; } @Override public void validate() throws CommandSQLParsingException { super.validate();//TODO } @Override public void toString(Map<Object, Object> params, StringBuilder builder) { builder.append("ALTER PROPERTY "); typeName.toString(params, builder); builder.append("."); propertyName.toString(params, builder); if (customPropertyName != null) { builder.append(" CUSTOM "); customPropertyName.toString(params, builder); builder.append(" = "); customPropertyValue.toString(params, builder); } else { builder.append(" "); settingName.toString(params, builder); builder.append(" "); settingValue.toString(params, builder); } } @Override public AlterPropertyStatement copy() { AlterPropertyStatement result = new AlterPropertyStatement(-1); result.typeName = typeName == null ? null : typeName.copy(); result.propertyName = propertyName == null ? null : propertyName.copy(); result.customPropertyName = customPropertyName == null ? null : customPropertyName.copy(); result.customPropertyValue = customPropertyValue == null ? null : customPropertyValue.copy(); result.settingName = settingName == null ? null : settingName.copy(); result.settingValue = settingValue == null ? null : settingValue.copy(); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlterPropertyStatement that = (AlterPropertyStatement) o; if (typeName != null ? !typeName.equals(that.typeName) : that.typeName != null) return false; if (propertyName != null ? !propertyName.equals(that.propertyName) : that.propertyName != null) return false; if (customPropertyName != null ? !customPropertyName.equals(that.customPropertyName) : that.customPropertyName != null) return false; if (customPropertyValue != null ? !customPropertyValue.equals(that.customPropertyValue) : that.customPropertyValue != null) return false; if (settingName != null ? !settingName.equals(that.settingName) : that.settingName != null) return false; return settingValue != null ? settingValue.equals(that.settingValue) : that.settingValue == null; } @Override public int hashCode() { int result = typeName != null ? typeName.hashCode() : 0; result = 31 * result + (propertyName != null ? propertyName.hashCode() : 0); result = 31 * result + (customPropertyName != null ? customPropertyName.hashCode() : 0); result = 31 * result + (customPropertyValue != null ? customPropertyValue.hashCode() : 0); result = 31 * result + (settingName != null ? settingName.hashCode() : 0); result = 31 * result + (settingValue != null ? settingValue.hashCode() : 0); return result; } } /* JavaCC - OriginalChecksum=2421f6ad3b5f1f8e18149650ff80f1e7 (do not edit this line) */
/******************************************************************************* * Copyright (c) 2017 Universitat Politécnica de Catalunya (UPC) * * 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. * * Contributors: * Edith Zavala *******************************************************************************/ package org.loopa.generic.element; import java.util.Map; import org.loopa.element.receiver.IReceiver; public interface ILoopAElement { public IReceiver getReceiver(); public void setElementRecipients(Map<String, Object> r); public Map<String, Object> getElementRecipients(); public void addRecipient(String id, Object o); public void removeRecipient(String id); public String getElementId(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Tutorial2; /** * * @author John Barber (john.barber@cqumail.com) */ public class Truck extends Vehicle { private double loadingCapacity; public Truck(String description, int year, int month, double economy, double capacity) { super(description, year, month, economy); this.loadingCapacity = capacity; } Truck() { super(); this.loadingCapacity = 10; } public double getLoadingCapacity() { return this.loadingCapacity; } public void setLoadingCapacity(double loading) { this.loadingCapacity = loading; } @Override public String toString() { return super.toString() + " Loading Capacity: " + this.getLoadingCapacity(); } }
package org.checkerframework.framework.type; // The imports from com.sun are all @jdk.Exported and therefore somewhat safe to use. // Try to avoid using non-@jdk.Exported classes. import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCNewClass; import java.io.File; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.IntersectionType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.WildcardType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.checkerframework.checker.interning.qual.FindDistinct; import org.checkerframework.checker.interning.qual.InternedDistinct; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.signature.qual.CanonicalName; import org.checkerframework.checker.signature.qual.FullyQualifiedName; import org.checkerframework.common.basetype.BaseTypeChecker; import org.checkerframework.common.basetype.BaseTypeVisitor; import org.checkerframework.common.reflection.DefaultReflectionResolver; import org.checkerframework.common.reflection.MethodValAnnotatedTypeFactory; import org.checkerframework.common.reflection.MethodValChecker; import org.checkerframework.common.reflection.ReflectionResolver; import org.checkerframework.common.reflection.qual.MethodVal; import org.checkerframework.common.wholeprograminference.WholeProgramInference; import org.checkerframework.common.wholeprograminference.WholeProgramInferenceImplementation; import org.checkerframework.common.wholeprograminference.WholeProgramInferenceJavaParserStorage; import org.checkerframework.common.wholeprograminference.WholeProgramInferenceScenesStorage; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.framework.qual.AnnotatedFor; import org.checkerframework.framework.qual.EnsuresQualifier; import org.checkerframework.framework.qual.EnsuresQualifierIf; import org.checkerframework.framework.qual.FieldInvariant; import org.checkerframework.framework.qual.FromStubFile; import org.checkerframework.framework.qual.HasQualifierParameter; import org.checkerframework.framework.qual.InheritedAnnotation; import org.checkerframework.framework.qual.NoQualifierParameter; import org.checkerframework.framework.qual.RequiresQualifier; import org.checkerframework.framework.source.SourceChecker; import org.checkerframework.framework.stub.AnnotationFileElementTypes; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedNullType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType; import org.checkerframework.framework.type.visitor.AnnotatedTypeCombiner; import org.checkerframework.framework.type.visitor.SimpleAnnotatedTypeScanner; import org.checkerframework.framework.util.AnnotatedTypes; import org.checkerframework.framework.util.AnnotationFormatter; import org.checkerframework.framework.util.CheckerMain; import org.checkerframework.framework.util.DefaultAnnotationFormatter; import org.checkerframework.framework.util.FieldInvariants; import org.checkerframework.framework.util.TreePathCacher; import org.checkerframework.framework.util.typeinference.DefaultTypeArgumentInference; import org.checkerframework.framework.util.typeinference.TypeArgInferenceUtil; import org.checkerframework.framework.util.typeinference.TypeArgumentInference; import org.checkerframework.javacutil.AnnotationBuilder; import org.checkerframework.javacutil.AnnotationProvider; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.BugInCF; import org.checkerframework.javacutil.CollectionUtils; import org.checkerframework.javacutil.ElementUtils; import org.checkerframework.javacutil.Pair; import org.checkerframework.javacutil.TreePathUtil; import org.checkerframework.javacutil.TreeUtils; import org.checkerframework.javacutil.TypeKindUtils; import org.checkerframework.javacutil.TypeSystemError; import org.checkerframework.javacutil.TypesUtils; import org.checkerframework.javacutil.UserError; import org.checkerframework.javacutil.trees.DetachedVarSymbol; import org.plumelib.util.CollectionsPlume; import org.plumelib.util.StringsPlume; import scenelib.annotations.el.AMethod; import scenelib.annotations.el.ATypeElement; /** * The methods of this class take an element or AST node, and return the annotated type as an {@link * AnnotatedTypeMirror}. The methods are: * * <ul> * <li>{@link #getAnnotatedType(ClassTree)} * <li>{@link #getAnnotatedType(MethodTree)} * <li>{@link #getAnnotatedType(Tree)} * <li>{@link #getAnnotatedTypeFromTypeTree(Tree)} * <li>{@link #getAnnotatedType(TypeElement)} * <li>{@link #getAnnotatedType(ExecutableElement)} * <li>{@link #getAnnotatedType(Element)} * </ul> * * This implementation only adds qualifiers explicitly specified by the programmer. Subclasses * override {@link #addComputedTypeAnnotations} to add defaults, flow-sensitive refinement, and * type-system-specific rules. * * <p>Unless otherwise indicated, each public method in this class returns a "fully annotated" type, * which is one that has an annotation in all positions. * * <p>Type system checker writers may need to subclass this class, to add default qualifiers * according to the type system semantics. Subclasses should especially override {@link * #addComputedTypeAnnotations(Element, AnnotatedTypeMirror)} and {@link * #addComputedTypeAnnotations(Tree, AnnotatedTypeMirror)} to handle default annotations. (Also, * {@link #addDefaultAnnotations(AnnotatedTypeMirror)} adds annotations, but that method is a * workaround for <a href="https://github.com/typetools/checker-framework/issues/979">Issue * 979</a>.) * * @checker_framework.manual #creating-a-checker How to write a checker plug-in */ public class AnnotatedTypeFactory implements AnnotationProvider { /** Whether to print verbose debugging messages about stub files. */ private final boolean debugStubParser; /** The {@link Trees} instance to use for tree node path finding. */ protected final Trees trees; /** Optional! The AST of the source file being operated on. */ // TODO: when should root be null? What are the use cases? // None of the existing test checkers has a null root. // Should not be modified between calls to "visit". protected @Nullable CompilationUnitTree root; /** The processing environment to use for accessing compiler internals. */ protected final ProcessingEnvironment processingEnv; /** Utility class for working with {@link Element}s. */ protected final Elements elements; /** Utility class for working with {@link TypeMirror}s. */ public final Types types; /** The state of the visitor. */ protected final VisitorState visitorState; /** The AnnotatedFor.value argument/element. */ private final ExecutableElement annotatedForValueElement; /** The EnsuresQualifier.expression field/element. */ final ExecutableElement ensuresQualifierExpressionElement; /** The EnsuresQualifier.List.value field/element. */ final ExecutableElement ensuresQualifierListValueElement; /** The EnsuresQualifierIf.expression field/element. */ final ExecutableElement ensuresQualifierIfExpressionElement; /** The EnsuresQualifierIf.result argument/element. */ final ExecutableElement ensuresQualifierIfResultElement; /** The EnsuresQualifierIf.List.value field/element. */ final ExecutableElement ensuresQualifierIfListValueElement; /** The FieldInvariant.field argument/element. */ private final ExecutableElement fieldInvariantFieldElement; /** The FieldInvariant.qualifier argument/element. */ private final ExecutableElement fieldInvariantQualifierElement; /** The HasQualifierParameter.value field/element. */ private final ExecutableElement hasQualifierParameterValueElement; /** The MethodVal.className argument/element. */ public final ExecutableElement methodValClassNameElement; /** The MethodVal.methodName argument/element. */ public final ExecutableElement methodValMethodNameElement; /** The MethodVal.params argument/element. */ public final ExecutableElement methodValParamsElement; /** The NoQualifierParameter.value field/element. */ private final ExecutableElement noQualifierParameterValueElement; /** The RequiresQualifier.expression field/element. */ final ExecutableElement requiresQualifierExpressionElement; /** The RequiresQualifier.List.value field/element. */ final ExecutableElement requiresQualifierListValueElement; /** The RequiresQualifier type. */ TypeMirror requiresQualifierTM; /** The RequiresQualifier.List type. */ TypeMirror requiresQualifierListTM; /** The EnsuresQualifier type. */ TypeMirror ensuresQualifierTM; /** The EnsuresQualifier.List type. */ TypeMirror ensuresQualifierListTM; /** The EnsuresQualifierIf type. */ TypeMirror ensuresQualifierIfTM; /** The EnsuresQualifierIf.List type. */ TypeMirror ensuresQualifierIfListTM; /** * ===== postInit initialized fields ==== Note: qualHierarchy and typeHierarchy are both * initialized in the postInit. * * @see #postInit() This means, they cannot be final and cannot be referred to in any subclass * constructor or method until after postInit is called */ /** Represent the annotation relations. */ protected QualifierHierarchy qualHierarchy; /** Represent the type relations. */ protected TypeHierarchy typeHierarchy; /** Performs whole-program inference. If null, whole-program inference is disabled. */ private final @Nullable WholeProgramInference wholeProgramInference; /** * This formatter is used for converting AnnotatedTypeMirrors to Strings. This formatter will be * used by all AnnotatedTypeMirrors created by this factory in their toString methods. */ protected final AnnotatedTypeFormatter typeFormatter; /** * Annotation formatter is used to format AnnotationMirrors. It is primarily used by SourceChecker * when generating error messages. */ private final AnnotationFormatter annotationFormatter; /** Holds the qualifier upper bounds for type uses. */ protected QualifierUpperBounds qualifierUpperBounds; /** * Provides utility method to substitute arguments for their type variables. Field should be * final, but can only be set in postInit, because subtypes might need other state to be * initialized first. */ protected TypeVariableSubstitutor typeVarSubstitutor; /** Provides utility method to infer type arguments. */ protected TypeArgumentInference typeArgumentInference; /** * Caches the supported type qualifier classes. Call {@link #getSupportedTypeQualifiers()} instead * of using this field directly, as it may not have been initialized. */ private final Set<Class<? extends Annotation>> supportedQuals; /** * Caches the fully-qualified names of the classes in {@link #supportedQuals}. Call {@link * #getSupportedTypeQualifierNames()} instead of using this field directly, as it may not have * been initialized. */ private final Set<@CanonicalName String> supportedQualNames; /** Parses stub files and stores annotations on public elements from stub files. */ public final AnnotationFileElementTypes stubTypes; /** Parses ajava files and stores annotations on public elements from ajava files. */ public final AnnotationFileElementTypes ajavaTypes; /** * If type checking a Java file, stores annotations read from an ajava file for that class if one * exists. Unlike {@link #ajavaTypes}, which only stores annotations on public elements, this * stores annotations on all element locations such as in anonymous class bodies. */ public @Nullable AnnotationFileElementTypes currentFileAjavaTypes; /** * A cache used to store elements whose declaration annotations have already been stored by * calling the method {@link #getDeclAnnotations(Element)}. */ private final Map<Element, Set<AnnotationMirror>> cacheDeclAnnos; /** * A set containing declaration annotations that should be inherited. A declaration annotation * will be inherited if it is in this set, or if it has the meta-annotation @InheritedAnnotation. */ private final Set<AnnotationMirror> inheritedAnnotations = AnnotationUtils.createAnnotationSet(); /** The checker to use for option handling and resource management. */ protected final BaseTypeChecker checker; /** Map keys are canonical names of aliased annotations. */ private final Map<@FullyQualifiedName String, Alias> aliases = new HashMap<>(); /** * Information about one annotation alias. * * <p>The information is either an AnotationMirror that can be used directly, or information for a * builder (name and fields not to copy); see checkRep. */ private static class Alias { /** The canonical annotation (or null if copyElements == true). */ AnnotationMirror canonical; /** Whether elements should be copied over when translating to the canonical annotation. */ boolean copyElements; /** The canonical annotation name (or null if copyElements == false). */ @CanonicalName String canonicalName; /** Which elements should not be copied over (or null if copyElements == false). */ String[] ignorableElements; /** * Create an Alias with the given components. * * @param aliasName the alias name; only used for debugging * @param canonical the canonical annotation * @param copyElements whether elements should be copied over when translating to the canonical * annotation * @param canonicalName the canonical annotation name (or null if copyElements == false) * @param ignorableElements elements that should not be copied over */ Alias( String aliasName, AnnotationMirror canonical, boolean copyElements, @CanonicalName String canonicalName, String[] ignorableElements) { this.canonical = canonical; this.copyElements = copyElements; this.canonicalName = canonicalName; this.ignorableElements = ignorableElements; checkRep(aliasName); } /** * Throw an exception if this object is malformed. * * @param aliasName the alias name; only used for diagnostic messages */ void checkRep(String aliasName) { if (copyElements) { if (!(canonical == null && canonicalName != null && ignorableElements != null)) { throw new BugInCF( "Bad Alias for %s: [canonical=%s] copyElements=%s canonicalName=%s" + " ignorableElements=%s", aliasName, canonical, copyElements, canonicalName, ignorableElements); } } else { if (!(canonical != null && canonicalName == null && ignorableElements == null)) { throw new BugInCF( "Bad Alias for %s: canonical=%s copyElements=%s [canonicalName=%s" + " ignorableElements=%s]", aliasName, canonical, copyElements, canonicalName, ignorableElements); } } } } /** * A map from the class of an annotation to the set of classes for annotations with the same * meaning, as well as the annotation mirror that should be used. */ private final Map< Class<? extends Annotation>, Pair<AnnotationMirror, Set<Class<? extends Annotation>>>> declAliases = new HashMap<>(); /** Unique ID counter; for debugging purposes. */ private static int uidCounter = 0; /** Unique ID of the current object; for debugging purposes. */ public final int uid; /** * Object that is used to resolve reflective method calls, if reflection resolution is turned on. */ protected ReflectionResolver reflectionResolver; /** AnnotationClassLoader used to load type annotation classes via reflective lookup. */ protected AnnotationClassLoader loader; /** * Which whole-program inference output format to use, if doing whole-program inference. This * variable would be final, but it is not set unless WPI is enabled. */ protected WholeProgramInference.OutputFormat wpiOutputFormat; /** * Should results be cached? This means that ATM.deepCopy() will be called. ATM.deepCopy() used to * (and perhaps still does) side effect the ATM being copied. So setting this to false is not * equivalent to setting shouldReadCache to false. */ public boolean shouldCache; /** Size of LRU cache if one isn't specified using the atfCacheSize option. */ private static final int DEFAULT_CACHE_SIZE = 300; /** Mapping from a Tree to its annotated type; defaults have been applied. */ private final Map<Tree, AnnotatedTypeMirror> classAndMethodTreeCache; /** * Mapping from an expression tree to its annotated type; before defaults are applied, just what * the programmer wrote. */ protected final Map<Tree, AnnotatedTypeMirror> fromExpressionTreeCache; /** * Mapping from a member tree to its annotated type; before defaults are applied, just what the * programmer wrote. */ protected final Map<Tree, AnnotatedTypeMirror> fromMemberTreeCache; /** * Mapping from a type tree to its annotated type; before defaults are applied, just what the * programmer wrote. */ protected final Map<Tree, AnnotatedTypeMirror> fromTypeTreeCache; /** * Mapping from an Element to its annotated type; before defaults are applied, just what the * programmer wrote. */ private final Map<Element, AnnotatedTypeMirror> elementCache; /** Mapping from an Element to the source Tree of the declaration. */ private final Map<Element, Tree> elementToTreeCache; /** Mapping from a Tree to its TreePath. Shared between all instances. */ private final TreePathCacher treePathCache; /** Mapping from CFG-generated trees to their enclosing elements. */ protected final Map<Tree, Element> artificialTreeToEnclosingElementMap; /** * Whether to ignore uninferred type arguments. This is a temporary flag to work around Issue 979. */ public final boolean ignoreUninferredTypeArguments; /** The Object.getClass method. */ protected final ExecutableElement objectGetClass; /** Size of the annotationClassNames cache. */ private static final int ANNOTATION_CACHE_SIZE = 500; /** Maps classes representing AnnotationMirrors to their canonical names. */ private final Map<Class<? extends Annotation>, @CanonicalName String> annotationClassNames; /** An annotated type of the declaration of {@link Iterable} without any annotations. */ private AnnotatedDeclaredType iterableDeclType; /** * Constructs a factory from the given {@link ProcessingEnvironment} instance and syntax tree * root. (These parameters are required so that the factory may conduct the appropriate * annotation-gathering analyses on certain tree types.) * * <p>Root can be {@code null} if the factory does not operate on trees. * * <p>A subclass must call postInit at the end of its constructor. postInit must be the last call * in the constructor or else types from stub files may not be created as expected. * * @param checker the {@link SourceChecker} to which this factory belongs * @throws IllegalArgumentException if either argument is {@code null} */ public AnnotatedTypeFactory(BaseTypeChecker checker) { uid = ++uidCounter; this.processingEnv = checker.getProcessingEnvironment(); // this.root = root; this.checker = checker; this.trees = Trees.instance(processingEnv); this.elements = processingEnv.getElementUtils(); this.types = processingEnv.getTypeUtils(); this.visitorState = new VisitorState(); this.supportedQuals = new HashSet<>(); this.supportedQualNames = new HashSet<>(); this.stubTypes = new AnnotationFileElementTypes(this); this.ajavaTypes = new AnnotationFileElementTypes(this); this.currentFileAjavaTypes = null; this.cacheDeclAnnos = new HashMap<>(); this.artificialTreeToEnclosingElementMap = new HashMap<>(); // get the shared instance from the checker this.treePathCache = checker.getTreePathCacher(); this.shouldCache = !checker.hasOption("atfDoNotCache"); if (shouldCache) { int cacheSize = getCacheSize(); this.classAndMethodTreeCache = CollectionUtils.createLRUCache(cacheSize); this.fromExpressionTreeCache = CollectionUtils.createLRUCache(cacheSize); this.fromMemberTreeCache = CollectionUtils.createLRUCache(cacheSize); this.fromTypeTreeCache = CollectionUtils.createLRUCache(cacheSize); this.elementCache = CollectionUtils.createLRUCache(cacheSize); this.elementToTreeCache = CollectionUtils.createLRUCache(cacheSize); this.annotationClassNames = Collections.synchronizedMap(CollectionUtils.createLRUCache(ANNOTATION_CACHE_SIZE)); } else { this.classAndMethodTreeCache = null; this.fromExpressionTreeCache = null; this.fromMemberTreeCache = null; this.fromTypeTreeCache = null; this.elementCache = null; this.elementToTreeCache = null; this.annotationClassNames = null; } this.typeFormatter = createAnnotatedTypeFormatter(); this.annotationFormatter = createAnnotationFormatter(); if (checker.hasOption("infer")) { checkInvalidOptionsInferSignatures(); String inferArg = checker.getOption("infer"); // No argument means "jaifs", for (temporary) backwards compatibility. if (inferArg == null) { inferArg = "jaifs"; } switch (inferArg) { case "stubs": wpiOutputFormat = WholeProgramInference.OutputFormat.STUB; break; case "jaifs": wpiOutputFormat = WholeProgramInference.OutputFormat.JAIF; break; case "ajava": wpiOutputFormat = WholeProgramInference.OutputFormat.AJAVA; break; default: throw new UserError( "Bad argument -Ainfer=" + inferArg + " should be one of: -Ainfer=jaifs, -Ainfer=stubs, -Ainfer=ajava"); } if (wpiOutputFormat == WholeProgramInference.OutputFormat.AJAVA) { wholeProgramInference = new WholeProgramInferenceImplementation<AnnotatedTypeMirror>( this, new WholeProgramInferenceJavaParserStorage(this)); } else { wholeProgramInference = new WholeProgramInferenceImplementation<ATypeElement>( this, new WholeProgramInferenceScenesStorage(this)); } if (!checker.hasOption("warns")) { // Without -Awarns, the inference output may be incomplete, because javac halts // after issuing an error. checker.message(Diagnostic.Kind.ERROR, "Do not supply -Ainfer without -Awarns"); } } else { wholeProgramInference = null; } ignoreUninferredTypeArguments = !checker.hasOption("conservativeUninferredTypeArguments"); objectGetClass = TreeUtils.getMethod("java.lang.Object", "getClass", 0, processingEnv); this.debugStubParser = checker.hasOption("stubDebug"); annotatedForValueElement = TreeUtils.getMethod(AnnotatedFor.class, "value", 0, processingEnv); ensuresQualifierExpressionElement = TreeUtils.getMethod(EnsuresQualifier.class, "expression", 0, processingEnv); ensuresQualifierListValueElement = TreeUtils.getMethod(EnsuresQualifier.List.class, "value", 0, processingEnv); ensuresQualifierIfExpressionElement = TreeUtils.getMethod(EnsuresQualifierIf.class, "expression", 0, processingEnv); ensuresQualifierIfResultElement = TreeUtils.getMethod(EnsuresQualifierIf.class, "result", 0, processingEnv); ensuresQualifierIfListValueElement = TreeUtils.getMethod(EnsuresQualifierIf.List.class, "value", 0, processingEnv); fieldInvariantFieldElement = TreeUtils.getMethod(FieldInvariant.class, "field", 0, processingEnv); fieldInvariantQualifierElement = TreeUtils.getMethod(FieldInvariant.class, "qualifier", 0, processingEnv); hasQualifierParameterValueElement = TreeUtils.getMethod(HasQualifierParameter.class, "value", 0, processingEnv); methodValClassNameElement = TreeUtils.getMethod(MethodVal.class, "className", 0, processingEnv); methodValMethodNameElement = TreeUtils.getMethod(MethodVal.class, "methodName", 0, processingEnv); methodValParamsElement = TreeUtils.getMethod(MethodVal.class, "params", 0, processingEnv); noQualifierParameterValueElement = TreeUtils.getMethod(NoQualifierParameter.class, "value", 0, processingEnv); requiresQualifierExpressionElement = TreeUtils.getMethod(RequiresQualifier.class, "expression", 0, processingEnv); requiresQualifierListValueElement = TreeUtils.getMethod(RequiresQualifier.List.class, "value", 0, processingEnv); requiresQualifierTM = ElementUtils.getTypeElement(processingEnv, RequiresQualifier.class).asType(); requiresQualifierListTM = ElementUtils.getTypeElement(processingEnv, RequiresQualifier.List.class).asType(); ensuresQualifierTM = ElementUtils.getTypeElement(processingEnv, EnsuresQualifier.class).asType(); ensuresQualifierListTM = ElementUtils.getTypeElement(processingEnv, EnsuresQualifier.List.class).asType(); ensuresQualifierIfTM = ElementUtils.getTypeElement(processingEnv, EnsuresQualifierIf.class).asType(); ensuresQualifierIfListTM = ElementUtils.getTypeElement(processingEnv, EnsuresQualifierIf.List.class).asType(); } /** * @throws BugInCF If supportedQuals is empty or if any of the support qualifiers has a @Target * meta-annotation that contain something besides TYPE_USE or TYPE_PARAMETER. (@Target({}) is * allowed.) */ private void checkSupportedQuals() { if (supportedQuals.isEmpty()) { throw new TypeSystemError("Found no supported qualifiers."); } for (Class<? extends Annotation> annotationClass : supportedQuals) { // Check @Target values ElementType[] targetValues = annotationClass.getAnnotation(Target.class).value(); List<ElementType> badTargetValues = new ArrayList<>(); for (ElementType element : targetValues) { if (!(element == ElementType.TYPE_USE || element == ElementType.TYPE_PARAMETER)) { // if there's an ElementType with an enumerated value of something other // than TYPE_USE or TYPE_PARAMETER then it isn't a valid qualifier badTargetValues.add(element); } } if (!badTargetValues.isEmpty()) { String msg = "The @Target meta-annotation on type qualifier " + annotationClass.toString() + " must not contain " + StringsPlume.conjunction("or", badTargetValues) + "."; throw new TypeSystemError(msg); } } } /** * This method is called only when {@code -Ainfer} is passed as an option. It checks if another * option that should not occur simultaneously with the whole-program inference is also passed as * argument, and aborts the process if that is the case. For example, the whole-program inference * process was not designed to work with conservative defaults. * * <p>Subclasses may override this method to add more options. */ protected void checkInvalidOptionsInferSignatures() { // See Issue 683 // https://github.com/typetools/checker-framework/issues/683 if (checker.useConservativeDefault("source") || checker.useConservativeDefault("bytecode")) { throw new UserError( "The option -Ainfer=... cannot be used together with conservative defaults."); } } /** * Actions that logically belong in the constructor, but need to run after the subclass * constructor has completed. In particular, parseStubFiles() may try to do type resolution with * this AnnotatedTypeFactory. */ protected void postInit() { this.qualHierarchy = createQualifierHierarchy(); if (qualHierarchy == null) { throw new TypeSystemError( "AnnotatedTypeFactory with null qualifier hierarchy not supported."); } else if (!qualHierarchy.isValid()) { throw new TypeSystemError( "AnnotatedTypeFactory: invalid qualifier hierarchy: %s %s ", qualHierarchy.getClass(), qualHierarchy); } this.typeHierarchy = createTypeHierarchy(); this.typeVarSubstitutor = createTypeVariableSubstitutor(); this.typeArgumentInference = createTypeArgumentInference(); this.qualifierUpperBounds = createQualifierUpperBounds(); // TODO: is this the best location for declaring this alias? addAliasedDeclAnnotation( org.jmlspecs.annotation.Pure.class, org.checkerframework.dataflow.qual.Pure.class, AnnotationBuilder.fromClass(elements, org.checkerframework.dataflow.qual.Pure.class)); // Accommodate the inability to write @InheritedAnnotation on these annotations. addInheritedAnnotation( AnnotationBuilder.fromClass(elements, org.checkerframework.dataflow.qual.Pure.class)); addInheritedAnnotation( AnnotationBuilder.fromClass( elements, org.checkerframework.dataflow.qual.SideEffectFree.class)); addInheritedAnnotation( AnnotationBuilder.fromClass( elements, org.checkerframework.dataflow.qual.Deterministic.class)); addInheritedAnnotation( AnnotationBuilder.fromClass( elements, org.checkerframework.dataflow.qual.TerminatesExecution.class)); initializeReflectionResolution(); if (this.getClass() == AnnotatedTypeFactory.class) { this.parseAnnotationFiles(); } TypeMirror iterableTypeMirror = ElementUtils.getTypeElement(processingEnv, Iterable.class).asType(); this.iterableDeclType = (AnnotatedDeclaredType) AnnotatedTypeMirror.createType(iterableTypeMirror, this, true); } /** * Returns the checker associated with this factory. * * @return the checker associated with this factory */ public BaseTypeChecker getChecker() { return checker; } /** * Creates {@link QualifierUpperBounds} for this type factory. * * @return a new {@link QualifierUpperBounds} for this type factory */ protected QualifierUpperBounds createQualifierUpperBounds() { return new QualifierUpperBounds(this); } /** * Return {@link QualifierUpperBounds} for this type factory. * * @return {@link QualifierUpperBounds} for this type factory */ public QualifierUpperBounds getQualifierUpperBounds() { return qualifierUpperBounds; } /** * Returns the WholeProgramInference instance (may be null). * * @return the WholeProgramInference instance, or null */ public WholeProgramInference getWholeProgramInference() { return wholeProgramInference; } protected void initializeReflectionResolution() { if (checker.shouldResolveReflection()) { boolean debug = "debug".equals(checker.getOption("resolveReflection")); MethodValChecker methodValChecker = checker.getSubchecker(MethodValChecker.class); assert methodValChecker != null : "AnnotatedTypeFactory: reflection resolution was requested, but MethodValChecker isn't" + " a subchecker."; MethodValAnnotatedTypeFactory methodValATF = (MethodValAnnotatedTypeFactory) methodValChecker.getAnnotationProvider(); reflectionResolver = new DefaultReflectionResolver(checker, methodValATF, debug); } } /** * Set the CompilationUnitTree that should be used. * * @param root the new compilation unit to use */ public void setRoot(@Nullable CompilationUnitTree root) { if (root != null && wholeProgramInference != null) { for (Tree typeDecl : root.getTypeDecls()) { if (typeDecl.getKind() == Kind.CLASS) { ClassTree classTree = (ClassTree) typeDecl; wholeProgramInference.preprocessClassTree(classTree); } } } this.root = root; // Do not clear here. Only the primary checker should clear this cache. // treePathCache.clear(); // setRoot in a GenericAnnotatedTypeFactory will clear this; // if this isn't a GenericATF, then it must clear it itself. if (!(this instanceof GenericAnnotatedTypeFactory)) { artificialTreeToEnclosingElementMap.clear(); } if (shouldCache) { // Clear the caches with trees because once the compilation unit changes, // the trees may be modified and lose type arguments. elementToTreeCache.clear(); fromExpressionTreeCache.clear(); fromMemberTreeCache.clear(); fromTypeTreeCache.clear(); classAndMethodTreeCache.clear(); // There is no need to clear the following cache, it is limited by cache size and it // contents won't change between compilation units. // elementCache.clear(); } if (root != null && checker.hasOption("ajava")) { // Search for an ajava file with annotations for the current source file and the current // checker. It will be in a directory specified by the "ajava" option in a subdirectory // corresponding to this file's package. For example, a file in package a.b would be in a // subdirectory a/b. The filename is ClassName-checker.qualified.name.ajava. If such a file // exists, read its detailed annotation data, including annotations on private elements. String packagePrefix = root.getPackageName() != null ? TreeUtils.nameExpressionToString(root.getPackageName()) + "." : ""; // The method getName() returns a path. String className = root.getSourceFile().getName(); // Extract the basename. int lastSeparator = className.lastIndexOf(File.separator); if (lastSeparator != -1) { className = className.substring(lastSeparator + 1); } // Drop the ".java" extension. if (className.endsWith(".java")) { className = className.substring(0, className.length() - ".java".length()); } String qualifiedName = packagePrefix + className; for (String ajavaLocation : checker.getOption("ajava").split(File.pathSeparator)) { String ajavaPath = ajavaLocation + File.separator + qualifiedName.replaceAll("\\.", "/") + "-" + checker.getClass().getCanonicalName() + ".ajava"; File ajavaFile = new File(ajavaPath); if (ajavaFile.exists()) { currentFileAjavaTypes = new AnnotationFileElementTypes(this); currentFileAjavaTypes.parseAjavaFileWithTree(ajavaPath, root); break; } } } else { currentFileAjavaTypes = null; } } @SideEffectFree @Override public String toString() { return getClass().getSimpleName() + "#" + uid; } /** * Returns the {@link QualifierHierarchy} to be used by this checker. * * <p>The implementation builds the type qualifier hierarchy for the {@link * #getSupportedTypeQualifiers()} using the meta-annotations found in them. The current * implementation returns an instance of {@code NoElementQualifierHierarchy}. * * <p>Subclasses must override this method if their qualifiers have elements; the method must * return an implementation of {@link QualifierHierarchy}, such as {@link * ElementQualifierHierarchy}. * * @return a QualifierHierarchy for this type system */ protected QualifierHierarchy createQualifierHierarchy() { return new NoElementQualifierHierarchy(this.getSupportedTypeQualifiers(), elements); } /** * Returns the type qualifier hierarchy graph to be used by this processor. * * @see #createQualifierHierarchy() * @return the {@link QualifierHierarchy} for this checker */ public final QualifierHierarchy getQualifierHierarchy() { return qualHierarchy; } /** * To continue to use a subclass of {@link * org.checkerframework.framework.util.MultiGraphQualifierHierarchy} or {@link * org.checkerframework.framework.util.GraphQualifierHierarchy}, override this method so that it * returns a new instance of the subclass. Then override {@link #createQualifierHierarchy()} so * that it returns the result of a call to {@link * org.checkerframework.framework.util.MultiGraphQualifierHierarchy#createMultiGraphQualifierHierarchy(AnnotatedTypeFactory)}. * * @param factory MultiGraphFactory * @return QualifierHierarchy * @deprecated Use either {@link ElementQualifierHierarchy}, {@link NoElementQualifierHierarchy}, * or {@link MostlyNoElementQualifierHierarchy} instead. This method will be removed in a * future release. */ @Deprecated // 2020-09-10 public QualifierHierarchy createQualifierHierarchyWithMultiGraphFactory( org.checkerframework.framework.util.MultiGraphQualifierHierarchy.MultiGraphFactory factory) { throw new TypeSystemError( "Checker must override AnnotatedTypeFactory#createQualifierHierarchyWithMultiGraphFactory" + " when using AnnotatedTypeFactory#createMultiGraphQualifierHierarchy."); } /** * Creates the type hierarchy to be used by this factory. * * <p>Subclasses may override this method to specify new type-checking rules beyond the typical * Java subtyping rules. * * @return the type relations class to check type subtyping */ protected TypeHierarchy createTypeHierarchy() { return new DefaultTypeHierarchy( checker, getQualifierHierarchy(), checker.getBooleanOption("ignoreRawTypeArguments", true), checker.hasOption("invariantArrays")); } public final TypeHierarchy getTypeHierarchy() { return typeHierarchy; } /** TypeVariableSubstitutor provides a method to replace type parameters with their arguments. */ protected TypeVariableSubstitutor createTypeVariableSubstitutor() { return new TypeVariableSubstitutor(); } public TypeVariableSubstitutor getTypeVarSubstitutor() { return typeVarSubstitutor; } /** * TypeArgumentInference infers the method type arguments when they are not explicitly written. */ protected TypeArgumentInference createTypeArgumentInference() { return new DefaultTypeArgumentInference(this); } public TypeArgumentInference getTypeArgumentInference() { return typeArgumentInference; } /** * Factory method to easily change what {@link AnnotationClassLoader} is created to load type * annotation classes. Subclasses can override this method and return a custom * AnnotationClassLoader subclass to customize loading logic. */ protected AnnotationClassLoader createAnnotationClassLoader() { return new AnnotationClassLoader(checker); } /** * Returns a mutable set of annotation classes that are supported by a checker. * * <p>Subclasses may override this method to return a mutable set of their supported type * qualifiers through one of the 5 approaches shown below. * * <p>Subclasses should not call this method; they should call {@link #getSupportedTypeQualifiers} * instead. * * <p>By default, a checker supports all annotations located in a subdirectory called {@literal * qual} that's located in the same directory as the checker. Note that only annotations defined * with the {@code @Target({ElementType.TYPE_USE})} meta-annotation (and optionally with the * additional value of {@code ElementType.TYPE_PARAMETER}, but no other {@code ElementType} * values) are automatically considered as supported annotations. * * <p>To support a different set of annotations than those in the {@literal qual} subdirectory, or * that have other {@code ElementType} values, see examples below. * * <p>In total, there are 5 ways to indicate annotations that are supported by a checker: * * <ol> * <li>Only support annotations located in a checker's {@literal qual} directory: * <p>This is the default behavior. Simply place those annotations within the {@literal * qual} directory. * <li>Support annotations located in a checker's {@literal qual} directory and a list of other * annotations: * <p>Place those annotations within the {@literal qual} directory, and override {@link * #createSupportedTypeQualifiers()} by calling {@link #getBundledTypeQualifiers(Class...)} * with a varargs parameter list of the other annotations. Code example: * <pre> * {@code @Override protected Set<Class<? extends Annotation>> createSupportedTypeQualifiers() { * return getBundledTypeQualifiers(Regex.class, PartialRegex.class, RegexBottom.class, UnknownRegex.class); * } } * </pre> * <li>Supporting only annotations that are explicitly listed: Override {@link * #createSupportedTypeQualifiers()} and return a mutable set of the supported annotations. * Code example: * <pre> * {@code @Override protected Set<Class<? extends Annotation>> createSupportedTypeQualifiers() { * return new HashSet<Class<? extends Annotation>>( * Arrays.asList(A.class, B.class)); * } } * </pre> * The set of qualifiers returned by {@link #createSupportedTypeQualifiers()} must be a * fresh, mutable set. The methods {@link #getBundledTypeQualifiers(Class...)} must return a * fresh, mutable set * </ol> * * @return the type qualifiers supported this processor, or an empty set if none */ protected Set<Class<? extends Annotation>> createSupportedTypeQualifiers() { return getBundledTypeQualifiers(); } /** * Loads all annotations contained in the qual directory of a checker via reflection; if a * polymorphic type qualifier exists, and an explicit array of annotations to the set of * annotation classes. * * <p>This method can be called in the overridden versions of {@link * #createSupportedTypeQualifiers()} in each checker. * * @param explicitlyListedAnnotations a varargs array of explicitly listed annotation classes to * be added to the returned set. For example, it is used frequently to add Bottom qualifiers. * @return a mutable set of the loaded and listed annotation classes */ @SafeVarargs protected final Set<Class<? extends Annotation>> getBundledTypeQualifiers( Class<? extends Annotation>... explicitlyListedAnnotations) { return loadTypeAnnotationsFromQualDir(explicitlyListedAnnotations); } /** * Instantiates the AnnotationClassLoader and loads all annotations contained in the qual * directory of a checker via reflection, and has the option to include an explicitly stated list * of annotations (eg ones found in a different directory than qual). * * <p>The annotations that are automatically loaded must have the {@link * java.lang.annotation.Target Target} meta-annotation with the value of {@link * ElementType#TYPE_USE} (and optionally {@link ElementType#TYPE_PARAMETER}). If it has other * {@link ElementType} values, it won't be loaded. Other annotation classes must be explicitly * listed even if they are in the same directory as the checker's qual directory. * * @param explicitlyListedAnnotations a set of explicitly listed annotation classes to be added to * the returned set, for example, it is used frequently to add Bottom qualifiers * @return a set of annotation class instances */ @SafeVarargs @SuppressWarnings("varargs") private final Set<Class<? extends Annotation>> loadTypeAnnotationsFromQualDir( Class<? extends Annotation>... explicitlyListedAnnotations) { loader = createAnnotationClassLoader(); Set<Class<? extends Annotation>> annotations = loader.getBundledAnnotationClasses(); // add in all explicitly Listed qualifiers if (explicitlyListedAnnotations != null) { annotations.addAll(Arrays.asList(explicitlyListedAnnotations)); } return annotations; } /** * Creates the AnnotatedTypeFormatter used by this type factory and all AnnotatedTypeMirrors it * creates. The AnnotatedTypeFormatter is used in AnnotatedTypeMirror.toString and will affect the * error messages printed for checkers that use this type factory. * * @return the AnnotatedTypeFormatter to pass to all instantiated AnnotatedTypeMirrors */ protected AnnotatedTypeFormatter createAnnotatedTypeFormatter() { boolean printVerboseGenerics = checker.hasOption("printVerboseGenerics"); return new DefaultAnnotatedTypeFormatter( printVerboseGenerics, // -AprintVerboseGenerics implies -AprintAllQualifiers printVerboseGenerics || checker.hasOption("printAllQualifiers")); } public AnnotatedTypeFormatter getAnnotatedTypeFormatter() { return typeFormatter; } protected AnnotationFormatter createAnnotationFormatter() { return new DefaultAnnotationFormatter(); } public AnnotationFormatter getAnnotationFormatter() { return annotationFormatter; } /** * Returns an immutable set of the classes corresponding to the type qualifiers supported by this * checker. * * <p>Subclasses cannot override this method; they should override {@link * #createSupportedTypeQualifiers createSupportedTypeQualifiers} instead. * * @see #createSupportedTypeQualifiers() * @return an immutable set of the supported type qualifiers, or an empty set if no qualifiers are * supported */ public final Set<Class<? extends Annotation>> getSupportedTypeQualifiers() { if (this.supportedQuals.isEmpty()) { supportedQuals.addAll(createSupportedTypeQualifiers()); checkSupportedQuals(); } return Collections.unmodifiableSet(supportedQuals); } /** * Returns an immutable set of the fully qualified names of the type qualifiers supported by this * checker. * * <p>Subclasses cannot override this method; they should override {@link * #createSupportedTypeQualifiers createSupportedTypeQualifiers} instead. * * @see #createSupportedTypeQualifiers() * @return an immutable set of the supported type qualifiers, or an empty set if no qualifiers are * supported */ public final Set<@CanonicalName String> getSupportedTypeQualifierNames() { if (this.supportedQualNames.isEmpty()) { for (Class<?> clazz : getSupportedTypeQualifiers()) { supportedQualNames.add(clazz.getCanonicalName()); } } return Collections.unmodifiableSet(supportedQualNames); } // ********************************************************************** // Factories for annotated types that account for default qualifiers // ********************************************************************** /** * Returns the size for LRU caches. It is either the value supplied via the {@code -AatfCacheSize} * option or the default cache size. * * @return cache size passed as argument to checker or DEFAULT_CACHE_SIZE */ protected int getCacheSize() { String option = checker.getOption("atfCacheSize"); if (option == null) { return DEFAULT_CACHE_SIZE; } try { return Integer.valueOf(option); } catch (NumberFormatException ex) { throw new UserError("atfCacheSize was not an integer: " + option); } } /** * Returns an AnnotatedTypeMirror representing the annotated type of {@code elt}. * * @param elt the element * @return the annotated type of {@code elt} */ public AnnotatedTypeMirror getAnnotatedType(Element elt) { if (elt == null) { throw new BugInCF("AnnotatedTypeFactory.getAnnotatedType: null element"); } // Annotations explicitly written in the source code, // or obtained from bytecode. AnnotatedTypeMirror type = fromElement(elt); addComputedTypeAnnotations(elt, type); return type; } /** * Returns an AnnotatedTypeMirror representing the annotated type of {@code clazz}. * * @param clazz a class * @return the annotated type of {@code clazz} */ public AnnotatedTypeMirror getAnnotatedType(Class<?> clazz) { return getAnnotatedType(elements.getTypeElement(clazz.getCanonicalName())); } @Override public @Nullable AnnotationMirror getAnnotationMirror( Tree tree, Class<? extends Annotation> target) { if (isSupportedQualifier(target)) { AnnotatedTypeMirror atm = getAnnotatedType(tree); return atm.getAnnotation(target); } return null; } /** * Returns an AnnotatedTypeMirror representing the annotated type of {@code tree}. * * @param tree the AST node * @return the annotated type of {@code tree} */ public AnnotatedTypeMirror getAnnotatedType(Tree tree) { if (tree == null) { throw new BugInCF("AnnotatedTypeFactory.getAnnotatedType: null tree"); } if (shouldCache && classAndMethodTreeCache.containsKey(tree)) { return classAndMethodTreeCache.get(tree).deepCopy(); } AnnotatedTypeMirror type; if (TreeUtils.isClassTree(tree)) { type = fromClass((ClassTree) tree); } else if (tree.getKind() == Tree.Kind.METHOD || tree.getKind() == Tree.Kind.VARIABLE) { type = fromMember(tree); } else if (TreeUtils.isExpressionTree(tree)) { tree = TreeUtils.withoutParens((ExpressionTree) tree); type = fromExpression((ExpressionTree) tree); } else { throw new BugInCF( "AnnotatedTypeFactory.getAnnotatedType: query of annotated type for tree " + tree.getKind()); } addComputedTypeAnnotations(tree, type); if (TreeUtils.isClassTree(tree) || tree.getKind() == Tree.Kind.METHOD) { // Don't cache VARIABLE if (shouldCache) { classAndMethodTreeCache.put(tree, type.deepCopy()); } } else { // No caching otherwise } return type; } /** * Called by {@link BaseTypeVisitor#visitClass(ClassTree, Void)} before the classTree is type * checked. * * @param classTree ClassTree on which to perform preprocessing */ public void preProcessClassTree(ClassTree classTree) {} /** * Called by {@link BaseTypeVisitor#visitClass(ClassTree, Void)} after the ClassTree has been type * checked. * * <p>The default implementation uses this to store the defaulted AnnotatedTypeMirrors and * inherited declaration annotations back into the corresponding Elements. Subclasses might want * to override this method if storing defaulted types is not desirable. */ public void postProcessClassTree(ClassTree tree) { TypesIntoElements.store(processingEnv, this, tree); DeclarationsIntoElements.store(processingEnv, this, tree); if (wholeProgramInference != null) { // Write out the results of whole-program inference, just once for each class. As soon as any // class is finished processing, all modified scenes are written to files, in case this was // the last class to be processed. Post-processing of subsequent classes might result in // re-writing some of the scenes if new information has been written to them. wholeProgramInference.writeResultsToFile(wpiOutputFormat, this.checker); } } /** * Determines the annotated type from a type in tree form. * * <p>Note that we cannot decide from a Tree whether it is a type use or an expression. * TreeUtils.isTypeTree is only an under-approximation. For example, an identifier can be either a * type or an expression. * * @param tree the type tree * @return the annotated type of the type in the AST */ public AnnotatedTypeMirror getAnnotatedTypeFromTypeTree(Tree tree) { if (tree == null) { throw new BugInCF("AnnotatedTypeFactory.getAnnotatedTypeFromTypeTree: null tree"); } AnnotatedTypeMirror type = fromTypeTree(tree); addComputedTypeAnnotations(tree, type); return type; } /** * Returns the set of qualifiers that are the upper bounds for a use of the type. * * @param type a type whose upper bounds to obtain */ public Set<AnnotationMirror> getTypeDeclarationBounds(TypeMirror type) { return qualifierUpperBounds.getBoundQualifiers(type); } /** * Returns the set of qualifiers that are the upper bound for a type use if no other bound is * specified for the type. * * <p>This implementation returns the top qualifiers by default. Subclass may override to return * different qualifiers. * * @return the set of qualifiers that are the upper bound for a type use if no other bound is * specified for the type */ protected Set<? extends AnnotationMirror> getDefaultTypeDeclarationBounds() { return qualHierarchy.getTopAnnotations(); } /** * Returns the type of the extends or implements clause. * * <p>The primary qualifier is either an explicit annotation on {@code clause}, or it is the * qualifier upper bounds for uses of the type of the clause. * * @param clause tree that represents an extends or implements clause * @return the type of the extends or implements clause */ public AnnotatedTypeMirror getTypeOfExtendsImplements(Tree clause) { AnnotatedTypeMirror fromTypeTree = fromTypeTree(clause); Set<AnnotationMirror> bound = getTypeDeclarationBounds(fromTypeTree.getUnderlyingType()); fromTypeTree.addMissingAnnotations(bound); return fromTypeTree; } // ********************************************************************** // Factories for annotated types that do not account for default qualifiers. // They only include qualifiers explicitly inserted by the user. // ********************************************************************** /** * Creates an AnnotatedTypeMirror for {@code elt} that includes: annotations explicitly written on * the element and annotations from stub files. * * <p>Does not include default qualifiers. To obtain them, use {@link #getAnnotatedType(Element)}. * * <p>Does not include fake overrides from the stub file. * * @param elt the element * @return AnnotatedTypeMirror of the element with explicitly-written and stub file annotations */ public AnnotatedTypeMirror fromElement(Element elt) { if (shouldCache && elementCache.containsKey(elt)) { return elementCache.get(elt).deepCopy(); } if (elt.getKind() == ElementKind.PACKAGE) { return toAnnotatedType(elt.asType(), false); } AnnotatedTypeMirror type; // Because of a bug in Java 8, annotations on type parameters are not stored in elements, so get // explicit annotations from the tree. (This bug has been fixed in Java 9.) Also, since // annotations computed by the AnnotatedTypeFactory are stored in the element, the annotations // have to be retrieved from the tree so that only explicit annotations are returned. Tree decl = declarationFromElement(elt); if (decl == null) { type = stubTypes.getAnnotatedTypeMirror(elt); if (type == null) { type = toAnnotatedType(elt.asType(), ElementUtils.isTypeDeclaration(elt)); ElementAnnotationApplier.apply(type, elt, this); } } else if (decl instanceof ClassTree) { type = fromClass((ClassTree) decl); } else if (decl instanceof VariableTree) { type = fromMember(decl); } else if (decl instanceof MethodTree) { type = fromMember(decl); } else if (decl.getKind() == Tree.Kind.TYPE_PARAMETER) { type = fromTypeTree(decl); } else { throw new BugInCF( "AnnotatedTypeFactory.fromElement: cannot be here. decl: " + decl.getKind() + " elt: " + elt); } type = mergeAnnotationFileAnnosIntoType(type, elt, ajavaTypes); if (currentFileAjavaTypes != null) { type = mergeAnnotationFileAnnosIntoType(type, elt, currentFileAjavaTypes); } if (checker.hasOption("mergeStubsWithSource")) { if (debugStubParser) { System.out.printf("fromElement: mergeStubsIntoType(%s, %s)", type, elt); } type = mergeAnnotationFileAnnosIntoType(type, elt, stubTypes); if (debugStubParser) { System.out.printf(" => %s%n", type); } } // Caching is disabled if annotation files are being parsed, because calls to this // method before the annotation files are fully read can return incorrect results. if (shouldCache && !stubTypes.isParsing() && !ajavaTypes.isParsing() && (currentFileAjavaTypes == null || !currentFileAjavaTypes.isParsing())) { elementCache.put(elt, type.deepCopy()); } return type; } /** * Returns an AnnotatedDeclaredType with explicit annotations from the ClassTree {@code tree}. * * @param tree the class declaration * @return AnnotatedDeclaredType with explicit annotations from {@code tree} */ private AnnotatedDeclaredType fromClass(ClassTree tree) { return TypeFromTree.fromClassTree(this, tree); } /** * Creates an AnnotatedTypeMirror for a variable or method declaration tree. The * AnnotatedTypeMirror contains annotations explicitly written on the tree. * * <p>If a VariableTree is a parameter to a lambda, this method also adds annotations from the * declared type of the functional interface and the executable type of its method. * * <p>The returned AnnotatedTypeMirror also contains explicitly written annotations from any ajava * file and if {@code -AmergeStubsWithSource} is passed, it also merges any explicitly written * annotations from stub files. * * @param tree MethodTree or VariableTree * @return AnnotatedTypeMirror with explicit annotations from {@code tree} */ private final AnnotatedTypeMirror fromMember(Tree tree) { if (!(tree instanceof MethodTree || tree instanceof VariableTree)) { throw new BugInCF( "AnnotatedTypeFactory.fromMember: not a method or variable declaration: " + tree); } if (shouldCache && fromMemberTreeCache.containsKey(tree)) { return fromMemberTreeCache.get(tree).deepCopy(); } AnnotatedTypeMirror result = TypeFromTree.fromMember(this, tree); result = mergeAnnotationFileAnnosIntoType(result, tree, ajavaTypes); if (currentFileAjavaTypes != null) { result = mergeAnnotationFileAnnosIntoType(result, tree, currentFileAjavaTypes); } if (checker.hasOption("mergeStubsWithSource")) { if (debugStubParser) { System.out.printf("fromClass: mergeStubsIntoType(%s, %s)", result, tree); } result = mergeAnnotationFileAnnosIntoType(result, tree, stubTypes); if (debugStubParser) { System.out.printf(" => %s%n", result); } } if (shouldCache) { fromMemberTreeCache.put(tree, result.deepCopy()); } return result; } /** * Merges types from annotation files for {@code tree} into {@code type} by taking the greatest * lower bound of the annotations in both. * * @param type the type to apply annotation file types to * @param tree the tree from which to read annotation file types * @param source storage for current annotation file annotations * @return the given type, side-effected to add the annotation file types */ private AnnotatedTypeMirror mergeAnnotationFileAnnosIntoType( @Nullable AnnotatedTypeMirror type, Tree tree, AnnotationFileElementTypes source) { Element elt = TreeUtils.elementFromTree(tree); return mergeAnnotationFileAnnosIntoType(type, elt, source); } /** * A scanner used to combine annotations from two AnnotatedTypeMirrors. The scanner requires * {@link #qualHierarchy}, which is set in {@link #postInit()} rather than the construtor, so * lazily initialize this field before use. */ private @MonotonicNonNull AnnotatedTypeCombiner annotatedTypeCombiner = null; /** * Merges types from annotation files for {@code elt} into {@code type} by taking the greatest * lower bound of the annotations in both. * * @param type the type to apply annotation file types to * @param elt the element from which to read annotation file types * @param source storage for current annotation file annotations * @return the type, side-effected to add the annotation file types */ protected AnnotatedTypeMirror mergeAnnotationFileAnnosIntoType( @Nullable AnnotatedTypeMirror type, Element elt, AnnotationFileElementTypes source) { AnnotatedTypeMirror typeFromFile = source.getAnnotatedTypeMirror(elt); if (typeFromFile == null) { return type; } if (type == null) { return typeFromFile; } if (annotatedTypeCombiner == null) { annotatedTypeCombiner = new AnnotatedTypeCombiner(qualHierarchy); } // Must merge (rather than only take the annotation file type if it is a subtype) to support // WPI. annotatedTypeCombiner.visit(typeFromFile, type); return type; } /** * Creates an AnnotatedTypeMirror for an ExpressionTree. The AnnotatedTypeMirror contains explicit * annotations written on the expression and for some expressions, annotations from * sub-expressions that could have been explicitly written, defaulted, refined, or otherwise * computed. (Expression whose type include annotations from sub-expressions are: ArrayAccessTree, * ConditionalExpressionTree, IdentifierTree, MemberSelectTree, and MethodInvocationTree.) * * <p>For example, the AnnotatedTypeMirror returned for an array access expression is the fully * annotated type of the array component of the array being accessed. * * @param tree an expression * @return AnnotatedTypeMirror of the expressions either fully-annotated or partially annotated * depending on the kind of expression * @see TypeFromExpressionVisitor */ private AnnotatedTypeMirror fromExpression(ExpressionTree tree) { if (shouldCache && fromExpressionTreeCache.containsKey(tree)) { return fromExpressionTreeCache.get(tree).deepCopy(); } AnnotatedTypeMirror result = TypeFromTree.fromExpression(this, tree); if (shouldCache && tree.getKind() != Tree.Kind.NEW_CLASS && tree.getKind() != Kind.NEW_ARRAY && tree.getKind() != Kind.CONDITIONAL_EXPRESSION) { // Don't cache the type of some expressions, because incorrect annotations would be // cached during dataflow analysis. See Issue #602. fromExpressionTreeCache.put(tree, result.deepCopy()); } return result; } /** * Creates an AnnotatedTypeMirror for the tree. The AnnotatedTypeMirror contains annotations * explicitly written on the tree. It also adds type arguments to raw types that include * annotations from the element declaration of the type {@link #fromElement(Element)}. * * <p>Called on the following trees: AnnotatedTypeTree, ArrayTypeTree, ParameterizedTypeTree, * PrimitiveTypeTree, TypeParameterTree, WildcardTree, UnionType, IntersectionTypeTree, and * IdentifierTree, MemberSelectTree. * * @param tree the type tree * @return the (partially) annotated type of the type in the AST */ /*package private*/ final AnnotatedTypeMirror fromTypeTree(Tree tree) { if (shouldCache && fromTypeTreeCache.containsKey(tree)) { return fromTypeTreeCache.get(tree).deepCopy(); } AnnotatedTypeMirror result = TypeFromTree.fromTypeTree(this, tree); if (shouldCache) { fromTypeTreeCache.put(tree, result.deepCopy()); } return result; } // ********************************************************************** // Customization methods meant to be overridden by subclasses to include // defaulted annotations // ********************************************************************** /** * Changes annotations on a type obtained from a {@link Tree}. By default, this method does * nothing. GenericAnnotatedTypeFactory uses this method to implement defaulting and inference * (flow-sensitive type refinement). Its subclasses usually override it only to customize default * annotations. * * <p>Subclasses that override this method should also override {@link * #addComputedTypeAnnotations(Element, AnnotatedTypeMirror)}. * * <p>In classes that extend {@link GenericAnnotatedTypeFactory}, override {@link * GenericAnnotatedTypeFactory#addComputedTypeAnnotations(Tree, AnnotatedTypeMirror, boolean)} * instead of this method. * * @param tree an AST node * @param type the type obtained from {@code tree} */ protected void addComputedTypeAnnotations(Tree tree, AnnotatedTypeMirror type) { // Pass. } /** * Changes annotations on a type obtained from an {@link Element}. By default, this method does * nothing. GenericAnnotatedTypeFactory uses this method to implement defaulting. * * <p>Subclasses that override this method should also override {@link * #addComputedTypeAnnotations(Tree, AnnotatedTypeMirror)}. * * @param elt an element * @param type the type obtained from {@code elt} */ protected void addComputedTypeAnnotations(Element elt, AnnotatedTypeMirror type) { // Pass. } /** * Adds default annotations to {@code type}. This method should only be used in places where the * correct annotations cannot be computed because of uninferred type arguments. (See {@link * AnnotatedWildcardType#isUninferredTypeArgument()}.) * * @param type annotated type to which default annotations are added */ public void addDefaultAnnotations(AnnotatedTypeMirror type) { // Pass. } /** * A callback method for the AnnotatedTypeFactory subtypes to customize directSupertypes(). * Overriding methods should merely change the annotations on the supertypes, without adding or * removing new types. * * <p>The default provided implementation adds {@code type} annotations to {@code supertypes}. * This allows the {@code type} and its supertypes to have the qualifiers. * * @param type the type whose supertypes are desired * @param supertypes the supertypes as specified by the base AnnotatedTypeFactory */ protected void postDirectSuperTypes( AnnotatedTypeMirror type, List<? extends AnnotatedTypeMirror> supertypes) { // Use the effective annotations here to get the correct annotations // for type variables and wildcards. Set<AnnotationMirror> annotations = type.getEffectiveAnnotations(); for (AnnotatedTypeMirror supertype : supertypes) { if (!annotations.equals(supertype.getEffectiveAnnotations())) { supertype.clearAnnotations(); // TODO: is this correct for type variables and wildcards? supertype.addAnnotations(annotations); } } } /** * A callback method for the AnnotatedTypeFactory subtypes to customize * AnnotatedTypes.asMemberOf(). Overriding methods should merely change the annotations on the * subtypes, without changing the types. * * @param type the annotated type of the element * @param owner the annotated type of the receiver of the accessing tree * @param element the element of the field or method */ public void postAsMemberOf(AnnotatedTypeMirror type, AnnotatedTypeMirror owner, Element element) { if (element.getKind() == ElementKind.FIELD) { addAnnotationFromFieldInvariant(type, owner, (VariableElement) element); } addComputedTypeAnnotations(element, type); } /** * Adds the qualifier specified by a field invariant for {@code field} to {@code type}. * * @param type annotated type to which the annotation is added * @param accessedVia the annotated type of the receiver of the accessing tree. (Only used to get * the type element of the underling type.) * @param field element representing the field */ protected void addAnnotationFromFieldInvariant( AnnotatedTypeMirror type, AnnotatedTypeMirror accessedVia, VariableElement field) { TypeMirror declaringType = accessedVia.getUnderlyingType(); // Find the first upper bound that isn't a wildcard or type variable while (declaringType.getKind() == TypeKind.WILDCARD || declaringType.getKind() == TypeKind.TYPEVAR) { if (declaringType.getKind() == TypeKind.WILDCARD) { declaringType = TypesUtils.wildUpperBound(declaringType, processingEnv); } else if (declaringType.getKind() == TypeKind.TYPEVAR) { declaringType = ((TypeVariable) declaringType).getUpperBound(); } } TypeElement typeElement = TypesUtils.getTypeElement(declaringType); if (ElementUtils.enclosingTypeElement(field).equals(typeElement)) { // If the field is declared in the accessedVia class, then the field in the invariant // cannot be this field, even if the field has the same name. return; } FieldInvariants invariants = getFieldInvariants(typeElement); if (invariants == null) { return; } List<AnnotationMirror> invariantAnnos = invariants.getQualifiersFor(field.getSimpleName()); type.replaceAnnotations(invariantAnnos); } /** * Returns the field invariants for the given class, as expressed by the user in {@link * FieldInvariant @FieldInvariant} method annotations. * * <p>Subclasses may implement their own field invariant annotations if {@link * FieldInvariant @FieldInvariant} is not expressive enough. They must override this method to * properly create AnnotationMirror and also override {@link * #getFieldInvariantDeclarationAnnotations()} to return their field invariants. * * @param element class for which to get invariants * @return field invariants for {@code element} */ public FieldInvariants getFieldInvariants(TypeElement element) { if (element == null) { return null; } AnnotationMirror fieldInvarAnno = getDeclAnnotation(element, FieldInvariant.class); if (fieldInvarAnno == null) { return null; } List<String> fields = AnnotationUtils.getElementValueArray( fieldInvarAnno, fieldInvariantFieldElement, String.class); List<@CanonicalName Name> classes = AnnotationUtils.getElementValueClassNames(fieldInvarAnno, fieldInvariantQualifierElement); List<AnnotationMirror> qualifiers = CollectionsPlume.mapList( (Name name) -> // Calling AnnotationBuilder.fromName (which ignores elements/fields) is acceptable // because @FieldInvariant does not handle classes with elements/fields. AnnotationBuilder.fromName(elements, name), classes); if (qualifiers.size() == 1) { while (fields.size() > qualifiers.size()) { qualifiers.add(qualifiers.get(0)); } } if (fields.size() != qualifiers.size()) { // The user wrote a malformed @FieldInvariant annotation, so just return a malformed // FieldInvariants object. The BaseTypeVisitor will issue an error. return new FieldInvariants(fields, qualifiers); } // Only keep qualifiers that are supported by this checker. (The other qualifiers cannot // be checked by this checker, so they must be ignored.) List<String> annotatedFields = new ArrayList<>(); List<AnnotationMirror> supportedQualifiers = new ArrayList<>(); for (int i = 0; i < fields.size(); i++) { if (isSupportedQualifier(qualifiers.get(i))) { annotatedFields.add(fields.get(i)); supportedQualifiers.add(qualifiers.get(i)); } } if (annotatedFields.isEmpty()) { return null; } return new FieldInvariants(annotatedFields, supportedQualifiers); } /** * Returns the AnnotationTree which is a use of one of the field invariant annotations (as * specified via {@link #getFieldInvariantDeclarationAnnotations()}. If one isn't found, null is * returned. * * @param annoTrees list of trees to search; the result is one of the list elements, or null * @return the AnnotationTree that is a use of one of the field invariant annotations, or null if * one isn't found */ public AnnotationTree getFieldInvariantAnnotationTree(List<? extends AnnotationTree> annoTrees) { List<AnnotationMirror> annos = TreeUtils.annotationsFromTypeAnnotationTrees(annoTrees); for (int i = 0; i < annos.size(); i++) { for (Class<? extends Annotation> clazz : getFieldInvariantDeclarationAnnotations()) { if (areSameByClass(annos.get(i), clazz)) { return annoTrees.get(i); } } } return null; } /** Returns the set of classes of field invariant annotations. */ protected Set<Class<? extends Annotation>> getFieldInvariantDeclarationAnnotations() { return Collections.singleton(FieldInvariant.class); } /** * A callback method for the AnnotatedTypeFactory subtypes to customize * AnnotatedTypeMirror.substitute(). * * @param varDecl a declaration of a type variable * @param varUse a use of the same type variable * @param value the new type to substitute in for the type variable */ public void postTypeVarSubstitution( AnnotatedTypeVariable varDecl, AnnotatedTypeVariable varUse, AnnotatedTypeMirror value) { if (!varUse.getAnnotationsField().isEmpty() && !AnnotationUtils.areSame(varUse.getAnnotationsField(), varDecl.getAnnotationsField())) { value.replaceAnnotations(varUse.getAnnotationsField()); } } /** * Adapt the upper bounds of the type variables of a class relative to the type instantiation. In * some type systems, the upper bounds depend on the instantiation of the class. For example, in * the Generic Universe Type system, consider a class declaration * * <pre>{@code class C<X extends @Peer Object> }</pre> * * then the instantiation * * <pre>{@code @Rep C<@Rep Object> }</pre> * * is legal. The upper bounds of class C have to be adapted by the main modifier. * * <p>An example of an adaptation follows. Suppose, I have a declaration: * * <pre>{@code class MyClass<E extends List<E>>}</pre> * * And an instantiation: * * <pre>{@code new MyClass<@NonNull String>()}</pre> * * <p>The upper bound of E adapted to the argument String, would be {@code List<@NonNull String>} * and the lower bound would be an AnnotatedNullType. * * <p>TODO: ensure that this method is consistently used instead of directly querying the type * variables. * * @param type the use of the type * @param element the corresponding element * @return the adapted bounds of the type parameters */ public List<AnnotatedTypeParameterBounds> typeVariablesFromUse( AnnotatedDeclaredType type, TypeElement element) { AnnotatedDeclaredType generic = getAnnotatedType(element); List<AnnotatedTypeMirror> targs = type.getTypeArguments(); List<AnnotatedTypeMirror> tvars = generic.getTypeArguments(); assert targs.size() == tvars.size() : "Mismatch in type argument size between " + type + " and " + generic; // System.err.printf("TVFU%n type: %s%n generic: %s%n", type, generic); Map<TypeVariable, AnnotatedTypeMirror> mapping = new HashMap<>(); AnnotatedDeclaredType enclosing = type; while (enclosing != null) { List<AnnotatedTypeMirror> enclosingTArgs = enclosing.getTypeArguments(); AnnotatedDeclaredType declaredType = getAnnotatedType((TypeElement) enclosing.getUnderlyingType().asElement()); List<AnnotatedTypeMirror> enclosingTVars = declaredType.getTypeArguments(); for (int i = 0; i < enclosingTArgs.size(); i++) { AnnotatedTypeVariable enclosingTVar = (AnnotatedTypeVariable) enclosingTVars.get(i); mapping.put(enclosingTVar.getUnderlyingType(), enclosingTArgs.get(i)); } enclosing = enclosing.getEnclosingType(); } List<AnnotatedTypeParameterBounds> res = new ArrayList<>(tvars.size()); for (AnnotatedTypeMirror atm : tvars) { AnnotatedTypeVariable atv = (AnnotatedTypeVariable) atm; AnnotatedTypeMirror upper = typeVarSubstitutor.substitute(mapping, atv.getUpperBound()); AnnotatedTypeMirror lower = typeVarSubstitutor.substitute(mapping, atv.getLowerBound()); res.add(new AnnotatedTypeParameterBounds(upper, lower)); } return res; } /** * Creates and returns an AnnotatedNullType qualified with {@code annotations}. * * @param annotations set of AnnotationMirrors to qualify the returned type with * @return AnnotatedNullType qualified with {@code annotations} */ public AnnotatedNullType getAnnotatedNullType(Set<? extends AnnotationMirror> annotations) { final AnnotatedTypeMirror.AnnotatedNullType nullType = (AnnotatedNullType) toAnnotatedType(processingEnv.getTypeUtils().getNullType(), false); nullType.addAnnotations(annotations); return nullType; } // ********************************************************************** // Utilities method for getting specific types from trees or elements // ********************************************************************** /** * Return the implicit receiver type of an expression tree. * * <p>The result is null for expressions that don't have a receiver, e.g. for a local variable or * method parameter access. The result is also null for expressions that have an explicit * receiver. * * <p>Clients should generally call {@link #getReceiverType}. * * @param tree the expression that might have an implicit receiver * @return the type of the implicit receiver */ protected @Nullable AnnotatedDeclaredType getImplicitReceiverType(ExpressionTree tree) { assert (tree.getKind() == Tree.Kind.IDENTIFIER || tree.getKind() == Tree.Kind.MEMBER_SELECT || tree.getKind() == Tree.Kind.METHOD_INVOCATION || tree.getKind() == Tree.Kind.NEW_CLASS) : "Unexpected tree kind: " + tree.getKind(); // Return null if the element kind has no receiver. Element element = TreeUtils.elementFromTree(tree); assert element != null : "Unexpected null element for tree: " + tree; if (!ElementUtils.hasReceiver(element)) { return null; } // Return null if the receiver is explicit. if (TreeUtils.getReceiverTree(tree) != null) { return null; } TypeElement elementOfImplicitReceiver = ElementUtils.enclosingTypeElement(element); if (tree.getKind() == Kind.NEW_CLASS) { if (elementOfImplicitReceiver.getEnclosingElement() != null) { elementOfImplicitReceiver = ElementUtils.enclosingTypeElement(elementOfImplicitReceiver.getEnclosingElement()); } else { elementOfImplicitReceiver = null; } if (elementOfImplicitReceiver == null) { // If the typeElt does not have an enclosing class, then the NewClassTree // does not have an implicit receiver. return null; } } TypeMirror typeOfImplicitReceiver = elementOfImplicitReceiver.asType(); AnnotatedDeclaredType thisType = getSelfType(tree); if (thisType == null) { return null; } // An implicit receiver is the first enclosing type that is a subtype of the type where // element is declared. while (!isSubtype(thisType.getUnderlyingType(), typeOfImplicitReceiver)) { thisType = thisType.getEnclosingType(); } return thisType; } /** * Returns the type of {@code this} at the location of {@code tree}. Returns {@code null} if * {@code tree} is in a location where {@code this} has no meaning, such as the body of a static * method. * * <p>The parameter is an arbitrary tree and does not have to mention "this", neither explicitly * nor implicitly. This method can be overridden for type-system specific behavior. * * @param tree location used to decide the type of {@code this} * @return the type of {@code this} at the location of {@code tree} */ public @Nullable AnnotatedDeclaredType getSelfType(Tree tree) { if (TreeUtils.isClassTree(tree)) { return getAnnotatedType(TreeUtils.elementFromDeclaration((ClassTree) tree)); } Tree enclosingTree = getEnclosingClassOrMethod(tree); if (enclosingTree == null) { // tree is inside an annotation, where "this" is not allowed. So, no self type exists. return null; } else if (enclosingTree.getKind() == Kind.METHOD) { MethodTree enclosingMethod = (MethodTree) enclosingTree; if (TreeUtils.isConstructor(enclosingMethod)) { return (AnnotatedDeclaredType) getAnnotatedType(enclosingMethod).getReturnType(); } else { return getAnnotatedType(enclosingMethod).getReceiverType(); } } else if (TreeUtils.isClassTree(enclosingTree)) { return (AnnotatedDeclaredType) getAnnotatedType(enclosingTree); } return null; } /** A set containing class, method, and annotation tree kinds. */ private static final Set<Tree.Kind> classMethodAnnotationKinds = EnumSet.copyOf(TreeUtils.classTreeKinds()); static { classMethodAnnotationKinds.add(Kind.METHOD); classMethodAnnotationKinds.add(Kind.TYPE_ANNOTATION); classMethodAnnotationKinds.add(Kind.ANNOTATION); } /** * Returns the innermost enclosing method or class tree of {@code tree}. If {@code tree} is * artificial (that is, created by dataflow), then {@link #artificialTreeToEnclosingElementMap} is * used to find the enclosing tree. * * <p>If the tree is inside an annotation, then {@code null} is returned. * * @param tree tree to whose innermost enclosing method or class to return * @return the innermost enclosing method or class tree of {@code tree}, or {@code null} if {@code * tree} is inside an annotation */ public @Nullable Tree getEnclosingClassOrMethod(Tree tree) { TreePath path = getPath(tree); Tree enclosing = TreePathUtil.enclosingOfKind(path, classMethodAnnotationKinds); if (enclosing != null) { if (enclosing.getKind() == Kind.ANNOTATION || enclosing.getKind() == Kind.TYPE_ANNOTATION) { return null; } return enclosing; } Element e = getEnclosingElementForArtificialTree(tree); if (e != null) { Element enclosingMethodOrClass = e; while (enclosingMethodOrClass != null && enclosingMethodOrClass.getKind() != ElementKind.METHOD && !enclosingMethodOrClass.getKind().isClass() && !enclosingMethodOrClass.getKind().isInterface()) { enclosingMethodOrClass = enclosingMethodOrClass.getEnclosingElement(); } return declarationFromElement(enclosingMethodOrClass); } return getCurrentClassTree(tree); } /** * Returns the {@link AnnotatedTypeMirror} of the enclosing type at the location of {@code tree} * that is the same type as {@code typeElement}. * * @param typeElement type of the enclosing type to return * @param tree location to use * @return the enclosing type at the location of {@code tree} that is the same type as {@code * typeElement} */ public AnnotatedDeclaredType getEnclosingType(TypeElement typeElement, Tree tree) { AnnotatedDeclaredType thisType = getSelfType(tree); while (!isSameType(thisType.getUnderlyingType(), typeElement.asType())) { thisType = thisType.getEnclosingType(); } return thisType; } /** * Returns true if the erasure of {@code type1} is a subtype of the erasure of {@code type2}. * * @param type1 a type * @param type2 a type * @return true if the erasure of {@code type1} is a subtype of the erasure of {@code type2} */ private boolean isSubtype(TypeMirror type1, TypeMirror type2) { return types.isSubtype(types.erasure(type1), types.erasure(type2)); } /** * Returns true if the erasure of {@code type1} is the same type as the erasure of {@code type2}. * * @param type1 a type * @param type2 a type * @return true if the erasure of {@code type1} is the same type as the erasure of {@code type2} */ private boolean isSameType(TypeMirror type1, TypeMirror type2) { return types.isSameType(types.erasure(type1), types.erasure(type2)); } /** * Returns the receiver type of the expression tree, which might be the type of an implicit {@code * this}. Returns null if the expression has no explicit or implicit receiver. * * @param expression the expression for which to determine the receiver type * @return the type of the receiver of expression */ public final AnnotatedTypeMirror getReceiverType(ExpressionTree expression) { ExpressionTree receiver = TreeUtils.getReceiverTree(expression); if (receiver != null) { return getAnnotatedType(receiver); } Element element = TreeUtils.elementFromUse(expression); if (element != null && ElementUtils.hasReceiver(element)) { // The tree references an element that has a receiver, but the tree does not have an explicit // receiver. So, the tree must have an implicit receiver of "this" or "Outer.this". return getImplicitReceiverType(expression); } else { return null; } } /** The type for an instantiated generic method or constructor. */ public static class ParameterizedExecutableType { /** The method's/constructor's type. */ public final AnnotatedExecutableType executableType; /** The types of the generic type arguments. */ public final List<AnnotatedTypeMirror> typeArgs; /** Create a ParameterizedExecutableType. */ public ParameterizedExecutableType( AnnotatedExecutableType executableType, List<AnnotatedTypeMirror> typeArgs) { this.executableType = executableType; this.typeArgs = typeArgs; } @Override public String toString() { if (typeArgs.isEmpty()) { return executableType.toString(); } else { StringJoiner typeArgsString = new StringJoiner(",", "<", ">"); for (AnnotatedTypeMirror atm : typeArgs) { typeArgsString.add(atm.toString()); } return typeArgsString + " " + executableType.toString(); } } } /** * Determines the type of the invoked method based on the passed method invocation tree. * * <p>The returned method type has all type variables resolved, whether based on receiver type, * passed type parameters if any, and method invocation parameter. * * <p>Subclasses may override this method to customize inference of types or qualifiers based on * method invocation parameters. * * <p>As an implementation detail, this method depends on {@link AnnotatedTypes#asMemberOf(Types, * AnnotatedTypeFactory, AnnotatedTypeMirror, Element)}, and customization based on receiver type * should be in accordance to its specification. * * <p>The return type is a pair of the type of the invoked method and the (inferred) type * arguments. Note that neither the explicitly passed nor the inferred type arguments are * guaranteed to be subtypes of the corresponding upper bounds. See method {@link * org.checkerframework.common.basetype.BaseTypeVisitor#checkTypeArguments} for the checks of type * argument well-formedness. * * <p>Note that "this" and "super" constructor invocations are also handled by this method * (explicit or implicit ones, at the beginning of a constructor). Method {@link * #constructorFromUse(NewClassTree)} is only used for a constructor invocation in a "new" * expression. * * @param tree the method invocation tree * @return the method type being invoked with tree and the (inferred) type arguments */ public ParameterizedExecutableType methodFromUse(MethodInvocationTree tree) { ExecutableElement methodElt = TreeUtils.elementFromUse(tree); AnnotatedTypeMirror receiverType = getReceiverType(tree); if (receiverType == null && TreeUtils.isSuperConstructorCall(tree)) { // super() calls don't have a receiver, but they should be view-point adapted as if // "this" is the receiver. receiverType = getSelfType(tree); } ParameterizedExecutableType result = methodFromUse(tree, methodElt, receiverType); if (checker.shouldResolveReflection() && reflectionResolver.isReflectiveMethodInvocation(tree)) { result = reflectionResolver.resolveReflectiveCall(this, tree, result); } AnnotatedExecutableType method = result.executableType; if (method.getReturnType().getKind() == TypeKind.WILDCARD && ((AnnotatedWildcardType) method.getReturnType()).isUninferredTypeArgument()) { // Get the correct Java type from the tree and use it as the upper bound of the wildcard. TypeMirror tm = TreeUtils.typeOf(tree); AnnotatedTypeMirror t = toAnnotatedType(tm, false); AnnotatedWildcardType wildcard = (AnnotatedWildcardType) method.getReturnType(); if (ignoreUninferredTypeArguments) { // Remove the annotations so that default annotations are used instead. // (See call to addDefaultAnnotations below.) t.clearAnnotations(); } else { t.replaceAnnotations(wildcard.getExtendsBound().getAnnotations()); } wildcard.setExtendsBound(t); addDefaultAnnotations(wildcard); } return result; } /** * Determines the type of the invoked method based on the passed expression tree, executable * element, and receiver type. * * @param tree either a MethodInvocationTree or a MemberReferenceTree * @param methodElt the element of the referenced method * @param receiverType the type of the receiver * @return the method type being invoked with tree and the (inferred) type arguments * @see #methodFromUse(MethodInvocationTree) */ public ParameterizedExecutableType methodFromUse( ExpressionTree tree, ExecutableElement methodElt, AnnotatedTypeMirror receiverType) { AnnotatedExecutableType memberTypeWithoutOverrides = getAnnotatedType(methodElt); // get unsubstituted type AnnotatedExecutableType memberTypeWithOverrides = (AnnotatedExecutableType) applyFakeOverrides(receiverType, methodElt, memberTypeWithoutOverrides); methodFromUsePreSubstitution(tree, memberTypeWithOverrides); AnnotatedExecutableType methodType = AnnotatedTypes.asMemberOf(types, this, receiverType, methodElt, memberTypeWithOverrides); List<AnnotatedTypeMirror> typeargs = new ArrayList<>(methodType.getTypeVariables().size()); Map<TypeVariable, AnnotatedTypeMirror> typeVarMapping = AnnotatedTypes.findTypeArguments(processingEnv, this, tree, methodElt, methodType); if (!typeVarMapping.isEmpty()) { for (AnnotatedTypeVariable tv : methodType.getTypeVariables()) { if (typeVarMapping.get(tv.getUnderlyingType()) == null) { throw new BugInCF( "AnnotatedTypeFactory.methodFromUse:mismatch between declared method type variables" + " and the inferred method type arguments. Method type variables: " + methodType.getTypeVariables() + "; " + "Inferred method type arguments: " + typeVarMapping); } typeargs.add(typeVarMapping.get(tv.getUnderlyingType())); } methodType = (AnnotatedExecutableType) typeVarSubstitutor.substitute(typeVarMapping, methodType); } if (tree.getKind() == Tree.Kind.METHOD_INVOCATION && TreeUtils.isMethodInvocation(tree, objectGetClass, processingEnv)) { adaptGetClassReturnTypeToReceiver(methodType, receiverType); } return new ParameterizedExecutableType(methodType, typeargs); } /** * Given a member and its type, returns the type with fake overrides applied to it. * * @param receiverType the type of the class that contains member (or a subtype of it) * @param member a type member, such as a method or field * @param memberType the type of {@code member} * @return {@code memberType}, adjusted according to fake overrides */ private AnnotatedTypeMirror applyFakeOverrides( AnnotatedTypeMirror receiverType, Element member, AnnotatedTypeMirror memberType) { // Currently, handle only methods, not fields. TODO: Handle fields. if (memberType.getKind() != TypeKind.EXECUTABLE) { return memberType; } AnnotationFileElementTypes afet = stubTypes; AnnotatedExecutableType methodType = (AnnotatedExecutableType) afet.getFakeOverride(member, receiverType); if (methodType == null) { methodType = (AnnotatedExecutableType) memberType; } return methodType; } /** * A callback method for the AnnotatedTypeFactory subtypes to customize the handling of the * declared method type before type variable substitution. * * @param tree either a method invocation or a member reference tree * @param type declared method type before type variable substitution */ protected void methodFromUsePreSubstitution(ExpressionTree tree, AnnotatedExecutableType type) { assert tree instanceof MethodInvocationTree || tree instanceof MemberReferenceTree; } /** * Java special-cases the return type of {@link java.lang.Class#getClass() getClass()}. Though the * method has a return type of {@code Class<?>}, the compiler special cases this return-type and * changes the bound of the type argument to the erasure of the receiver type. For example: * * <ul> * <li>{@code x.getClass()} has the type {@code Class< ? extends erasure_of_x >} * <li>{@code someInteger.getClass()} has the type {@code Class< ? extends Integer >} * </ul> * * @param getClassType this must be a type representing a call to Object.getClass otherwise a * runtime exception will be thrown. It is modified by side effect. * @param receiverType the receiver type of the method invocation (not the declared receiver type) */ protected void adaptGetClassReturnTypeToReceiver( final AnnotatedExecutableType getClassType, final AnnotatedTypeMirror receiverType) { // TODO: should the receiver type ever be a declaration?? // Work on removing the asUse() call. final AnnotatedTypeMirror newBound = receiverType.getErased().asUse(); final AnnotatedTypeMirror returnType = getClassType.getReturnType(); if (returnType == null || !(returnType.getKind() == TypeKind.DECLARED) || ((AnnotatedDeclaredType) returnType).getTypeArguments().size() != 1) { throw new BugInCF( "Unexpected type passed to AnnotatedTypes.adaptGetClassReturnTypeToReceiver%n" + "getClassType=%s%nreceiverType=%s", getClassType, receiverType); } final AnnotatedDeclaredType returnAdt = (AnnotatedDeclaredType) getClassType.getReturnType(); final List<AnnotatedTypeMirror> typeArgs = returnAdt.getTypeArguments(); // Usually, the only locations that will add annotations to the return type are getClass in stub // files defaults and propagation tree annotator. Since getClass is final they cannot come from // source code. Also, since the newBound is an erased type we have no type arguments. So, we // just copy the annotations from the bound of the declared type to the new bound. final AnnotatedWildcardType classWildcardArg = (AnnotatedWildcardType) typeArgs.get(0); Set<AnnotationMirror> newAnnos = AnnotationUtils.createAnnotationSet(); Set<AnnotationMirror> typeBoundAnnos = getTypeDeclarationBounds(newBound.getUnderlyingType()); Set<AnnotationMirror> wildcardBoundAnnos = classWildcardArg.getExtendsBound().getAnnotations(); for (AnnotationMirror typeBoundAnno : typeBoundAnnos) { AnnotationMirror wildcardAnno = qualHierarchy.findAnnotationInSameHierarchy(wildcardBoundAnnos, typeBoundAnno); if (qualHierarchy.isSubtype(typeBoundAnno, wildcardAnno)) { newAnnos.add(typeBoundAnno); } else { newAnnos.add(wildcardAnno); } } newBound.replaceAnnotations(newAnnos); classWildcardArg.setExtendsBound(newBound); } /** * Return the element type of {@code expression}. This is usually the type of {@code * expression.itertor().next()}. If {@code expression} is an array, it is the component type of * the array. * * @param expression an expression whose type is an array or implements {@link Iterable} * @return the type of {@code expression.itertor().next()} or if {@code expression} is an array, * the component type of the array. */ public AnnotatedTypeMirror getIterableElementType(ExpressionTree expression) { return getIterableElementType(expression, getAnnotatedType(expression)); } /** * Return the element type of {@code iterableType}. This is usually the type of {@code * expression.itertor().next()}. If {@code expression} is an array, it is the component type of * the array. * * @param expression an expression whose type is an array or implements {@link Iterable} * @param iterableType the type of the expression * @return the type of {@code expression.itertor().next()} or if {@code expression} is an array, * the component type of the array. */ protected AnnotatedTypeMirror getIterableElementType( ExpressionTree expression, AnnotatedTypeMirror iterableType) { switch (iterableType.getKind()) { case ARRAY: return ((AnnotatedArrayType) iterableType).getComponentType(); case WILDCARD: return getIterableElementType( expression, ((AnnotatedWildcardType) iterableType).getExtendsBound().deepCopy()); case TYPEVAR: return getIterableElementType( expression, ((AnnotatedTypeVariable) iterableType).getUpperBound()); case DECLARED: AnnotatedDeclaredType dt = AnnotatedTypes.asSuper(this, iterableType, this.iterableDeclType); if (dt.getTypeArguments().isEmpty()) { TypeElement e = ElementUtils.getTypeElement(processingEnv, Object.class); return getAnnotatedType(e); } else { return dt.getTypeArguments().get(0); } // TODO: Properly desugar Iterator.next(), which is needed if an annotated JDK has // annotations on Iterator#next. // The below doesn't work because methodFromUse() assumes that the expression tree // matches the method element. // TypeElement iteratorElement = // ElementUtils.getTypeElement(processingEnv, Iterator.class); // AnnotatedTypeMirror iteratorType = // AnnotatedTypeMirror.createType(iteratorElement.asType(), this, false); // Map<TypeVariable, AnnotatedTypeMirror> mapping = new HashMap<>(); // mapping.put( // (TypeVariable) iteratorElement.getTypeParameters().get(0).asType(), // typeArg); // iteratorType = typeVarSubstitutor.substitute(mapping, iteratorType); // ExecutableElement next = // TreeUtils.getMethod("java.util.Iterator", "next", 0, processingEnv); // ParameterizedExecutableType m = methodFromUse(expression, next, iteratorType); // return m.executableType.getReturnType(); default: throw new BugInCF( "AnnotatedTypeFactory.getIterableElementType: not iterable type: " + iterableType); } } /** * Determines the type of the invoked constructor based on the passed new class tree. * * <p>The returned method type has all type variables resolved, whether based on receiver type, * passed type parameters if any, and constructor invocation parameter. * * <p>Subclasses may override this method to customize inference of types or qualifiers based on * constructor invocation parameters. * * <p>As an implementation detail, this method depends on {@link AnnotatedTypes#asMemberOf(Types, * AnnotatedTypeFactory, AnnotatedTypeMirror, Element)}, and customization based on receiver type * should be in accordance with its specification. * * <p>The return type is a pair of the type of the invoked constructor and the (inferred) type * arguments. Note that neither the explicitly passed nor the inferred type arguments are * guaranteed to be subtypes of the corresponding upper bounds. See method {@link * org.checkerframework.common.basetype.BaseTypeVisitor#checkTypeArguments} for the checks of type * argument well-formedness. * * <p>Note that "this" and "super" constructor invocations are handled by method {@link * #methodFromUse}. This method only handles constructor invocations in a "new" expression. * * @param tree the constructor invocation tree * @return the annotated type of the invoked constructor (as an executable type) and the * (inferred) type arguments */ public ParameterizedExecutableType constructorFromUse(NewClassTree tree) { AnnotatedTypeMirror type = fromNewClass(tree); addComputedTypeAnnotations(tree, type); ExecutableElement ctor = TreeUtils.constructor(tree); AnnotatedExecutableType con = getAnnotatedType(ctor); // get unsubstituted type if (TreeUtils.hasSyntheticArgument(tree)) { AnnotatedExecutableType t = (AnnotatedExecutableType) getAnnotatedType(((JCNewClass) tree).constructor); List<AnnotatedTypeMirror> p = new ArrayList<>(con.getParameterTypes().size() + 1); p.add(t.getParameterTypes().get(0)); p.addAll(1, con.getParameterTypes()); t.setParameterTypes(p); con = t; } constructorFromUsePreSubstitution(tree, con); con = AnnotatedTypes.asMemberOf(types, this, type, ctor, con); Map<TypeVariable, AnnotatedTypeMirror> typeVarMapping = AnnotatedTypes.findTypeArguments(processingEnv, this, tree, ctor, con); List<AnnotatedTypeMirror> typeargs = new ArrayList<>(con.getTypeVariables().size()); if (typeVarMapping.isEmpty()) { typeargs = Collections.emptyList(); } else { typeargs = CollectionsPlume.mapList( (AnnotatedTypeVariable tv) -> typeVarMapping.get(tv.getUnderlyingType()), con.getTypeVariables()); con = (AnnotatedExecutableType) typeVarSubstitutor.substitute(typeVarMapping, con); } return new ParameterizedExecutableType(con, typeargs); } /** * A callback method for the AnnotatedTypeFactory subtypes to customize the handling of the * declared constructor type before type variable substitution. * * @param tree a NewClassTree from constructorFromUse() * @param type declared method type before type variable substitution */ protected void constructorFromUsePreSubstitution( NewClassTree tree, AnnotatedExecutableType type) {} /** * Returns the return type of the method {@code m}. * * @param m tree of a method declaration * @return the return type of the method */ public AnnotatedTypeMirror getMethodReturnType(MethodTree m) { AnnotatedExecutableType methodType = getAnnotatedType(m); AnnotatedTypeMirror ret = methodType.getReturnType(); return ret; } /** * Returns the return type of the method {@code m} at the return statement {@code r}. This * implementation just calls {@link #getMethodReturnType(MethodTree)}, but subclasses may override * this method to change the type based on the return statement. * * @param m tree of a method declaration * @param r a return statement within method {@code m} * @return the return type of the method {@code m} at the return statement {@code r} */ public AnnotatedTypeMirror getMethodReturnType(MethodTree m, ReturnTree r) { return getMethodReturnType(m); } /** * Creates an AnnotatedDeclaredType for a NewClassTree. Only adds explicit annotations, unless * newClassTree has a diamond operator. In that case, the annotations on the type arguments are * inferred using the assignment context and contain defaults. * * <p>Also, fully annotates the enclosing type of the returned declared type. * * <p>(Subclass beside {@link GenericAnnotatedTypeFactory} should not override this method.) * * @param newClassTree NewClassTree * @return AnnotatedDeclaredType */ public AnnotatedDeclaredType fromNewClass(NewClassTree newClassTree) { AnnotatedDeclaredType enclosingType = (AnnotatedDeclaredType) getReceiverType(newClassTree); // Diamond trees that are not anonymous classes. if (TreeUtils.isDiamondTree(newClassTree) && newClassTree.getClassBody() == null) { AnnotatedDeclaredType type = (AnnotatedDeclaredType) toAnnotatedType(TreeUtils.typeOf(newClassTree), false); if (((com.sun.tools.javac.code.Type) type.underlyingType) .tsym .getTypeParameters() .nonEmpty()) { Pair<Tree, AnnotatedTypeMirror> ctx = this.visitorState.getAssignmentContext(); if (ctx != null) { AnnotatedTypeMirror ctxtype = ctx.second; fromNewClassContextHelper(type, ctxtype); } else { TreePath p = getPath(newClassTree); AnnotatedTypeMirror ctxtype = TypeArgInferenceUtil.assignedTo(this, p); if (ctxtype != null) { fromNewClassContextHelper(type, ctxtype); } else { // give up trying and set to raw. type.setWasRaw(); } } } AnnotatedDeclaredType fromTypeTree = (AnnotatedDeclaredType) TypeFromTree.fromTypeTree(this, newClassTree.getIdentifier()); type.replaceAnnotations(fromTypeTree.getAnnotations()); type.setEnclosingType(enclosingType); return type; } else if (newClassTree.getClassBody() != null) { AnnotatedDeclaredType type = (AnnotatedDeclaredType) toAnnotatedType(TreeUtils.typeOf(newClassTree), false); // If newClassTree creates an anonymous class, then annotations in this location: // new @HERE Class() {} // are on not on the identifier newClassTree, but rather on the modifier newClassTree. List<? extends AnnotationTree> annos = newClassTree.getClassBody().getModifiers().getAnnotations(); type.addAnnotations(TreeUtils.annotationsFromTypeAnnotationTrees(annos)); type.setEnclosingType(enclosingType); return type; } else { // If newClassTree does not create anonymous class, // newClassTree.getIdentifier includes the explicit annotations in this location: // new @HERE Class() AnnotatedDeclaredType type = (AnnotatedDeclaredType) TypeFromTree.fromTypeTree(this, newClassTree.getIdentifier()); type.setEnclosingType(enclosingType); return type; } } // This method extracts the ugly hacky parts. // This method should be rewritten and in particular diamonds should be // implemented cleanly. // See Issue 289. private void fromNewClassContextHelper(AnnotatedDeclaredType type, AnnotatedTypeMirror ctxtype) { switch (ctxtype.getKind()) { case DECLARED: AnnotatedDeclaredType adctx = (AnnotatedDeclaredType) ctxtype; if (type.getTypeArguments().size() == adctx.getTypeArguments().size()) { // Try to simply take the type arguments from LHS. List<AnnotatedTypeMirror> oldArgs = type.getTypeArguments(); List<AnnotatedTypeMirror> newArgs = adctx.getTypeArguments(); for (int i = 0; i < type.getTypeArguments().size(); ++i) { if (!types.isSubtype(newArgs.get(i).underlyingType, oldArgs.get(i).underlyingType)) { // One of the underlying types doesn't match. Give up. return; } } type.setTypeArguments(newArgs); /* It would be nice to call isSubtype for a basic sanity check. * However, the type might not have been completely initialized yet, * so isSubtype might fail. * if (!typeHierarchy.isSubtype(type, ctxtype)) { // Simply taking the newArgs didn't result in a valid subtype. // Give up and simply use the inferred types. type.setTypeArguments(oldArgs); } */ } else { // TODO: Find a way to determine annotated type arguments. // Look at what Attr and Resolve are doing and rework this whole method. } break; case ARRAY: // This new class is in the initializer of an array. // The array being created can't have a generic component type, so nothing to be done. break; case TYPEVAR: // TODO: this should NOT be necessary. // org.checkerframework.dataflow.cfg.node.MethodAccessNode.MethodAccessNode(ExpressionTree, // Node) // Uses an ExecutableElement, which did not substitute type variables. break; case WILDCARD: // TODO: look at bounds of wildcard and see whether we can improve. break; default: if (ctxtype.getKind().isPrimitive()) { // See Issue 438. Ignore primitive types for diamond inference - a primitive // type is never a suitable context anyway. } else { throw new BugInCF( "AnnotatedTypeFactory.fromNewClassContextHelper: unexpected context: " + ctxtype + " (" + ctxtype.getKind() + ")"); } } } /** * Returns the annotated boxed type of the given primitive type. The returned type would only have * the annotations on the given type. * * <p>Subclasses may override this method safely to override this behavior. * * @param type the primitive type * @return the boxed declared type of the passed primitive type */ public AnnotatedDeclaredType getBoxedType(AnnotatedPrimitiveType type) { TypeElement typeElt = types.boxedClass(type.getUnderlyingType()); AnnotatedDeclaredType dt = fromElement(typeElt); dt.addAnnotations(type.getAnnotations()); return dt; } /** * Return a primitive type: either the argument, or the result of unboxing it (which might affect * its annotations). * * <p>Subclasses should override {@link #getUnboxedType} rather than this method. * * @param type a type: a primitive or boxed primitive * @return the unboxed variant of the type */ public final AnnotatedPrimitiveType applyUnboxing(AnnotatedTypeMirror type) { TypeMirror underlying = type.getUnderlyingType(); if (TypesUtils.isPrimitive(underlying)) { return (AnnotatedPrimitiveType) type; } else if (TypesUtils.isBoxedPrimitive(underlying)) { return getUnboxedType((AnnotatedDeclaredType) type); } else { throw new BugInCF("Bad argument to applyUnboxing: " + type); } } /** * Returns the annotated primitive type of the given declared type if it is a boxed declared type. * Otherwise, it throws <i>IllegalArgumentException</i> exception. * * <p>In the {@code AnnotatedTypeFactory} implementation, the returned type has the same primary * annotations as the given type. Subclasses may override this behavior. * * @param type the declared type * @return the unboxed primitive type * @throws IllegalArgumentException if the type given has no unbox conversion */ public AnnotatedPrimitiveType getUnboxedType(AnnotatedDeclaredType type) throws IllegalArgumentException { PrimitiveType primitiveType = types.unboxedType(type.getUnderlyingType()); AnnotatedPrimitiveType pt = (AnnotatedPrimitiveType) AnnotatedTypeMirror.createType(primitiveType, this, false); pt.addAnnotations(type.getAnnotations()); return pt; } /** * Returns AnnotatedDeclaredType with underlying type String and annotations copied from type. * Subclasses may change the annotations. * * @param type type to convert to String * @return AnnotatedTypeMirror that results from converting type to a String type */ // TODO: Test that this is called in all the correct locations // See Issue #715 // https://github.com/typetools/checker-framework/issues/715 public AnnotatedDeclaredType getStringType(AnnotatedTypeMirror type) { TypeMirror stringTypeMirror = TypesUtils.typeFromClass(String.class, types, elements); AnnotatedDeclaredType stringATM = (AnnotatedDeclaredType) AnnotatedTypeMirror.createType(stringTypeMirror, this, type.isDeclaration()); stringATM.addAnnotations(type.getEffectiveAnnotations()); return stringATM; } /** * Returns a widened type if applicable, otherwise returns its first argument. * * <p>Subclasses should override {@link #getWidenedAnnotations} rather than this method. * * @param exprType type to possibly widen * @param widenedType type to possibly widen to; its annotations are ignored * @return if widening is applicable, the result of converting {@code type} to the underlying type * of {@code widenedType}; otherwise {@code type} */ public final AnnotatedTypeMirror getWidenedType( AnnotatedTypeMirror exprType, AnnotatedTypeMirror widenedType) { TypeKind exprKind = exprType.getKind(); TypeKind widenedKind = widenedType.getKind(); if (!TypeKindUtils.isNumeric(widenedKind)) { // The target type is not a numeric primitive, so primitive widening is not applicable. return exprType; } AnnotatedPrimitiveType exprPrimitiveType; if (TypeKindUtils.isNumeric(exprKind)) { exprPrimitiveType = (AnnotatedPrimitiveType) exprType; } else if (TypesUtils.isNumericBoxed(exprType.getUnderlyingType())) { exprPrimitiveType = getUnboxedType((AnnotatedDeclaredType) exprType); } else { return exprType; } switch (TypeKindUtils.getPrimitiveConversionKind( exprPrimitiveType.getKind(), widenedType.getKind())) { case WIDENING: return getWidenedPrimitive(exprPrimitiveType, widenedType.getUnderlyingType()); case NARROWING: return getNarrowedPrimitive(exprPrimitiveType, widenedType.getUnderlyingType()); case SAME: return exprType; default: throw new Error("unhandled PrimitiveConversionKind"); } } /** * Applies widening if applicable, otherwise returns its first argument. * * <p>Subclasses should override {@link #getWidenedAnnotations} rather than this method. * * @param exprAnnos annotations to possibly widen * @param exprTypeMirror type to possibly widen * @param widenedType type to possibly widen to; its annotations are ignored * @return if widening is applicable, the result of converting {@code type} to the underlying type * of {@code widenedType}; otherwise {@code type} */ public final AnnotatedTypeMirror getWidenedType( Set<AnnotationMirror> exprAnnos, TypeMirror exprTypeMirror, AnnotatedTypeMirror widenedType) { AnnotatedTypeMirror exprType = toAnnotatedType(exprTypeMirror, false); exprType.replaceAnnotations(exprAnnos); return getWidenedType(exprType, widenedType); } /** * Returns an AnnotatedPrimitiveType with underlying type {@code widenedTypeMirror} and with * annotations copied or adapted from {@code type}. * * @param type type to widen; a primitive or boxed primitive * @param widenedTypeMirror underlying type for the returned type mirror; a primitive or boxed * primitive (same boxing as {@code type}) * @return result of converting {@code type} to {@code widenedTypeMirror} */ private AnnotatedPrimitiveType getWidenedPrimitive( AnnotatedPrimitiveType type, TypeMirror widenedTypeMirror) { AnnotatedPrimitiveType result = (AnnotatedPrimitiveType) AnnotatedTypeMirror.createType(widenedTypeMirror, this, type.isDeclaration()); result.addAnnotations( getWidenedAnnotations(type.getAnnotations(), type.getKind(), result.getKind())); return result; } /** * Returns annotations applicable to type {@code narrowedTypeKind}, that are copied or adapted * from {@code annos}. * * @param annos annotations to narrow, from a primitive or boxed primitive * @param typeKind primitive type to narrow * @param narrowedTypeKind target for the returned annotations; a primitive type that is narrower * than {@code typeKind} (in the sense of JLS 5.1.3). * @return result of converting {@code annos} from {@code typeKind} to {@code narrowedTypeKind} */ public Set<AnnotationMirror> getNarrowedAnnotations( Set<AnnotationMirror> annos, TypeKind typeKind, TypeKind narrowedTypeKind) { return annos; } /** * Returns annotations applicable to type {@code widenedTypeKind}, that are copied or adapted from * {@code annos}. * * @param annos annotations to widen, from a primitive or boxed primitive * @param typeKind primitive type to widen * @param widenedTypeKind target for the returned annotations; a primitive type that is wider than * {@code typeKind} (in the sense of JLS 5.1.2) * @return result of converting {@code annos} from {@code typeKind} to {@code widenedTypeKind} */ public Set<AnnotationMirror> getWidenedAnnotations( Set<AnnotationMirror> annos, TypeKind typeKind, TypeKind widenedTypeKind) { return annos; } /** * Returns the types of the two arguments to the BinaryTree, accounting for widening and unboxing * if applicable. * * @param node a binary tree * @return the types of the two arguments */ public Pair<AnnotatedTypeMirror, AnnotatedTypeMirror> binaryTreeArgTypes(BinaryTree node) { return binaryTreeArgTypes( getAnnotatedType(node.getLeftOperand()), getAnnotatedType(node.getRightOperand())); } /** * Returns the types of the two arguments to the CompoundAssignmentTree, accounting for widening * and unboxing if applicable. * * @param node a compound assignment tree * @return the types of the two arguments */ public Pair<AnnotatedTypeMirror, AnnotatedTypeMirror> compoundAssignmentTreeArgTypes( CompoundAssignmentTree node) { return binaryTreeArgTypes( getAnnotatedType(node.getVariable()), getAnnotatedType(node.getExpression())); } /** * Returns the types of the two arguments to a binarya operation, accounting for widening and * unboxing if applicable. * * @param left the type of the left argument of a binary operation * @param right the type of the right argument of a binary operation * @return the types of the two arguments */ public Pair<AnnotatedTypeMirror, AnnotatedTypeMirror> binaryTreeArgTypes( AnnotatedTypeMirror left, AnnotatedTypeMirror right) { TypeKind resultTypeKind = TypeKindUtils.widenedNumericType(left.getUnderlyingType(), right.getUnderlyingType()); if (TypeKindUtils.isNumeric(resultTypeKind)) { TypeMirror resultTypeMirror = types.getPrimitiveType(resultTypeKind); AnnotatedPrimitiveType leftUnboxed = applyUnboxing(left); AnnotatedPrimitiveType rightUnboxed = applyUnboxing(right); AnnotatedPrimitiveType leftWidened = (leftUnboxed.getKind() == resultTypeKind ? leftUnboxed : getWidenedPrimitive(leftUnboxed, resultTypeMirror)); AnnotatedPrimitiveType rightWidened = (rightUnboxed.getKind() == resultTypeKind ? rightUnboxed : getWidenedPrimitive(rightUnboxed, resultTypeMirror)); return Pair.of(leftWidened, rightWidened); } else { return Pair.of(left, right); } } /** * Returns AnnotatedPrimitiveType with underlying type {@code narrowedTypeMirror} and with * annotations copied or adapted from {@code type}. * * <p>Currently this method is called only for primitives that are narrowed at assignments from * literal ints, for example, {@code byte b = 1;}. All other narrowing conversions happen at * typecasts. * * @param type type to narrow * @param narrowedTypeMirror underlying type for the returned type mirror * @return result of converting {@code type} to {@code narrowedTypeMirror} */ public AnnotatedPrimitiveType getNarrowedPrimitive( AnnotatedPrimitiveType type, TypeMirror narrowedTypeMirror) { AnnotatedPrimitiveType narrowed = (AnnotatedPrimitiveType) AnnotatedTypeMirror.createType(narrowedTypeMirror, this, type.isDeclaration()); narrowed.addAnnotations(type.getAnnotations()); return narrowed; } /** * Returns the VisitorState instance used by the factory to infer types. * * @return the VisitorState instance used by the factory to infer types */ public VisitorState getVisitorState() { return this.visitorState; } // ********************************************************************** // random methods wrapping #getAnnotatedType(Tree) and #fromElement(Tree) // with appropriate casts to reduce casts on the client side // ********************************************************************** /** * See {@link #getAnnotatedType(Tree)}. * * @see #getAnnotatedType(Tree) */ public final AnnotatedDeclaredType getAnnotatedType(ClassTree tree) { return (AnnotatedDeclaredType) getAnnotatedType((Tree) tree); } /** * See {@link #getAnnotatedType(Tree)}. * * @see #getAnnotatedType(Tree) */ public final AnnotatedDeclaredType getAnnotatedType(NewClassTree tree) { return (AnnotatedDeclaredType) getAnnotatedType((Tree) tree); } /** * See {@link #getAnnotatedType(Tree)}. * * @see #getAnnotatedType(Tree) */ public final AnnotatedArrayType getAnnotatedType(NewArrayTree tree) { return (AnnotatedArrayType) getAnnotatedType((Tree) tree); } /** * See {@link #getAnnotatedType(Tree)}. * * @see #getAnnotatedType(Tree) */ public final AnnotatedExecutableType getAnnotatedType(MethodTree tree) { return (AnnotatedExecutableType) getAnnotatedType((Tree) tree); } /** * See {@link #getAnnotatedType(Element)}. * * @see #getAnnotatedType(Element) */ public final AnnotatedDeclaredType getAnnotatedType(TypeElement elt) { return (AnnotatedDeclaredType) getAnnotatedType((Element) elt); } /** * See {@link #getAnnotatedType(Element)}. * * @see #getAnnotatedType(Element) */ public final AnnotatedExecutableType getAnnotatedType(ExecutableElement elt) { return (AnnotatedExecutableType) getAnnotatedType((Element) elt); } /** * See {@link #fromElement(Element)}. * * @see #fromElement(Element) */ public final AnnotatedDeclaredType fromElement(TypeElement elt) { return (AnnotatedDeclaredType) fromElement((Element) elt); } /** * See {@link #fromElement(Element)}. * * @see #fromElement(Element) */ public final AnnotatedExecutableType fromElement(ExecutableElement elt) { return (AnnotatedExecutableType) fromElement((Element) elt); } // ********************************************************************** // Helper methods for this classes // ********************************************************************** /** * Determines whether the given annotation is a part of the type system under which this type * factory operates. Null is never a supported qualifier; the parameter is nullable to allow the * result of canonicalAnnotation to be passed in directly. * * @param a any annotation * @return true if that annotation is part of the type system under which this type factory * operates, false otherwise */ public boolean isSupportedQualifier(@Nullable AnnotationMirror a) { if (a == null) { return false; } return isSupportedQualifier(AnnotationUtils.annotationName(a)); } /** * Determines whether the given class is a part of the type system under which this type factory * operates. * * @param clazz annotation class * @return true if that class is a type qualifier in the type system under which this type factory * operates, false otherwise */ public boolean isSupportedQualifier(Class<? extends Annotation> clazz) { return getSupportedTypeQualifiers().contains(clazz); } /** * Determines whether the given class name is a part of the type system under which this type * factory operates. * * @param className fully-qualified annotation class name * @return true if that class name is a type qualifier in the type system under which this type * factory operates, false otherwise */ public boolean isSupportedQualifier(String className) { return getSupportedTypeQualifierNames().contains(className); } /** * Adds the annotation {@code aliasClass} as an alias for the canonical annotation {@code type} * that will be used by the Checker Framework in the alias's place. * * <p>By specifying the alias/canonical relationship using this method, the elements of the alias * are not preserved when the canonical annotation to use is constructed from the alias. If you * want the elements to be copied over as well, use {@link #addAliasedTypeAnnotation(Class, Class, * boolean, String...)}. * * @param aliasClass the class of the aliased annotation * @param type the canonical annotation * @deprecated use {@code addAliasedTypeAnnotation} */ @Deprecated // 2020-12-15 protected void addAliasedAnnotation(Class<?> aliasClass, AnnotationMirror type) { addAliasedTypeAnnotation(aliasClass, type); } /** * Adds the annotation {@code aliasClass} as an alias for the canonical annotation {@code * canonicalAnno} that will be used by the Checker Framework in the alias's place. * * <p>By specifying the alias/canonical relationship using this method, the elements of the alias * are not preserved when the canonical annotation to use is constructed from the alias. If you * want the elements to be copied over as well, use {@link #addAliasedTypeAnnotation(Class, Class, * boolean, String...)}. * * @param aliasClass the class of the aliased annotation * @param canonicalAnno the canonical annotation */ protected void addAliasedTypeAnnotation(Class<?> aliasClass, AnnotationMirror canonicalAnno) { if (getSupportedTypeQualifiers().contains(aliasClass)) { throw new BugInCF( "AnnotatedTypeFactory: alias %s should not be in type hierarchy for %s", aliasClass, this.getClass().getSimpleName()); } addAliasedTypeAnnotation(aliasClass.getCanonicalName(), canonicalAnno); } /** * Adds the annotation, whose fully-qualified name is given by {@code aliasName}, as an alias for * the canonical annotation {@code canonicalAnno} that will be used by the Checker Framework in * the alias's place. * * <p>Use this method if the alias class is not necessarily on the classpath at Checker Framework * compile and run time. Otherwise, use {@link #addAliasedTypeAnnotation(Class, AnnotationMirror)} * which prevents the possibility of a typo in the class name. * * @param aliasName the canonical name of the aliased annotation * @param canonicalAnno the canonical annotation * @deprecated use {@link #addAliasedTypeAnnotation} */ // aliasName is annotated as @FullyQualifiedName because there is no way to confirm that the // name of an external annotation is a canoncal name. @Deprecated // 2020-12-15 protected void addAliasedAnnotation( @FullyQualifiedName String aliasName, AnnotationMirror canonicalAnno) { addAliasedTypeAnnotation(aliasName, canonicalAnno); } /** * Adds the annotation, whose fully-qualified name is given by {@code aliasName}, as an alias for * the canonical annotation {@code canonicalAnno} that will be used by the Checker Framework in * the alias's place. * * <p>Use this method if the alias class is not necessarily on the classpath at Checker Framework * compile and run time. Otherwise, use {@link #addAliasedTypeAnnotation(Class, AnnotationMirror)} * which prevents the possibility of a typo in the class name. * * @param aliasName the canonical name of the aliased annotation * @param canonicalAnno the canonical annotation */ // aliasName is annotated as @FullyQualifiedName because there is no way to confirm that the // name of an external annotation is a canoncal name. protected void addAliasedTypeAnnotation( @FullyQualifiedName String aliasName, AnnotationMirror canonicalAnno) { aliases.put(aliasName, new Alias(aliasName, canonicalAnno, false, null, null)); } /** * Adds the annotation {@code aliasClass} as an alias for the canonical annotation {@code * canonicalAnno} that will be used by the Checker Framework in the alias's place. * * <p>You may specify the copyElements flag to indicate whether you want the elements of the alias * to be copied over when the canonical annotation is constructed as a copy of {@code * canonicalAnno}. Be careful that the framework will try to copy the elements by name matching, * so make sure that names and types of the elements to be copied over are exactly the same as the * ones in the canonical annotation. Otherwise, an 'Couldn't find element in annotation' error is * raised. * * <p>To facilitate the cases where some of the elements are ignored on purpose when constructing * the canonical annotation, this method also provides a varargs {@code ignorableElements} for you * to explicitly specify the ignoring rules. For example, {@code * org.checkerframework.checker.index.qual.IndexFor} is an alias of {@code * org.checkerframework.checker.index.qual.NonNegative}, but the element "value" of * {@code @IndexFor} should be ignored when constructing {@code @NonNegative}. In the cases where * all elements are ignored, we can simply use {@link #addAliasedTypeAnnotation(Class, * AnnotationMirror)} instead. * * @param aliasClass the class of the aliased annotation * @param canonical the canonical annotation * @param copyElements a flag that indicates whether you want to copy the elements over when * getting the alias from the canonical annotation * @param ignorableElements a list of elements that can be safely dropped when the elements are * being copied over * @deprecated use {@code addAliasedTypeAnnotation} */ @Deprecated // 2020-12-15 protected void addAliasedAnnotation( Class<?> aliasClass, Class<?> canonical, boolean copyElements, String... ignorableElements) { addAliasedTypeAnnotation(aliasClass, canonical, copyElements, ignorableElements); } /** * Adds the annotation {@code aliasClass} as an alias for the canonical annotation {@code * canonicalClass} that will be used by the Checker Framework in the alias's place. * * <p>You may specify the copyElements flag to indicate whether you want the elements of the alias * to be copied over when the canonical annotation is constructed as a copy of {@code * canonicalClass}. Be careful that the framework will try to copy the elements by name matching, * so make sure that names and types of the elements to be copied over are exactly the same as the * ones in the canonical annotation. Otherwise, an 'Couldn't find element in annotation' error is * raised. * * <p>To facilitate the cases where some of the elements are ignored on purpose when constructing * the canonical annotation, this method also provides a varargs {@code ignorableElements} for you * to explicitly specify the ignoring rules. For example, {@code * org.checkerframework.checker.index.qual.IndexFor} is an alias of {@code * org.checkerframework.checker.index.qual.NonNegative}, but the element "value" of * {@code @IndexFor} should be ignored when constructing {@code @NonNegative}. In the cases where * all elements are ignored, we can simply use {@link #addAliasedTypeAnnotation(Class, * AnnotationMirror)} instead. * * @param aliasClass the class of the aliased annotation * @param canonicalClass the class of the canonical annotation * @param copyElements a flag that indicates whether you want to copy the elements over when * getting the alias from the canonical annotation * @param ignorableElements a list of elements that can be safely dropped when the elements are * being copied over */ protected void addAliasedTypeAnnotation( Class<?> aliasClass, Class<?> canonicalClass, boolean copyElements, String... ignorableElements) { if (getSupportedTypeQualifiers().contains(aliasClass)) { throw new BugInCF( "AnnotatedTypeFactory: alias %s should not be in type hierarchy for %s", aliasClass, this.getClass().getSimpleName()); } addAliasedTypeAnnotation( aliasClass.getCanonicalName(), canonicalClass, copyElements, ignorableElements); } /** * Adds the annotation, whose fully-qualified name is given by {@code aliasName}, as an alias for * the canonical annotation {@code canonicalAnno} that will be used by the Checker Framework in * the alias's place. * * <p>Use this method if the alias class is not necessarily on the classpath at Checker Framework * compile and run time. Otherwise, use {@link #addAliasedTypeAnnotation(Class, Class, boolean, * String[])} which prevents the possibility of a typo in the class name. * * @param aliasName the canonical name of the aliased class * @param canonicalAnno the canonical annotation * @param copyElements a flag that indicates whether we want to copy the elements over when * getting the alias from the canonical annotation * @param ignorableElements a list of elements that can be safely dropped when the elements are * being copied over */ // aliasName is annotated as @FullyQualifiedName because there is no way to confirm that the // name of an external annotation is a canoncal name. protected void addAliasedTypeAnnotation( @FullyQualifiedName String aliasName, Class<?> canonicalAnno, boolean copyElements, String... ignorableElements) { // The copyElements argument disambiguates overloading. if (!copyElements) { throw new BugInCF("Do not call with false"); } aliases.put( aliasName, new Alias( aliasName, null, copyElements, canonicalAnno.getCanonicalName(), ignorableElements)); } /** * Returns the canonical annotation for the passed annotation. Returns null if the passed * annotation is not an alias of a canonical one in the framework. * * <p>A canonical annotation is the internal annotation that will be used by the Checker Framework * in the aliased annotation's place. * * @param a the qualifier to check for an alias * @return the canonical annotation, or null if none exists */ public @Nullable AnnotationMirror canonicalAnnotation(AnnotationMirror a) { TypeElement elem = (TypeElement) a.getAnnotationType().asElement(); String qualName = elem.getQualifiedName().toString(); Alias alias = aliases.get(qualName); if (alias == null) { return null; } if (alias.copyElements) { AnnotationBuilder builder = new AnnotationBuilder(processingEnv, alias.canonicalName); builder.copyElementValuesFromAnnotation(a, alias.ignorableElements); return builder.build(); } else { return alias.canonical; } } /** * Add the annotation {@code alias} as an alias for the declaration annotation {@code annotation}, * where the annotation mirror {@code annotationToUse} will be used instead. If multiple calls are * made with the same {@code annotation}, then the {@code annotationToUse} must be the same. * * <p>The point of {@code annotationToUse} is that it may include elements/fields. */ protected void addAliasedDeclAnnotation( Class<? extends Annotation> alias, Class<? extends Annotation> annotation, AnnotationMirror annotationToUse) { Pair<AnnotationMirror, Set<Class<? extends Annotation>>> pair = declAliases.get(annotation); if (pair != null) { if (!AnnotationUtils.areSame(annotationToUse, pair.first)) { throw new BugInCF("annotationToUse should be the same: %s %s", pair.first, annotationToUse); } } else { pair = Pair.of(annotationToUse, new HashSet<>()); declAliases.put(annotation, pair); } Set<Class<? extends Annotation>> aliases = pair.second; aliases.add(alias); } /** * Adds the annotation {@code annotation} in the set of declaration annotations that should be * inherited. A declaration annotation will be inherited if it is in this list, or if it has the * meta-annotation @InheritedAnnotation. The meta-annotation @InheritedAnnotation should be used * instead of this method, if possible. */ protected void addInheritedAnnotation(AnnotationMirror annotation) { inheritedAnnotations.add(annotation); } /** * A convenience method that converts a {@link TypeMirror} to an empty {@link AnnotatedTypeMirror} * using {@link AnnotatedTypeMirror#createType}. * * @param t the {@link TypeMirror} * @param declaration true if the result should be marked as a type declaration * @return an {@link AnnotatedTypeMirror} that has {@code t} as its underlying type */ protected final AnnotatedTypeMirror toAnnotatedType(TypeMirror t, boolean declaration) { return AnnotatedTypeMirror.createType(t, this, declaration); } /** * Determines an empty annotated type of the given tree. In other words, finds the {@link * TypeMirror} for the tree and converts that into an {@link AnnotatedTypeMirror}, but does not * add any annotations to the result. * * <p>Most users will want to use {@link #getAnnotatedType(Tree)} instead; this method is mostly * for internal use. * * @param node the tree to analyze * @return the type of {@code node}, without any annotations */ protected final AnnotatedTypeMirror type(Tree node) { boolean isDeclaration = TreeUtils.isTypeDeclaration(node); // Attempt to obtain the type via JCTree. if (TreeUtils.typeOf(node) != null) { AnnotatedTypeMirror result = toAnnotatedType(TreeUtils.typeOf(node), isDeclaration); return result; } // Attempt to obtain the type via TreePath (slower). TreePath path = this.getPath(node); assert path != null : "No path or type in tree: " + node + " [" + node.getClass().getSimpleName() + "]"; TypeMirror t = trees.getTypeMirror(path); assert validType(t) : "Invalid type " + t + " for node " + t; AnnotatedTypeMirror result = toAnnotatedType(t, isDeclaration); return result; } /** * Gets the declaration tree for the element, if the source is available. * * <p>TODO: would be nice to move this to InternalUtils/TreeUtils. * * @param elt an element * @return the tree declaration of the element if found */ public final Tree declarationFromElement(Element elt) { // if root is null, we cannot find any declaration if (root == null) { return null; } if (shouldCache && elementToTreeCache.containsKey(elt)) { return elementToTreeCache.get(elt); } // Check for new declarations, outside of the AST. if (elt instanceof DetachedVarSymbol) { return ((DetachedVarSymbol) elt).getDeclaration(); } // TODO: handle type parameter declarations? Tree fromElt; // Prevent calling declarationFor on elements we know we don't have the tree for. switch (elt.getKind()) { case CLASS: case ENUM: case INTERFACE: case ANNOTATION_TYPE: case FIELD: case ENUM_CONSTANT: case METHOD: case CONSTRUCTOR: fromElt = trees.getTree(elt); break; default: fromElt = com.sun.tools.javac.tree.TreeInfo.declarationFor( (com.sun.tools.javac.code.Symbol) elt, (com.sun.tools.javac.tree.JCTree) root); break; } if (shouldCache) { elementToTreeCache.put(elt, fromElt); } return fromElt; } /** * Returns the current class type being visited by the visitor. The method uses the parameter only * if the most enclosing class cannot be found directly. * * @return type of the most enclosing class being visited */ // This method is used to wrap access to visitorState protected final ClassTree getCurrentClassTree(Tree tree) { if (visitorState.getClassTree() != null) { return visitorState.getClassTree(); } return TreePathUtil.enclosingClass(getPath(tree)); } protected final AnnotatedDeclaredType getCurrentClassType(Tree tree) { return getAnnotatedType(getCurrentClassTree(tree)); } /** * Returns the receiver type of the current method being visited, and returns null if the visited * tree is not within a method or if that method has no receiver (e.g. a static method). * * <p>The method uses the parameter only if the most enclosing method cannot be found directly. * * @return receiver type of the most enclosing method being visited */ protected final @Nullable AnnotatedDeclaredType getCurrentMethodReceiver(Tree tree) { AnnotatedDeclaredType res = visitorState.getMethodReceiver(); if (res == null) { TreePath path = getPath(tree); if (path != null) { @SuppressWarnings("interning:assignment") // used for == test @InternedDistinct MethodTree enclosingMethod = TreePathUtil.enclosingMethod(path); ClassTree enclosingClass = TreePathUtil.enclosingClass(path); boolean found = false; for (Tree member : enclosingClass.getMembers()) { if (member.getKind() == Tree.Kind.METHOD) { if (member == enclosingMethod) { found = true; } } } if (found && enclosingMethod != null) { AnnotatedExecutableType method = getAnnotatedType(enclosingMethod); res = method.getReceiverType(); // TODO: three tests fail if one adds the following, which would make sense, or not? // visitorState.setMethodReceiver(res); } else { // We are within an anonymous class or field initializer res = this.getAnnotatedType(enclosingClass); } } } return res; } protected final boolean isWithinConstructor(Tree tree) { if (visitorState.getClassType() != null) { return visitorState.getMethodTree() != null && TreeUtils.isConstructor(visitorState.getMethodTree()); } MethodTree enclosingMethod = TreePathUtil.enclosingMethod(getPath(tree)); return enclosingMethod != null && TreeUtils.isConstructor(enclosingMethod); } /** * Gets the path for the given {@link Tree} under the current root by checking from the visitor's * current path, and using {@link Trees#getPath(CompilationUnitTree, Tree)} (which is much slower) * only if {@code node} is not found on the current path. * * <p>Note that the given Tree has to be within the current compilation unit, otherwise null will * be returned. * * @param node the {@link Tree} to get the path for * @return the path for {@code node} under the current root. Returns null if {@code node} is not * within the current compilation unit. */ public final @Nullable TreePath getPath(@FindDistinct Tree node) { assert root != null : "AnnotatedTypeFactory.getPath(" + node.getKind() + "): root needs to be set when used on trees; factory: " + this.getClass().getSimpleName(); if (node == null) { return null; } if (artificialTreeToEnclosingElementMap.containsKey(node)) { return null; } if (treePathCache.isCached(node)) { return treePathCache.getPath(root, node); } TreePath currentPath = visitorState.getPath(); if (currentPath == null) { TreePath path = TreePath.getPath(root, node); treePathCache.addPath(node, path); return path; } // This method uses multiple heuristics to avoid calling // TreePath.getPath() // If the current path you are visiting is for this node we are done if (currentPath.getLeaf() == node) { treePathCache.addPath(node, currentPath); return currentPath; } // When running on Daikon, we noticed that a lot of calls happened // within a small subtree containing the node we are currently visiting // When testing on Daikon, two steps resulted in the best performance if (currentPath.getParentPath() != null) { currentPath = currentPath.getParentPath(); treePathCache.addPath(currentPath.getLeaf(), currentPath); if (currentPath.getLeaf() == node) { return currentPath; } if (currentPath.getParentPath() != null) { currentPath = currentPath.getParentPath(); treePathCache.addPath(currentPath.getLeaf(), currentPath); if (currentPath.getLeaf() == node) { return currentPath; } } } final TreePath pathWithinSubtree = TreePath.getPath(currentPath, node); if (pathWithinSubtree != null) { treePathCache.addPath(node, pathWithinSubtree); return pathWithinSubtree; } // climb the current path till we see that // Works when getPath called on the enclosing method, enclosing class. TreePath current = currentPath; while (current != null) { treePathCache.addPath(current.getLeaf(), current); if (current.getLeaf() == node) { return current; } current = current.getParentPath(); } // OK, we give up. Use the cache to look up. return treePathCache.getPath(root, node); } /** * Gets the {@link Element} representing the declaration of the method enclosing a tree node. This * feature is used to record the enclosing methods of {@link Tree}s that are created internally by * the checker. * * <p>TODO: Find a better way to store information about enclosing Trees. * * @param node the {@link Tree} to get the enclosing method for * @return the method {@link Element} enclosing the argument, or null if none has been recorded */ public final Element getEnclosingElementForArtificialTree(Tree node) { return artificialTreeToEnclosingElementMap.get(node); } /** * Adds the given mapping from a synthetic (generated) tree to its enclosing element. * * <p>See {@code * org.checkerframework.framework.flow.CFCFGBuilder.CFCFGTranslationPhaseOne.handleArtificialTree(Tree)}. * * @param tree artifical tree * @param enclosing element that encloses {@code tree} */ public final void setEnclosingElementForArtificialTree(Tree tree, Element enclosing) { artificialTreeToEnclosingElementMap.put(tree, enclosing); } /** * Assert that the type is a type of valid type mirror, i.e. not an ERROR or OTHER type. * * @param type an annotated type * @return true if the type is a valid annotated type, false otherwise */ static final boolean validAnnotatedType(AnnotatedTypeMirror type) { if (type == null) { return false; } return validType(type.getUnderlyingType()); } /** * Used for asserting that a type is valid for converting to an annotated type. * * @return true if {@code type} can be converted to an annotated type, false otherwise */ private static final boolean validType(TypeMirror type) { if (type == null) { return false; } switch (type.getKind()) { case ERROR: case OTHER: case PACKAGE: return false; default: return true; } } /** * Parses all annotation files in the following order: * * <ol> * <li>jdk.astub in the same directory as the checker, if it exists and ignorejdkastub option is * not supplied <br> * <li>jdkN.astub, where N is the Java version in the same directory as the checker, if it * exists and ignorejdkastub option is not supplied <br> * <li>Stub files listed in @StubFiles annotation on the checker; must be in same directory as * the checker<br> * <li>Stub files provided via -Astubs compiler option * <li>Ajava files provided via -Aajava compiler option * </ol> * * <p>If a type is annotated with a qualifier from the same hierarchy in more than one stub file, * the qualifier in the last stub file is applied. * * <p>The annotations are stored by side-effecting {@link #stubTypes} and {@link #ajavaTypes}. */ protected void parseAnnotationFiles() { stubTypes.parseStubFiles(); ajavaTypes.parseAjavaFiles(); } /** * Returns all of the declaration annotations whose name equals the passed annotation class (or is * an alias for it) including annotations: * * <ul> * <li>on the element * <li>written in stubfiles * <li>inherited from overriden methods, (see {@link InheritedAnnotation}) * <li>inherited from superclasses or super interfaces (see {@link Inherited}) * </ul> * * @see #getDeclAnnotationNoAliases * @param elt the element to retrieve the declaration annotation from * @param anno annotation class * @return the annotation mirror for anno */ @Override public final AnnotationMirror getDeclAnnotation(Element elt, Class<? extends Annotation> anno) { return getDeclAnnotation(elt, anno, true); } /** * Returns the actual annotation mirror used to annotate this element, whose name equals the * passed annotation class. Returns null if none exists. Does not check for aliases of the * annotation class. * * <p>Call this method from a checker that needs to alias annotations for one purpose and not for * another. For example, in the Lock Checker, {@code @LockingFree} and {@code @ReleasesNoLocks} * are both aliases of {@code @SideEffectFree} since they are all considered side-effect-free with * regard to the set of locks held before and after the method call. However, a {@code * synchronized} block is permitted inside a {@code @ReleasesNoLocks} method but not inside a * {@code @LockingFree} or {@code @SideEffectFree} method. * * @see #getDeclAnnotation * @param elt the element to retrieve the declaration annotation from * @param anno annotation class * @return the annotation mirror for anno */ public final AnnotationMirror getDeclAnnotationNoAliases( Element elt, Class<? extends Annotation> anno) { return getDeclAnnotation(elt, anno, false); } /** * Returns true if the element appears in a stub file (Currently only works for methods, * constructors, and fields). */ public boolean isFromStubFile(Element element) { return this.getDeclAnnotation(element, FromStubFile.class) != null; } /** * Returns true if the element is from bytecode and the if the element did not appear in a stub * file. Currently only works for methods, constructors, and fields. */ public boolean isFromByteCode(Element element) { if (isFromStubFile(element)) { return false; } return ElementUtils.isElementFromByteCode(element); } /** * Returns true if redundancy between a stub file and bytecode should be reported. * * <p>For most type systems the default behavior of returning true is correct. For subcheckers, * redundancy in one of the type hierarchies can be ok. Such implementations should return false. * * @return whether to warn about redundancy between a stub file and bytecode */ public boolean shouldWarnIfStubRedundantWithBytecode() { return true; } /** * Returns the actual annotation mirror used to annotate this element, whose name equals the * passed annotation class (or is an alias for it). Returns null if none exists. May return the * canonical annotation that annotationName is an alias for. * * <p>This is the private implementation of the same-named, public method. * * <p>An option is provided to not to check for aliases of annotations. For example, an annotated * type factory may use aliasing for a pair of annotations for convenience while needing in some * cases to determine a strict ordering between them, such as when determining whether the * annotations on an overrider method are more specific than the annotations of an overridden * method. * * @param elt the element to retrieve the annotation from * @param annoClass the class the annotation to retrieve * @param checkAliases whether to return an annotation mirror for an alias of the requested * annotation class name * @return the annotation mirror for the requested annotation, or null if not found */ private AnnotationMirror getDeclAnnotation( Element elt, Class<? extends Annotation> annoClass, boolean checkAliases) { Set<AnnotationMirror> declAnnos = getDeclAnnotations(elt); for (AnnotationMirror am : declAnnos) { if (areSameByClass(am, annoClass)) { return am; } } // Look through aliases. if (checkAliases) { Pair<AnnotationMirror, Set<Class<? extends Annotation>>> aliases = declAliases.get(annoClass); if (aliases != null) { for (Class<? extends Annotation> alias : aliases.second) { for (AnnotationMirror am : declAnnos) { if (areSameByClass(am, alias)) { // TODO: need to copy over elements/fields return aliases.first; } } } } } // Not found. return null; } /** * Returns all of the declaration annotations on this element including annotations: * * <ul> * <li>on the element * <li>written in stubfiles * <li>inherited from overriden methods, (see {@link InheritedAnnotation}) * <li>inherited from superclasses or super interfaces (see {@link Inherited}) * </ul> * * <p>This method returns the actual annotations not their aliases. {@link * #getDeclAnnotation(Element, Class)} returns aliases. * * @param elt the element for which to determine annotations * @return all of the declaration annotations on this element, written in stub files, or inherited */ public Set<AnnotationMirror> getDeclAnnotations(Element elt) { Set<AnnotationMirror> cachedValue = cacheDeclAnnos.get(elt); if (cachedValue != null) { // Found in cache, return result. return cachedValue; } Set<AnnotationMirror> results = AnnotationUtils.createAnnotationSet(); // Retrieving the annotations from the element. // This includes annotations inherited from superclasses, but not superinterfaces or // overriden methods. List<? extends AnnotationMirror> fromEle = elements.getAllAnnotationMirrors(elt); for (AnnotationMirror annotation : fromEle) { try { results.add(annotation); } catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) { // If a CompletionFailure occurs, issue a warning. checker.reportWarning( annotation.getAnnotationType().asElement(), "annotation.not.completed", ElementUtils.getQualifiedName(elt), annotation); } } // If parsing annotation files, return only the annotations in the element. if (stubTypes.isParsing() || ajavaTypes.isParsing() || (currentFileAjavaTypes != null && currentFileAjavaTypes.isParsing())) { return results; } // Add annotations from annotation files. results.addAll(stubTypes.getDeclAnnotation(elt)); results.addAll(ajavaTypes.getDeclAnnotation(elt)); if (currentFileAjavaTypes != null) { results.addAll(currentFileAjavaTypes.getDeclAnnotation(elt)); } if (elt.getKind() == ElementKind.METHOD) { // Retrieve the annotations from the overridden method's element. inheritOverriddenDeclAnnos((ExecutableElement) elt, results); } else if (ElementUtils.isTypeDeclaration(elt)) { inheritOverriddenDeclAnnosFromTypeDecl(elt.asType(), results); } // Add the element and its annotations to the cache. cacheDeclAnnos.put(elt, results); return results; } /** * Adds into {@code results} the inherited declaration annotations found in all elements of the * super types of {@code typeMirror}. (Both superclasses and superinterfaces.) * * @param typeMirror type * @param results set of AnnotationMirrors to which this method adds declarations annotations */ private void inheritOverriddenDeclAnnosFromTypeDecl( TypeMirror typeMirror, Set<AnnotationMirror> results) { List<? extends TypeMirror> superTypes = types.directSupertypes(typeMirror); for (TypeMirror superType : superTypes) { TypeElement elt = TypesUtils.getTypeElement(superType); if (elt == null) { continue; } Set<AnnotationMirror> superAnnos = getDeclAnnotations(elt); for (AnnotationMirror annotation : superAnnos) { List<? extends AnnotationMirror> annotationsOnAnnotation; try { annotationsOnAnnotation = annotation.getAnnotationType().asElement().getAnnotationMirrors(); } catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) { // Fix for Issue 348: If a CompletionFailure occurs, issue a warning. checker.reportWarning( annotation.getAnnotationType().asElement(), "annotation.not.completed", ElementUtils.getQualifiedName(elt), annotation); continue; } if (containsSameByClass(annotationsOnAnnotation, Inherited.class) || AnnotationUtils.containsSameByName(inheritedAnnotations, annotation)) { addOrMerge(results, annotation); } } } } /** * Adds into {@code results} the declaration annotations found in all elements that the method * element {@code elt} overrides. * * @param elt method element * @param results {@code elt} local declaration annotations. The ones found in stub files and in * the element itself. */ private void inheritOverriddenDeclAnnos(ExecutableElement elt, Set<AnnotationMirror> results) { Map<AnnotatedDeclaredType, ExecutableElement> overriddenMethods = AnnotatedTypes.overriddenMethods(elements, this, elt); if (overriddenMethods != null) { for (ExecutableElement superElt : overriddenMethods.values()) { Set<AnnotationMirror> superAnnos = getDeclAnnotations(superElt); for (AnnotationMirror annotation : superAnnos) { List<? extends AnnotationMirror> annotationsOnAnnotation; try { annotationsOnAnnotation = annotation.getAnnotationType().asElement().getAnnotationMirrors(); } catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) { // Fix for Issue 348: If a CompletionFailure occurs, // issue a warning. checker.reportWarning( annotation.getAnnotationType().asElement(), "annotation.not.completed", ElementUtils.getQualifiedName(elt), annotation); continue; } if (containsSameByClass(annotationsOnAnnotation, InheritedAnnotation.class) || AnnotationUtils.containsSameByName(inheritedAnnotations, annotation)) { addOrMerge(results, annotation); } } } } } private void addOrMerge(Set<AnnotationMirror> results, AnnotationMirror annotation) { if (AnnotationUtils.containsSameByName(results, annotation)) { /* * TODO: feature request: figure out a way to merge multiple annotations * of the same kind. For some annotations this might mean merging some * arrays, for others it might mean converting a single annotation into a * container annotation. We should define a protected method for subclasses * to adapt the behavior. * For now, do nothing and just take the first, most concrete, annotation. AnnotationMirror prev = null; for (AnnotationMirror an : results) { if (AnnotationUtils.areSameByName(an, annotation)) { prev = an; break; } } results.remove(prev); AnnotationMirror merged = ...; results.add(merged); */ } else { results.add(annotation); } } /** * Returns a list of all declaration annotations used to annotate the element, which have a * meta-annotation (i.e., an annotation on that annotation) with class {@code * metaAnnotationClass}. * * @param element the element for which to determine annotations * @param metaAnnotationClass the class of the meta-annotation that needs to be present * @return a list of pairs {@code (anno, metaAnno)} where {@code anno} is the annotation mirror at * {@code element}, and {@code metaAnno} is the annotation mirror (of type {@code * metaAnnotationClass}) used to meta-annotate the declaration of {@code anno} */ public List<Pair<AnnotationMirror, AnnotationMirror>> getDeclAnnotationWithMetaAnnotation( Element element, Class<? extends Annotation> metaAnnotationClass) { List<Pair<AnnotationMirror, AnnotationMirror>> result = new ArrayList<>(); Set<AnnotationMirror> annotationMirrors = getDeclAnnotations(element); for (AnnotationMirror candidate : annotationMirrors) { List<? extends AnnotationMirror> metaAnnotationsOnAnnotation; try { metaAnnotationsOnAnnotation = candidate.getAnnotationType().asElement().getAnnotationMirrors(); } catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) { // Fix for Issue 309: If a CompletionFailure occurs, issue a warning. // I didn't find a nicer alternative to check whether the Symbol can be completed. // The completer field of a Symbol might be non-null also in successful cases. // Issue a warning (exception only happens once) and continue. checker.reportWarning( candidate.getAnnotationType().asElement(), "annotation.not.completed", ElementUtils.getQualifiedName(element), candidate); continue; } // First call copier, if exception, continue normal modula laws. for (AnnotationMirror ma : metaAnnotationsOnAnnotation) { if (areSameByClass(ma, metaAnnotationClass)) { // This candidate has the right kind of meta-annotation. // It might be a real contract, or a list of contracts. if (isListForRepeatedAnnotation(candidate)) { @SuppressWarnings("deprecation") // concrete annotation class is not known List<AnnotationMirror> wrappedCandidates = AnnotationUtils.getElementValueArray( candidate, "value", AnnotationMirror.class, false); for (AnnotationMirror wrappedCandidate : wrappedCandidates) { result.add(Pair.of(wrappedCandidate, ma)); } } else { result.add(Pair.of(candidate, ma)); } } } } return result; } /** Cache for {@link #isListForRepeatedAnnotation}. */ private final Map<DeclaredType, Boolean> isListForRepeatedAnnotationCache = new HashMap<>(); /** * Returns true if the given annotation is a wrapper for multiple repeated annotations. * * @param a an annotation that might be a wrapper * @return true if the argument is a wrapper for multiple repeated annotations */ private boolean isListForRepeatedAnnotation(AnnotationMirror a) { DeclaredType annotationType = a.getAnnotationType(); Boolean resultObject = isListForRepeatedAnnotationCache.get(annotationType); if (resultObject != null) { return resultObject; } boolean result = isListForRepeatedAnnotationImplementation(annotationType); isListForRepeatedAnnotationCache.put(annotationType, result); return result; } /** * Returns true if the annotation is a wrapper for multiple repeated annotations. * * @param annotationType the declaration of the annotation to test * @return true if the annotation is a wrapper for multiple repeated annotations */ private boolean isListForRepeatedAnnotationImplementation(DeclaredType annotationType) { TypeMirror enclosingType = annotationType.getEnclosingType(); if (enclosingType == null) { return false; } if (!annotationType.asElement().getSimpleName().contentEquals("List")) { return false; } List<? extends Element> annoElements = annotationType.asElement().getEnclosedElements(); if (annoElements.size() != 1) { return false; } // TODO: should check that the type of the single element is: "array of enclosingType". return true; } /** * Returns a list of all annotations used to annotate this element, which have a meta-annotation * (i.e., an annotation on that annotation) with class {@code metaAnnotationClass}. * * @param element the element at which to look for annotations * @param metaAnnotationClass the class of the meta-annotation that needs to be present * @return a list of pairs {@code (anno, metaAnno)} where {@code anno} is the annotation mirror at * {@code element}, and {@code metaAnno} is the annotation mirror used to annotate {@code * anno}. */ public List<Pair<AnnotationMirror, AnnotationMirror>> getAnnotationWithMetaAnnotation( Element element, Class<? extends Annotation> metaAnnotationClass) { Set<AnnotationMirror> annotationMirrors = AnnotationUtils.createAnnotationSet(); // Consider real annotations. annotationMirrors.addAll(getAnnotatedType(element).getAnnotations()); // Consider declaration annotations annotationMirrors.addAll(getDeclAnnotations(element)); List<Pair<AnnotationMirror, AnnotationMirror>> result = new ArrayList<>(); // Go through all annotations found. for (AnnotationMirror annotation : annotationMirrors) { List<? extends AnnotationMirror> annotationsOnAnnotation = annotation.getAnnotationType().asElement().getAnnotationMirrors(); for (AnnotationMirror a : annotationsOnAnnotation) { if (areSameByClass(a, metaAnnotationClass)) { result.add(Pair.of(annotation, a)); } } } return result; } /** * Whether or not the {@code annotatedTypeMirror} has a qualifier parameter. * * @param annotatedTypeMirror AnnotatedTypeMirror to check * @param top the top of the hierarchy to check * @return true if the type has a qualifier parameter */ public boolean hasQualifierParameterInHierarchy( AnnotatedTypeMirror annotatedTypeMirror, AnnotationMirror top) { return AnnotationUtils.containsSame(getQualifierParameterHierarchies(annotatedTypeMirror), top); } /** * Whether or not the {@code element} has a qualifier parameter. * * @param element element to check * @param top the top of the hierarchy to check * @return true if the type has a qualifier parameter */ public boolean hasQualifierParameterInHierarchy(@Nullable Element element, AnnotationMirror top) { if (element == null) { return false; } return AnnotationUtils.containsSame(getQualifierParameterHierarchies(element), top); } /** * Returns whether the {@code HasQualifierParameter} annotation was explicitly written on {@code * element} for the hierarchy given by {@code top}. * * @param element the Element to check * @param top the top qualifier for the hierarchy to check * @return whether the class given by {@code element} has been explicitly annotated with {@code * HasQualifierParameter} for the given hierarchy */ public boolean hasExplicitQualifierParameterInHierarchy(Element element, AnnotationMirror top) { return AnnotationUtils.containsSame( getSupportedAnnotationsInElementAnnotation( element, HasQualifierParameter.class, hasQualifierParameterValueElement), top); } /** * Returns whether the {@code NoQualifierParameter} annotation was explicitly written on {@code * element} for the hierarchy given by {@code top}. * * @param element the Element to check * @param top the top qualifier for the hierarchy to check * @return whether the class given by {@code element} has been explicitly annotated with {@code * NoQualifierParameter} for the given hierarchy */ public boolean hasExplicitNoQualifierParameterInHierarchy(Element element, AnnotationMirror top) { return AnnotationUtils.containsSame( getSupportedAnnotationsInElementAnnotation( element, NoQualifierParameter.class, noQualifierParameterValueElement), top); } /** * Returns the set of top annotations representing all the hierarchies for which this type has a * qualifier parameter. * * @param annotatedType AnnotatedTypeMirror to check * @return the set of top annotations representing all the hierarchies for which this type has a * qualifier parameter */ public Set<AnnotationMirror> getQualifierParameterHierarchies(AnnotatedTypeMirror annotatedType) { while (annotatedType.getKind() == TypeKind.TYPEVAR || annotatedType.getKind() == TypeKind.WILDCARD) { if (annotatedType.getKind() == TypeKind.TYPEVAR) { annotatedType = ((AnnotatedTypeVariable) annotatedType).getUpperBound(); } else if (annotatedType.getKind() == TypeKind.WILDCARD) { annotatedType = ((AnnotatedWildcardType) annotatedType).getSuperBound(); } } if (annotatedType.getKind() != TypeKind.DECLARED) { return Collections.emptySet(); } AnnotatedDeclaredType declaredType = (AnnotatedDeclaredType) annotatedType; Element element = declaredType.getUnderlyingType().asElement(); if (element == null) { return Collections.emptySet(); } return getQualifierParameterHierarchies(element); } /** * Returns the set of top annotations representing all the hierarchies for which this element has * a qualifier parameter. * * @param element the Element to check * @return the set of top annotations representing all the hierarchies for which this element has * a qualifier parameter */ public Set<AnnotationMirror> getQualifierParameterHierarchies(Element element) { if (!ElementUtils.isTypeDeclaration(element)) { return Collections.emptySet(); } Set<AnnotationMirror> found = AnnotationUtils.createAnnotationSet(); found.addAll( getSupportedAnnotationsInElementAnnotation( element, HasQualifierParameter.class, hasQualifierParameterValueElement)); Set<AnnotationMirror> hasQualifierParameterTops = AnnotationUtils.createAnnotationSet(); PackageElement packageElement = ElementUtils.enclosingPackage(element); // Traverse all packages containing this element. while (packageElement != null) { Set<AnnotationMirror> packageDefaultTops = getSupportedAnnotationsInElementAnnotation( packageElement, HasQualifierParameter.class, hasQualifierParameterValueElement); hasQualifierParameterTops.addAll(packageDefaultTops); packageElement = ElementUtils.parentPackage(packageElement, elements); } Set<AnnotationMirror> noQualifierParamClasses = getSupportedAnnotationsInElementAnnotation( element, NoQualifierParameter.class, noQualifierParameterValueElement); for (AnnotationMirror anno : hasQualifierParameterTops) { if (!AnnotationUtils.containsSame(noQualifierParamClasses, anno)) { found.add(anno); } } return found; } /** * Returns a set of supported annotation mirrors corresponding to the annotation classes listed in * the value element of an annotation with class {@code annoClass} on {@code element}. * * @param element the Element to check * @param annoClass the class for an annotation that's written on elements, whose value element is * a list of annotation classes. It is always HasQualifierParameter or NoQualifierParameter * @param valueElement the {@code value} field/element of an annotation with class {@code * annoClass} * @return the set of supported annotations with classes listed in the value element of an * annotation with class {@code annoClass} on the {@code element}. Returns an empty set if * {@code annoClass} is not written on {@code element} or {@code element} is null. */ private Set<AnnotationMirror> getSupportedAnnotationsInElementAnnotation( @Nullable Element element, Class<? extends Annotation> annoClass, ExecutableElement valueElement) { if (element == null) { return Collections.emptySet(); } // TODO: caching AnnotationMirror annotation = getDeclAnnotation(element, annoClass); if (annotation == null) { return Collections.emptySet(); } Set<AnnotationMirror> found = AnnotationUtils.createAnnotationSet(); List<@CanonicalName Name> qualClasses = AnnotationUtils.getElementValueClassNames(annotation, valueElement); for (Name qual : qualClasses) { AnnotationMirror annotationMirror = AnnotationBuilder.fromName(elements, qual); if (isSupportedQualifier(annotationMirror)) { found.add(annotationMirror); } } return found; } /** * A scanner that replaces annotations in one type with annotations from another. Used by {@link * #replaceAnnotations(AnnotatedTypeMirror, AnnotatedTypeMirror)} and {@link * #replaceAnnotations(AnnotatedTypeMirror, AnnotatedTypeMirror, AnnotationMirror)}. */ private final AnnotatedTypeReplacer annotatedTypeReplacer = new AnnotatedTypeReplacer(); /** * Replaces or adds all annotations from {@code from} to {@code to}. Annotations from {@code from} * will be used everywhere they exist, but annotations in {@code to} will be kept anywhere that * {@code from} is unannotated. * * @param from the annotated type mirror from which to take new annotations * @param to the annotated type mirror to which the annotations will be added */ public void replaceAnnotations(final AnnotatedTypeMirror from, final AnnotatedTypeMirror to) { annotatedTypeReplacer.visit(from, to); } /** * Replaces or adds annotations in {@code top}'s hierarchy from {@code from} to {@code to}. * Annotations from {@code from} will be used everywhere they exist, but annotations in {@code to} * will be kept anywhere that {@code from} is unannotated. * * @param from the annotated type mirror from which to take new annotations * @param to the annotated type mirror to which the annotations will be added * @param top the top type of the hierarchy whose annotations will be added */ public void replaceAnnotations( final AnnotatedTypeMirror from, final AnnotatedTypeMirror to, final AnnotationMirror top) { annotatedTypeReplacer.setTop(top); annotatedTypeReplacer.visit(from, to); annotatedTypeReplacer.setTop(null); } /** The implementation of the visitor for #containsUninferredTypeArguments. */ private final SimpleAnnotatedTypeScanner<Boolean, Void> uninferredTypeArgumentScanner = new SimpleAnnotatedTypeScanner<>( (type, p) -> type.getKind() == TypeKind.WILDCARD && ((AnnotatedWildcardType) type).isUninferredTypeArgument(), Boolean::logicalOr, false); /** * Returns whether this type or any component type is a wildcard type for which Java 7 type * inference is insufficient. See issue 979, or the documentation on AnnotatedWildcardType. * * @param type type to check * @return whether this type or any component type is a wildcard type for which Java 7 type * inference is insufficient */ public boolean containsUninferredTypeArguments(AnnotatedTypeMirror type) { return uninferredTypeArgumentScanner.visit(type); } /** * Returns a wildcard type to be used as a type argument when the correct type could not be * inferred. The wildcard will be marked as an uninferred wildcard so that {@link * AnnotatedWildcardType#isUninferredTypeArgument()} returns true. * * <p>This method should only be used by type argument inference. * org.checkerframework.framework.util.AnnotatedTypes.inferTypeArguments(ProcessingEnvironment, * AnnotatedTypeFactory, ExpressionTree, ExecutableElement) * * @param typeVar TypeVariable which could not be inferred * @return a wildcard that is marked as an uninferred type argument */ public AnnotatedWildcardType getUninferredWildcardType(AnnotatedTypeVariable typeVar) { final boolean intersectionType; final TypeMirror boundType; if (typeVar.getUpperBound().getKind() == TypeKind.INTERSECTION) { boundType = typeVar.getUpperBound().directSupertypes().get(0).getUnderlyingType(); intersectionType = true; } else { boundType = typeVar.getUnderlyingType().getUpperBound(); intersectionType = false; } WildcardType wc = types.getWildcardType(boundType, null); AnnotatedWildcardType wctype = (AnnotatedWildcardType) AnnotatedTypeMirror.createType(wc, this, false); wctype.setTypeVariable(typeVar.getUnderlyingType()); if (!intersectionType) { wctype.setExtendsBound(typeVar.getUpperBound().deepCopy()); } else { wctype.getExtendsBound().addAnnotations(typeVar.getUpperBound().getAnnotations()); } wctype.setSuperBound(typeVar.getLowerBound().deepCopy()); wctype.addAnnotations(typeVar.getAnnotations()); addDefaultAnnotations(wctype); wctype.setUninferredTypeArgument(); return wctype; } /** * If {@code wildcard}'s upper bound is a super type of {@code annotatedTypeMirror}, this method * returns an AnnotatedTypeMirror with the same qualifiers as {@code annotatedTypeMirror}, but the * underlying Java type is the most specific base type of {@code annotatedTypeMirror} whose * erasure type is equivalent to the upper bound of {@code wildcard}. * * <p>Otherwise, returns {@code annotatedTypeMirror} unmodified. * * <p>For example: * * <pre> * wildcard := @NonNull ? extends @NonNull Object * annotatedTypeMirror := @Nullable String * * widenToUpperBound(annotatedTypeMirror, wildcard) returns @Nullable Object * </pre> * * This method is needed because, the Java compiler allows wildcards to have upper bounds above * the type variable upper bounds for which they are type arguments. For example, given the * following parametric type: * * <pre> * {@code class MyClass<T extends Number>} * </pre> * * the following is legal: * * <pre> * {@code MyClass<? extends Object>} * </pre> * * This is sound because in Java the wildcard is capture converted to: {@code CAP#1 extends Number * from capture of ? extends Object}. * * <p>Because the Checker Framework does not implement capture conversion, wildcard upper bounds * may cause spurious errors in subtyping checks. This method prevents those errors by widening * the upper bound of the type parameter. * * <p>This method widens the underlying Java type of the upper bound of the type parameter rather * than narrowing the bound of the wildcard in order to avoid issuing an error with an upper bound * that is not in source code. * * <p>The widened type should only be used for typing checks that require it. Using the widened * type elsewhere would cause confusing error messages with types not in the source code. * * @param annotatedTypeMirror AnnotatedTypeMirror to widen * @param wildcard AnnotatedWildcardType whose upper bound is used to widen * @return {@code annotatedTypeMirror} widen to the upper bound of {@code wildcard} */ public AnnotatedTypeMirror widenToUpperBound( final AnnotatedTypeMirror annotatedTypeMirror, final AnnotatedWildcardType wildcard) { final TypeMirror toModifyTypeMirror = annotatedTypeMirror.getUnderlyingType(); final TypeMirror wildcardUBTypeMirror = wildcard.getExtendsBound().getUnderlyingType(); if (TypesUtils.isErasedSubtype(wildcardUBTypeMirror, toModifyTypeMirror, types)) { return annotatedTypeMirror; } else if (TypesUtils.isErasedSubtype(toModifyTypeMirror, wildcardUBTypeMirror, types)) { return AnnotatedTypes.asSuper(this, annotatedTypeMirror, wildcard); } else if (wildcardUBTypeMirror.getKind() == TypeKind.DECLARED && TypesUtils.getTypeElement(wildcardUBTypeMirror).getKind().isInterface()) { // If the Checker Framework implemented capture conversion, then in this case, then // the upper bound of the capture converted wildcard would be an intersection type. // See JLS 15.1.10 // (https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.1.10) // For example: // class MyClass<@A T extends @B Number> {} // MyClass<@C ? extends @D Serializable> // The upper bound of the captured wildcard: // glb(@B Number, @D Serializable) = @B Number & @D Serializable // The about upper bound must be a subtype of the declared upper bound: // @B Number & @D Serializable <: @B Number, which is always true. // So, replace the upper bound at the declaration with the wildcard's upper bound so // that the rest of the subtyping test pass. return wildcard.getExtendsBound(); } return annotatedTypeMirror; } /** * Returns the function type that this member reference targets. * * <p>The function type is the type of the single method declared in the functional interface * adapted as if it were invoked using the functional interface as the receiver expression. * * <p>The target type of a member reference is the type to which it is assigned or casted. * * @param tree member reference tree * @return the function type that this method reference targets */ public AnnotatedExecutableType getFunctionTypeFromTree(MemberReferenceTree tree) { return getFnInterfaceFromTree(tree).second; } /** * Returns the function type that this lambda targets. * * <p>The function type is the type of the single method declared in the functional interface * adapted as if it were invoked using the functional interface as the receiver expression. * * <p>The target type of a lambda is the type to which it is assigned or casted. * * @param tree lambda expression tree * @return the function type that this lambda targets */ public AnnotatedExecutableType getFunctionTypeFromTree(LambdaExpressionTree tree) { return getFnInterfaceFromTree(tree).second; } /** * Returns the functional interface and the function type that this lambda or member references * targets. * * <p>The function type is the type of the single method declared in the functional interface * adapted as if it were invoked using the functional interface as the receiver expression. * * <p>The target type of a lambda or a method reference is the type to which it is assigned or * casted. * * @param tree lambda expression tree or member reference tree * @return the functional interface and the function type that this method reference or lambda * targets */ public Pair<AnnotatedTypeMirror, AnnotatedExecutableType> getFnInterfaceFromTree(Tree tree) { // Functional interface AnnotatedTypeMirror functionalInterfaceType = getFunctionalInterfaceType(tree); if (functionalInterfaceType.getKind() == TypeKind.DECLARED) { makeGroundTargetType( (AnnotatedDeclaredType) functionalInterfaceType, (DeclaredType) TreeUtils.typeOf(tree)); } // Functional method Element fnElement = TreeUtils.findFunction(tree, processingEnv); // Function type AnnotatedExecutableType functionType = (AnnotatedExecutableType) AnnotatedTypes.asMemberOf(types, this, functionalInterfaceType, fnElement); return Pair.of(functionalInterfaceType, functionType); } /** * Get the AnnotatedDeclaredType for the FunctionalInterface from assignment context of the method * reference or lambda expression which may be a variable assignment, a method call, or a cast. * * <p>The assignment context is not always correct, so we must search up the AST. It will * recursively search for lambdas nested in lambdas. * * @param tree the tree of the lambda or method reference * @return the functional interface type or an uninferred type argument */ private AnnotatedTypeMirror getFunctionalInterfaceType(Tree tree) { Tree parentTree = getPath(tree).getParentPath().getLeaf(); switch (parentTree.getKind()) { case PARENTHESIZED: return getFunctionalInterfaceType(parentTree); case TYPE_CAST: TypeCastTree cast = (TypeCastTree) parentTree; assert isFunctionalInterface( trees.getTypeMirror(getPath(cast.getType())), parentTree, tree); AnnotatedTypeMirror castATM = getAnnotatedType(cast.getType()); if (castATM.getKind() == TypeKind.INTERSECTION) { AnnotatedIntersectionType itype = (AnnotatedIntersectionType) castATM; for (AnnotatedTypeMirror t : itype.directSupertypes()) { if (TypesUtils.isFunctionalInterface(t.getUnderlyingType(), getProcessingEnv())) { return t; } } // We should never reach here: isFunctionalInterface performs the same check // and would have raised an error already. throw new BugInCF( "Expected the type of a cast tree in an assignment context to contain a functional" + " interface bound. Found type: %s for tree: %s in lambda tree: %s", castATM, cast, tree); } return castATM; case NEW_CLASS: NewClassTree newClass = (NewClassTree) parentTree; int indexOfLambda = newClass.getArguments().indexOf(tree); ParameterizedExecutableType con = this.constructorFromUse(newClass); AnnotatedTypeMirror constructorParam = AnnotatedTypes.getAnnotatedTypeMirrorOfParameter(con.executableType, indexOfLambda); assert isFunctionalInterface(constructorParam.getUnderlyingType(), parentTree, tree); return constructorParam; case NEW_ARRAY: NewArrayTree newArray = (NewArrayTree) parentTree; AnnotatedArrayType newArrayATM = getAnnotatedType(newArray); AnnotatedTypeMirror elementATM = newArrayATM.getComponentType(); assert isFunctionalInterface(elementATM.getUnderlyingType(), parentTree, tree); return elementATM; case METHOD_INVOCATION: MethodInvocationTree method = (MethodInvocationTree) parentTree; int index = method.getArguments().indexOf(tree); ParameterizedExecutableType exe = this.methodFromUse(method); AnnotatedTypeMirror param = AnnotatedTypes.getAnnotatedTypeMirrorOfParameter(exe.executableType, index); if (param.getKind() == TypeKind.WILDCARD) { // param is an uninferred wildcard. TypeMirror typeMirror = TreeUtils.typeOf(tree); param = AnnotatedTypeMirror.createType(typeMirror, this, false); addDefaultAnnotations(param); } assert isFunctionalInterface(param.getUnderlyingType(), parentTree, tree); return param; case VARIABLE: VariableTree varTree = (VariableTree) parentTree; assert isFunctionalInterface(TreeUtils.typeOf(varTree), parentTree, tree); return getAnnotatedType(varTree.getType()); case ASSIGNMENT: AssignmentTree assignmentTree = (AssignmentTree) parentTree; assert isFunctionalInterface(TreeUtils.typeOf(assignmentTree), parentTree, tree); return getAnnotatedType(assignmentTree.getVariable()); case RETURN: Tree enclosing = TreePathUtil.enclosingOfKind( getPath(parentTree), new HashSet<>(Arrays.asList(Tree.Kind.METHOD, Tree.Kind.LAMBDA_EXPRESSION))); if (enclosing.getKind() == Tree.Kind.METHOD) { MethodTree enclosingMethod = (MethodTree) enclosing; return getAnnotatedType(enclosingMethod.getReturnType()); } else { LambdaExpressionTree enclosingLambda = (LambdaExpressionTree) enclosing; AnnotatedExecutableType methodExe = getFunctionTypeFromTree(enclosingLambda); return methodExe.getReturnType(); } case LAMBDA_EXPRESSION: LambdaExpressionTree enclosingLambda = (LambdaExpressionTree) parentTree; AnnotatedExecutableType methodExe = getFunctionTypeFromTree(enclosingLambda); return methodExe.getReturnType(); case CONDITIONAL_EXPRESSION: ConditionalExpressionTree conditionalExpressionTree = (ConditionalExpressionTree) parentTree; final AnnotatedTypeMirror falseType = getAnnotatedType(conditionalExpressionTree.getFalseExpression()); final AnnotatedTypeMirror trueType = getAnnotatedType(conditionalExpressionTree.getTrueExpression()); // Known cases where we must use LUB because falseType/trueType will not be equal: // a) when one of the types is a type variable that extends a functional interface // or extends a type variable that extends a functional interface // b) When one of the two sides of the expression is a reference to a sub-interface. // e.g. interface ConsumeStr { // public void consume(String s) // } // interface SubConsumer extends ConsumeStr { // default void someOtherMethod() { ... } // } // SubConsumer s = ...; // ConsumeStr stringConsumer = (someCondition) ? s : System.out::println; AnnotatedTypeMirror conditionalType = AnnotatedTypes.leastUpperBound(this, trueType, falseType); assert isFunctionalInterface(conditionalType.getUnderlyingType(), parentTree, tree); return conditionalType; default: throw new BugInCF( "Could not find functional interface from assignment context. " + "Unexpected tree type: " + parentTree.getKind() + " For lambda tree: " + tree); } } private boolean isFunctionalInterface(TypeMirror typeMirror, Tree contextTree, Tree tree) { if (typeMirror.getKind() == TypeKind.WILDCARD) { // Ignore wildcards, because they are uninferred type arguments. return true; } Type type = (Type) typeMirror; if (!TypesUtils.isFunctionalInterface(type, processingEnv)) { if (type.getKind() == TypeKind.INTERSECTION) { IntersectionType itype = (IntersectionType) type; for (TypeMirror t : itype.getBounds()) { if (TypesUtils.isFunctionalInterface(t, processingEnv)) { // As long as any of the bounds is a functional interface // we should be fine. return true; } } } throw new BugInCF( "Expected the type of %s tree in assignment context to be a functional interface. " + "Found type: %s for tree: %s in lambda tree: %s", contextTree.getKind(), type, contextTree, tree); } return true; } /** * Create the ground target type of the functional interface. * * <p>Basically, it replaces the wildcards with their bounds doing a capture conversion like glb * for extends bounds. * * @see "JLS 9.9" * @param functionalType the functional interface type * @param groundTargetJavaType the Java type as found by javac */ private void makeGroundTargetType( AnnotatedDeclaredType functionalType, DeclaredType groundTargetJavaType) { if (functionalType.getTypeArguments().isEmpty()) { return; } List<AnnotatedTypeParameterBounds> bounds = this.typeVariablesFromUse( functionalType, (TypeElement) functionalType.getUnderlyingType().asElement()); List<AnnotatedTypeMirror> newTypeArguments = new ArrayList<>(functionalType.getTypeArguments()); boolean sizesDiffer = functionalType.getTypeArguments().size() != groundTargetJavaType.getTypeArguments().size(); for (int i = 0; i < functionalType.getTypeArguments().size(); i++) { AnnotatedTypeMirror argType = functionalType.getTypeArguments().get(i); if (argType.getKind() == TypeKind.WILDCARD) { AnnotatedWildcardType wildcardType = (AnnotatedWildcardType) argType; TypeMirror wildcardUbType = wildcardType.getExtendsBound().getUnderlyingType(); if (wildcardType.isUninferredTypeArgument()) { // Keep the uninferred type so that it is ignored by later subtyping and containment // checks. newTypeArguments.set(i, wildcardType); } else if (isExtendsWildcard(wildcardType)) { TypeMirror correctArgType; if (sizesDiffer) { // The java type is raw. TypeMirror typeParamUbType = bounds.get(i).getUpperBound().getUnderlyingType(); correctArgType = TypesUtils.greatestLowerBound( typeParamUbType, wildcardUbType, this.checker.getProcessingEnvironment()); } else { correctArgType = groundTargetJavaType.getTypeArguments().get(i); } final AnnotatedTypeMirror newArg; if (types.isSameType(wildcardUbType, correctArgType)) { newArg = wildcardType.getExtendsBound().deepCopy(); } else if (correctArgType.getKind() == TypeKind.TYPEVAR) { newArg = this.toAnnotatedType(correctArgType, false); AnnotatedTypeVariable newArgAsTypeVar = (AnnotatedTypeVariable) newArg; newArgAsTypeVar .getUpperBound() .replaceAnnotations(wildcardType.getExtendsBound().getAnnotations()); newArgAsTypeVar .getLowerBound() .replaceAnnotations(wildcardType.getSuperBound().getAnnotations()); } else { newArg = this.toAnnotatedType(correctArgType, false); newArg.replaceAnnotations(wildcardType.getExtendsBound().getAnnotations()); } newTypeArguments.set(i, newArg); } else { newTypeArguments.set(i, wildcardType.getSuperBound()); } } } functionalType.setTypeArguments(newTypeArguments); // When the groundTargetJavaType is different from the underlying type of functionalType, only // the main annotations are copied. Add default annotations in places without annotations. addDefaultAnnotations(functionalType); } /** * Check that a wildcard is an extends wildcard. * * @param awt the wildcard type * @return true if awt is an extends wildcard */ private boolean isExtendsWildcard(AnnotatedWildcardType awt) { return awt.getUnderlyingType().getSuperBound() == null; } /** Accessor for the element utilities. */ public Elements getElementUtils() { return this.elements; } /** Accessor for the tree utilities. */ public Trees getTreeUtils() { return this.trees; } /** Accessor for the processing environment. */ public ProcessingEnvironment getProcessingEnv() { return this.processingEnv; } /** Matches addition of a constant. */ static final Pattern plusConstant = Pattern.compile(" *\\+ *(-?[0-9]+)$"); /** Matches subtraction of a constant. */ static final Pattern minusConstant = Pattern.compile(" *- *(-?[0-9]+)$"); /** Matches a string whose only parens are at the beginning and end of the string. */ private static Pattern surroundingParensPattern = Pattern.compile("^\\([^()]\\)"); /** * Given an expression, split it into a subexpression and a constant offset. For example: * * <pre>{@code * "a" => <"a", "0"> * "a + 5" => <"a", "5"> * "a + -5" => <"a", "-5"> * "a - 5" => <"a", "-5"> * }</pre> * * There are methods that can only take as input an expression that represents a JavaExpression. * The purpose of this is to pre-process expressions to make those methods more likely to succeed. * * @param expression an expression to remove a constant offset from * @return a sub-expression and a constant offset. The offset is "0" if this routine is unable to * splite the given expression */ // TODO: generalize. There is no reason this couldn't handle arbitrary addition and subtraction // expressions, given the Index Checker's support for OffsetEquation. That might even make its // implementation simpler. public static Pair<String, String> getExpressionAndOffset(String expression) { String expr = expression; String offset = "0"; // Is this normalization necessary? // Remove surrounding whitespace. expr = expr.trim(); // Remove surrounding parentheses. if (surroundingParensPattern.matcher(expr).matches()) { expr = expr.substring(1, expr.length() - 2).trim(); } Matcher mPlus = plusConstant.matcher(expr); Matcher mMinus = minusConstant.matcher(expr); if (mPlus.find()) { expr = expr.substring(0, mPlus.start()); offset = mPlus.group(1); } else if (mMinus.find()) { expr = expr.substring(0, mMinus.start()); offset = negateConstant(mMinus.group(1)); } if (offset.equals("-0")) { offset = "0"; } expr = expr.intern(); offset = offset.intern(); return Pair.of(expr, offset); } /** * Given an expression string, returns its negation. * * @param constantExpression a string representing an integer constant * @return the negation of constantExpression */ // Also see Subsequence.negateString which is similar but more sophisticated. public static String negateConstant(String constantExpression) { if (constantExpression.startsWith("-")) { return constantExpression.substring(1); } else { if (constantExpression.startsWith("+")) { constantExpression = constantExpression.substring(1); } return "-" + constantExpression; } } /** * Returns {@code null} or an annotated type mirror that type argument inference should assume * {@code expressionTree} is assigned to. * * <p>If {@code null} is returned, inference proceeds normally. * * <p>If a type is returned, then inference assumes that {@code expressionTree} was asigned to it. * This biases the inference algorithm toward the annotations in the returned type. In particular, * if the annotations on type variables in invariant positions are a super type of the annotations * inferred, the super type annotations are chosen. * * <p>This implementation returns null, but subclasses may override this method to return a type. * * @param expressionTree an expression which has no assignment context and for which type * arguments need to be inferred * @return {@code null} or an annotated type mirror that inferrence should pretend {@code * expressionTree} is assigned to */ public @Nullable AnnotatedTypeMirror getDummyAssignedTo(ExpressionTree expressionTree) { return null; } /** * Checks that the annotation {@code am} has the name of {@code annoClass}. Values are ignored. * * <p>This method is faster than {@link AnnotationUtils#areSameByClass(AnnotationMirror, Class)} * because it caches the name of the class rather than computing it each time. * * @param am the AnnotationMirror whose class to compare * @param annoClass the class to compare * @return true if annoclass is the class of am */ public boolean areSameByClass(AnnotationMirror am, Class<? extends Annotation> annoClass) { if (!shouldCache) { return AnnotationUtils.areSameByName(am, annoClass.getCanonicalName()); } @SuppressWarnings("nullness") // assume getCanonicalName returns non-null String canonicalName = annotationClassNames.computeIfAbsent(annoClass, Class::getCanonicalName); return AnnotationUtils.areSameByName(am, canonicalName); } /** * Checks that the collection contains the annotation. Using Collection.contains does not always * work, because it does not use areSame for comparison. * * <p>This method is faster than {@link AnnotationUtils#containsSameByClass(Collection, Class)} * because is caches the name of the class rather than computing it each time. * * @param c a collection of AnnotationMirrors * @param anno the annotation class to search for in c * @return true iff c contains anno, according to areSameByClass */ public boolean containsSameByClass( Collection<? extends AnnotationMirror> c, Class<? extends Annotation> anno) { return getAnnotationByClass(c, anno) != null; } /** * Returns the AnnotationMirror in {@code c} that has the same class as {@code anno}. * * <p>This method is faster than {@link AnnotationUtils#getAnnotationByClass(Collection, Class)} * because is caches the name of the class rather than computing it each time. * * @param c a collection of AnnotationMirrors * @param anno the class to search for in c * @return AnnotationMirror with the same class as {@code anno} iff c contains anno, according to * areSameByClass; otherwise, {@code null} */ public @Nullable AnnotationMirror getAnnotationByClass( Collection<? extends AnnotationMirror> c, Class<? extends Annotation> anno) { for (AnnotationMirror an : c) { if (areSameByClass(an, anno)) { return an; } } return null; } /** * Changes the type of {@code rhsATM} when being assigned to a field, for use by whole-program * inference. The default implementation does nothing. * * @param lhsTree the tree for the field whose type will be changed * @param element the element for the field whose type will be changed * @param fieldName the name of the field whose type will be changed * @param rhsATM the type of the expression being assigned to the field, which is side-effected by * this method */ public void wpiAdjustForUpdateField( Tree lhsTree, Element element, String fieldName, AnnotatedTypeMirror rhsATM) {} /** * Changes the type of {@code rhsATM} when being assigned to anything other than a field, for use * by whole-program inference. The default implementation does nothing. * * @param rhsATM the type of the rhs of the pseudo-assignment, which is side-effected by this * method */ public void wpiAdjustForUpdateNonField(AnnotatedTypeMirror rhsATM) {} /** * Side-effects the method or constructor annotations to make any desired changes before writing * to an annotation file. * * @param methodAnnos the method or constructor annotations to modify */ public void prepareMethodForWriting(AMethod methodAnnos) { // This implementation does nothing. } /** * Side-effects the method or constructor annotations to make any desired changes before writing * to an ajava file. * * @param methodAnnos the method or constructor annotations to modify */ public void prepareMethodForWriting( WholeProgramInferenceJavaParserStorage.CallableDeclarationAnnos methodAnnos) { // This implementation does nothing. } /** * Does {@code anno}, which is an {@link org.checkerframework.framework.qual.AnnotatedFor} * annotation, apply to this checker? * * @param annotatedForAnno an {@link AnnotatedFor} annotation * @return whether {@code anno} applies to this checker */ public boolean doesAnnotatedForApplyToThisChecker(AnnotationMirror annotatedForAnno) { List<String> annotatedForCheckers = AnnotationUtils.getElementValueArray( annotatedForAnno, annotatedForValueElement, String.class); for (String annoForChecker : annotatedForCheckers) { if (checker.getUpstreamCheckerNames().contains(annoForChecker) || CheckerMain.matchesFullyQualifiedProcessor( annoForChecker, checker.getUpstreamCheckerNames(), true)) { return true; } } return false; } /** * Get the {@code expression} field/element of the given contract annotation. * * @param contractAnno a {@link RequiresQualifier}, {@link EnsuresQualifier}, or {@link * EnsuresQualifier} * @return the {@code expression} field/element of the given annotation */ public List<String> getContractExpressions(AnnotationMirror contractAnno) { DeclaredType annoType = contractAnno.getAnnotationType(); if (types.isSameType(annoType, requiresQualifierTM)) { return AnnotationUtils.getElementValueArray( contractAnno, requiresQualifierExpressionElement, String.class); } else if (types.isSameType(annoType, ensuresQualifierTM)) { return AnnotationUtils.getElementValueArray( contractAnno, ensuresQualifierExpressionElement, String.class); } else if (types.isSameType(annoType, ensuresQualifierIfTM)) { return AnnotationUtils.getElementValueArray( contractAnno, ensuresQualifierIfExpressionElement, String.class); } else { throw new BugInCF("Not a contract annotation: " + contractAnno); } } /** * Get the {@code value} field/element of the given contract list annotation. * * @param contractListAnno a {@link RequiresQualifier.List}, {@link EnsuresQualifier.List}, or * {@link EnsuresQualifier.List} * @return the {@code value} field/element of the given annotation */ public List<AnnotationMirror> getContractListValues(AnnotationMirror contractListAnno) { DeclaredType annoType = contractListAnno.getAnnotationType(); if (types.isSameType(annoType, requiresQualifierListTM)) { return AnnotationUtils.getElementValueArray( contractListAnno, requiresQualifierListValueElement, AnnotationMirror.class); } else if (types.isSameType(annoType, ensuresQualifierListTM)) { return AnnotationUtils.getElementValueArray( contractListAnno, ensuresQualifierListValueElement, AnnotationMirror.class); } else if (types.isSameType(annoType, ensuresQualifierIfListTM)) { return AnnotationUtils.getElementValueArray( contractListAnno, ensuresQualifierIfListValueElement, AnnotationMirror.class); } else { throw new BugInCF("Not a contract list annotation: " + contractListAnno); } } }
/** * Copyright (c) 2005 The Apereo 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://opensource.org/licenses/ecl2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.webservices; import static org.mockito.Mockito.mock; import lombok.extern.slf4j.Slf4j; import org.sakaiproject.api.app.messageforums.AreaManager; import org.sakaiproject.api.app.messageforums.MessageForumsForumManager; import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager; import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager; import org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager; import org.sakaiproject.api.app.scheduler.SchedulerManager; import org.sakaiproject.assignment.api.AssignmentService; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.event.api.ActivityService; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.event.api.UsageSessionService; import org.sakaiproject.id.api.IdManager; import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.shortenedurl.api.ShortenedUrlService; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.time.api.TimeService; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.tool.assessment.samlite.api.SamLiteService; import org.sakaiproject.user.api.AuthenticationManager; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.PreferencesService; import org.sakaiproject.tool.assessment.shared.impl.questionpool.QuestionPoolServiceImpl; @Slf4j public class MockingAbstractWebService { public static <U extends AbstractWebService> AbstractWebService getMockedAbstractWebService(Class<U> service) { AbstractWebService instance = null; try { instance = service.newInstance(); instance.setAreaManager(mock(AreaManager.class)); instance.setSessionManager(mock(SessionManager.class)); instance.setAuthenticationManager(mock(AuthenticationManager.class)); instance.setAssignmentService(mock(AssignmentService.class)); instance.setAuthzGroupService(mock(AuthzGroupService.class)); instance.setCalendarService(mock(CalendarService.class)); instance.setEventTrackingService(mock(EventTrackingService.class)); instance.setGradebookService(mock(GradebookService.class)); instance.setSecurityService(mock(SecurityService.class)); instance.setServerConfigurationService(mock(ServerConfigurationService.class)); instance.setSiteService(mock(SiteService.class)); instance.setTimeService(mock(TimeService.class)); instance.setToolManager(mock(ToolManager.class)); instance.setUsageSessionService(mock(UsageSessionService.class)); instance.setUserDirectoryService(mock(UserDirectoryService.class)); instance.setContentHostingService(mock(ContentHostingService.class)); instance.setEntityManager(mock(EntityManager.class)); instance.setDiscussionForumManager(mock(DiscussionForumManager.class)); instance.setMessageForumsForumManager(mock(MessageForumsForumManager.class)); instance.setMessageForumsMessageManager(mock(MessageForumsMessageManager.class)); instance.setMessageForumsTypeManager(mock(MessageForumsTypeManager.class)); instance.setThreadLocalManager(mock(ThreadLocalManager.class)); instance.setSchedulerManager(mock(SchedulerManager.class)); instance.setShortenedUrlService(mock(ShortenedUrlService.class)); instance.setSamLiteService(mock(SamLiteService.class)); instance.setIdManager(mock(IdManager.class)); instance.setGradebookExternalAssessmentService(mock(GradebookExternalAssessmentService.class)); instance.setActivityService(mock(ActivityService.class)); instance.setPreferencesService(mock(PreferencesService.class)); instance.setQuestionPoolServiceImpl(mock(QuestionPoolServiceImpl.class)); } catch (InstantiationException | IllegalAccessException e) { log.error(e.getMessage(), e); } return instance; } }
package com.microandroid.modules.sys.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.microandroid.modules.sys.dto.User; import org.springframework.stereotype.Repository; @Repository public interface IUserMapper extends BaseMapper<User> { User selectByUsername(String username); }
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.rxjava3.internal.operators.observable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.internal.disposables.DisposableHelper; import io.reactivex.rxjava3.internal.queue.SpscLinkedArrayQueue; public final class ObservableSkipLastTimed<T> extends AbstractObservableWithUpstream<T, T> { final long time; final TimeUnit unit; final Scheduler scheduler; final int bufferSize; final boolean delayError; public ObservableSkipLastTimed(ObservableSource<T> source, long time, TimeUnit unit, Scheduler scheduler, int bufferSize, boolean delayError) { super(source); this.time = time; this.unit = unit; this.scheduler = scheduler; this.bufferSize = bufferSize; this.delayError = delayError; } @Override public void subscribeActual(Observer<? super T> t) { source.subscribe(new SkipLastTimedObserver<>(t, time, unit, scheduler, bufferSize, delayError)); } static final class SkipLastTimedObserver<T> extends AtomicInteger implements Observer<T>, Disposable { private static final long serialVersionUID = -5677354903406201275L; final Observer<? super T> downstream; final long time; final TimeUnit unit; final Scheduler scheduler; final SpscLinkedArrayQueue<Object> queue; final boolean delayError; Disposable upstream; volatile boolean cancelled; volatile boolean done; Throwable error; SkipLastTimedObserver(Observer<? super T> actual, long time, TimeUnit unit, Scheduler scheduler, int bufferSize, boolean delayError) { this.downstream = actual; this.time = time; this.unit = unit; this.scheduler = scheduler; this.queue = new SpscLinkedArrayQueue<>(bufferSize); this.delayError = delayError; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); } } @Override public void onNext(T t) { final SpscLinkedArrayQueue<Object> q = queue; long now = scheduler.now(unit); q.offer(now, t); drain(); } @Override public void onError(Throwable t) { error = t; done = true; drain(); } @Override public void onComplete() { done = true; drain(); } @Override public void dispose() { if (!cancelled) { cancelled = true; upstream.dispose(); if (getAndIncrement() == 0) { queue.clear(); } } } @Override public boolean isDisposed() { return cancelled; } void drain() { if (getAndIncrement() != 0) { return; } int missed = 1; final Observer<? super T> a = downstream; final SpscLinkedArrayQueue<Object> q = queue; final boolean delayError = this.delayError; final TimeUnit unit = this.unit; final Scheduler scheduler = this.scheduler; final long time = this.time; for (;;) { for (;;) { if (cancelled) { queue.clear(); return; } boolean d = done; Long ts = (Long)q.peek(); boolean empty = ts == null; long now = scheduler.now(unit); if (!empty && ts > now - time) { empty = true; } if (d) { if (delayError) { if (empty) { Throwable e = error; if (e != null) { a.onError(e); } else { a.onComplete(); } return; } } else { Throwable e = error; if (e != null) { queue.clear(); a.onError(e); return; } else if (empty) { a.onComplete(); return; } } } if (empty) { break; } q.poll(); @SuppressWarnings("unchecked") T v = (T)q.poll(); a.onNext(v); } missed = addAndGet(-missed); if (missed == 0) { break; } } } } }
import java.util.Scanner; public class odev_36 { static int pattern(int n) { System.out.print(n + " "); if (n <= 0) { return n; } int temp = pattern(n - 5) + 5; System.out.print(temp + " "); return temp; } public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("N Sayısı : "); int n = input.nextInt(); System.out.print("Çıktısı: "); pattern(n); } }
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * 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 aic-expresso 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.grinder.rewriter.help; import static com.sri.ai.expresso.helper.Expressions.FALSE; import static com.sri.ai.expresso.helper.Expressions.TRUE; import static com.sri.ai.grinder.theory.base.ExpressionConditionedOnLiteralSolutionStep.stepDependingOnLiteral; import com.google.common.annotations.Beta; import com.sri.ai.expresso.api.Expression; import com.sri.ai.grinder.api.Context; import com.sri.ai.grinder.api.ExpressionLiteralSplitterStepSolver.Solution; import com.sri.ai.grinder.api.ExpressionLiteralSplitterStepSolver.Step; import com.sri.ai.grinder.rewriter.api.Rewriter; import com.sri.ai.grinder.rewriter.api.RewriterFromStepMaker; /** * A rewriter that replaces literals by their values according to the context or, * if not defined by the context, splits on them (after a simplification according to a given simplifier). * * @author braz * */ @Beta public class LiteralRewriter implements RewriterFromStepMaker { private Rewriter simplifier; public LiteralRewriter(Rewriter simplifier) { this.simplifier = simplifier; } @Override public Step make(Expression expression, Context context) { if (context.isLiteral(expression)) { Expression completelySimplifiedLiteral = simplifier.apply(expression, context); return stepDependingOnLiteral(completelySimplifiedLiteral, TRUE, FALSE, context); } else { return new Solution(expression); } } }
/* * Copyright 2018-2020 adorsys GmbH & Co KG * * 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 de.adorsys.psd2.xs2a.service; import de.adorsys.psd2.xs2a.core.profile.NotificationSupportedMode; import de.adorsys.psd2.xs2a.core.tpp.TppNotificationData; import de.adorsys.psd2.xs2a.domain.NotificationModeResponseHeaders; import de.adorsys.psd2.xs2a.service.profile.AspspProfileServiceWrapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @Slf4j @Component @RequiredArgsConstructor public class NotificationSupportedModeService { private static final String HEADER_PREFIX = "status="; private static final String MODES_SEPARATOR = ","; private final AspspProfileServiceWrapper aspspProfileServiceWrapper; public NotificationModeResponseHeaders resolveNotificationHeaders(List<NotificationSupportedMode> usedModes) { List<NotificationSupportedMode> supportedModes = aspspProfileServiceWrapper.getNotificationSupportedModes(); if (supportedModes.contains(NotificationSupportedMode.NONE)) { return new NotificationModeResponseHeaders(null, null); } if (CollectionUtils.isEmpty(usedModes)) { log.info("TPP notification URI is not correct or requested modes are not supported!"); return new NotificationModeResponseHeaders(false, null); } return new NotificationModeResponseHeaders(true, getModesAsString(usedModes)); } public TppNotificationData getTppNotificationData(String tppNotificationContentPreferred, String tppNotificationUri) { List<NotificationSupportedMode> modesFromRequest = parseTppNotificationContentPreferred(tppNotificationContentPreferred); return new TppNotificationData(getProcessedNotificationModes(modesFromRequest), tppNotificationUri); } private String getModesAsString(List<NotificationSupportedMode> modes) { StringBuilder modesStr = new StringBuilder(HEADER_PREFIX); modesStr.append(StringUtils.join(modes, MODES_SEPARATOR)); return modesStr.toString(); } private List<NotificationSupportedMode> getProcessedNotificationModes(List<NotificationSupportedMode> modesFromRequest) { List<NotificationSupportedMode> supportedModes = aspspProfileServiceWrapper.getNotificationSupportedModes(); if (supportedModes.contains(NotificationSupportedMode.NONE)) { return Collections.emptyList(); } return modesFromRequest.stream() .filter(supportedModes::contains) .collect(Collectors.toList()); } private List<NotificationSupportedMode> parseTppNotificationContentPreferred(String tppNotificationContentPreferred) { if (StringUtils.isEmpty(tppNotificationContentPreferred)) { return Collections.emptyList(); } String[] modes = tppNotificationContentPreferred.replace(HEADER_PREFIX, "").split(MODES_SEPARATOR); return Arrays.stream(modes) .map(mode -> NotificationSupportedMode.getByValue(mode.trim())) .filter(mode -> !mode.equals(NotificationSupportedMode.NONE)) .collect(Collectors.toList()); } }
package gvgai.ontology.effects.binary; import gvgai.core.content.InteractionContent; import gvgai.core.game.Game; import gvgai.core.vgdl.VGDLSprite; import gvgai.ontology.effects.Effect; import gvgai.tools.Direction; import gvgai.tools.Vector2d; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * Created with IntelliJ IDEA. * User: Diego * Date: 04/11/13 * Time: 15:56 * This is a Java port from Tom Schaul's VGDL - https://github.com/schaul/py-vgdl */ public class WallReverse extends Effect { private double friction; private int lastGameTime; private ArrayList<VGDLSprite> spritesThisCycle; public WallReverse(InteractionContent cnt) { super.inBatch = true; lastGameTime = -1; spritesThisCycle = new ArrayList<VGDLSprite>(); this.parseParameters(cnt); } @Override public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game) { doReverse(sprite1, sprite2.rect, game); sprite1.setRect(sprite1.lastrect); sprite2.setRect(sprite2.lastrect); } public int executeBatch(VGDLSprite sprite1, ArrayList<VGDLSprite> sprite2list, Game game) { int nColls = super.sortBatch(sprite1, sprite2list, game); if(nColls == 1) { doReverse(sprite1, sprite2list.get(0).rect, game); }else{ doReverse(sprite1, collision, game); } sprite1.setRect(sprite1.lastrect); for (VGDLSprite sprite2 : sprite2list) sprite2.setRect(sprite2.lastrect); return nColls; } private void doReverse(VGDLSprite sprite1, Rectangle s2rect, Game g) { boolean collisions[] = super.determineCollision(sprite1, s2rect, g); boolean horizontalBounce = collisions[0]; boolean verticalBounce = collisions[1]; Vector2d v; if(verticalBounce) { v = new Vector2d(sprite1.orientation.x(), 0); }else if(horizontalBounce) { v = new Vector2d(-sprite1.orientation.x(), 0); }else{ //By default: v = new Vector2d(-sprite1.orientation.x(), 0); } double mag = v.mag(); v.normalise(); sprite1.orientation = new Direction(v.x, v.y); sprite1.speed = mag * sprite1.speed; if (sprite1.speed < sprite1.gravity){ sprite1.speed = sprite1.gravity; } } }
/* * 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.directory.studio.connection.ui.dialogs; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * This class get messages from the resources file. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public final class Messages { /** The resource name */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( Messages.class.getPackage().getName() + ".messages" ); /** * A private constructor : this is an utility class */ private Messages() { } /** * Get back a message from the resource file given a key * * @param key The key associated with the message * @return The found message */ public static String getString( String key ) { try { return RESOURCE_BUNDLE.getString( key ); } catch ( MissingResourceException e ) { return '!' + key + '!'; } } }
package com.lpq.mail.server; import com.lpq.mail.dao.LocalMailInfoDao; import com.lpq.mail.dao.MailAccountInfoDao; import com.lpq.mail.dao.MailInfoDao; import com.lpq.mail.dao.UserInfoDao; import com.lpq.mail.entity.*; import lombok.SneakyThrows; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.*; import java.net.Socket; import java.util.Date; import java.util.List; /** * 创建人:肖易安 * 创建时间: 2020/5/23 * 注释:null **/ public class SMTPServerHandler implements Runnable { private Socket socket ; private BufferedWriter out ; private BufferedReader in ; private SqlSessionFactory factory; private SqlSession sqlSession; private LocalMailInfoDao mailInfoDao ; private MailAccountInfoDao mailAccountInfoDao; public SMTPServerHandler(Socket socket) throws IOException { this.socket = socket ; in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); sqlSession = factory.openSession(true); this.mailInfoDao = sqlSession.getMapper(LocalMailInfoDao.class); this.mailAccountInfoDao = sqlSession.getMapper(MailAccountInfoDao.class); } @SneakyThrows @Override public void run() { try{ LocalMailInfo mailInfo = new LocalMailInfo(); String userID = getRequest(in); mailInfo.setFrom(getRequest(in)); String to = getRequest(in); mailInfo.setTo(to); mailInfo.setSubject(getRequest(in)); mailInfo.setContent(getRequest(in)); mailInfo.setDate(new Date()); MailAccountInfoExample example = new MailAccountInfoExample(); example.createCriteria().andMailAccountEqualTo(to); List<MailAccountInfo> mailAccount = mailAccountInfoDao.selectByExample(example); int userId ; if(mailAccount.size() < 1){ userId = -1 ; }else{ userId = mailAccount.get(0).getUserId(); } mailInfo.setUserId(userId); mailInfoDao.insert(mailInfo); sendMessage("250 发送成功" , out); } catch (IOException e) { e.printStackTrace(); sendMessage("554 发送失败" , out); }finally { this.socket = null ; this.in = null ; this.out = null ; } } //接收请求 public String getRequest(BufferedReader in) { String line = null; try { line = in.readLine(); } catch (IOException e) { e.printStackTrace(); } finally { return line; } } //发送信息 public void sendMessage(String str,BufferedWriter out) throws IOException { out.write(str); out.newLine(); out.flush(); } }
package fr.umlv.ditto.graphs; import java.util.Arrays; public class ShortestPathFromOneVertex { private final int source; private final int[] d; private final int[] pi; ShortestPathFromOneVertex(int source, int[] d, int[] pi) { this.source = source; this.d = d; this.pi = pi; } public void printShortestPathTo(int destination) { if(destination > d.length) { throw new IllegalArgumentException("destination is superior than number of vertices ..."); } StringBuilder sb = new StringBuilder(); int nextNode = destination; while(nextNode != source) { sb.append(nextNode).append(" <-- "); nextNode = pi[nextNode]; } sb.append(source); System.out.println(sb.toString()); } public void printShortestPaths() { for (int i = 0; i < d.length; i++) { if (i == source) { continue; } printShortestPathTo(i); } } @Override public String toString() { return source + " " + Arrays.toString(d) + " " + Arrays.toString(pi); } }
package com.greatanan.autoconfigue.annotation; import org.springframework.stereotype.Repository; import java.lang.annotation.*; /** * 二级 {@link Repository} */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @FirstLevelRepository public @interface SecondLevelRepository { String value() default ""; }
package de.taimos.pipeline.aws; /*- * #%L * Pipeline: AWS Steps * %% * Copyright (C) 2016 - 2017 Taimos GmbH * %% * 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. * #L% */ import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl; import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials; import com.cloudbees.plugins.credentials.Credentials; import hudson.model.Result; import java.util.ArrayList; import java.util.List; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.cloudbees.hudson.plugins.folder.AbstractFolder; import com.cloudbees.hudson.plugins.folder.Folder; import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import hudson.EnvVars; import hudson.util.ListBoxModel; /** * Test the behavior of the {@link WithAWSStep} * * @author Allan Burdajewicz */ public class WithAWSStepTest { @ClassRule public static JenkinsRule jenkinsRule = new JenkinsRule(); @Before public void before() throws Exception { List<Credentials> credentials = SystemCredentialsProvider.getInstance().getCredentials(); SystemCredentialsProvider.getInstance().getCredentials().removeAll(credentials); SystemCredentialsProvider.getInstance().save(); } @Test public void testStepWithGlobalCredentials() throws Exception { String globalCredentialsId = "global-aws-creds"; List<String> credentialIds = new ArrayList<>(); credentialIds.add(globalCredentialsId); StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, globalCredentialsId, "test-global-creds", "global-aws-access-key-id", "global-aws-secret-access-key"); SystemCredentialsProvider.getInstance().getCredentials().add(key); SystemCredentialsProvider.getInstance().save(); WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + globalCredentialsId + "') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); } @Test public void testStepWithBasicAndAwsGlobalCredentials() throws Exception { String globalBaseCreds = "global-basic-creds"; String globalAwsCreds = "global-aws-creds"; List<String> credentialIds = new ArrayList<>(); credentialIds.add(globalBaseCreds); StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, globalBaseCreds, "test-global-creds", "global-aws-access-key-id", "global-aws-secret-access-key"); AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL, globalAwsCreds, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description", "Arn::Something:or:Other", "12345678"); SystemCredentialsProvider.getInstance().getCredentials().add(amazonWebServicesCredentials); SystemCredentialsProvider.getInstance().getCredentials().add(key); SystemCredentialsProvider.getInstance().save(); WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithBasicAndAwsGlobalCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + globalBaseCreds + "') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); } @Test public void testStepWithNotFoundGlobalCredentials() throws Exception { String globalBaseCreds = "something-random"; List<String> credentialIds = new ArrayList<>(); credentialIds.add(globalBaseCreds); WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithNotFoundGlobalCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + globalBaseCreds + "') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); jenkinsRule.assertBuildStatus(Result.FAILURE, job.scheduleBuild2(0)); } @Test public void testStepWithGlobalAWSCredentials() throws Exception { String globalCredentialsId = "global-aws-creds"; List<String> credentialIds = new ArrayList<>(); credentialIds.add(globalCredentialsId); AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL, globalCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description", "Arn::Something:or:Other", "12345678"); SystemCredentialsProvider.getInstance().getCredentials().add(amazonWebServicesCredentials); SystemCredentialsProvider.getInstance().save(); WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalAWSCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + globalCredentialsId + "') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); WorkflowRun workflowRun = job.scheduleBuild2(0).get(); jenkinsRule.waitForCompletion(workflowRun); jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun); jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun); } @Test public void testSettingEndpointUrl() throws Exception { final EnvVars envVars = new EnvVars(); envVars.put(AWSClientFactory.AWS_ENDPOINT_URL, "https://minio.mycompany.com"); envVars.put(AWSClientFactory.AWS_REGION, Regions.DEFAULT_REGION.getName()); final AmazonS3ClientBuilder amazonS3ClientBuilder = AWSClientFactory.configureBuilder(AmazonS3ClientBuilder.standard(), envVars); Assert.assertEquals("https://minio.mycompany.com", amazonS3ClientBuilder.getEndpoint().getServiceEndpoint()); } @Test public void testStepWithFolderCredentials() throws Exception { String folderCredentialsId = "folders-aws-creds"; // Create a folder with credentials in its store Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size()); CredentialsStore folderStore = this.getFolderStore(folder); StandardUsernamePasswordCredentials inFolderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, folderCredentialsId, "test-folder-creds", "folder-aws-access-key-id", "folder-aws-secret-access-key"); folderStore.addCredentials(Domain.global(), inFolderCredentials); SystemCredentialsProvider.getInstance().save(); List<String> credentialIds = new ArrayList<>(); credentialIds.add(folderCredentialsId); WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + folderCredentialsId + "') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); } @Test public void testStepWithAWSFolderCredentials() throws Exception { String folderCredentialsId = "folders-aws-creds"; // Create a folder with credentials in its store Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size()); CredentialsStore folderStore = this.getFolderStore(folder); AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL, folderCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description", "Arn::Something:or:Other", "12345678"); folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials); SystemCredentialsProvider.getInstance().save(); List<String> credentialIds = new ArrayList<>(); credentialIds.add(folderCredentialsId); WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithAWSFolderCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + folderCredentialsId + "') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); WorkflowRun workflowRun = job.scheduleBuild2(0).get(); jenkinsRule.waitForCompletion(workflowRun); jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun); jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun); jenkinsRule.assertLogContains("Constructing AWS Credentials", workflowRun); } @Test public void testStepWithAWSIamMFAFolderCredentials() throws Exception { String folderCredentialsId = "folders-aws-creds"; // Create a folder with credentials in its store Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size()); CredentialsStore folderStore = this.getFolderStore(folder); AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL, folderCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description", "Arn::Something:or:Other", "12345678"); folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials); SystemCredentialsProvider.getInstance().save(); List<String> credentialIds = new ArrayList<>(); credentialIds.add(folderCredentialsId); WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithAWSIamMFAFolderCredentials"); job.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withAWS (credentials: '" + folderCredentialsId + "', iamMfaToken: '1234567') {\n" + " echo 'It works!'\n" + " }\n" + "}\n", true) ); WorkflowRun workflowRun = job.scheduleBuild2(0).get(); jenkinsRule.waitForCompletion(workflowRun); jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun); jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun); jenkinsRule.assertLogContains("Constructing AWS Credentials", workflowRun); jenkinsRule.assertLogContains("utilizing MFA Token", workflowRun); } @Test public void testListCredentials() throws Exception { Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size()); CredentialsStore folderStore = this.getFolderStore(folder); StandardUsernamePasswordCredentials folderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "folder-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key"); StandardUsernamePasswordCredentials globalCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "global-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key"); folderStore.addCredentials(Domain.global(), folderCredentials); SystemCredentialsProvider.getInstance().getCredentials().add(globalCredentials); SystemCredentialsProvider.getInstance().save(); WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials"); final WithAWSStep.DescriptorImpl descriptor = jenkinsRule.jenkins.getDescriptorByType(WithAWSStep.DescriptorImpl.class); // 3 options: Root credentials, folder credentials and "none" ListBoxModel list = descriptor.doFillCredentialsItems(job); Assert.assertEquals(3, list.size()); StandardUsernamePasswordCredentials systemCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, "system-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key"); SystemCredentialsProvider.getInstance().getCredentials().add(systemCredentials); // Still 3 options: Root credentials, folder credentials and "none" list = descriptor.doFillCredentialsItems(job); Assert.assertEquals(3, list.size()); } @Test public void testListAWSCredentials() throws Exception { Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size()); CredentialsStore folderStore = this.getFolderStore(folder); AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL, "test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description", "Arn::Something:or:Other", "12345678"); AmazonWebServicesCredentials globalAmazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL, "global-test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description", "Arn::Something:or:Other", "12345678"); folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials); SystemCredentialsProvider.getInstance().getCredentials().add(globalAmazonWebServicesCredentials); SystemCredentialsProvider.getInstance().save(); WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials"); final WithAWSStep.DescriptorImpl descriptor = jenkinsRule.jenkins.getDescriptorByType(WithAWSStep.DescriptorImpl.class); // 3 options: Root credentials, folder credentials and "none" ListBoxModel list = descriptor.doFillCredentialsItems(job); Assert.assertEquals(3, list.size()); StandardUsernamePasswordCredentials systemCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, "system-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key"); SystemCredentialsProvider.getInstance().getCredentials().add(systemCredentials); // Still 3 options: Root credentials, folder credentials and "none" list = descriptor.doFillCredentialsItems(job); Assert.assertEquals(3, list.size()); } private CredentialsStore getFolderStore(AbstractFolder f) { Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f); CredentialsStore folderStore = null; for (CredentialsStore s : stores) { if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) { folderStore = s; break; } } return folderStore; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.repositories.gcs; import com.google.api.gax.retrying.RetrySettings; import com.google.cloud.http.HttpTransportOptions; import com.google.cloud.storage.StorageException; import com.google.cloud.storage.StorageOptions; import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpServer; import fixture.gcs.FakeOAuth2HttpHandler; import org.apache.http.HttpStatus; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.blobstore.BlobContainer; import org.elasticsearch.common.blobstore.BlobPath; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.lucene.store.ByteArrayIndexInput; import org.elasticsearch.common.lucene.store.InputStreamIndexInput; import org.elasticsearch.common.network.InetAddresses; import org.elasticsearch.common.settings.MockSecureSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.CountDown; import org.elasticsearch.mocksocket.MockHttpServer; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.RestUtils; import org.elasticsearch.test.ESTestCase; import org.junit.After; import org.junit.Before; import org.threeten.bp.Duration; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.nio.file.NoSuchFileException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static fixture.gcs.GoogleCloudStorageHttpHandler.getContentRangeEnd; import static fixture.gcs.GoogleCloudStorageHttpHandler.getContentRangeLimit; import static fixture.gcs.GoogleCloudStorageHttpHandler.getContentRangeStart; import static fixture.gcs.GoogleCloudStorageHttpHandler.parseMultipartRequestBody; import static java.nio.charset.StandardCharsets.UTF_8; import static org.elasticsearch.repositories.ESBlobStoreTestCase.randomBytes; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.CREDENTIALS_FILE_SETTING; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.ENDPOINT_SETTING; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.READ_TIMEOUT_SETTING; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.TOKEN_URI_SETTING; import static org.elasticsearch.repositories.gcs.TestUtils.createServiceAccount; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @SuppressForbidden(reason = "use a http server") public class GoogleCloudStorageBlobContainerRetriesTests extends ESTestCase { private HttpServer httpServer; private String httpServerUrl() { assertThat(httpServer, notNullValue()); InetSocketAddress address = httpServer.getAddress(); return "http://" + InetAddresses.toUriString(address.getAddress()) + ":" + address.getPort(); } @Before public void setUp() throws Exception { httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); httpServer.start(); super.setUp(); } @After public void tearDown() throws Exception { httpServer.stop(0); super.tearDown(); } private BlobContainer createBlobContainer(final int maxRetries, final @Nullable TimeValue readTimeout) { final Settings.Builder clientSettings = Settings.builder(); final String client = randomAlphaOfLength(5).toLowerCase(Locale.ROOT); clientSettings.put(ENDPOINT_SETTING.getConcreteSettingForNamespace(client).getKey(), httpServerUrl()); clientSettings.put(TOKEN_URI_SETTING.getConcreteSettingForNamespace(client).getKey(), httpServerUrl() + "/token"); if (readTimeout != null) { clientSettings.put(READ_TIMEOUT_SETTING.getConcreteSettingForNamespace(client).getKey(), readTimeout); } final MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setFile(CREDENTIALS_FILE_SETTING.getConcreteSettingForNamespace(client).getKey(), createServiceAccount(random())); clientSettings.setSecureSettings(secureSettings); final GoogleCloudStorageService service = new GoogleCloudStorageService() { @Override StorageOptions createStorageOptions(final GoogleCloudStorageClientSettings clientSettings, final HttpTransportOptions httpTransportOptions) { StorageOptions options = super.createStorageOptions(clientSettings, httpTransportOptions); return options.toBuilder() .setRetrySettings(RetrySettings.newBuilder() .setTotalTimeout(options.getRetrySettings().getTotalTimeout()) .setInitialRetryDelay(Duration.ofMillis(10L)) .setRetryDelayMultiplier(options.getRetrySettings().getRetryDelayMultiplier()) .setMaxRetryDelay(Duration.ofSeconds(1L)) .setMaxAttempts(maxRetries) .setJittered(false) .setInitialRpcTimeout(options.getRetrySettings().getInitialRpcTimeout()) .setRpcTimeoutMultiplier(options.getRetrySettings().getRpcTimeoutMultiplier()) .setMaxRpcTimeout(options.getRetrySettings().getMaxRpcTimeout()) .build()) .build(); } }; service.refreshAndClearCache(GoogleCloudStorageClientSettings.load(clientSettings.build())); final List<HttpContext> httpContexts = Arrays.asList( // Auth httpServer.createContext("/token", new FakeOAuth2HttpHandler()), // Does bucket exists? httpServer.createContext("/storage/v1/b/bucket", exchange -> { byte[] response = ("{\"kind\":\"storage#bucket\",\"name\":\"bucket\",\"id\":\"0\"}").getBytes(UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8"); exchange.sendResponseHeaders(HttpStatus.SC_OK, response.length); exchange.getResponseBody().write(response); exchange.close(); }) ); final GoogleCloudStorageBlobStore blobStore = new GoogleCloudStorageBlobStore("bucket", client, service); httpContexts.forEach(httpContext -> httpServer.removeContext(httpContext)); return new GoogleCloudStorageBlobContainer(BlobPath.cleanPath(), blobStore); } public void testReadNonexistentBlobThrowsNoSuchFileException() { final BlobContainer blobContainer = createBlobContainer(between(1, 5), null); final Exception exception = expectThrows(NoSuchFileException.class, () -> Streams.readFully(blobContainer.readBlob("read_nonexistent_blob"))); assertThat(exception.getMessage().toLowerCase(Locale.ROOT), containsString("blob [read_nonexistent_blob] does not exist")); } public void testReadBlobWithRetries() throws Exception { final int maxRetries = randomIntBetween(2, 10); final CountDown countDown = new CountDown(maxRetries); final byte[] bytes = randomBlobContent(); httpServer.createContext("/download/storage/v1/b/bucket/o/read_blob_max_retries", exchange -> { Streams.readFully(exchange.getRequestBody()); if (countDown.countDown()) { exchange.getResponseHeaders().add("Content-Type", "application/octet-stream"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), bytes.length); exchange.getResponseBody().write(bytes); exchange.close(); return; } exchange.sendResponseHeaders(HttpStatus.SC_INTERNAL_SERVER_ERROR, -1); if (randomBoolean()) { exchange.close(); } }); final BlobContainer blobContainer = createBlobContainer(maxRetries, TimeValue.timeValueMillis(between(100, 500))); try (InputStream inputStream = blobContainer.readBlob("read_blob_max_retries")) { assertArrayEquals(bytes, BytesReference.toBytes(Streams.readFully(inputStream))); assertThat(countDown.isCountedDown(), is(true)); } } public void testReadBlobWithReadTimeouts() { final int maxRetries = randomIntBetween(1, 3); final BlobContainer blobContainer = createBlobContainer(maxRetries, TimeValue.timeValueMillis(between(100, 200))); // HTTP server does not send a response httpServer.createContext("/download/storage/v1/b/bucket/o/read_blob_unresponsive", exchange -> {}); StorageException storageException = expectThrows(StorageException.class, () -> Streams.readFully(blobContainer.readBlob("read_blob_unresponsive"))); assertThat(storageException.getMessage().toLowerCase(Locale.ROOT), containsString("read timed out")); assertThat(storageException.getCause(), instanceOf(SocketTimeoutException.class)); // HTTP server sends a partial response final byte[] bytes = randomBlobContent(); httpServer.createContext("/download/storage/v1/b/bucket/o/read_blob_incomplete", exchange -> { exchange.getResponseHeaders().add("Content-Type", "text/plain; charset=utf-8"); exchange.sendResponseHeaders(HttpStatus.SC_OK, bytes.length); final int bytesToSend = randomIntBetween(0, bytes.length - 1); if (bytesToSend > 0) { exchange.getResponseBody().write(bytes, 0, bytesToSend); } if (randomBoolean()) { exchange.getResponseBody().flush(); } }); storageException = expectThrows(StorageException.class, () -> { try (InputStream stream = blobContainer.readBlob("read_blob_incomplete")) { Streams.readFully(stream); } }); assertThat(storageException.getMessage().toLowerCase(Locale.ROOT), containsString("read timed out")); assertThat(storageException.getCause(), instanceOf(SocketTimeoutException.class)); } public void testWriteBlobWithRetries() throws Exception { final int maxRetries = randomIntBetween(2, 10); final CountDown countDown = new CountDown(maxRetries); final byte[] bytes = randomBlobContent(); httpServer.createContext("/upload/storage/v1/b/bucket/o", exchange -> { assertThat(exchange.getRequestURI().getQuery(), containsString("uploadType=multipart")); if (countDown.countDown()) { Optional<Tuple<String, BytesArray>> content = parseMultipartRequestBody(exchange.getRequestBody()); assertThat(content.isPresent(), is(true)); assertThat(content.get().v1(), equalTo("write_blob_max_retries")); if (Objects.deepEquals(bytes, content.get().v2().array())) { byte[] response = ("{\"bucket\":\"bucket\",\"name\":\"" + content.get().v1() + "\"}").getBytes(UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } else { exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, -1); } exchange.close(); return; } if (randomBoolean()) { if (randomBoolean()) { Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.max(1, bytes.length - 1))]); } else { Streams.readFully(exchange.getRequestBody()); exchange.sendResponseHeaders(HttpStatus.SC_INTERNAL_SERVER_ERROR, -1); } } exchange.close(); }); final BlobContainer blobContainer = createBlobContainer(maxRetries, null); try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", bytes), bytes.length)) { blobContainer.writeBlob("write_blob_max_retries", stream, bytes.length, false); } assertThat(countDown.isCountedDown(), is(true)); } public void testWriteBlobWithReadTimeouts() { final byte[] bytes = randomByteArrayOfLength(randomIntBetween(10, 128)); final TimeValue readTimeout = TimeValue.timeValueMillis(randomIntBetween(100, 500)); final BlobContainer blobContainer = createBlobContainer(1, readTimeout); // HTTP server does not send a response httpServer.createContext("/upload/storage/v1/b/bucket/o", exchange -> { if (randomBoolean()) { if (randomBoolean()) { Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, bytes.length - 1)]); } else { Streams.readFully(exchange.getRequestBody()); } } }); Exception exception = expectThrows(StorageException.class, () -> { try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", bytes), bytes.length)) { blobContainer.writeBlob("write_blob_timeout", stream, bytes.length, false); } }); assertThat(exception.getMessage().toLowerCase(Locale.ROOT), containsString("read timed out")); assertThat(exception.getCause(), instanceOf(SocketTimeoutException.class)); assertThat(exception.getCause().getMessage().toLowerCase(Locale.ROOT), containsString("read timed out")); } public void testWriteLargeBlob() throws IOException { // See {@link BaseWriteChannel#DEFAULT_CHUNK_SIZE} final int defaultChunkSize = 8 * 256 * 1024; final int nbChunks = randomIntBetween(3, 5); final int lastChunkSize = randomIntBetween(1, defaultChunkSize - 1); final int totalChunks = nbChunks + 1; final byte[] data = randomBytes(defaultChunkSize * nbChunks + lastChunkSize); assertThat(data.length, greaterThan(GoogleCloudStorageBlobStore.LARGE_BLOB_THRESHOLD_BYTE_SIZE)); logger.debug("resumable upload is composed of [{}] total chunks ([{}] chunks of length [{}] and last chunk of length [{}]", totalChunks, nbChunks, defaultChunkSize, lastChunkSize); final int nbErrors = 2; // we want all requests to fail at least once final AtomicInteger countInits = new AtomicInteger(nbErrors); final AtomicInteger countUploads = new AtomicInteger(nbErrors * totalChunks); final AtomicBoolean allow410Gone = new AtomicBoolean(randomBoolean()); final AtomicBoolean allowReadTimeout = new AtomicBoolean(rarely()); final int wrongChunk = randomIntBetween(1, totalChunks); final AtomicReference<String> sessionUploadId = new AtomicReference<>(UUIDs.randomBase64UUID()); logger.debug("starting with resumable upload id [{}]", sessionUploadId.get()); httpServer.createContext("/upload/storage/v1/b/bucket/o", exchange -> { final Map<String, String> params = new HashMap<>(); RestUtils.decodeQueryString(exchange.getRequestURI().getQuery(), 0, params); assertThat(params.get("uploadType"), equalTo("resumable")); if ("POST".equals(exchange.getRequestMethod())) { assertThat(params.get("name"), equalTo("write_large_blob")); if (countInits.decrementAndGet() <= 0) { byte[] response = Streams.readFully(exchange.getRequestBody()).utf8ToString().getBytes(UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.getResponseHeaders().add("Location", httpServerUrl() + "/upload/storage/v1/b/bucket/o?uploadType=resumable&upload_id=" + sessionUploadId.get()); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); exchange.close(); return; } if (allowReadTimeout.get()) { assertThat(wrongChunk, greaterThan(0)); return; } } else if ("PUT".equals(exchange.getRequestMethod())) { final String uploadId = params.get("upload_id"); if (uploadId.equals(sessionUploadId.get()) == false) { logger.debug("session id [{}] is gone", uploadId); assertThat(wrongChunk, greaterThan(0)); Streams.readFully(exchange.getRequestBody()); exchange.sendResponseHeaders(HttpStatus.SC_GONE, -1); exchange.close(); return; } if (countUploads.get() == (wrongChunk * nbErrors)) { if (allowReadTimeout.compareAndSet(true, false)) { assertThat(wrongChunk, greaterThan(0)); return; } if (allow410Gone.compareAndSet(true, false)) { final String newUploadId = UUIDs.randomBase64UUID(random()); logger.debug("chunk [{}] gone, updating session ids [{} -> {}]", wrongChunk, sessionUploadId.get(), newUploadId); sessionUploadId.set(newUploadId); // we must reset the counters because the whole object upload will be retried countInits.set(nbErrors); countUploads.set(nbErrors * totalChunks); Streams.readFully(exchange.getRequestBody()); exchange.sendResponseHeaders(HttpStatus.SC_GONE, -1); exchange.close(); return; } } final String range = exchange.getRequestHeaders().getFirst("Content-Range"); assertTrue(Strings.hasLength(range)); if (countUploads.decrementAndGet() % 2 == 0) { final ByteArrayOutputStream requestBody = new ByteArrayOutputStream(); final long bytesRead = Streams.copy(exchange.getRequestBody(), requestBody); assertThat(Math.toIntExact(bytesRead), anyOf(equalTo(defaultChunkSize), equalTo(lastChunkSize))); final int rangeStart = getContentRangeStart(range); final int rangeEnd = getContentRangeEnd(range); assertThat(rangeEnd + 1 - rangeStart, equalTo(Math.toIntExact(bytesRead))); assertArrayEquals(Arrays.copyOfRange(data, rangeStart, rangeEnd + 1), requestBody.toByteArray()); final Integer limit = getContentRangeLimit(range); if (limit != null) { exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1); exchange.close(); return; } else { exchange.getResponseHeaders().add("Range", String.format(Locale.ROOT, "bytes=%d/%d", rangeStart, rangeEnd)); exchange.getResponseHeaders().add("Content-Length", "0"); exchange.sendResponseHeaders(308 /* Resume Incomplete */, -1); exchange.close(); return; } } } // read all the request body, otherwise the SDK client throws a non-retryable StorageException Streams.readFully(exchange.getRequestBody()); if (randomBoolean()) { exchange.sendResponseHeaders(HttpStatus.SC_INTERNAL_SERVER_ERROR, -1); } exchange.close(); }); final TimeValue readTimeout = allowReadTimeout.get() ? TimeValue.timeValueSeconds(3) : null; final BlobContainer blobContainer = createBlobContainer(nbErrors + 1, readTimeout); try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", data), data.length)) { blobContainer.writeBlob("write_large_blob", stream, data.length, false); } assertThat(countInits.get(), equalTo(0)); assertThat(countUploads.get(), equalTo(0)); assertThat(allow410Gone.get(), is(false)); } private static byte[] randomBlobContent() { return randomByteArrayOfLength(randomIntBetween(1, frequently() ? 512 : 1 << 20)); // rarely up to 1mb } }
package ch.heigvd.amt.txejb.services; import ch.heigvd.amt.txejb.model.Engine; import ch.heigvd.amt.txejb.model.Tire; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public class TireDAO implements TireDAOLocal { private final String queryInsertTire = "INSERT INTO `tires` (`id`, `orderId`) VALUES (NULL, ?)"; private final String queryGetInsertedTireId = "SELECT LAST_INSERT_ID()"; private final String queryCount = "SELECT count(*) FROM `tires`"; @Resource(name = "jdbc/AMTCars") DataSource dataSource; @Override public Tire[] buildTires(UUID orderId, int numberOfTires) { Tire[] result = new Tire[numberOfTires]; for (int i = 0; i < numberOfTires; i++) { result[i] = buildTire(orderId); } return result; } public long count() { try (Connection connection = dataSource.getConnection()) { ResultSet rs = connection .prepareStatement(queryCount) .executeQuery(); rs.next(); return rs.getLong(1); } catch (SQLException e) { throw new RuntimeException(e); } } private Tire buildTire(UUID orderId) { Tire tire = new Tire(); PreparedStatement statement2; try (Connection connection = dataSource.getConnection()) { PreparedStatement statement = connection.prepareStatement(queryInsertTire); statement.setString(1, orderId.toString()); statement.execute(); statement2 = connection.prepareStatement(queryGetInsertedTireId); ResultSet rs = statement2.executeQuery(); rs.next(); Long engineId = rs.getLong(1); tire.setId(engineId); tire.setOderId(orderId); return tire; } catch (SQLException e) { throw new RuntimeException(e); } } }
package com.qingchi.server.controller; import com.qingchi.base.common.ResultVO; import com.qingchi.base.constant.ErrorCode; import com.qingchi.base.constant.ErrorMsg; import com.qingchi.base.constant.PlatformType; import com.qingchi.base.model.account.AccountDO; import com.qingchi.base.model.user.UserDO; import com.qingchi.base.model.user.UserLogDO; import com.qingchi.base.platform.weixin.WxDecode; import com.qingchi.base.platform.weixin.login.AppLoginVO; import com.qingchi.base.platform.weixin.login.LoginDataVO; import com.qingchi.base.platform.weixin.login.LoginResult; import com.qingchi.base.repository.user.AccountRepository; import com.qingchi.base.repository.user.TokenRepository; import com.qingchi.base.repository.log.UserLogRepository; import com.qingchi.base.repository.user.UserRepository; import com.qingchi.base.service.UserService; import com.qingchi.base.utils.JsonUtils; import com.qingchi.base.utils.QingLogger; import com.qingchi.server.model.PhoneNumVO; import com.qingchi.server.model.UserDetailVO; import com.qingchi.server.service.LoginService; import com.qingchi.server.store.UserLogStoreUtils; import org.apache.commons.lang.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import javax.validation.Valid; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author qinkaiyuan * @date 2019-02-17 14:14 */ @RestController @RequestMapping("user") public class MiniAppLoginController { @Resource private TokenRepository tokenRepository; @Resource private AccountRepository accountRepository; @Resource private UserService userService; @Resource private RestTemplate restTemplate; @Resource private UserRepository userRepository; @Resource private UserLogRepository userLogRepository; @Resource private LoginService loginService; /** * 微信小程序界面点击绑定手机号触发 * @param bindPhoneVO * @param user * @return */ @PostMapping("bindPhoneNum") @ResponseBody public ResultVO<?> bindPhoneNum(@RequestBody LoginDataVO bindPhoneVO, UserDO user) { return bindPhone(bindPhoneVO, user); } /** * 这个是手机号直接绑定的 * * @param bindPhoneVO * @param user * @return */ @PostMapping("bindPhoneNum2") @ResponseBody public ResultVO<?> bindPhoneNum2(@RequestBody LoginDataVO bindPhoneVO, UserDO user) { return bindPhone(bindPhoneVO, user); } private ResultVO<?> bindPhone(LoginDataVO bindPhoneVO, UserDO user) { String userPhoneNum = user.getPhoneNum(); //判断用户是否已绑定手机号 if (StringUtils.isNotEmpty(userPhoneNum)) { QingLogger.logger.warn("您已绑定手机号,不可重复绑定:{}", user.getId()); UserLogStoreUtils.save(new UserLogDO("您已绑定手机号,不可重复绑定", user, userPhoneNum)); return new ResultVO<>("您已绑定手机号,不可重复绑定"); } Boolean sessionEnable = bindPhoneVO.getSessionEnable(); Optional<AccountDO> accountDOOptional = accountRepository.findOneByUserId(user.getId()); if (!accountDOOptional.isPresent()) { return new ResultVO<>(ErrorCode.SYSTEM_ERROR); } AccountDO accountDO = accountDOOptional.get(); Date curDate = new Date(); String sessionKey = accountDO.getSessionKey(); //如果过期不可用 或者 为空 if (sessionEnable) { if (StringUtils.isEmpty(sessionKey)) { return new ResultVO<>(ErrorCode.CUSTOM_ERROR); } } else { //session未失效,从数据库中获取 //session失效 //校验各个参数 String provider = bindPhoneVO.getProvider(); if (StringUtils.isEmpty(provider)) { provider = bindPhoneVO.getLoginType(); } if (StringUtils.isEmpty(bindPhoneVO.getCode()) || StringUtils.isEmpty(provider) ) { QingLogger.logger.error("触发了不应该出现的异常,入参为空"); return new ResultVO<>(ErrorCode.SYSTEM_ERROR); } //获取key ResultVO<LoginResult> resultVO = loginService.getMpPlatformInfo(provider, bindPhoneVO); if (resultVO.hasError()) { return resultVO; } LoginResult loginResult = resultVO.getData(); sessionKey = loginResult.getSession_key(); //更新数据库的key accountDO.setUserId(user.getId()); accountDO.setUpdateTime(curDate); accountDO.setSessionKey(sessionKey); accountRepository.save(accountDO); } ResultVO<String> resultVO1 = new ResultVO<>(); String phoneJson; try { phoneJson = WxDecode.decrypt(bindPhoneVO.getEncryptedData(), sessionKey, bindPhoneVO.getIv()); } catch (Exception e) { resultVO1.setData("再点击一次绑定按钮即可完成绑定"); return resultVO1; } if (StringUtils.isEmpty(phoneJson)) { QingLogger.logger.error("系统异常,不该走到这里"); resultVO1.setData("再点击一次绑定按钮即可完成绑定"); return resultVO1; } try { PhoneNumVO phoneNumVO = JsonUtils.objectMapper.readValue(phoneJson, PhoneNumVO.class); String phoneNum = phoneNumVO.getPurePhoneNumber(); Optional<UserDO> userDOOptional = userRepository.findFirstByPhoneNumOrderByIdAsc(phoneNum); if (userDOOptional.isPresent()) { UserLogStoreUtils.save(new UserLogDO("此手机号已被绑定,请更换其他手机号", user, phoneNum)); return new ResultVO<>("此手机号已被绑定,请更换其他手机号," + ErrorMsg.CONTACT_SERVICE); } user.setPhoneCountryCode(phoneNumVO.getCountryCode()); user.setPhoneNum(phoneNum); user.setUpdateTime(new Date()); user = userRepository.save(user); } catch (Exception e) { e.printStackTrace(); } Map<String, Object> map = new HashMap<>(); map.put("user", new UserDetailVO(user, true)); map.put("hint", "绑定手机号成功"); return new ResultVO<>(map); } /** * 登录接口,登录后返回用户的token * toDO 还没有做百度和头条平台的适配 * * @param loginVO * @return */ @PostMapping("appLogin") public ResultVO<?> appLogin(@RequestBody @Valid AppLoginVO loginVO) { System.out.println(loginVO); return new ResultVO<>(); } /** * 登录接口,登录后返回用户的token * toDO 还没有做百度和头条平台的适配 * * @param loginVO * @return */ @PostMapping("miniAppLogin") public ResultVO<?> miniAppLogin(@RequestBody LoginDataVO loginVO) { String provider = loginVO.getProvider(); if (StringUtils.isEmpty(provider)) { provider = loginVO.getLoginType(); } //需要手动赋值 loginVO.setPlatform(PlatformType.mp); return loginService.mpPlatformLogin(provider, loginVO); } }
/** * CHANGELOG * * Jul 5, 2013 schaat - File created * */ package modules.interfaces; import java.util.ArrayList; import base.datatypes.clsEmotion; /** * DOCUMENT (schaat) - insert description * * @author schaat * Jul 5, 2013, 2:37:47 PM * */ public interface I6_14_receive { public void receive_I6_14(ArrayList<clsEmotion> poEmotions_Input); }
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ddmlib; import com.android.ddmlib.AdbHelper.AdbResponse; import com.android.ddmlib.ClientData.DebuggerStatus; import com.android.ddmlib.DebugPortManager.IDebugPortProvider; import com.android.ddmlib.IDevice.DeviceState; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; 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; /** * A Device monitor. This connects to the Android Debug Bridge and get device and * debuggable process information from it. */ final class DeviceMonitor { private byte[] mLengthBuffer = new byte[4]; private byte[] mLengthBuffer2 = new byte[4]; private boolean mQuit = false; private AndroidDebugBridge mServer; private SocketChannel mMainAdbConnection = null; private boolean mMonitoring = false; private int mConnectionAttempt = 0; private int mRestartAttemptCount = 0; private boolean mInitialDeviceListDone = false; private Selector mSelector; private final ArrayList<Device> mDevices = new ArrayList<Device>(); private final ArrayList<Integer> mDebuggerPorts = new ArrayList<Integer>(); private final HashMap<Client, Integer> mClientsToReopen = new HashMap<Client, Integer>(); /** * Creates a new {@link DeviceMonitor} object and links it to the running * {@link AndroidDebugBridge} object. * @param server the running {@link AndroidDebugBridge}. */ DeviceMonitor(AndroidDebugBridge server) { mServer = server; mDebuggerPorts.add(DdmPreferences.getDebugPortBase()); } /** * Starts the monitoring. */ void start() { new Thread("Device List Monitor") { //$NON-NLS-1$ @Override public void run() { deviceMonitorLoop(); } }.start(); } /** * Stops the monitoring. */ void stop() { mQuit = true; // wakeup the main loop thread by closing the main connection to adb. try { if (mMainAdbConnection != null) { mMainAdbConnection.close(); } } catch (IOException e1) { } // wake up the secondary loop by closing the selector. if (mSelector != null) { mSelector.wakeup(); } } /** * Returns if the monitor is currently connected to the debug bridge server. * @return */ boolean isMonitoring() { return mMonitoring; } int getConnectionAttemptCount() { return mConnectionAttempt; } int getRestartAttemptCount() { return mRestartAttemptCount; } /** * Returns the devices. */ Device[] getDevices() { synchronized (mDevices) { return mDevices.toArray(new Device[mDevices.size()]); } } boolean hasInitialDeviceList() { return mInitialDeviceListDone; } AndroidDebugBridge getServer() { return mServer; } void addClientToDropAndReopen(Client client, int port) { synchronized (mClientsToReopen) { Log.d("DeviceMonitor", "Adding " + client + " to list of client to reopen (" + port +")."); if (mClientsToReopen.get(client) == null) { mClientsToReopen.put(client, port); } } mSelector.wakeup(); } /** * Monitors the devices. This connects to the Debug Bridge */ private void deviceMonitorLoop() { do { try { if (mMainAdbConnection == null) { Log.d("DeviceMonitor", "Opening adb connection"); mMainAdbConnection = openAdbConnection(); if (mMainAdbConnection == null) { mConnectionAttempt++; Log.e("DeviceMonitor", "Connection attempts: " + mConnectionAttempt); if (mConnectionAttempt > 10) { if (mServer.startAdb() == false) { mRestartAttemptCount++; Log.e("DeviceMonitor", "adb restart attempts: " + mRestartAttemptCount); } else { mRestartAttemptCount = 0; } } waitABit(); } else { Log.d("DeviceMonitor", "Connected to adb for device monitoring"); mConnectionAttempt = 0; } } if (mMainAdbConnection != null && mMonitoring == false) { mMonitoring = sendDeviceListMonitoringRequest(); } if (mMonitoring) { // read the length of the incoming message int length = readLength(mMainAdbConnection, mLengthBuffer); if (length >= 0) { // read the incoming message processIncomingDeviceData(length); // flag the fact that we have build the list at least once. mInitialDeviceListDone = true; } } } catch (AsynchronousCloseException ace) { // this happens because of a call to Quit. We do nothing, and the loop will break. } catch (TimeoutException ioe) { handleExpectioninMonitorLoop(ioe); } catch (IOException ioe) { handleExpectioninMonitorLoop(ioe); } } while (mQuit == false); } private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { // we can safely ignore that one. } mMainAdbConnection = null; // remove all devices from list // because we are going to call mServer.deviceDisconnected which will acquire this // lock we lock it first, so that the AndroidDebugBridge lock is always locked // first. synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { for (int n = mDevices.size() - 1; n >= 0; n--) { Device device = mDevices.get(0); removeDevice(device); mServer.deviceDisconnected(device); } } } } } } /** * Sleeps for a little bit. */ private void waitABit() { try { Thread.sleep(1000); } catch (InterruptedException e1) { } } /** * Attempts to connect to the debug bridge server. * @return a connect socket if success, null otherwise */ private SocketChannel openAdbConnection() { Log.d("DeviceMonitor", "Connecting to adb for Device List Monitoring..."); SocketChannel adbChannel = null; try { adbChannel = SocketChannel.open(AndroidDebugBridge.getSocketAddress()); adbChannel.socket().setTcpNoDelay(true); } catch (IOException e) { } return adbChannel; } /** * * @return * @throws IOException */ private boolean sendDeviceListMonitoringRequest() throws TimeoutException, IOException { byte[] request = AdbHelper.formAdbRequest("host:track-devices"); //$NON-NLS-1$ try { AdbHelper.write(mMainAdbConnection, request); AdbResponse resp = AdbHelper.readAdbResponse(mMainAdbConnection, false /* readDiagString */); if (resp.okay == false) { // request was refused by adb! Log.e("DeviceMonitor", "adb refused request: " + resp.message); } return resp.okay; } catch (IOException e) { Log.e("DeviceMonitor", "Sending Tracking request failed!"); mMainAdbConnection.close(); throw e; } } /** * Processes an incoming device message from the socket * @param socket * @param length * @throws IOException */ private void processIncomingDeviceData(int length) throws IOException { ArrayList<Device> list = new ArrayList<Device>(); if (length > 0) { byte[] buffer = new byte[length]; String result = read(mMainAdbConnection, buffer); String[] devices = result.split("\n"); //$NON-NLS-1$ for (String d : devices) { String[] param = d.split("\t"); //$NON-NLS-1$ if (param.length == 2) { // new adb uses only serial numbers to identify devices Device device = new Device(this, param[0] /*serialnumber*/, DeviceState.getState(param[1])); //add the device to the list list.add(device); } } } // now merge the new devices with the old ones. updateDevices(list); } /** * Updates the device list with the new items received from the monitoring service. */ private void updateDevices(ArrayList<Device> newList) { // because we are going to call mServer.deviceDisconnected which will acquire this lock // we lock it first, so that the AndroidDebugBridge lock is always locked first. synchronized (AndroidDebugBridge.getLock()) { // array to store the devices that must be queried for information. // it's important to not do it inside the synchronized loop as this could block // the whole workspace (this lock is acquired during build too). ArrayList<Device> devicesToQuery = new ArrayList<Device>(); synchronized (mDevices) { // For each device in the current list, we look for a matching the new list. // * if we find it, we update the current object with whatever new information // there is // (mostly state change, if the device becomes ready, we query for build info). // We also remove the device from the new list to mark it as "processed" // * if we do not find it, we remove it from the current list. // Once this is done, the new list contains device we aren't monitoring yet, so we // add them to the list, and start monitoring them. for (int d = 0 ; d < mDevices.size() ;) { Device device = mDevices.get(d); // look for a similar device in the new list. int count = newList.size(); boolean foundMatch = false; for (int dd = 0 ; dd < count ; dd++) { Device newDevice = newList.get(dd); // see if it matches in id and serial number. if (newDevice.getSerialNumber().equals(device.getSerialNumber())) { foundMatch = true; // update the state if needed. if (device.getState() != newDevice.getState()) { device.setState(newDevice.getState()); device.update(Device.CHANGE_STATE); // if the device just got ready/online, we need to start // monitoring it. if (device.isOnline()) { if (AndroidDebugBridge.getClientSupport() == true) { if (startMonitoringDevice(device) == false) { Log.e("DeviceMonitor", "Failed to start monitoring " + device.getSerialNumber()); } } if (device.getPropertyCount() == 0) { devicesToQuery.add(device); } } } // remove the new device from the list since it's been used newList.remove(dd); break; } } if (foundMatch == false) { // the device is gone, we need to remove it, and keep current index // to process the next one. removeDevice(device); mServer.deviceDisconnected(device); } else { // process the next one d++; } } // at this point we should still have some new devices in newList, so we // process them. for (Device newDevice : newList) { // add them to the list mDevices.add(newDevice); mServer.deviceConnected(newDevice); // start monitoring them. if (AndroidDebugBridge.getClientSupport() == true) { if (newDevice.isOnline()) { startMonitoringDevice(newDevice); } } // look for their build info. if (newDevice.isOnline()) { devicesToQuery.add(newDevice); } } } // query the new devices for info. for (Device d : devicesToQuery) { queryNewDeviceForInfo(d); } } newList.clear(); } private void removeDevice(Device device) { device.clearClientList(); mDevices.remove(device); SocketChannel channel = device.getClientMonitoringSocket(); if (channel != null) { try { channel.close(); } catch (IOException e) { // doesn't really matter if the close fails. } } } /** * Queries a device for its build info. * @param device the device to query. */ private void queryNewDeviceForInfo(Device device) { // TODO: do this in a separate thread. try { // first get the list of properties. device.executeShellCommand(GetPropReceiver.GETPROP_COMMAND, new GetPropReceiver(device)); queryNewDeviceForMountingPoint(device, IDevice.MNT_EXTERNAL_STORAGE); queryNewDeviceForMountingPoint(device, IDevice.MNT_DATA); queryNewDeviceForMountingPoint(device, IDevice.MNT_ROOT); // now get the emulator Virtual Device name (if applicable). if (device.isEmulator()) { EmulatorConsole console = EmulatorConsole.getConsole(device); if (console != null) { device.setAvdName(console.getAvdName()); } } } catch (TimeoutException e) { Log.w("DeviceMonitor", String.format("Connection timeout getting info for device %s", device.getSerialNumber())); } catch (AdbCommandRejectedException e) { // This should never happen as we only do this once the device is online. Log.w("DeviceMonitor", String.format( "Adb rejected command to get device %1$s info: %2$s", device.getSerialNumber(), e.getMessage())); } catch (ShellCommandUnresponsiveException e) { Log.w("DeviceMonitor", String.format( "Adb shell command took too long returning info for device %s", device.getSerialNumber())); } catch (IOException e) { Log.w("DeviceMonitor", String.format( "IO Error getting info for device %s", device.getSerialNumber())); } } private void queryNewDeviceForMountingPoint(final Device device, final String name) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException { device.executeShellCommand("echo $" + name, new MultiLineReceiver() { //$NON-NLS-1$ @Override public boolean isCancelled() { return false; } @Override public void processNewLines(String[] lines) { for (String line : lines) { if (line.length() > 0) { // this should be the only one. device.setMountingPoint(name, line); } } } }); } /** * Starts a monitoring service for a device. * @param device the device to monitor. * @return true if success. */ private boolean startMonitoringDevice(Device device) { SocketChannel socketChannel = openAdbConnection(); if (socketChannel != null) { try { boolean result = sendDeviceMonitoringRequest(socketChannel, device); if (result) { if (mSelector == null) { startDeviceMonitorThread(); } device.setClientMonitoringSocket(socketChannel); synchronized (mDevices) { // always wakeup before doing the register. The synchronized block // ensure that the selector won't select() before the end of this block. // @see deviceClientMonitorLoop mSelector.wakeup(); socketChannel.configureBlocking(false); socketChannel.register(mSelector, SelectionKey.OP_READ, device); } return true; } } catch (TimeoutException e) { try { // attempt to close the socket if needed. socketChannel.close(); } catch (IOException e1) { // we can ignore that one. It may already have been closed. } Log.d("DeviceMonitor", "Connection Failure when starting to monitor device '" + device + "' : timeout"); } catch (AdbCommandRejectedException e) { try { // attempt to close the socket if needed. socketChannel.close(); } catch (IOException e1) { // we can ignore that one. It may already have been closed. } Log.d("DeviceMonitor", "Adb refused to start monitoring device '" + device + "' : " + e.getMessage()); } catch (IOException e) { try { // attempt to close the socket if needed. socketChannel.close(); } catch (IOException e1) { // we can ignore that one. It may already have been closed. } Log.d("DeviceMonitor", "Connection Failure when starting to monitor device '" + device + "' : " + e.getMessage()); } } return false; } private void startDeviceMonitorThread() throws IOException { mSelector = Selector.open(); new Thread("Device Client Monitor") { //$NON-NLS-1$ @Override public void run() { deviceClientMonitorLoop(); } }.start(); } private void deviceClientMonitorLoop() { do { try { // This synchronized block stops us from doing the select() if a new // Device is being added. // @see startMonitoringDevice() synchronized (mDevices) { } int count = mSelector.select(); if (mQuit) { return; } synchronized (mClientsToReopen) { if (mClientsToReopen.size() > 0) { Set<Client> clients = mClientsToReopen.keySet(); MonitorThread monitorThread = MonitorThread.getInstance(); for (Client client : clients) { Device device = client.getDeviceImpl(); int pid = client.getClientData().getPid(); monitorThread.dropClient(client, false /* notify */); // This is kinda bad, but if we don't wait a bit, the client // will never answer the second handshake! waitABit(); int port = mClientsToReopen.get(client); if (port == IDebugPortProvider.NO_STATIC_PORT) { port = getNextDebuggerPort(); } Log.d("DeviceMonitor", "Reopening " + client); openClient(device, pid, port, monitorThread); device.update(Device.CHANGE_CLIENT_LIST); } mClientsToReopen.clear(); } } if (count == 0) { continue; } Set<SelectionKey> keys = mSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isValid() && key.isReadable()) { Object attachment = key.attachment(); if (attachment instanceof Device) { Device device = (Device)attachment; SocketChannel socket = device.getClientMonitoringSocket(); if (socket != null) { try { int length = readLength(socket, mLengthBuffer2); processIncomingJdwpData(device, socket, length); } catch (IOException ioe) { Log.d("DeviceMonitor", "Error reading jdwp list: " + ioe.getMessage()); socket.close(); // restart the monitoring of that device synchronized (mDevices) { if (mDevices.contains(device)) { Log.d("DeviceMonitor", "Restarting monitoring service for " + device); startMonitoringDevice(device); } } } } } } } } catch (IOException e) { if (mQuit == false) { } } } while (mQuit == false); } private boolean sendDeviceMonitoringRequest(SocketChannel socket, Device device) throws TimeoutException, AdbCommandRejectedException, IOException { try { AdbHelper.setDevice(socket, device); byte[] request = AdbHelper.formAdbRequest("track-jdwp"); //$NON-NLS-1$ AdbHelper.write(socket, request); AdbResponse resp = AdbHelper.readAdbResponse(socket, false /* readDiagString */); if (resp.okay == false) { // request was refused by adb! Log.e("DeviceMonitor", "adb refused request: " + resp.message); } return resp.okay; } catch (TimeoutException e) { Log.e("DeviceMonitor", "Sending jdwp tracking request timed out!"); throw e; } catch (IOException e) { Log.e("DeviceMonitor", "Sending jdwp tracking request failed!"); throw e; } } private void processIncomingJdwpData(Device device, SocketChannel monitorSocket, int length) throws IOException { // This methods reads @length bytes from the @monitorSocket channel. // These bytes correspond to the pids of the current set of processes on the device. // It takes this set of pids and compares them with the existing set of clients // for the device. Clients that correspond to pids that are not alive anymore are // dropped, and new clients are created for pids that don't have a corresponding Client. if (length >= 0) { // array for the current pids. Set<Integer> newPids = new HashSet<Integer>(); // get the string data if there are any if (length > 0) { byte[] buffer = new byte[length]; String result = read(monitorSocket, buffer); // split each line in its own list and create an array of integer pid String[] pids = result.split("\n"); //$NON-NLS-1$ for (String pid : pids) { try { newPids.add(Integer.valueOf(pid)); } catch (NumberFormatException nfe) { // looks like this pid is not really a number. Lets ignore it. continue; } } } MonitorThread monitorThread = MonitorThread.getInstance(); List<Client> clients = device.getClientList(); Map<Integer, Client> existingClients = new HashMap<Integer, Client>(); synchronized (clients) { for (Client c : clients) { existingClients.put( Integer.valueOf(c.getClientData().getPid()), c); } } Set<Client> clientsToRemove = new HashSet<Client>(); for (Integer pid : existingClients.keySet()) { if (!newPids.contains(pid)) { clientsToRemove.add(existingClients.get(pid)); } } Set<Integer> pidsToAdd = new HashSet<Integer>(newPids); pidsToAdd.removeAll(existingClients.keySet()); monitorThread.dropClients(clientsToRemove, false); // at this point whatever pid is left in the list needs to be converted into Clients. for (int newPid : pidsToAdd) { openClient(device, newPid, getNextDebuggerPort(), monitorThread); } if (pidsToAdd.size() > 0 || clientsToRemove.size() > 0) { mServer.deviceChanged(device, Device.CHANGE_CLIENT_LIST); } } } /** * Opens and creates a new client. * @return */ private void openClient(Device device, int pid, int port, MonitorThread monitorThread) { SocketChannel clientSocket; try { clientSocket = AdbHelper.createPassThroughConnection( AndroidDebugBridge.getSocketAddress(), device, pid); // required for Selector clientSocket.configureBlocking(false); } catch (UnknownHostException uhe) { Log.d("DeviceMonitor", "Unknown Jdwp pid: " + pid); return; } catch (TimeoutException e) { Log.w("DeviceMonitor", "Failed to connect to client '" + pid + "': timeout"); return; } catch (AdbCommandRejectedException e) { Log.w("DeviceMonitor", "Adb rejected connection to client '" + pid + "': " + e.getMessage()); return; } catch (IOException ioe) { Log.w("DeviceMonitor", "Failed to connect to client '" + pid + "': " + ioe.getMessage()); return ; } createClient(device, pid, clientSocket, port, monitorThread); } /** * Creates a client and register it to the monitor thread * @param device * @param pid * @param socket * @param debuggerPort the debugger port. * @param monitorThread the {@link MonitorThread} object. */ private void createClient(Device device, int pid, SocketChannel socket, int debuggerPort, MonitorThread monitorThread) { /* * Successfully connected to something. Create a Client object, add * it to the list, and initiate the JDWP handshake. */ Client client = new Client(device, socket, pid); if (client.sendHandshake()) { try { if (AndroidDebugBridge.getClientSupport()) { client.listenForDebugger(debuggerPort); } } catch (IOException ioe) { client.getClientData().setDebuggerConnectionStatus(DebuggerStatus.ERROR); Log.e("ddms", "Can't bind to local " + debuggerPort + " for debugger"); // oh well } client.requestAllocationStatus(); } else { Log.e("ddms", "Handshake with " + client + " failed!"); /* * The handshake send failed. We could remove it now, but if the * failure is "permanent" we'll just keep banging on it and * getting the same result. Keep it in the list with its "error" * state so we don't try to reopen it. */ } if (client.isValid()) { device.addClient(client); monitorThread.addClient(client); } else { client = null; } } private int getNextDebuggerPort() { // get the first port and remove it synchronized (mDebuggerPorts) { if (mDebuggerPorts.size() > 0) { int port = mDebuggerPorts.get(0); // remove it. mDebuggerPorts.remove(0); // if there's nothing left, add the next port to the list if (mDebuggerPorts.size() == 0) { mDebuggerPorts.add(port+1); } return port; } } return -1; } void addPortToAvailableList(int port) { if (port > 0) { synchronized (mDebuggerPorts) { // because there could be case where clients are closed twice, we have to make // sure the port number is not already in the list. if (mDebuggerPorts.indexOf(port) == -1) { // add the port to the list while keeping it sorted. It's not like there's // going to be tons of objects so we do it linearly. int count = mDebuggerPorts.size(); for (int i = 0 ; i < count ; i++) { if (port < mDebuggerPorts.get(i)) { mDebuggerPorts.add(i, port); break; } } // TODO: check if we can compact the end of the list. } } } } /** * Reads the length of the next message from a socket. * @param socket The {@link SocketChannel} to read from. * @return the length, or 0 (zero) if no data is available from the socket. * @throws IOException if the connection failed. */ private int readLength(SocketChannel socket, byte[] buffer) throws IOException { String msg = read(socket, buffer); if (msg != null) { try { return Integer.parseInt(msg, 16); } catch (NumberFormatException nfe) { // we'll throw an exception below. } } // we receive something we can't read. It's better to reset the connection at this point. throw new IOException("Unable to read length"); } /** * Fills a buffer from a socket. * @param socket * @param buffer * @return the content of the buffer as a string, or null if it failed to convert the buffer. * @throws IOException */ private String read(SocketChannel socket, byte[] buffer) throws IOException { ByteBuffer buf = ByteBuffer.wrap(buffer, 0, buffer.length); while (buf.position() != buf.limit()) { int count; count = socket.read(buf); if (count < 0) { throw new IOException("EOF"); } } try { return new String(buffer, 0, buf.position(), AdbHelper.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // we'll return null below. } return null; } }
/* * The MIT License * * Copyright (c) 2016 The Broad Institute * * 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 htsjdk.samtools; import htsjdk.samtools.util.CloseableIterator; import java.io.Closeable; import java.text.MessageFormat; /** * Describes functionality for objects that produce {@link SAMRecord}s and associated information. * * Currently, only deprecated readers implement this directly; actual readers implement this * via {@link ReaderImplementation} and {@link PrimitiveSamReader}, which {@link SamReaderFactory} * converts into full readers by using {@link PrimitiveSamReaderToSamReaderAdapter}. * * @author mccowan */ public interface SamReader extends Iterable<SAMRecord>, Closeable { /** Describes a type of SAM file. */ public abstract class Type { /** A string representation of this type. */ public abstract String name(); /** The recommended file extension for SAMs of this type, without a period. */ public abstract String fileExtension(); /** The recommended file extension for SAM indexes of this type, without a period, or null if this type is not associated with indexes. */ public abstract String indexExtension(); static class TypeImpl extends Type { final String name, fileExtension, indexExtension; TypeImpl(final String name, final String fileExtension, final String indexExtension) { this.name = name; this.fileExtension = fileExtension; this.indexExtension = indexExtension; } @Override public String name() { return name; } @Override public String fileExtension() { return fileExtension; } @Override public String indexExtension() { return indexExtension; } @Override public String toString() { return String.format("TypeImpl{name='%s', fileExtension='%s', indexExtension='%s'}", name, fileExtension, indexExtension); } } public static final Type SRA_TYPE = new TypeImpl("SRA", "sra", null); public static final Type CRAM_TYPE = new TypeImpl("CRAM", "cram", "crai"); public static final Type BAM_TYPE = new TypeImpl("BAM", "bam", "bai"); public static final Type SAM_TYPE = new TypeImpl("SAM", "sam", null); } /** * Facet for index-related operations. */ public interface Indexing { /** * Retrieves the index for the given file type. Ensure that the index is of the specified type. * * @return An index of the given type. */ public BAMIndex getIndex(); /** * Returns true if the supported index is browseable, meaning the bins in it can be traversed * and chunk data inspected and retrieved. * * @return True if the index supports the BrowseableBAMIndex interface. False otherwise. */ public boolean hasBrowseableIndex(); /** * Gets an index tagged with the BrowseableBAMIndex interface. Throws an exception if no such * index is available. * * @return An index with a browseable interface, if possible. * @throws SAMException if no such index is available. */ public BrowseableBAMIndex getBrowseableIndex(); /** * Iterate through the given chunks in the file. * * @param chunks List of chunks for which to retrieve data. * @return An iterator over the given chunks. */ public SAMRecordIterator iterator(final SAMFileSpan chunks); /** * Gets a pointer spanning all reads in the BAM file. * * @return Unbounded pointer to the first record, in chunk format. */ public SAMFileSpan getFilePointerSpanningReads(); } public SAMFileHeader getFileHeader(); /** * @return the {@link htsjdk.samtools.SamReader.Type} of this {@link htsjdk.samtools.SamReader} */ public Type type(); /** * @return a human readable description of the resource backing this sam reader */ public String getResourceDescription(); /** * @return true if ths is a BAM file, and has an index */ public boolean hasIndex(); /** * Exposes the {@link SamReader.Indexing} facet of this {@link SamReader}. * * @throws java.lang.UnsupportedOperationException If {@link #hasIndex()} returns false. */ public Indexing indexing(); /** * Iterate through file in order. For a SamReader constructed from an InputStream, and for any SAM file, * a 2nd iteration starts where the 1st one left off. For a BAM constructed from a SeekableStream or File, each new iteration * starts at the first record. * <p/> * Only a single open iterator on a SAM or BAM file may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. */ @Override public SAMRecordIterator iterator(); /** * Iterate over records that match the given interval. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. You can use a second SamReader to iterate * in parallel over the same underlying file. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param sequence Reference sequence of interest. * @param start 1-based, inclusive start of interval of interest. Zero implies start of the reference sequence. * @param end 1-based, inclusive end of interval of interest. Zero implies end of the reference sequence. * @param contained If true, each SAMRecord returned will have its alignment completely contained in the * interval of interest. If false, the alignment of the returned SAMRecords need only overlap the interval of interest. * @return Iterator over the SAMRecords matching the interval. */ public SAMRecordIterator query(final String sequence, final int start, final int end, final boolean contained); /** * Iterate over records that overlap the given interval. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param sequence Reference sequence of interest. * @param start 1-based, inclusive start of interval of interest. Zero implies start of the reference sequence. * @param end 1-based, inclusive end of interval of interest. Zero implies end of the reference sequence. * @return Iterator over the SAMRecords overlapping the interval. */ public SAMRecordIterator queryOverlapping(final String sequence, final int start, final int end); /** * Iterate over records that are contained in the given interval. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param sequence Reference sequence of interest. * @param start 1-based, inclusive start of interval of interest. Zero implies start of the reference sequence. * @param end 1-based, inclusive end of interval of interest. Zero implies end of the reference sequence. * @return Iterator over the SAMRecords contained in the interval. */ public SAMRecordIterator queryContained(final String sequence, final int start, final int end); /** * Iterate over records that match one of the given intervals. This may be more efficient than querying * each interval separately, because multiple reads of the same SAMRecords is avoided. * <p/> * Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. You can use a second SamReader to iterate * in parallel over the same underlying file. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match an interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param intervals Intervals to be queried. The intervals must be optimized, i.e. in order, with overlapping * and abutting intervals merged. This can be done with {@link htsjdk.samtools.QueryInterval#optimizeIntervals} * @param contained If true, each SAMRecord returned is will have its alignment completely contained in one of the * intervals of interest. If false, the alignment of the returned SAMRecords need only overlap one of * the intervals of interest. * @return Iterator over the SAMRecords matching the interval. */ public SAMRecordIterator query(final QueryInterval[] intervals, final boolean contained); /** * Iterate over records that overlap any of the given intervals. This may be more efficient than querying * each interval separately, because multiple reads of the same SAMRecords is avoided. * <p/> * Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param intervals Intervals to be queried. The intervals must be optimized, i.e. in order, with overlapping * and abutting intervals merged. This can be done with {@link htsjdk.samtools.QueryInterval#optimizeIntervals} */ public SAMRecordIterator queryOverlapping(final QueryInterval[] intervals); /** * Iterate over records that are contained in the given interval. This may be more efficient than querying * each interval separately, because multiple reads of the same SAMRecords is avoided. * <p/> * Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param intervals Intervals to be queried. The intervals must be optimized, i.e. in order, with overlapping * and abutting intervals merged. This can be done with {@link htsjdk.samtools.QueryInterval#optimizeIntervals} * @return Iterator over the SAMRecords contained in any of the intervals. */ public SAMRecordIterator queryContained(final QueryInterval[] intervals); public SAMRecordIterator queryUnmapped(); /** * Iterate over records that map to the given sequence and start at the given position. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SamReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * matches the arguments. * * @param sequence Reference sequence of interest. * @param start Alignment start of interest. * @return Iterator over the SAMRecords with the given alignment start. */ public SAMRecordIterator queryAlignmentStart(final String sequence, final int start); /** * Fetch the mate for the given read. Only valid to call this if hasIndex() == true. * This will work whether the mate has a coordinate or not, so long as the given read has correct * mate information. This method iterates over the SAM file, so there may not be an unclosed * iterator on the SAM file when this method is called. * <p/> * Note that it is not possible to call queryMate when iterating over the SamReader, because queryMate * requires its own iteration, and there cannot be two simultaneous iterations on the same SamReader. The * work-around is to open a second SamReader on the same input file, and call queryMate on the second * reader. * * @param rec Record for which mate is sought. Must be a paired read. * @return rec's mate, or null if it cannot be found. */ public SAMRecord queryMate(final SAMRecord rec); /** * The minimal subset of functionality needed for a {@link SAMRecord} data source. * {@link SamReader} itself is somewhat large and bulky, but the core functionality can be captured in * relatively few methods, which are included here. For documentation, see the corresponding methods * in {@link SamReader}. * * See also: {@link PrimitiveSamReaderToSamReaderAdapter}, {@link ReaderImplementation} * */ public interface PrimitiveSamReader { Type type(); boolean hasIndex(); BAMIndex getIndex(); SAMFileHeader getFileHeader(); CloseableIterator<SAMRecord> getIterator(); CloseableIterator<SAMRecord> getIterator(SAMFileSpan fileSpan); SAMFileSpan getFilePointerSpanningReads(); CloseableIterator<SAMRecord> query(QueryInterval[] intervals, boolean contained); CloseableIterator<SAMRecord> queryAlignmentStart(String sequence, int start); CloseableIterator<SAMRecord> queryUnmapped(); void close(); ValidationStringency getValidationStringency(); } /** * Decorator for a {@link SamReader.PrimitiveSamReader} that expands its functionality into a {@link SamReader}, * given the backing {@link SamInputResource}. * * Wraps the {@link Indexing} interface as well, which was originally separate from {@link SamReader} but in practice * the two are always implemented by the same class. * */ class PrimitiveSamReaderToSamReaderAdapter implements SamReader, Indexing { final PrimitiveSamReader p; final SamInputResource resource; public PrimitiveSamReaderToSamReaderAdapter(final PrimitiveSamReader p, final SamInputResource resource) { this.p = p; this.resource = resource; } /** * Access the underlying {@link PrimitiveSamReader} used by this adapter. * @return the {@link PrimitiveSamReader} used by this adapter. */ public PrimitiveSamReader underlyingReader() { return p; } @Override public SAMRecordIterator queryOverlapping(final String sequence, final int start, final int end) { return query(sequence, start, end, false); } @Override public SAMRecordIterator queryOverlapping(final QueryInterval[] intervals) { return query(intervals, false); } @Override public SAMRecordIterator queryContained(final String sequence, final int start, final int end) { return query(sequence, start, end, true); } @Override public SAMRecordIterator queryContained(final QueryInterval[] intervals) { return query(intervals, true); } /** * Wraps the boilerplate code for querying a record's mate, which is common across many implementations. * * @param rec Record for which mate is sought. Must be a paired read. * @return */ @Override public SAMRecord queryMate(final SAMRecord rec) { if (!rec.getReadPairedFlag()) { throw new IllegalArgumentException("queryMate called for unpaired read."); } if (rec.getFirstOfPairFlag() == rec.getSecondOfPairFlag()) { throw new IllegalArgumentException("SAMRecord must be either first and second of pair, but not both."); } final boolean firstOfPair = rec.getFirstOfPairFlag(); final CloseableIterator<SAMRecord> it; if (rec.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { it = queryUnmapped(); } else { it = queryAlignmentStart(rec.getMateReferenceName(), rec.getMateAlignmentStart()); } try { SAMRecord mateRec = null; while (it.hasNext()) { final SAMRecord next = it.next(); if (!next.getReadPairedFlag()) { if (rec.getReadName().equals(next.getReadName())) { throw new SAMFormatException("Paired and unpaired reads with same name: " + rec.getReadName()); } continue; } if (firstOfPair) { if (next.getFirstOfPairFlag()) continue; } else { if (next.getSecondOfPairFlag()) continue; } if (rec.getReadName().equals(next.getReadName())) { if (mateRec != null) { throw new SAMFormatException("Multiple SAMRecord with read name " + rec.getReadName() + " for " + (firstOfPair ? "second" : "first") + " end."); } mateRec = next; } } return mateRec; } finally { it.close(); } } @Override public boolean hasBrowseableIndex() { return hasIndex() && getIndex() instanceof BrowseableBAMIndex; } @Override public BrowseableBAMIndex getBrowseableIndex() { final BAMIndex index = getIndex(); if (!(index instanceof BrowseableBAMIndex)) throw new SAMException("Cannot return index: index created by BAM is not browseable."); return BrowseableBAMIndex.class.cast(index); } @Override public SAMRecordIterator iterator() { return new AssertingIterator(p.getIterator()); } @Override public SAMRecordIterator iterator(final SAMFileSpan chunks) { return new AssertingIterator(p.getIterator(chunks)); } @Override public void close() { p.close(); } @Override public SAMFileSpan getFilePointerSpanningReads() { return p.getFilePointerSpanningReads(); } @Override public SAMFileHeader getFileHeader() { return p.getFileHeader(); } @Override public Type type() { return p.type(); } @Override public String getResourceDescription() { return this.resource.toString(); } @Override public boolean hasIndex() { return p.hasIndex(); } @Override public Indexing indexing() { return this; } @Override public BAMIndex getIndex() { return p.getIndex(); } @Override public SAMRecordIterator query(final QueryInterval[] intervals, final boolean contained) { return AssertingIterator.of(p.query(intervals, contained)); } @Override public SAMRecordIterator query(final String sequence, final int start, final int end, final boolean contained) { return query(new QueryInterval[]{new QueryInterval(getFileHeader().getSequenceIndex(sequence), start, end)}, contained); } @Override public SAMRecordIterator queryUnmapped() { return AssertingIterator.of(p.queryUnmapped()); } @Override public SAMRecordIterator queryAlignmentStart(final String sequence, final int start) { return AssertingIterator.of(p.queryAlignmentStart(sequence, start)); } } static class AssertingIterator implements SAMRecordIterator { static AssertingIterator of(final CloseableIterator<SAMRecord> iterator) { return new AssertingIterator(iterator); } private final CloseableIterator<SAMRecord> wrappedIterator; private SAMSortOrderChecker checker; public AssertingIterator(final CloseableIterator<SAMRecord> iterator) { wrappedIterator = iterator; } @Override public SAMRecordIterator assertSorted(final SAMFileHeader.SortOrder sortOrder) { checker = new SAMSortOrderChecker(sortOrder); return this; } @Override public SAMRecord next() { final SAMRecord result = wrappedIterator.next(); if (checker != null) { final SAMRecord previous = checker.getPreviousRecord(); if (!checker.isSorted(result)) { throw new IllegalStateException(String.format( "Record %s should come after %s when sorting with %s ordering.", previous.getSAMString().trim(), result.getSAMString().trim(), checker.getSortOrder())); } } return result; } @Override public void close() { wrappedIterator.close(); } @Override public boolean hasNext() { return wrappedIterator.hasNext(); } @Override public void remove() { wrappedIterator.remove(); } } /** * Internal interface for SAM/BAM/CRAM file reader implementations, * as distinct from non-file-based readers. * * Implemented as an abstract class to enforce better access control. * * TODO -- Many of these methods only apply for a subset of implementations, * TODO -- and either no-op or throw an exception for the others. * TODO -- We should consider refactoring things to avoid this; * TODO -- perhaps we can get away with not having this class at all. */ abstract class ReaderImplementation implements PrimitiveSamReader { abstract void enableFileSource(final SamReader reader, final boolean enabled); abstract void enableIndexCaching(final boolean enabled); abstract void enableIndexMemoryMapping(final boolean enabled); abstract void enableCrcChecking(final boolean enabled); abstract void setSAMRecordFactory(final SAMRecordFactory factory); abstract void setValidationStringency(final ValidationStringency validationStringency); } }
package cn.intellimuyan.bardclient.nettyclient.anno; import org.springframework.stereotype.Component; import java.lang.annotation.*; /** * 表明被注解的类为netty控制器 * * @author hason * @version 19-1-29 */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface NettyController { }
/* * Copyright ConsenSys AG. * * 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.hyperledger.besu.tests.acceptance.crypto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SECP256R1; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.tests.acceptance.dsl.AcceptanceTestBase; import org.hyperledger.besu.tests.acceptance.dsl.account.Account; import org.hyperledger.besu.tests.acceptance.dsl.node.BesuNodeRunner; import org.hyperledger.besu.tests.acceptance.dsl.node.Node; import org.hyperledger.besu.tests.acceptance.dsl.node.cluster.Cluster; import org.hyperledger.besu.tests.acceptance.dsl.node.cluster.ClusterConfiguration; import org.hyperledger.besu.tests.acceptance.dsl.node.cluster.ClusterConfigurationBuilder; import java.util.List; import org.apache.tuweni.bytes.Bytes32; import org.junit.Before; import org.junit.Test; public class SECP256R1AcceptanceTest extends AcceptanceTestBase { private Node minerNode; private Node otherNode; private Cluster noDiscoveryCluster; private static final String GENESIS_FILE = "/crypto/secp256r1.json"; private static final String MINER_NODE_PRIVATE_KEY = "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63"; private static final String OTHER_NODE_PRIVATE_KEY = "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3"; private static final SECP256R1 SECP256R1_SIGNATURE_ALGORITHM = new SECP256R1(); @Before public void setUp() throws Exception { KeyPair minerNodeKeyPair = createKeyPair(MINER_NODE_PRIVATE_KEY); KeyPair otherNodeKeyPair = createKeyPair(OTHER_NODE_PRIVATE_KEY); final ClusterConfiguration clusterConfiguration = new ClusterConfigurationBuilder().awaitPeerDiscovery(false).build(); noDiscoveryCluster = new Cluster(clusterConfiguration, net); minerNode = besu.createNodeWithNonDefaultSignatureAlgorithm( "minerNode", GENESIS_FILE, minerNodeKeyPair); noDiscoveryCluster.start(minerNode); otherNode = besu.createNodeWithNonDefaultSignatureAlgorithm( "otherNode", GENESIS_FILE, otherNodeKeyPair, List.of(minerNode)); noDiscoveryCluster.addNode(otherNode); } @Test public void transactionShouldBeSuccessful() { // SignatureAlgorithmFactory.instance is static. When ThreadBesuRunner is used, we cannot change // the signature algorithm instance to SECP256R1 as it could influence other tests running at // the same time. So we only execute the test when ProcessBesuNodeRunner is used, as there is // not conflict because we use separate processes. assumeThat(BesuNodeRunner.isProcessBesuNodeRunner()).isTrue(); minerNode.verify(net.awaitPeerCount(1)); otherNode.verify(net.awaitPeerCount(1)); final Account recipient = accounts.createAccount("recipient"); final Hash transactionHash = minerNode.execute(accountTransactions.createTransfer(recipient, 5, new SECP256R1())); assertThat(transactionHash).isNotNull(); cluster.verify(recipient.balanceEquals(5)); } @Override public void tearDownAcceptanceTestBase() { super.tearDownAcceptanceTestBase(); noDiscoveryCluster.stop(); } private KeyPair createKeyPair(final String privateKey) { return SECP256R1_SIGNATURE_ALGORITHM.createKeyPair( SECP256R1_SIGNATURE_ALGORITHM.createPrivateKey(Bytes32.fromHexString(privateKey))); } }
package cn.leancloud; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import cn.leancloud.ops.Utils; import com.alibaba.fastjson.JSON; public class EngineFunctionParamInfo { final String name; final Class type; public EngineFunctionParamInfo(Class type, String name) { this.name = name; this.type = type; } public String getName() { return name; } public Class getType() { return type; } public Object parseParams(String content) { if (AVObject.class.isAssignableFrom(type)) { return Utils.getParsedObject(JSON.parseObject(content)); } else { if (Map.class.isAssignableFrom(type)) { return parseParams((Map) JSON.parseObject(content, type)); } else if (Collection.class.isAssignableFrom(type)) { return parseParams((Collection) JSON.parseObject(content, type)); } else { return JSON.parseObject(content, type); } } } public Collection parseParams(Collection collection) { List result = new LinkedList(); for (Object o : collection) { if (o instanceof Map) { result.add(parseParams((Map) o)); } else if (o instanceof Collection) { result.add(parseParams((Collection) o)); } else { result.add(o); } } return result; } public Object parseParams(Map<String, Object> map) { if (map != null && map.containsKey("className") && map.containsKey("__type") && "Object".equals(map.get("__type"))) { // 这肯定是一个AVObject吧 AVObject object = Transformer.objectFromClassName((String) map.get("className")); object.resetServerData(map); return object; } else if (map != null) { HashMap result = new HashMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { Object parsedValue = null; if (entry.getValue() instanceof Map) { parsedValue = parseParams((Map) entry.getValue()); } else if (entry.getValue() instanceof Collection) { parsedValue = parseParams((Collection) entry.getValue()); } else { parsedValue = entry.getValue(); } result.put(entry.getKey(), parsedValue); } return result; } return null; } }
package com.puttysoftware.brainmaze.prefs; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; class PreferencesStoreManager { // Fields private final Properties store; // Constructors public PreferencesStoreManager() { this.store = new Properties(); } // Methods public String getString(final String key, final String defaultValue) { return this.store.getProperty(key, defaultValue); } public void setString(final String key, final String newValue) { this.store.setProperty(key, newValue); } public boolean getBoolean(final String key, final boolean defaultValue) { final String strVal = this.getString(key, Boolean.toString(defaultValue)); return Boolean.parseBoolean(strVal); } public void setBoolean(final String key, final boolean newValue) { this.setString(key, Boolean.toString(newValue)); } public int getInteger(final String key, final int defaultValue) { final String strVal = this.getString(key, Integer.toString(defaultValue)); return Integer.parseInt(strVal); } public void setInteger(final String key, final int newValue) { this.setString(key, Integer.toString(newValue)); } public void loadStore(final InputStream source) throws IOException { this.store.loadFromXML(source); } public void saveStore(final OutputStream dest) throws IOException { this.store.storeToXML(dest, null); } }
package com.mrbonono63.create.content.contraptions.components.structureMovement.piston; import com.simibubi.create.AllBlocks; import com.mrbonono63.create.content.contraptions.base.IRotate; import com.mrbonono63.create.content.contraptions.components.structureMovement.AssemblyException; import com.mrbonono63.create.content.contraptions.components.structureMovement.ContraptionCollider; import com.mrbonono63.create.content.contraptions.components.structureMovement.ControlledContraptionEntity; import com.mrbonono63.create.content.contraptions.components.structureMovement.DirectionalExtenderScrollOptionSlot; import com.mrbonono63.create.content.contraptions.components.structureMovement.piston.MechanicalPistonBlock.PistonState; import com.mrbonono63.create.foundation.tileEntity.behaviour.ValueBoxTransform; import com.mrbonono63.create.foundation.utility.ServerSpeedProvider; import net.minecraft.block.BlockState; import net.minecraft.nbt.CompoundNBT; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.Direction; import net.minecraft.util.Direction.Axis; import net.minecraft.util.Direction.AxisDirection; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3d; public class MechanicalPistonTileEntity extends LinearActuatorTileEntity { protected boolean hadCollisionWithOtherPiston; protected int extensionLength; public MechanicalPistonTileEntity(TileEntityType<? extends MechanicalPistonTileEntity> type) { super(type); } @Override protected void fromTag(BlockState state, CompoundNBT compound, boolean clientPacket) { extensionLength = compound.getInt("ExtensionLength"); super.fromTag(state, compound, clientPacket); } @Override protected void write(CompoundNBT tag, boolean clientPacket) { tag.putInt("ExtensionLength", extensionLength); super.write(tag, clientPacket); } @Override public void assemble() throws AssemblyException { if (!(world.getBlockState(pos) .getBlock() instanceof MechanicalPistonBlock)) return; Direction direction = getBlockState().get(BlockStateProperties.FACING); // Collect Construct PistonContraption contraption = new PistonContraption(direction, getMovementSpeed() < 0); if (!contraption.assemble(world, pos)) return; Direction positive = Direction.getFacingFromAxis(AxisDirection.POSITIVE, direction.getAxis()); Direction movementDirection = getSpeed() > 0 ^ direction.getAxis() != Axis.Z ? positive : positive.getOpposite(); BlockPos anchor = contraption.anchor.offset(direction, contraption.initialExtensionProgress); if (ContraptionCollider.isCollidingWithWorld(world, contraption, anchor.offset(movementDirection), movementDirection)) return; // Check if not at limit already extensionLength = contraption.extensionLength; float resultingOffset = contraption.initialExtensionProgress + Math.signum(getMovementSpeed()) * .5f; if (resultingOffset <= 0 || resultingOffset >= extensionLength) { return; } // Run running = true; offset = contraption.initialExtensionProgress; sendData(); clientOffsetDiff = 0; BlockPos startPos = BlockPos.ZERO.offset(direction, contraption.initialExtensionProgress); contraption.removeBlocksFromWorld(world, startPos); movedContraption = ControlledContraptionEntity.create(getWorld(), this, contraption); applyContraptionPosition(); forceMove = true; world.addEntity(movedContraption); } @Override public void disassemble() { if (!running && movedContraption == null) return; if (!removed) getWorld().setBlockState(pos, getBlockState().with(MechanicalPistonBlock.STATE, PistonState.EXTENDED), 3 | 16); if (movedContraption != null) { applyContraptionPosition(); movedContraption.disassemble(); } running = false; movedContraption = null; sendData(); if (removed) AllBlocks.MECHANICAL_PISTON.get() .onBlockHarvested(world, pos, getBlockState(), null); } @Override public void collided() { super.collided(); if (!running && getMovementSpeed() > 0) assembleNextTick = true; } @Override public float getMovementSpeed() { float movementSpeed = MathHelper.clamp(getSpeed() / 512f, -.49f, .49f); if (world.isRemote) movementSpeed *= ServerSpeedProvider.get(); Direction pistonDirection = getBlockState().get(BlockStateProperties.FACING); int movementModifier = pistonDirection.getAxisDirection() .getOffset() * (pistonDirection.getAxis() == Axis.Z ? -1 : 1); movementSpeed = movementSpeed * -movementModifier + clientOffsetDiff / 2f; int extensionRange = getExtensionRange(); movementSpeed = MathHelper.clamp(movementSpeed, 0 - offset, extensionRange - offset); return movementSpeed; } @Override protected int getExtensionRange() { return extensionLength; } @Override protected void visitNewPosition() {} @Override protected Vector3d toMotionVector(float speed) { Direction pistonDirection = getBlockState().get(BlockStateProperties.FACING); return Vector3d.of(pistonDirection.getDirectionVec()) .scale(speed); } @Override protected Vector3d toPosition(float offset) { Vector3d position = Vector3d.of(getBlockState().get(BlockStateProperties.FACING) .getDirectionVec()) .scale(offset); return position.add(Vector3d.of(movedContraption.getContraption().anchor)); } @Override protected ValueBoxTransform getMovementModeSlot() { return new DirectionalExtenderScrollOptionSlot((state, d) -> { Axis axis = d.getAxis(); Axis extensionAxis = state.get(MechanicalPistonBlock.FACING) .getAxis(); Axis shaftAxis = ((IRotate) state.getBlock()).getRotationAxis(state); return extensionAxis != axis && shaftAxis != axis; }); } @Override protected int getInitialOffset() { return movedContraption == null ? 0 : ((PistonContraption) movedContraption.getContraption()).initialExtensionProgress; } }
public class Foo { void m() { IFoo.new<caret> f(); } } interface IFoo { }
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cn.vlabs.duckling.vwb.service.share; import cn.vlabs.duckling.vwb.service.mail.Mail; /** * Introduction Here. * @date Apr 30, 2010 * @author Sun Peng (sunp@cnic.cn) */ public interface SharePageMailService{ Mail parepareMail(int siteId, String subjectLine); void sendNotifications(int siteId, Mail mail,String subscriber, String recipient, String subjectLine, String url, String title, String content); }
package org.example.pinda.database.datasource; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.ArrayUtil; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties; import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer; import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS; import com.baomidou.mybatisplus.core.MybatisConfiguration; import com.baomidou.mybatisplus.core.config.GlobalConfig; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator; import com.baomidou.mybatisplus.core.injector.ISqlInjector; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.mapping.DatabaseIdProvider; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.scripting.LanguageDriver; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.type.TypeHandler; import org.example.pinda.database.properties.DatabaseProperties; import org.springframework.aop.Advisor; import org.springframework.aop.ClassFilter; import org.springframework.aop.MethodMatcher; import org.springframework.aop.Pointcut; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Controller; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.interceptor.*; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; import java.lang.annotation.Annotation; import java.util.*; /** * 数据库 & 事务 & MyBatis & MyBatis Plus 配置 */ @Slf4j public abstract class BaseDatabaseConfiguration implements InitializingBean { @Value("${spring.profiles.active:dev}") protected String profiles; /** * MyBatis Plus 配置属性 */ protected MybatisPlusProperties mybatisPlusProperties; /** * 测试环境 */ protected static final String[] DEV_PROFILES = new String[]{"dev"}; /** * 数据库配置 */ private DatabaseProperties databaseProperties; /** * 数据库拦截器 */ private Interceptor[] interceptors; /** * 类型处理器 */ private TypeHandler<?>[] typeHandlers; /** * 语言驱动 */ private LanguageDriver[] languageDrivers; /** * 资源加载器 */ private ResourceLoader resourceLoader; /** * 数据库Id提供器 */ private DatabaseIdProvider databaseIdProvider; /** * 配置定制器 */ private List<ConfigurationCustomizer> configurationCustomizers; /** * MyBatis Plus属性定制器 */ private List<MybatisPlusPropertiesCustomizer> mybatisPlusPropertiesCustomizers; /** * Spring 上下文 */ private ApplicationContext applicationContext; private static final List<Class<? extends Annotation>> AOP_POINTCUT_ANNOTATIONS = new ArrayList<>(2); // 事务在Controller层开启 static { AOP_POINTCUT_ANNOTATIONS.add(Controller.class); AOP_POINTCUT_ANNOTATIONS.add(RestController.class); } /** * 事务源处理,当前存在事务就使用当前的事务,如果不存在事务就新建一个事务 * * @return {@link TransactionAttributeSource} */ protected TransactionAttributeSource transactionAttributeSource() { Map<String, TransactionAttribute> txMap = buildTxMap(); txMap.put("*", buildReadOnlyTx()); NameMatchTransactionAttributeSource nameMatchTransactionAttributeSource = new NameMatchTransactionAttributeSource(); nameMatchTransactionAttributeSource.setNameMap(txMap); return nameMatchTransactionAttributeSource; } /** * 根据数据库属性配置构建事务属性集合 * * @return 事务属性集合 */ private Map<String, TransactionAttribute> buildTxMap() { RuleBasedTransactionAttribute requiredTx = buildRuleBasedTxAttribute(); List<String> transactionAttributes = this.databaseProperties.getTransactionAttributes(); Map<String, TransactionAttribute> txMap = new HashMap<>(transactionAttributes.size() + 5); transactionAttributes.forEach(prefix -> txMap.put(prefix, requiredTx)); return txMap; } /** * 构建只读的事务 * * @return 只读事务 */ private RuleBasedTransactionAttribute buildReadOnlyTx() { RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute(); readOnlyTx.setReadOnly(true); readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); return readOnlyTx; } /** * 构建事务规则 * * @return {@link RuleBasedTransactionAttribute} */ private RuleBasedTransactionAttribute buildRuleBasedTxAttribute() { RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute(); requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Throwable.class))); requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); requiredTx.setTimeout(this.databaseProperties.getTxTimeout()); return requiredTx; } protected Advisor txAdviceAdvisor(TransactionInterceptor interceptor) { return new DefaultPointcutAdvisor(new Pointcut() { @NonNull @Override public ClassFilter getClassFilter() { return cls -> { if (!cls.getName().startsWith(BaseDatabaseConfiguration.this.databaseProperties.getTransactionScanPackage())) { return false; } for (Class<? extends Annotation> aClass : AOP_POINTCUT_ANNOTATIONS) { if (cls.getAnnotation(aClass) == null) { continue; } log.warn("允许带事务的类:{}", cls); return true; } return false; }; } @NonNull @Override public MethodMatcher getMethodMatcher() { return MethodMatcher.TRUE; } }, interceptor); } protected SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setVfs(SpringBootVFS.class); this.applyMyBatisPlusProperties(factory); if (!ObjectUtils.isEmpty(this.interceptors)) { factory.setPlugins(this.interceptors); } if (this.databaseIdProvider != null) { factory.setDatabaseIdProvider(databaseIdProvider); } if (!ObjectUtils.isEmpty(this.typeHandlers)) { factory.setTypeHandlers(this.typeHandlers); } if (!ObjectUtils.isEmpty(this.languageDrivers)) { factory.setScriptingLanguageDrivers(this.languageDrivers); } // 设置全局配置 factory.setGlobalConfig(buildMyBatisGlobalConfig()); return factory.getObject(); } private GlobalConfig buildMyBatisGlobalConfig() { GlobalConfig globalConfig = this.mybatisPlusProperties.getGlobalConfig(); // 注入填充器 if (this.applicationContext.getBeanNamesForType(MetaObjectHandler.class, false, false).length > 0) { globalConfig.setMetaObjectHandler(this.applicationContext.getBean(MetaObjectHandler.class)); } // 注入主键生成器 if (this.applicationContext.getBeanNamesForType(IKeyGenerator.class, false, false).length > 0) { globalConfig.getDbConfig().setKeyGenerator(this.applicationContext.getBean(IKeyGenerator.class)); } // 注入SQL注入器 if (this.applicationContext.getBeanNamesForType(ISqlInjector.class, false, false).length > 0) { globalConfig.setSqlInjector(this.applicationContext.getBean(ISqlInjector.class)); } return globalConfig; } private void applyMyBatisPlusProperties(MybatisSqlSessionFactoryBean factory) { String configLocation = this.mybatisPlusProperties.getConfigLocation(); if (StringUtils.hasText(configLocation)) { factory.setConfigLocation(this.resourceLoader.getResource(configLocation)); } this.applyConfig(factory); Optional.ofNullable(this.mybatisPlusProperties.getConfigurationProperties()) .ifPresent(factory::setConfigurationProperties); String typeAliasesPackage = this.mybatisPlusProperties.getTypeAliasesPackage(); if (StringUtils.hasLength(typeAliasesPackage)) { factory.setTypeAliasesPackage(typeAliasesPackage); } Optional.ofNullable(this.mybatisPlusProperties.getTypeAliasesSuperType()) .ifPresent(factory::setTypeAliasesSuperType); String typeHandlersPackage = this.mybatisPlusProperties.getTypeHandlersPackage(); if (StringUtils.hasLength(typeHandlersPackage)) { factory.setTypeHandlersPackage(typeHandlersPackage); } Resource[] resources = this.mybatisPlusProperties.resolveMapperLocations(); if (!ObjectUtils.isEmpty(resources)) { factory.setMapperLocations(resources); } Optional.ofNullable(this.mybatisPlusProperties.getDefaultScriptingLanguageDriver()) .ifPresent(factory::setDefaultScriptingLanguageDriver); // 自定义枚举包 String typeEnumsPackage = this.mybatisPlusProperties.getTypeEnumsPackage(); if (StringUtils.hasLength(typeEnumsPackage)) { factory.setTypeEnumsPackage(typeEnumsPackage); } } /** * 应用配置 * * @param factory {@link MybatisSqlSessionFactoryBean} */ private void applyConfig(MybatisSqlSessionFactoryBean factory) { MybatisConfiguration customConfig = this.mybatisPlusProperties.getConfiguration(); MybatisConfiguration configToApply = new MybatisConfiguration(); // 解决多数据源时,拦截器等执行多次 BeanUtil.copyProperties(customConfig, configToApply); if (!CollectionUtils.isEmpty(this.configurationCustomizers)) { this.configurationCustomizers.forEach(customizer -> customizer.customize(configToApply)); } factory.setConfiguration(configToApply); } /** * 属性设置后的操作 */ @Override public void afterPropertiesSet() throws Exception { if (!CollectionUtils.isEmpty(this.mybatisPlusPropertiesCustomizers)) { this.mybatisPlusPropertiesCustomizers.forEach(customizer -> customizer.customize(this.mybatisPlusProperties)); } this.checkConfigFileExists(); } /** * 检查MyBaits Plus的配置文件是否存在 */ private void checkConfigFileExists() { String configLocation = this.mybatisPlusProperties.getConfigLocation(); if (this.mybatisPlusProperties.isCheckConfigLocation() && StringUtils.hasText(configLocation)) { Resource resource = this.resourceLoader.getResource(configLocation); Assert.state(resource.exists(), "Cannot find config location: " + resource + "(please add config file or check your MyBatis configuration)"); } } }
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.scwang.smartrefresh.header.flyrefresh; import android.graphics.Path; import androidx.annotation.RequiresApi; import android.annotation.TargetApi; import android.view.animation.Interpolator; /** * Base implementation for path interpolator compatibility. */ @RequiresApi(9) @TargetApi(9) class PathInterpolatorCompatBase { private PathInterpolatorCompatBase() { // prevent instantiation } public static Interpolator create(Path path) { return new PathInterpolatorGingerbread(path); } public static Interpolator create(float controlX, float controlY) { return new PathInterpolatorGingerbread(controlX, controlY); } public static Interpolator create(float controlX1, float controlY1, float controlX2, float controlY2) { return new PathInterpolatorGingerbread(controlX1, controlY1, controlX2, controlY2); } }
package Automata.diagram.part; import java.util.Iterator; import java.util.List; import org.eclipse.gef.EditPart; import org.eclipse.gef.Request; import org.eclipse.gef.commands.Command; import org.eclipse.gef.commands.UnexecutableCommand; import org.eclipse.gmf.runtime.diagram.ui.actions.AbstractDeleteFromAction; import org.eclipse.gmf.runtime.diagram.ui.actions.ActionIds; import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy; import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramUIMessages; import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; /** * @generated */ public class DeleteElementAction extends AbstractDeleteFromAction { /** * @generated */ public DeleteElementAction(IWorkbenchPart part) { super(part); } /** * @generated */ public DeleteElementAction(IWorkbenchPage workbenchPage) { super(workbenchPage); } /** * @generated */ public void init() { super.init(); setId(ActionIds.ACTION_DELETE_FROM_MODEL); setText(DiagramUIMessages.DiagramEditor_Delete_from_Model); setToolTipText(DiagramUIMessages.DiagramEditor_Delete_from_ModelToolTip); ISharedImages workbenchImages = PlatformUI.getWorkbench() .getSharedImages(); setHoverImageDescriptor(workbenchImages .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE)); setImageDescriptor(workbenchImages .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE)); setDisabledImageDescriptor(workbenchImages .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE_DISABLED)); } /** * @generated */ protected String getCommandLabel() { return DiagramUIMessages.DiagramEditor_Delete_from_Model; } /** * @generated */ protected Command getCommand(Request request) { List operationSet = getOperationSet(); if (operationSet.isEmpty()) { return UnexecutableCommand.INSTANCE; } Iterator editParts = operationSet.iterator(); CompositeTransactionalCommand command = new CompositeTransactionalCommand( getEditingDomain(), getCommandLabel()); while (editParts.hasNext()) { EditPart editPart = (EditPart) editParts.next(); Command curCommand = editPart.getCommand(request); if (curCommand != null) { command.compose(new CommandProxy(curCommand)); } } if (command.isEmpty() || command.size() != operationSet.size()) { return UnexecutableCommand.INSTANCE; } return new ICommandProxy(command); } }
package com.alibaba.otter.canal.meta; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.util.Assert; import com.alibaba.otter.canal.common.utils.JsonUtils; import com.alibaba.otter.canal.meta.exception.CanalMetaManagerException; import com.alibaba.otter.canal.protocol.ClientIdentity; import com.alibaba.otter.canal.protocol.position.LogPosition; import com.alibaba.otter.canal.protocol.position.Position; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; /** * 基于文件刷新的metaManager实现 * * <pre> * 策略: * 1. 先写内存,然后定时刷新数据到File * 2. 数据采取overwrite模式(只保留最后一次),通过logger实施append模式(记录历史版本) * </pre> * * @author jianghang 2013-4-15 下午05:55:57 * @version 1.0.4 */ public class FileMixedMetaManager extends MemoryMetaManager implements CanalMetaManager { private static final Logger logger = LoggerFactory.getLogger(FileMixedMetaManager.class); private static final Charset charset = Charset.forName("UTF-8"); private File dataDir; private String dataFileName = "meta.dat"; private Map<String, File> dataFileCaches; private ScheduledExecutorService executor; @SuppressWarnings("serial") private final Position nullCursor = new Position() { }; private long period = 1000; // 单位ms private Set<ClientIdentity> updateCursorTasks; public void start() { super.start(); Assert.notNull(dataDir); if (!dataDir.exists()) { try { FileUtils.forceMkdir(dataDir); } catch (IOException e) { throw new CanalMetaManagerException(e); } } if (!dataDir.canRead() || !dataDir.canWrite()) { throw new CanalMetaManagerException("dir[" + dataDir.getPath() + "] can not read/write"); } dataFileCaches = new MapMaker().makeComputingMap(new Function<String, File>() { public File apply(String destination) { return getDataFile(destination); } }); executor = Executors.newScheduledThreadPool(1); destinations = new MapMaker().makeComputingMap(new Function<String, List<ClientIdentity>>() { public List<ClientIdentity> apply(String destination) { return loadClientIdentity(destination); } }); cursors = new MapMaker().makeComputingMap(new Function<ClientIdentity, Position>() { public Position apply(ClientIdentity clientIdentity) { Position position = loadCursor(clientIdentity.getDestination(), clientIdentity); if (position == null) { return nullCursor; // 返回一个空对象标识,避免出现异常 } else { return position; } } }); updateCursorTasks = Collections.synchronizedSet(new HashSet<ClientIdentity>()); // 启动定时工作任务 executor.scheduleAtFixedRate(new Runnable() { public void run() { List<ClientIdentity> tasks = new ArrayList<ClientIdentity>(updateCursorTasks); for (ClientIdentity clientIdentity : tasks) { MDC.put("destination", String.valueOf(clientIdentity.getDestination())); try { // 定时将内存中的最新值刷到file中,多次变更只刷一次 if (logger.isInfoEnabled()) { LogPosition cursor = (LogPosition) getCursor(clientIdentity); logger.info("clientId:{} cursor:[{},{},{}] address[{}]", new Object[] { clientIdentity.getClientId(), cursor.getPostion().getJournalName(), cursor.getPostion().getPosition(), cursor.getPostion().getTimestamp(), cursor.getIdentity().getSourceAddress().toString() }); } flushDataToFile(clientIdentity.getDestination()); updateCursorTasks.remove(clientIdentity); } catch (Throwable e) { // ignore logger.error("period update" + clientIdentity.toString() + " curosr failed!", e); } } } }, period, period, TimeUnit.MILLISECONDS); } public void stop() { super.stop(); flushDataToFile();// 刷新数据 executor.shutdownNow(); destinations.clear(); batches.clear(); } public void subscribe(final ClientIdentity clientIdentity) throws CanalMetaManagerException { super.subscribe(clientIdentity); // 订阅信息频率发生比较低,不需要做定时merge处理 executor.submit(new Runnable() { public void run() { flushDataToFile(clientIdentity.getDestination()); } }); } public void unsubscribe(final ClientIdentity clientIdentity) throws CanalMetaManagerException { super.unsubscribe(clientIdentity); // 订阅信息频率发生比较低,不需要做定时merge处理 executor.submit(new Runnable() { public void run() { flushDataToFile(clientIdentity.getDestination()); } }); } public void updateCursor(ClientIdentity clientIdentity, Position position) throws CanalMetaManagerException { updateCursorTasks.add(clientIdentity);// 添加到任务队列中进行触发 super.updateCursor(clientIdentity, position); } public Position getCursor(ClientIdentity clientIdentity) throws CanalMetaManagerException { Position position = super.getCursor(clientIdentity); if (position == nullCursor) { return null; } else { return position; } } // ============================ helper method ====================== private File getDataFile(String destination) { File destinationMetaDir = new File(dataDir, destination); if (!destinationMetaDir.exists()) { try { FileUtils.forceMkdir(destinationMetaDir); } catch (IOException e) { throw new CanalMetaManagerException(e); } } return new File(destinationMetaDir, dataFileName); } private FileMetaInstanceData loadDataFromFile(File dataFile) { try { if (!dataFile.exists()) { return null; } String json = FileUtils.readFileToString(dataFile, charset.name()); return JsonUtils.unmarshalFromString(json, FileMetaInstanceData.class); } catch (IOException e) { throw new CanalMetaManagerException(e); } } private void flushDataToFile() { for (String destination : destinations.keySet()) { flushDataToFile(destination); } } private void flushDataToFile(String destination) { flushDataToFile(destination, dataFileCaches.get(destination)); } private void flushDataToFile(String destination, File dataFile) { FileMetaInstanceData data = new FileMetaInstanceData(); if (destinations.containsKey(destination)) { synchronized (destination.intern()) { // 基于destination控制一下并发更新 data.setDestination(destination); List<FileMetaClientIdentityData> clientDatas = Lists.newArrayList(); List<ClientIdentity> clientIdentitys = destinations.get(destination); for (ClientIdentity clientIdentity : clientIdentitys) { FileMetaClientIdentityData clientData = new FileMetaClientIdentityData(); clientData.setClientIdentity(clientIdentity); Position position = cursors.get(clientIdentity); if (position != null && position != nullCursor) { clientData.setCursor((LogPosition) position); } clientDatas.add(clientData); } data.setClientDatas(clientDatas); } String json = JsonUtils.marshalToString(data); try { FileUtils.writeStringToFile(dataFile, json); } catch (IOException e) { throw new CanalMetaManagerException(e); } } } private List<ClientIdentity> loadClientIdentity(String destination) { List<ClientIdentity> result = Lists.newArrayList(); FileMetaInstanceData data = loadDataFromFile(dataFileCaches.get(destination)); if (data == null) { return result; } List<FileMetaClientIdentityData> clientDatas = data.getClientDatas(); if (clientDatas == null) { return result; } for (FileMetaClientIdentityData clientData : clientDatas) { if (clientData.getClientIdentity().getDestination().equals(destination)) { result.add(clientData.getClientIdentity()); } } return result; } private Position loadCursor(String destination, ClientIdentity clientIdentity) { FileMetaInstanceData data = loadDataFromFile(dataFileCaches.get(destination)); if (data == null) { return null; } List<FileMetaClientIdentityData> clientDatas = data.getClientDatas(); if (clientDatas == null) { return null; } for (FileMetaClientIdentityData clientData : clientDatas) { if (clientData.getClientIdentity() != null && clientData.getClientIdentity().equals(clientIdentity)) { return clientData.getCursor(); } } return null; } /** * 描述一个clientIdentity对应的数据对象 * * @author jianghang 2013-4-15 下午06:19:40 * @version 1.0.4 */ public static class FileMetaClientIdentityData { private ClientIdentity clientIdentity; private LogPosition cursor; public FileMetaClientIdentityData(){ } public FileMetaClientIdentityData(ClientIdentity clientIdentity, MemoryClientIdentityBatch batch, LogPosition cursor){ this.clientIdentity = clientIdentity; this.cursor = cursor; } public ClientIdentity getClientIdentity() { return clientIdentity; } public void setClientIdentity(ClientIdentity clientIdentity) { this.clientIdentity = clientIdentity; } public Position getCursor() { return cursor; } public void setCursor(LogPosition cursor) { this.cursor = cursor; } } /** * 描述整个canal instance对应数据对象 * * @author jianghang 2013-4-15 下午06:20:22 * @version 1.0.4 */ public static class FileMetaInstanceData { private String destination; private List<FileMetaClientIdentityData> clientDatas; public FileMetaInstanceData(){ } public FileMetaInstanceData(String destination, List<FileMetaClientIdentityData> clientDatas){ this.destination = destination; this.clientDatas = clientDatas; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public List<FileMetaClientIdentityData> getClientDatas() { return clientDatas; } public void setClientDatas(List<FileMetaClientIdentityData> clientDatas) { this.clientDatas = clientDatas; } } public void setDataDir(String dataDir) { this.dataDir = new File(dataDir); } public void setDataDir(File dataDir) { this.dataDir = dataDir; } public void setPeriod(long period) { this.period = period; } }
/* * Copyright (C) 2013, Thomas Obenaus. All rights reserved. * Licensed under the New BSD License (3-clause lic) * See attached license-file. * * Author: Thomas Obenaus * EMail: obenaus.thomas@gmail.com * Project: JavaComponents/Widgets */ package thobe.widgets.inputSlider; import java.math.BigDecimal; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Vector; import javax.swing.JLabel; /** * Represents a widget that can be used to slide through double values. * @author Thomas Obenaus * @source DoubleSlider.java * @date 14 Nov 2008 */ @SuppressWarnings ( "serial") public class DoubleSlider extends Slider<Double> { /** * Class that can be used to specify the labeling of the slider. * @author Thomas Obenaus * @source DoubleLabelling.java * @date 14 Nov 2008 */ private static class DoubleLabelling extends Dictionary<Integer, JLabel> { private HashMap<Integer, JLabel> valueTable = new HashMap<Integer, JLabel>( ); @Override public Enumeration<JLabel> elements( ) { Vector<JLabel> elements = new Vector<JLabel>( ); for ( Map.Entry<Integer, JLabel> entry : this.valueTable.entrySet( ) ) elements.add( entry.getValue( ) ); return elements.elements( ); } @Override public JLabel get( Object key ) { return this.valueTable.get( key ); } @Override public boolean isEmpty( ) { return this.valueTable.isEmpty( ); } @Override public Enumeration<Integer> keys( ) { Vector<Integer> keys = new Vector<Integer>( ); for ( Integer key : this.valueTable.keySet( ) ) keys.add( key ); return keys.elements( ); } @Override public JLabel put( Integer key, JLabel value ) { return this.valueTable.put( key, value ); } @Override public JLabel remove( Object key ) { return this.valueTable.remove( key ); } @Override public int size( ) { return this.valueTable.size( ); } }; /** * The exponent used to scale the values, to avoid rounding-errors due to the conversion from * double to int. */ private int usedExponent; private int _minimumValue; private int _maximumValue; private int _tickSpacingValue; @Override protected int compareValues( Double val1, Double val2 ) { if ( val1 > val2 ) return 1; if ( val1 < val2 ) return -1; return 0; } @Override protected int convertTypeToInteger( Double valueToScale ) { return ( int ) ( Math.round( valueToScale * Math.pow( 10d, Math.abs( this.usedExponent ) ) ) ); } @Override public void setDefaultRange( ) { this.setRange( 0d, 1d, 0.1d ); } @Override public void setRange( Double minimum, Double maximum ) { double tickspacing = ( double ) ( maximum - minimum ) / 10d; this.setRange( minimum, maximum, tickspacing ); } @Override public void _setRange( Double minimum, Double maximum, Double tickSpacing ) { /* check if the values are valid */ if ( maximum <= minimum ) { System.err.println( "Wrong range specified. Maximum [" + maximum + "] have to be greater than the minimum [" + minimum + "]" ); return; } double tickSpacingRatio = Math.abs( tickSpacing / ( maximum - minimum ) ); /* * We want to display the incoming range of doubles. So we have to convert * the double-values to int-values, because the slider only takes int-values. * To reduce the rounding-error caused by the conversion from double to int, we have * to scale the values (right-shift the comma). Therefore we have to calculate * the maximum exponent. */ int exponent = this.getExponent( minimum ); this.usedExponent = this.getExponent( maximum ); if ( ( exponent > this.usedExponent ) && ( exponent != 0 ) ) this.usedExponent = exponent; exponent = this.getExponent( tickSpacing ); if ( ( exponent > this.usedExponent ) && ( exponent != 0 ) ) this.usedExponent = exponent; /* * Scale the values using the exponent determined before. */ this._maximumValue = ( int ) ( maximum * Math.pow( 10d, this.usedExponent ) ); this._minimumValue = ( int ) ( minimum * Math.pow( 10d, this.usedExponent ) ); this._tickSpacingValue = ( int ) ( ( this._maximumValue - this._minimumValue ) * tickSpacingRatio ); /* * Reduce the exponent if the given exponent caused an integer-over-/ underflow. */ while ( ( this._maximumValue == Integer.MAX_VALUE ) || ( this._minimumValue == Integer.MIN_VALUE ) ) { this.usedExponent--; this._maximumValue = ( int ) ( maximum * Math.pow( 10d, this.usedExponent ) ); this._minimumValue = ( int ) ( minimum * Math.pow( 10d, this.usedExponent ) ); this._tickSpacingValue = ( int ) ( ( this._maximumValue - this._minimumValue ) * tickSpacingRatio ); } /* guarantee that the tickspacing is not 0 */ if ( this._tickSpacingValue == 0 ) this._tickSpacingValue = 1; /* * Set the values */ this.setMajorTickSpacing( this._tickSpacingValue ); this.setMaximum( this._maximumValue ); this.setMinimum( this._minimumValue ); /* calculate the number of thicks */ int numTicks = ( ( this._maximumValue - this._minimumValue ) / this._tickSpacingValue ) + 1; if ( numTicks % 2 == 0 ) numTicks++; /* create the labelling */ DoubleLabelling labelling = new DoubleLabelling( ); for ( int i = 0; i < numTicks; i++ ) { int key = this._minimumValue + ( this._tickSpacingValue * i ); /* avoid an overflow */ if ( key > this._maximumValue ) key = this._maximumValue; /* guarantee that the last tick-mark points to the last value of the slider */ if ( i == ( numTicks - 1 ) ) key = this._maximumValue; BigDecimal bd = new BigDecimal( key / Math.pow( 10d, Math.abs( this.usedExponent ) ) ); labelling.put( key, new JLabel( String.format( "%1$.2E", bd.doubleValue( ) ) ) ); } this.setLabelTable( labelling ); } @Override protected Integer getNextRoundedKey( int value ) { int numValues = ( int ) Math.round( ( value - this._minimumValue ) / ( double ) this._tickSpacingValue ); value = ( numValues * this._tickSpacingValue ) + this._minimumValue; if ( value < this._minimumValue ) value = this._minimumValue; if ( value > this._maximumValue ) value = this._maximumValue; return value; } @Override protected Double convertIntegerToType( int integerToConvert ) { return ( integerToConvert / Math.pow( 10d, Math.abs( this.usedExponent ) ) ); } /** * Calculates the exponent of the given value. The function tries to find a exponent that can be * used to scale the given double value, whereby the rounding-error caused by an conversion of * the scaled double value to an int will be minimal. * @param value * @return */ private int getExponent( double value ) { int exponent = 0; if ( value == 0.0 ) return 0; double dbl_val = value * Math.pow( 10d, ( double ) exponent ); long int_val = ( long ) dbl_val; /* increment the exponent until the rounding-error is gone */ while ( Math.abs( int_val - dbl_val ) > 0.0000001 ) { exponent++; dbl_val = value * Math.pow( 10d, ( double ) exponent ); int_val = ( long ) dbl_val; } return exponent; } @Override public Double getIncreasedValue( ) { double value = this.getCurrentValue( ) + this.getTickSpacingValue( ); if ( value > this.getMaximumValue( ) ) value = this.getMaximumValue( ); if ( value < this.getMinimumValue( ) ) value = this.getMinimumValue( ); return value; } @Override public Double getDecreasedValue( ) { double value = this.getCurrentValue( ) - this.getTickSpacingValue( ); if ( value > this.getMaximumValue( ) ) value = this.getMaximumValue( ); if ( value < this.getMinimumValue( ) ) value = this.getMinimumValue( ); return value; } }
/* * 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.aliyuncs.sas.model.v20181203; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.sas.Endpoint; /** * @author auto create * @version */ public class CreateServiceLinkedRoleRequest extends RpcAcsRequest<CreateServiceLinkedRoleResponse> { public CreateServiceLinkedRoleRequest() { super("Sas", "2018-12-03", "CreateServiceLinkedRole"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } @Override public Class<CreateServiceLinkedRoleResponse> getResponseClass() { return CreateServiceLinkedRoleResponse.class; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1beta1/cluster_service.proto package com.google.container.v1beta1; /** * <pre> * Configuration options for private clusters. * </pre> * * Protobuf type {@code google.container.v1beta1.PrivateClusterConfig} */ public final class PrivateClusterConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1beta1.PrivateClusterConfig) PrivateClusterConfigOrBuilder { private static final long serialVersionUID = 0L; // Use PrivateClusterConfig.newBuilder() to construct. private PrivateClusterConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PrivateClusterConfig() { masterIpv4CidrBlock_ = ""; privateEndpoint_ = ""; publicEndpoint_ = ""; peeringName_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new PrivateClusterConfig(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private PrivateClusterConfig( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } 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 8: { enablePrivateNodes_ = input.readBool(); break; } case 16: { enablePrivateEndpoint_ = input.readBool(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); masterIpv4CidrBlock_ = s; break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); privateEndpoint_ = s; break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); publicEndpoint_ = s; break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); peeringName_ = s; break; } case 66: { com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.Builder subBuilder = null; if (masterGlobalAccessConfig_ != null) { subBuilder = masterGlobalAccessConfig_.toBuilder(); } masterGlobalAccessConfig_ = input.readMessage(com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(masterGlobalAccessConfig_); masterGlobalAccessConfig_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( 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.container.v1beta1.ClusterServiceProto.internal_static_google_container_v1beta1_PrivateClusterConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto.internal_static_google_container_v1beta1_PrivateClusterConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.PrivateClusterConfig.class, com.google.container.v1beta1.PrivateClusterConfig.Builder.class); } public static final int ENABLE_PRIVATE_NODES_FIELD_NUMBER = 1; private boolean enablePrivateNodes_; /** * <pre> * Whether nodes have internal IP addresses only. If enabled, all nodes are * given only RFC 1918 private addresses and communicate with the master via * private networking. * </pre> * * <code>bool enable_private_nodes = 1;</code> * @return The enablePrivateNodes. */ @java.lang.Override public boolean getEnablePrivateNodes() { return enablePrivateNodes_; } public static final int ENABLE_PRIVATE_ENDPOINT_FIELD_NUMBER = 2; private boolean enablePrivateEndpoint_; /** * <pre> * Whether the master's internal IP address is used as the cluster endpoint. * </pre> * * <code>bool enable_private_endpoint = 2;</code> * @return The enablePrivateEndpoint. */ @java.lang.Override public boolean getEnablePrivateEndpoint() { return enablePrivateEndpoint_; } public static final int MASTER_IPV4_CIDR_BLOCK_FIELD_NUMBER = 3; private volatile java.lang.Object masterIpv4CidrBlock_; /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @return The masterIpv4CidrBlock. */ @java.lang.Override public java.lang.String getMasterIpv4CidrBlock() { java.lang.Object ref = masterIpv4CidrBlock_; 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(); masterIpv4CidrBlock_ = s; return s; } } /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @return The bytes for masterIpv4CidrBlock. */ @java.lang.Override public com.google.protobuf.ByteString getMasterIpv4CidrBlockBytes() { java.lang.Object ref = masterIpv4CidrBlock_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); masterIpv4CidrBlock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PRIVATE_ENDPOINT_FIELD_NUMBER = 4; private volatile java.lang.Object privateEndpoint_; /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @return The privateEndpoint. */ @java.lang.Override public java.lang.String getPrivateEndpoint() { java.lang.Object ref = privateEndpoint_; 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(); privateEndpoint_ = s; return s; } } /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @return The bytes for privateEndpoint. */ @java.lang.Override public com.google.protobuf.ByteString getPrivateEndpointBytes() { java.lang.Object ref = privateEndpoint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); privateEndpoint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PUBLIC_ENDPOINT_FIELD_NUMBER = 5; private volatile java.lang.Object publicEndpoint_; /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @return The publicEndpoint. */ @java.lang.Override public java.lang.String getPublicEndpoint() { java.lang.Object ref = publicEndpoint_; 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(); publicEndpoint_ = s; return s; } } /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @return The bytes for publicEndpoint. */ @java.lang.Override public com.google.protobuf.ByteString getPublicEndpointBytes() { java.lang.Object ref = publicEndpoint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicEndpoint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PEERING_NAME_FIELD_NUMBER = 7; private volatile java.lang.Object peeringName_; /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @return The peeringName. */ @java.lang.Override public java.lang.String getPeeringName() { java.lang.Object ref = peeringName_; 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(); peeringName_ = s; return s; } } /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @return The bytes for peeringName. */ @java.lang.Override public com.google.protobuf.ByteString getPeeringNameBytes() { java.lang.Object ref = peeringName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); peeringName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MASTER_GLOBAL_ACCESS_CONFIG_FIELD_NUMBER = 8; private com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig masterGlobalAccessConfig_; /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> * @return Whether the masterGlobalAccessConfig field is set. */ @java.lang.Override public boolean hasMasterGlobalAccessConfig() { return masterGlobalAccessConfig_ != null; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> * @return The masterGlobalAccessConfig. */ @java.lang.Override public com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig getMasterGlobalAccessConfig() { return masterGlobalAccessConfig_ == null ? com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.getDefaultInstance() : masterGlobalAccessConfig_; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ @java.lang.Override public com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfigOrBuilder getMasterGlobalAccessConfigOrBuilder() { return getMasterGlobalAccessConfig(); } 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 (enablePrivateNodes_ != false) { output.writeBool(1, enablePrivateNodes_); } if (enablePrivateEndpoint_ != false) { output.writeBool(2, enablePrivateEndpoint_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(masterIpv4CidrBlock_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, masterIpv4CidrBlock_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(privateEndpoint_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, privateEndpoint_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(publicEndpoint_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, publicEndpoint_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(peeringName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, peeringName_); } if (masterGlobalAccessConfig_ != null) { output.writeMessage(8, getMasterGlobalAccessConfig()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (enablePrivateNodes_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, enablePrivateNodes_); } if (enablePrivateEndpoint_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(2, enablePrivateEndpoint_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(masterIpv4CidrBlock_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, masterIpv4CidrBlock_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(privateEndpoint_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, privateEndpoint_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(publicEndpoint_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, publicEndpoint_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(peeringName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, peeringName_); } if (masterGlobalAccessConfig_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, getMasterGlobalAccessConfig()); } 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.container.v1beta1.PrivateClusterConfig)) { return super.equals(obj); } com.google.container.v1beta1.PrivateClusterConfig other = (com.google.container.v1beta1.PrivateClusterConfig) obj; if (getEnablePrivateNodes() != other.getEnablePrivateNodes()) return false; if (getEnablePrivateEndpoint() != other.getEnablePrivateEndpoint()) return false; if (!getMasterIpv4CidrBlock() .equals(other.getMasterIpv4CidrBlock())) return false; if (!getPrivateEndpoint() .equals(other.getPrivateEndpoint())) return false; if (!getPublicEndpoint() .equals(other.getPublicEndpoint())) return false; if (!getPeeringName() .equals(other.getPeeringName())) return false; if (hasMasterGlobalAccessConfig() != other.hasMasterGlobalAccessConfig()) return false; if (hasMasterGlobalAccessConfig()) { if (!getMasterGlobalAccessConfig() .equals(other.getMasterGlobalAccessConfig())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ENABLE_PRIVATE_NODES_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEnablePrivateNodes()); hash = (37 * hash) + ENABLE_PRIVATE_ENDPOINT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEnablePrivateEndpoint()); hash = (37 * hash) + MASTER_IPV4_CIDR_BLOCK_FIELD_NUMBER; hash = (53 * hash) + getMasterIpv4CidrBlock().hashCode(); hash = (37 * hash) + PRIVATE_ENDPOINT_FIELD_NUMBER; hash = (53 * hash) + getPrivateEndpoint().hashCode(); hash = (37 * hash) + PUBLIC_ENDPOINT_FIELD_NUMBER; hash = (53 * hash) + getPublicEndpoint().hashCode(); hash = (37 * hash) + PEERING_NAME_FIELD_NUMBER; hash = (53 * hash) + getPeeringName().hashCode(); if (hasMasterGlobalAccessConfig()) { hash = (37 * hash) + MASTER_GLOBAL_ACCESS_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getMasterGlobalAccessConfig().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1beta1.PrivateClusterConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.PrivateClusterConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.PrivateClusterConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.PrivateClusterConfig 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.container.v1beta1.PrivateClusterConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.PrivateClusterConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.PrivateClusterConfig parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.PrivateClusterConfig 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.container.v1beta1.PrivateClusterConfig parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1beta1.PrivateClusterConfig 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.container.v1beta1.PrivateClusterConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.PrivateClusterConfig 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.container.v1beta1.PrivateClusterConfig 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> * Configuration options for private clusters. * </pre> * * Protobuf type {@code google.container.v1beta1.PrivateClusterConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1beta1.PrivateClusterConfig) com.google.container.v1beta1.PrivateClusterConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto.internal_static_google_container_v1beta1_PrivateClusterConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto.internal_static_google_container_v1beta1_PrivateClusterConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.PrivateClusterConfig.class, com.google.container.v1beta1.PrivateClusterConfig.Builder.class); } // Construct using com.google.container.v1beta1.PrivateClusterConfig.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(); enablePrivateNodes_ = false; enablePrivateEndpoint_ = false; masterIpv4CidrBlock_ = ""; privateEndpoint_ = ""; publicEndpoint_ = ""; peeringName_ = ""; if (masterGlobalAccessConfigBuilder_ == null) { masterGlobalAccessConfig_ = null; } else { masterGlobalAccessConfig_ = null; masterGlobalAccessConfigBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1beta1.ClusterServiceProto.internal_static_google_container_v1beta1_PrivateClusterConfig_descriptor; } @java.lang.Override public com.google.container.v1beta1.PrivateClusterConfig getDefaultInstanceForType() { return com.google.container.v1beta1.PrivateClusterConfig.getDefaultInstance(); } @java.lang.Override public com.google.container.v1beta1.PrivateClusterConfig build() { com.google.container.v1beta1.PrivateClusterConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1beta1.PrivateClusterConfig buildPartial() { com.google.container.v1beta1.PrivateClusterConfig result = new com.google.container.v1beta1.PrivateClusterConfig(this); result.enablePrivateNodes_ = enablePrivateNodes_; result.enablePrivateEndpoint_ = enablePrivateEndpoint_; result.masterIpv4CidrBlock_ = masterIpv4CidrBlock_; result.privateEndpoint_ = privateEndpoint_; result.publicEndpoint_ = publicEndpoint_; result.peeringName_ = peeringName_; if (masterGlobalAccessConfigBuilder_ == null) { result.masterGlobalAccessConfig_ = masterGlobalAccessConfig_; } else { result.masterGlobalAccessConfig_ = masterGlobalAccessConfigBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1beta1.PrivateClusterConfig) { return mergeFrom((com.google.container.v1beta1.PrivateClusterConfig)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1beta1.PrivateClusterConfig other) { if (other == com.google.container.v1beta1.PrivateClusterConfig.getDefaultInstance()) return this; if (other.getEnablePrivateNodes() != false) { setEnablePrivateNodes(other.getEnablePrivateNodes()); } if (other.getEnablePrivateEndpoint() != false) { setEnablePrivateEndpoint(other.getEnablePrivateEndpoint()); } if (!other.getMasterIpv4CidrBlock().isEmpty()) { masterIpv4CidrBlock_ = other.masterIpv4CidrBlock_; onChanged(); } if (!other.getPrivateEndpoint().isEmpty()) { privateEndpoint_ = other.privateEndpoint_; onChanged(); } if (!other.getPublicEndpoint().isEmpty()) { publicEndpoint_ = other.publicEndpoint_; onChanged(); } if (!other.getPeeringName().isEmpty()) { peeringName_ = other.peeringName_; onChanged(); } if (other.hasMasterGlobalAccessConfig()) { mergeMasterGlobalAccessConfig(other.getMasterGlobalAccessConfig()); } 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.container.v1beta1.PrivateClusterConfig parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.container.v1beta1.PrivateClusterConfig) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private boolean enablePrivateNodes_ ; /** * <pre> * Whether nodes have internal IP addresses only. If enabled, all nodes are * given only RFC 1918 private addresses and communicate with the master via * private networking. * </pre> * * <code>bool enable_private_nodes = 1;</code> * @return The enablePrivateNodes. */ @java.lang.Override public boolean getEnablePrivateNodes() { return enablePrivateNodes_; } /** * <pre> * Whether nodes have internal IP addresses only. If enabled, all nodes are * given only RFC 1918 private addresses and communicate with the master via * private networking. * </pre> * * <code>bool enable_private_nodes = 1;</code> * @param value The enablePrivateNodes to set. * @return This builder for chaining. */ public Builder setEnablePrivateNodes(boolean value) { enablePrivateNodes_ = value; onChanged(); return this; } /** * <pre> * Whether nodes have internal IP addresses only. If enabled, all nodes are * given only RFC 1918 private addresses and communicate with the master via * private networking. * </pre> * * <code>bool enable_private_nodes = 1;</code> * @return This builder for chaining. */ public Builder clearEnablePrivateNodes() { enablePrivateNodes_ = false; onChanged(); return this; } private boolean enablePrivateEndpoint_ ; /** * <pre> * Whether the master's internal IP address is used as the cluster endpoint. * </pre> * * <code>bool enable_private_endpoint = 2;</code> * @return The enablePrivateEndpoint. */ @java.lang.Override public boolean getEnablePrivateEndpoint() { return enablePrivateEndpoint_; } /** * <pre> * Whether the master's internal IP address is used as the cluster endpoint. * </pre> * * <code>bool enable_private_endpoint = 2;</code> * @param value The enablePrivateEndpoint to set. * @return This builder for chaining. */ public Builder setEnablePrivateEndpoint(boolean value) { enablePrivateEndpoint_ = value; onChanged(); return this; } /** * <pre> * Whether the master's internal IP address is used as the cluster endpoint. * </pre> * * <code>bool enable_private_endpoint = 2;</code> * @return This builder for chaining. */ public Builder clearEnablePrivateEndpoint() { enablePrivateEndpoint_ = false; onChanged(); return this; } private java.lang.Object masterIpv4CidrBlock_ = ""; /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @return The masterIpv4CidrBlock. */ public java.lang.String getMasterIpv4CidrBlock() { java.lang.Object ref = masterIpv4CidrBlock_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); masterIpv4CidrBlock_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @return The bytes for masterIpv4CidrBlock. */ public com.google.protobuf.ByteString getMasterIpv4CidrBlockBytes() { java.lang.Object ref = masterIpv4CidrBlock_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); masterIpv4CidrBlock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @param value The masterIpv4CidrBlock to set. * @return This builder for chaining. */ public Builder setMasterIpv4CidrBlock( java.lang.String value) { if (value == null) { throw new NullPointerException(); } masterIpv4CidrBlock_ = value; onChanged(); return this; } /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @return This builder for chaining. */ public Builder clearMasterIpv4CidrBlock() { masterIpv4CidrBlock_ = getDefaultInstance().getMasterIpv4CidrBlock(); onChanged(); return this; } /** * <pre> * The IP range in CIDR notation to use for the hosted master network. This * range will be used for assigning internal IP addresses to the master or * set of masters, as well as the ILB VIP. This range must not overlap with * any other ranges in use within the cluster's network. * </pre> * * <code>string master_ipv4_cidr_block = 3;</code> * @param value The bytes for masterIpv4CidrBlock to set. * @return This builder for chaining. */ public Builder setMasterIpv4CidrBlockBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); masterIpv4CidrBlock_ = value; onChanged(); return this; } private java.lang.Object privateEndpoint_ = ""; /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @return The privateEndpoint. */ public java.lang.String getPrivateEndpoint() { java.lang.Object ref = privateEndpoint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); privateEndpoint_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @return The bytes for privateEndpoint. */ public com.google.protobuf.ByteString getPrivateEndpointBytes() { java.lang.Object ref = privateEndpoint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); privateEndpoint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @param value The privateEndpoint to set. * @return This builder for chaining. */ public Builder setPrivateEndpoint( java.lang.String value) { if (value == null) { throw new NullPointerException(); } privateEndpoint_ = value; onChanged(); return this; } /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @return This builder for chaining. */ public Builder clearPrivateEndpoint() { privateEndpoint_ = getDefaultInstance().getPrivateEndpoint(); onChanged(); return this; } /** * <pre> * Output only. The internal IP address of this cluster's master endpoint. * </pre> * * <code>string private_endpoint = 4;</code> * @param value The bytes for privateEndpoint to set. * @return This builder for chaining. */ public Builder setPrivateEndpointBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); privateEndpoint_ = value; onChanged(); return this; } private java.lang.Object publicEndpoint_ = ""; /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @return The publicEndpoint. */ public java.lang.String getPublicEndpoint() { java.lang.Object ref = publicEndpoint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); publicEndpoint_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @return The bytes for publicEndpoint. */ public com.google.protobuf.ByteString getPublicEndpointBytes() { java.lang.Object ref = publicEndpoint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); publicEndpoint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @param value The publicEndpoint to set. * @return This builder for chaining. */ public Builder setPublicEndpoint( java.lang.String value) { if (value == null) { throw new NullPointerException(); } publicEndpoint_ = value; onChanged(); return this; } /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @return This builder for chaining. */ public Builder clearPublicEndpoint() { publicEndpoint_ = getDefaultInstance().getPublicEndpoint(); onChanged(); return this; } /** * <pre> * Output only. The external IP address of this cluster's master endpoint. * </pre> * * <code>string public_endpoint = 5;</code> * @param value The bytes for publicEndpoint to set. * @return This builder for chaining. */ public Builder setPublicEndpointBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); publicEndpoint_ = value; onChanged(); return this; } private java.lang.Object peeringName_ = ""; /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @return The peeringName. */ public java.lang.String getPeeringName() { java.lang.Object ref = peeringName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); peeringName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @return The bytes for peeringName. */ public com.google.protobuf.ByteString getPeeringNameBytes() { java.lang.Object ref = peeringName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); peeringName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @param value The peeringName to set. * @return This builder for chaining. */ public Builder setPeeringName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } peeringName_ = value; onChanged(); return this; } /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @return This builder for chaining. */ public Builder clearPeeringName() { peeringName_ = getDefaultInstance().getPeeringName(); onChanged(); return this; } /** * <pre> * Output only. The peering name in the customer VPC used by this cluster. * </pre> * * <code>string peering_name = 7;</code> * @param value The bytes for peeringName to set. * @return This builder for chaining. */ public Builder setPeeringNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); peeringName_ = value; onChanged(); return this; } private com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig masterGlobalAccessConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig, com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.Builder, com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfigOrBuilder> masterGlobalAccessConfigBuilder_; /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> * @return Whether the masterGlobalAccessConfig field is set. */ public boolean hasMasterGlobalAccessConfig() { return masterGlobalAccessConfigBuilder_ != null || masterGlobalAccessConfig_ != null; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> * @return The masterGlobalAccessConfig. */ public com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig getMasterGlobalAccessConfig() { if (masterGlobalAccessConfigBuilder_ == null) { return masterGlobalAccessConfig_ == null ? com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.getDefaultInstance() : masterGlobalAccessConfig_; } else { return masterGlobalAccessConfigBuilder_.getMessage(); } } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ public Builder setMasterGlobalAccessConfig(com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig value) { if (masterGlobalAccessConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } masterGlobalAccessConfig_ = value; onChanged(); } else { masterGlobalAccessConfigBuilder_.setMessage(value); } return this; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ public Builder setMasterGlobalAccessConfig( com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.Builder builderForValue) { if (masterGlobalAccessConfigBuilder_ == null) { masterGlobalAccessConfig_ = builderForValue.build(); onChanged(); } else { masterGlobalAccessConfigBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ public Builder mergeMasterGlobalAccessConfig(com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig value) { if (masterGlobalAccessConfigBuilder_ == null) { if (masterGlobalAccessConfig_ != null) { masterGlobalAccessConfig_ = com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.newBuilder(masterGlobalAccessConfig_).mergeFrom(value).buildPartial(); } else { masterGlobalAccessConfig_ = value; } onChanged(); } else { masterGlobalAccessConfigBuilder_.mergeFrom(value); } return this; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ public Builder clearMasterGlobalAccessConfig() { if (masterGlobalAccessConfigBuilder_ == null) { masterGlobalAccessConfig_ = null; onChanged(); } else { masterGlobalAccessConfig_ = null; masterGlobalAccessConfigBuilder_ = null; } return this; } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ public com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.Builder getMasterGlobalAccessConfigBuilder() { onChanged(); return getMasterGlobalAccessConfigFieldBuilder().getBuilder(); } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ public com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfigOrBuilder getMasterGlobalAccessConfigOrBuilder() { if (masterGlobalAccessConfigBuilder_ != null) { return masterGlobalAccessConfigBuilder_.getMessageOrBuilder(); } else { return masterGlobalAccessConfig_ == null ? com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.getDefaultInstance() : masterGlobalAccessConfig_; } } /** * <pre> * Controls master global access settings. * </pre> * * <code>.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig master_global_access_config = 8;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig, com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.Builder, com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfigOrBuilder> getMasterGlobalAccessConfigFieldBuilder() { if (masterGlobalAccessConfigBuilder_ == null) { masterGlobalAccessConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig, com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfig.Builder, com.google.container.v1beta1.PrivateClusterMasterGlobalAccessConfigOrBuilder>( getMasterGlobalAccessConfig(), getParentForChildren(), isClean()); masterGlobalAccessConfig_ = null; } return masterGlobalAccessConfigBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1beta1.PrivateClusterConfig) } // @@protoc_insertion_point(class_scope:google.container.v1beta1.PrivateClusterConfig) private static final com.google.container.v1beta1.PrivateClusterConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1beta1.PrivateClusterConfig(); } public static com.google.container.v1beta1.PrivateClusterConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PrivateClusterConfig> PARSER = new com.google.protobuf.AbstractParser<PrivateClusterConfig>() { @java.lang.Override public PrivateClusterConfig parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new PrivateClusterConfig(input, extensionRegistry); } }; public static com.google.protobuf.Parser<PrivateClusterConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PrivateClusterConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1beta1.PrivateClusterConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.domain.InsCertificatePaginationList; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.ins.marketing.certificate.batchquery response. * * @author auto create * @since 1.0, 2019-01-07 20:51:15 */ public class AlipayInsMarketingCertificateBatchqueryResponse extends AlipayResponse { private static final long serialVersionUID = 8694838633972579991L; /** * 分页查询结果 */ @ApiField("ins_certificate_pagination_list") private InsCertificatePaginationList insCertificatePaginationList; public void setInsCertificatePaginationList(InsCertificatePaginationList insCertificatePaginationList) { this.insCertificatePaginationList = insCertificatePaginationList; } public InsCertificatePaginationList getInsCertificatePaginationList() { return this.insCertificatePaginationList; } }
/** * Copyright 2005-2016 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.itests.support; import io.fabric8.api.DynamicReference; import io.fabric8.api.jcip.ThreadSafe; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.TimeUnit; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; @ThreadSafe public final class ServiceProxy<T> { public static long DEFAULT_TIMEOUT = 30000L; private final Class<T> serviceClazz; private final DelegatingInvocationHandler<T> invocationHandler; public static <T> ServiceProxy<T> createServiceProxy(BundleContext context, Class<T> serviceClazz) { return new ServiceProxy<T>(context, serviceClazz, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); } public static <T> ServiceProxy<T> createServiceProxy(BundleContext context, Class<T> serviceClazz, long timeout, TimeUnit timeUnit) { return new ServiceProxy<T>(context, serviceClazz, timeout, timeUnit); } private ServiceProxy(BundleContext bundleContext, Class<T> serviceClazz, long timeout, TimeUnit timeUnit) { this.invocationHandler = new DelegatingInvocationHandler<T>(bundleContext, serviceClazz, timeout, timeUnit); this.serviceClazz = serviceClazz; } @SuppressWarnings("unchecked") public T getService() { return (T) Proxy.newProxyInstance(serviceClazz.getClassLoader(), new Class[] { serviceClazz }, invocationHandler); } public void close() { invocationHandler.close(); } private static class DelegatingInvocationHandler<T> implements InvocationHandler { private final DynamicReference<T> dynamicReference; private final ServiceTracker<T, T> tracker; DelegatingInvocationHandler(BundleContext context, Class<T> type, long timeout, TimeUnit unit) { dynamicReference = new DynamicReference<T>(type.getSimpleName(), timeout, unit); tracker = new ServiceTracker<T, T>(context, type, null) { @Override public T addingService(ServiceReference<T> reference) { T service = super.addingService(reference); dynamicReference.bind(service); return service; } @Override public void modifiedService(ServiceReference<T> reference, T service) { super.modifiedService(reference, service); dynamicReference.bind(service); } @Override public void removedService(ServiceReference<T> reference, T service) { super.removedService(reference, service); dynamicReference.unbind(service); } }; tracker.open(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { T service = dynamicReference.get(); return method.invoke(service, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } void close() { tracker.close(); } } }
package com.wonderpush.sdk; import android.content.Context; /** * Information-storing class for the hook called when the SDK is trying to open the appropriate deep-link. * * @see WonderPushDelegate#urlForDeepLink(DeepLinkEvent) */ public class DeepLinkEvent { private Context context; private String url; DeepLinkEvent(Context context, String url) { this.context = context; this.url = url; } /** * The context we are running in. */ public Context getContext() { return context; } /** * The deep-link we are to open. */ public String getUrl() { return url; } @Override public String toString() { return "DeepLinkEvent{" + "url='" + url + '\'' + '}'; } }
package org.ovirt.engine.core.bll.storage.domain; import java.util.Collections; import java.util.Map; import org.ovirt.engine.core.bll.LockMessagesMatchUtil; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.storage.connection.StorageHelperDirector; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.LockProperties; import org.ovirt.engine.core.common.action.LockProperties.Scope; import org.ovirt.engine.core.common.action.ReconstructMasterParameters; import org.ovirt.engine.core.common.action.StorageDomainParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.storage.StorageType; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.vdscommands.DetachStorageDomainVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; public class ForceRemoveStorageDomainCommand<T extends StorageDomainParametersBase> extends StorageDomainCommandBase<T> { public ForceRemoveStorageDomainCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); } @Override protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Execution); } @Override protected void executeCommand() { if (getStoragePool() != null) { try { // if master try to reconstruct if (getStorageDomain().getStorageDomainType() == StorageDomainType.Master) { ReconstructMasterParameters tempVar = new ReconstructMasterParameters(getStoragePool().getId(), getStorageDomain().getId(), false); tempVar.setTransactionScopeOption(TransactionScopeOption.RequiresNew); runInternalAction(VdcActionType.ReconstructMasterDomain, tempVar); } // try to force detach first DetachStorageDomainVDSCommandParameters tempVar2 = new DetachStorageDomainVDSCommandParameters( getStoragePool().getId(), getStorageDomain().getId(), Guid.Empty, -1); tempVar2.setForce(true); runVdsCommand(VDSCommandType.DetachStorageDomain, tempVar2); } catch (RuntimeException ex) { log.error("Could not force detach storage domain '{}': {}", getStorageDomain().getStorageName(), ex.getMessage()); log.debug("Exception", ex); } } StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .storageDomainRemoved(getStorageDomain().getStorageStaticData()); storageDomainDao.remove(getStorageDomain().getId()); if (getStoragePool() != null) { // if iso reset path for pool if (getStorageDomain().getStorageDomainType() == StorageDomainType.ISO) { // todo: when iso in multiple pools will be implemented, we // should reset iso path for all related pools runVdsCommand(VDSCommandType.ResetISOPath, new IrsBaseVDSCommandParameters(getStoragePool().getId())); } if (getStorageDomain().getStorageDomainType() == StorageDomainType.Master) { calcStoragePoolStatusByDomainsStatus(); } } setSucceeded(true); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_FORCE_REMOVE_STORAGE_DOMAIN : AuditLogType.USER_FORCE_REMOVE_STORAGE_DOMAIN_FAILED; } @Override protected boolean validate() { boolean returnValue = super.validate() && checkStorageDomain() && (getStorageDomain().getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached || checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); if (returnValue && getStorageDomain().getStorageDomainType() == StorageDomainType.Master && getStoragePool() != null) { if (electNewMaster() == null) { returnValue = false; addValidationMessage(EngineMessage.ERROR_CANNOT_DESTROY_LAST_STORAGE_DOMAIN); } else if (!initializeVds()) { returnValue = false; addValidationMessage(EngineMessage.ERROR_CANNOT_DESTROY_LAST_STORAGE_DOMAIN_HOST_NOT_ACTIVE); } } if (returnValue && getStorageDomain().getStorageType() == StorageType.GLANCE) { addValidationMessage(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); returnValue = false; } return returnValue; } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { return Collections.singletonMap(getParameters().getStorageDomainId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.STORAGE, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } @Override protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__DESTROY_DOMAIN); } }
/******************************************************************************* * Copyright 2012 momock.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.momock.outlet.action; import com.momock.event.Event; import com.momock.event.IEvent; import com.momock.event.IEventArgs; import com.momock.event.IEventHandler; import com.momock.holder.ImageHolder; import com.momock.holder.TextHolder; import com.momock.outlet.IOutlet; import com.momock.outlet.Plug; public class ActionPlug extends Plug implements IActionPlug { int order = DEFAULT_ORDER; TextHolder text = null; ImageHolder icon = null; IOutlet<IActionPlug, ?> subOutlet = null; IEvent<IEventArgs> event = new Event<IEventArgs>(); private ActionPlug() { } @Override public int getOrder() { return order; } @Override public TextHolder getText() { return text; } public ActionPlug setText(TextHolder text) { this.text = text; return this; } @Override public ImageHolder getIcon() { return icon; } public ActionPlug setIcon(ImageHolder icon) { this.icon = icon; return this; } @Override public IOutlet<IActionPlug, ?> getSubOutlet() { return subOutlet; } public ActionPlug setSubOutlet(IOutlet<IActionPlug, ?> subOutlet) { this.subOutlet = subOutlet; return this; } @Override public IEvent<IEventArgs> getExecuteEvent() { return event; } public ActionPlug addExecuteEventHandler(IEventHandler<IEventArgs> handler) { event.addEventHandler(handler); return this; } public static ActionPlug get(TextHolder text) { ActionPlug plug = new ActionPlug(); return plug.setText(text); } public static ActionPlug get(TextHolder text, IEventHandler<IEventArgs> handler) { ActionPlug plug = new ActionPlug(); return plug.setText(text).addExecuteEventHandler(handler); } public static ActionPlug get(TextHolder text, ImageHolder icon) { ActionPlug plug = new ActionPlug(); return plug.setText(text).setIcon(icon); } public static ActionPlug get(TextHolder text, ImageHolder icon, IEventHandler<IEventArgs> handler) { ActionPlug plug = new ActionPlug(); return plug.setText(text).setIcon(icon).addExecuteEventHandler(handler); } }
package com.systemorderservice.insfrastructure.repository; import com.systemorderservice.domain.model.OrderService; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface IOrderServiceRepository extends JpaRepository<OrderService,Integer> { @Query("Select od from OrderService od where od.shippingForProduction = true") List<OrderService> findOrderServiceBy(); @Query("Select od from OrderService od where od.orderStatus = 'ABERTO'") Integer findAllQuantity(); @Query("Select od from OrderService od where od.orderStatus = 'PENDING'") Integer findAllQuantityPending(); @Query("Select od from OrderService od where od.orderStatus = 'LOST'") Integer findAllQuantityLost(); @Query("Select od from OrderService od where od.orderStatus = 'CLOSED'") Integer findAllQuantityClosed(); @Query("Select od from OrderService od where od.orderStatus = 'ABERTO'") Integer findAllQuantityService(); }
package me.ele.jarch.athena.netty; import io.netty.channel.ChannelHandlerContext; import me.ele.jarch.athena.exception.QuitException; import me.ele.jarch.athena.pg.proto.*; import me.ele.jarch.athena.server.pool.PGServerSession; import me.ele.jarch.athena.sql.CmdTcpPacket; import me.ele.jarch.athena.sql.PGCmdTcpPacket; import me.ele.jarch.athena.util.NoThrow; import me.ele.jarch.athena.util.PacketLengthUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PGSqlServerPacketDecoder extends SqlServerPacketDecoder { private static final Logger LOGGER = LoggerFactory.getLogger(PGSqlServerPacketDecoder.class); @Override protected CmdTcpPacket newPacket() { return new PGCmdTcpPacket(inputbuf); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { PacketLengthUtil.trySendErr2Client(sqlCtx, cause, () -> PacketLengthUtil .buildPGPktTooLargeErr(getClass().getSimpleName(), "db_packet_decode").toPacket()); super.exceptionCaught(ctx, cause); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); serverSession .dbServerWriteAndFlush(((PGServerSession) serverSession).newStartupMessage(), (s) -> { LOGGER.error( "Cannot send StartupMessage to server in channelActive. " + this.serverSession .getOriginDbConnInfo().getQualifiedDbId()); serverSession.doQuit(); }); } // PG复写该方法,使得异步结果仍然存储在packets里 @Override protected void recvPacketWhenNoSqlCtxBind() { try { for (byte[] packet : packets) { if (packet.length < 1) { continue; } // 暂时使用ERROR级别输出,方便查看线上异步操作的情况 // 待PG稳定后可以改成WARN或者INFO switch (packet[0]) { case PGFlags.PARAMETER_STATUS: LOGGER.error("Async ParameterStatus found: {} from {}", ParameterStatus.loadFromPacket(packet), serverSession); break; case PGFlags.NOTICE_RESPONSE: LOGGER.error("Async NoticeResponse found: {} from {}", NoticeResponse.loadFromPacket(packet), serverSession); break; case PGFlags.NOTIFICATION_RESPONSE: LOGGER.error("Async NotificationResponse found: {} from {}", NotificationResponse.loadFromPacket(packet), serverSession); break; case PGFlags.ERROR_RESPONSE: LOGGER.error("Async ErrorResponse found: {} from {}", ErrorResponse.loadFromPacket(packet), serverSession); break; default: LOGGER.error("Async Unknown Response found: {} from {}", (char) packet[0], serverSession); break; } } } catch (Exception e) { LOGGER.error("error when output packets when not sqlCtx bind", e); } } @Override protected void dealExtractPktQuitException(ChannelHandlerContext ctx, QuitException e) { if (PacketLengthUtil.isPacketTooLargeException(e)) { NoThrow.call(() -> this.exceptionCaught(ctx, e)); // packet长度过大时,不再处理inputbuf,并丢弃已经解析的包 inputbuf.clear(); packets.clear(); return; } super.dealExtractPktQuitException(ctx, e); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.plc4x.codegen.python; import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Store") public class StoreNode extends ContextNode { @Override public <T> T accept(NodeVisitor<T> visitor) { return visitor.visit(this); } }
package org.nwnx.nwnx2.jvm.constants; /** * This class contains all unique constants beginning with "METAMAGIC". * Non-distinct keys are filtered; only the LAST appearing was * kept. */ public final class Metamagic { private Metamagic() {} public final static int ANY = 255; public final static int EMPOWER = 1; public final static int EXTEND = 2; public final static int MAXIMIZE = 4; public final static int NONE = 0; public final static int QUICKEN = 8; public final static int SILENT = 16; public final static int STILL = 32; public static String nameOf(int value) { if (value == 255) return "Metamagic.ANY"; if (value == 1) return "Metamagic.EMPOWER"; if (value == 2) return "Metamagic.EXTEND"; if (value == 4) return "Metamagic.MAXIMIZE"; if (value == 0) return "Metamagic.NONE"; if (value == 8) return "Metamagic.QUICKEN"; if (value == 16) return "Metamagic.SILENT"; if (value == 32) return "Metamagic.STILL"; return "Metamagic.(not found: " + value + ")"; } public static String nameOf(float value) { return "Metamagic.(not found: " + value + ")"; } public static String nameOf(String value) { return "Metamagic.(not found: " + value + ")"; } }