hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
e3025f58f398bae99602ba46b1f6276941e0df6b
| 181,035
|
/*******************************************************************************
* Copyright (c) 2006, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation
*
******************************************************************************/
package org.eclipse.persistence.jpa.tests.jpql.parser;
import org.eclipse.persistence.jpa.jpql.ExpressionTools;
import org.eclipse.persistence.jpa.jpql.JPAVersion;
import org.eclipse.persistence.jpa.jpql.parser.AbsExpression;
import org.eclipse.persistence.jpa.jpql.parser.AbstractConditionalClause;
import org.eclipse.persistence.jpa.jpql.parser.AbstractDoubleEncapsulatedExpression;
import org.eclipse.persistence.jpa.jpql.parser.AbstractEncapsulatedExpression;
import org.eclipse.persistence.jpa.jpql.parser.AbstractFromClause;
import org.eclipse.persistence.jpa.jpql.parser.AbstractOrderByClause;
import org.eclipse.persistence.jpa.jpql.parser.AbstractPathExpression;
import org.eclipse.persistence.jpa.jpql.parser.AbstractSchemaName;
import org.eclipse.persistence.jpa.jpql.parser.AbstractSelectClause;
import org.eclipse.persistence.jpa.jpql.parser.AbstractSelectStatement;
import org.eclipse.persistence.jpa.jpql.parser.AbstractSingleEncapsulatedExpression;
import org.eclipse.persistence.jpa.jpql.parser.AbstractTripleEncapsulatedExpression;
import org.eclipse.persistence.jpa.jpql.parser.AdditionExpression;
import org.eclipse.persistence.jpa.jpql.parser.AllOrAnyExpression;
import org.eclipse.persistence.jpa.jpql.parser.AndExpression;
import org.eclipse.persistence.jpa.jpql.parser.ArithmeticFactor;
import org.eclipse.persistence.jpa.jpql.parser.AsOfClause;
import org.eclipse.persistence.jpa.jpql.parser.AvgFunction;
import org.eclipse.persistence.jpa.jpql.parser.BadExpression;
import org.eclipse.persistence.jpa.jpql.parser.BetweenExpression;
import org.eclipse.persistence.jpa.jpql.parser.CaseExpression;
import org.eclipse.persistence.jpa.jpql.parser.CastExpression;
import org.eclipse.persistence.jpa.jpql.parser.CoalesceExpression;
import org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;
import org.eclipse.persistence.jpa.jpql.parser.CollectionMemberDeclaration;
import org.eclipse.persistence.jpa.jpql.parser.CollectionMemberExpression;
import org.eclipse.persistence.jpa.jpql.parser.CollectionValuedPathExpression;
import org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;
import org.eclipse.persistence.jpa.jpql.parser.CompoundExpression;
import org.eclipse.persistence.jpa.jpql.parser.ConcatExpression;
import org.eclipse.persistence.jpa.jpql.parser.ConnectByClause;
import org.eclipse.persistence.jpa.jpql.parser.ConstructorExpression;
import org.eclipse.persistence.jpa.jpql.parser.CountFunction;
import org.eclipse.persistence.jpa.jpql.parser.DatabaseType;
import org.eclipse.persistence.jpa.jpql.parser.DateTime;
import org.eclipse.persistence.jpa.jpql.parser.DefaultEclipseLinkJPQLGrammar;
import org.eclipse.persistence.jpa.jpql.parser.DefaultJPQLGrammar;
import org.eclipse.persistence.jpa.jpql.parser.DeleteClause;
import org.eclipse.persistence.jpa.jpql.parser.DeleteStatement;
import org.eclipse.persistence.jpa.jpql.parser.DivisionExpression;
import org.eclipse.persistence.jpa.jpql.parser.EmptyCollectionComparisonExpression;
import org.eclipse.persistence.jpa.jpql.parser.EntityTypeLiteral;
import org.eclipse.persistence.jpa.jpql.parser.EntryExpression;
import org.eclipse.persistence.jpa.jpql.parser.ExistsExpression;
import org.eclipse.persistence.jpa.jpql.parser.Expression;
import org.eclipse.persistence.jpa.jpql.parser.ExtractExpression;
import org.eclipse.persistence.jpa.jpql.parser.FromClause;
import org.eclipse.persistence.jpa.jpql.parser.FunctionExpression;
import org.eclipse.persistence.jpa.jpql.parser.GroupByClause;
import org.eclipse.persistence.jpa.jpql.parser.HavingClause;
import org.eclipse.persistence.jpa.jpql.parser.HierarchicalQueryClause;
import org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable;
import org.eclipse.persistence.jpa.jpql.parser.IdentificationVariableDeclaration;
import org.eclipse.persistence.jpa.jpql.parser.InExpression;
import org.eclipse.persistence.jpa.jpql.parser.IndexExpression;
import org.eclipse.persistence.jpa.jpql.parser.InputParameter;
import org.eclipse.persistence.jpa.jpql.parser.JPQLExpression;
import org.eclipse.persistence.jpa.jpql.parser.JPQLGrammar;
import org.eclipse.persistence.jpa.jpql.parser.JPQLStatementBNF;
import org.eclipse.persistence.jpa.jpql.parser.Join;
import org.eclipse.persistence.jpa.jpql.parser.KeywordExpression;
import org.eclipse.persistence.jpa.jpql.parser.LengthExpression;
import org.eclipse.persistence.jpa.jpql.parser.LikeExpression;
import org.eclipse.persistence.jpa.jpql.parser.LocateExpression;
import org.eclipse.persistence.jpa.jpql.parser.LogicalExpression;
import org.eclipse.persistence.jpa.jpql.parser.LowerExpression;
import org.eclipse.persistence.jpa.jpql.parser.MaxFunction;
import org.eclipse.persistence.jpa.jpql.parser.MinFunction;
import org.eclipse.persistence.jpa.jpql.parser.ModExpression;
import org.eclipse.persistence.jpa.jpql.parser.MultiplicationExpression;
import org.eclipse.persistence.jpa.jpql.parser.NotExpression;
import org.eclipse.persistence.jpa.jpql.parser.NullComparisonExpression;
import org.eclipse.persistence.jpa.jpql.parser.NullExpression;
import org.eclipse.persistence.jpa.jpql.parser.NullIfExpression;
import org.eclipse.persistence.jpa.jpql.parser.NumericLiteral;
import org.eclipse.persistence.jpa.jpql.parser.ObjectExpression;
import org.eclipse.persistence.jpa.jpql.parser.OnClause;
import org.eclipse.persistence.jpa.jpql.parser.OrExpression;
import org.eclipse.persistence.jpa.jpql.parser.OrderByClause;
import org.eclipse.persistence.jpa.jpql.parser.OrderByItem;
import org.eclipse.persistence.jpa.jpql.parser.OrderByItem.NullOrdering;
import org.eclipse.persistence.jpa.jpql.parser.OrderByItem.Ordering;
import org.eclipse.persistence.jpa.jpql.parser.OrderSiblingsByClause;
import org.eclipse.persistence.jpa.jpql.parser.RangeVariableDeclaration;
import org.eclipse.persistence.jpa.jpql.parser.RegexpExpression;
import org.eclipse.persistence.jpa.jpql.parser.ResultVariable;
import org.eclipse.persistence.jpa.jpql.parser.SelectClause;
import org.eclipse.persistence.jpa.jpql.parser.SelectStatement;
import org.eclipse.persistence.jpa.jpql.parser.SimpleFromClause;
import org.eclipse.persistence.jpa.jpql.parser.SimpleSelectClause;
import org.eclipse.persistence.jpa.jpql.parser.SimpleSelectStatement;
import org.eclipse.persistence.jpa.jpql.parser.SizeExpression;
import org.eclipse.persistence.jpa.jpql.parser.SqrtExpression;
import org.eclipse.persistence.jpa.jpql.parser.StartWithClause;
import org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;
import org.eclipse.persistence.jpa.jpql.parser.StringLiteral;
import org.eclipse.persistence.jpa.jpql.parser.SubExpression;
import org.eclipse.persistence.jpa.jpql.parser.SubstringExpression;
import org.eclipse.persistence.jpa.jpql.parser.SubtractionExpression;
import org.eclipse.persistence.jpa.jpql.parser.SumFunction;
import org.eclipse.persistence.jpa.jpql.parser.TableExpression;
import org.eclipse.persistence.jpa.jpql.parser.TableVariableDeclaration;
import org.eclipse.persistence.jpa.jpql.parser.TreatExpression;
import org.eclipse.persistence.jpa.jpql.parser.TrimExpression;
import org.eclipse.persistence.jpa.jpql.parser.TrimExpression.Specification;
import org.eclipse.persistence.jpa.jpql.parser.TypeExpression;
import org.eclipse.persistence.jpa.jpql.parser.UnionClause;
import org.eclipse.persistence.jpa.jpql.parser.UnknownExpression;
import org.eclipse.persistence.jpa.jpql.parser.UpdateClause;
import org.eclipse.persistence.jpa.jpql.parser.UpdateItem;
import org.eclipse.persistence.jpa.jpql.parser.UpdateStatement;
import org.eclipse.persistence.jpa.jpql.parser.UpperExpression;
import org.eclipse.persistence.jpa.jpql.parser.WhenClause;
import org.eclipse.persistence.jpa.jpql.parser.WhereClause;
import org.eclipse.persistence.jpa.tests.jpql.JPQLBasicTest;
import static org.eclipse.persistence.jpa.jpql.parser.AbstractExpression.*;
import static org.eclipse.persistence.jpa.jpql.parser.Expression.*;
import static org.eclipse.persistence.jpa.tests.jpql.parser.JPQLParserTester.*;
import static org.eclipse.persistence.jpa.tests.jpql.parser.JPQLQueryBuilder.*;
import static org.junit.Assert.*;
/**
* This abstract class provides the functionality to test the parsed tree representation of a JPQL
* query by traversing the tree and comparing each node.
* <p>
* Note: This class provides the {@link ExpressionTester} for all JPQL grammars (1.0, 2.0 and 2.1),
* as well as for EclipseLink (all versions).
*
* @version 2.6
* @since 2.3
* @author Pascal Filion
*/
@SuppressWarnings({"nls", "unused" /* For the extra import statement, see bug 330740 */ })
public abstract class JPQLParserTest extends JPQLBasicTest {
@JPQLGrammarTestHelper
private JPQLGrammar jpqlGrammar;
protected JPQLGrammar getGrammar() {
return jpqlGrammar;
}
protected final boolean isEclipseLinkProvider() {
return DefaultEclipseLinkJPQLGrammar.PROVIDER_NAME == jpqlGrammar.getProvider();
}
protected final boolean isGenericProvider() {
return DefaultJPQLGrammar.PROVIDER_NAME == jpqlGrammar.getProvider();
}
protected final boolean isJPA1_0() {
return jpqlGrammar.getJPAVersion() == JPAVersion.VERSION_1_0;
}
protected final boolean isJPA2_0() {
return jpqlGrammar.getJPAVersion() == JPAVersion.VERSION_2_0;
}
protected final boolean isJPA2_1() {
return jpqlGrammar.getJPAVersion() == JPAVersion.VERSION_2_1;
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned on.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
*/
protected void testInvalidQuery(String jpqlQuery, ExpressionTester expressionTester) {
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, true);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned on.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param jpqlGrammar The {@link JPQLGrammar} used to determine how to parse the JPQL query
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testInvalidQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLGrammar jpqlGrammar) {
testQuery(jpqlQuery, expressionTester, jpqlGrammar, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, true);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned on.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testInvalidQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, formatter, true);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned on.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
*/
protected void testInvalidQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId) {
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, JPQLQueryStringFormatter.DEFAULT, true);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned on.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testInvalidQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, formatter, true);
}
/**
* Tests parsing the given JPQL query by comparing the parsed tree ({@link JPQLExpression}) with
* the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
*/
protected void testQuery(String jpqlQuery, ExpressionTester expressionTester) {
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, true);
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param jpqlGrammar The {@link JPQLGrammar} used to determine how to parse the JPQL query
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLGrammar jpqlGrammar) {
testQuery(jpqlQuery, expressionTester, jpqlGrammar, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, true);
testQuery(jpqlQuery, expressionTester, jpqlGrammar, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param jpqlGrammar The {@link JPQLGrammar} used to determine how to parse the JPQL query
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLGrammar jpqlGrammar,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, jpqlGrammar, JPQLStatementBNF.ID, formatter, true);
testQuery(jpqlQuery, expressionTester, jpqlGrammar, JPQLStatementBNF.ID, formatter, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLGrammar jpqlGrammar,
String jpqlQueryBNFId,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, jpqlGrammar, jpqlQueryBNFId, formatter, true);
testQuery(jpqlQuery, expressionTester, jpqlGrammar, jpqlQueryBNFId, formatter, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param jpqlGrammar The {@link JPQLGrammar} used to determine how to parse the JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
* @param tolerant Determines if the parsing system should be tolerant, meaning if it should try
* to parse grammatically invalid or incomplete queries
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLGrammar jpqlGrammar,
String jpqlQueryBNFId,
JPQLQueryStringFormatter formatter,
boolean tolerant) {
JPQLExpression jpqlExpression = buildQuery(jpqlQuery, jpqlGrammar, jpqlQueryBNFId, formatter, tolerant);
if (expressionTester.getClass() != JPQLExpressionTester.class) {
expressionTester = jpqlExpression(expressionTester);
}
expressionTester.test(jpqlExpression);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, formatter, true);
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, formatter, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId) {
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, JPQLQueryStringFormatter.DEFAULT, true);
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, JPQLQueryStringFormatter.DEFAULT, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* This method test both parsing modes: tolerant and non-tolerant. When the tolerant mode is
* turned on, it means it will parse valid/complete and invalid/incomplete JPQL queries. When the
* tolerant mode is turned off, it means the JPQL query has to be complete and has to be
* grammatically valid.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, formatter, true);
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, formatter, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
* @param tolerant Determines if the parsing system should be tolerant, meaning if it should try
* to parse grammatically invalid or incomplete queries
*/
protected void testQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId,
JPQLQueryStringFormatter formatter,
boolean tolerant) {
testQuery(jpqlQuery, expressionTester, jpqlGrammar, jpqlQueryBNFId, formatter, tolerant);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned off.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
*/
protected void testValidQuery(String jpqlQuery, ExpressionTester expressionTester) {
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, JPQLQueryStringFormatter.DEFAULT, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned off.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testValidQuery(String jpqlQuery,
ExpressionTester expressionTester,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, JPQLStatementBNF.ID, formatter, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned off.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
*/
protected void testValidQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId) {
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, JPQLQueryStringFormatter.DEFAULT, false);
}
/**
* Tests the parsing of the given JPQL query by comparing the parsed tree ({@link JPQLExpression})
* with the given tester, which is an equivalent representation of the parsed tree.
* <p>
* The parsing system will have the tolerance turned off.
*
* @param jpqlQuery The JPQL query to parse and to test the parsed tree representation
* @param expressionTester The tester used to verify the parsed tree is correctly representing the
* JPQL query
* @param queryBNFId The unique identifier of the {@link org.eclipse.persistence.jpa.jpql.parser.
* JPQLQueryBNF JPQLQueryBNF}
* @param formatter This formatter is used to personalized the formatting of the JPQL query
* before it is used to test the generated string
*/
protected void testValidQuery(String jpqlQuery,
ExpressionTester expressionTester,
String jpqlQueryBNFId,
JPQLQueryStringFormatter formatter) {
testQuery(jpqlQuery, expressionTester, jpqlQueryBNFId, formatter, false);
}
public static final class AbsExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected AbsExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return AbsExpression.class;
}
@Override
protected String identifier() {
return ABS;
}
}
public static abstract class AbstractConditionalClauseTester extends AbstractExpressionTester {
private ExpressionTester conditionalExpression;
public boolean hasSpaceAfterIdentifier;
protected AbstractConditionalClauseTester(ExpressionTester conditionalExpression) {
super();
this.conditionalExpression = conditionalExpression;
this.hasSpaceAfterIdentifier = !conditionalExpression.isNull();
}
protected abstract Class<? extends AbstractConditionalClause> expressionType();
protected abstract String identifier();
public void test(Expression expression) {
assertInstance(expression, expressionType());
AbstractConditionalClause conditionalClause = (AbstractConditionalClause) expression;
assertEquals(toString(), conditionalClause.toParsedText());
assertEquals(!conditionalExpression.isNull(), conditionalClause.hasConditionalExpression());
assertEquals(hasSpaceAfterIdentifier, conditionalClause.hasSpaceAfterIdentifier());
conditionalExpression.test(conditionalClause.getConditionalExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(identifier());
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
sb.append(conditionalExpression);
return sb.toString();
}
}
public static abstract class AbstractDoubleEncapsulatedExpressionTester extends AbstractEncapsulatedExpressionTester {
private ExpressionTester firstExpression;
public boolean hasComma;
public boolean hasSpaceAfterComma;
private ExpressionTester secondExpression;
protected AbstractDoubleEncapsulatedExpressionTester(ExpressionTester firstExpression,
ExpressionTester secondExpression) {
super();
this.hasComma = true;
this.hasSpaceAfterComma = true;
this.firstExpression = firstExpression;
this.secondExpression = secondExpression;
}
@Override
protected abstract Class<? extends AbstractDoubleEncapsulatedExpression> expressionType();
@Override
protected boolean hasEncapsulatedExpression() {
return !firstExpression.isNull() || hasComma || !secondExpression.isNull();
}
@Override
public void test(Expression expression) {
super.test(expression);
AbstractDoubleEncapsulatedExpression abstractDoubleEncapsulatedExpression = (AbstractDoubleEncapsulatedExpression) expression;
assertEquals(!firstExpression.isNull(), abstractDoubleEncapsulatedExpression.hasFirstExpression());
assertEquals(!secondExpression.isNull(), abstractDoubleEncapsulatedExpression.hasSecondExpression());
assertEquals(hasComma, abstractDoubleEncapsulatedExpression.hasComma());
assertEquals(hasSpaceAfterComma, abstractDoubleEncapsulatedExpression.hasSpaceAfterComma());
firstExpression .test(abstractDoubleEncapsulatedExpression.getFirstExpression());
secondExpression.test(abstractDoubleEncapsulatedExpression.getSecondExpression());
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
sb.append(firstExpression);
if (hasComma) {
sb.append(COMMA);
}
if (hasSpaceAfterComma) {
sb.append(SPACE);
}
sb.append(secondExpression);
}
}
public static abstract class AbstractEncapsulatedExpressionTester extends AbstractExpressionTester {
public boolean hasLeftParenthesis;
public boolean hasRightParenthesis;
protected AbstractEncapsulatedExpressionTester() {
super();
this.hasLeftParenthesis = true;
this.hasRightParenthesis = true;
}
protected abstract Class<? extends AbstractEncapsulatedExpression> expressionType();
protected abstract boolean hasEncapsulatedExpression();
protected abstract String identifier();
public void test(Expression expression) {
assertInstance(expression, expressionType());
AbstractEncapsulatedExpression abstractEncapsulatedExpression = (AbstractEncapsulatedExpression) expression;
assertEquals(toString(), abstractEncapsulatedExpression.toParsedText());
assertEquals(hasLeftParenthesis, abstractEncapsulatedExpression.hasLeftParenthesis());
assertEquals(hasRightParenthesis, abstractEncapsulatedExpression.hasRightParenthesis());
assertEquals(hasEncapsulatedExpression(), abstractEncapsulatedExpression.hasEncapsulatedExpression());
}
@Override
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append(identifier());
if (hasLeftParenthesis) {
sb.append(LEFT_PARENTHESIS);
}
else if (hasEncapsulatedExpression()) {
sb.append(SPACE);
}
toStringEncapsulatedExpression(sb);
if (hasRightParenthesis) {
sb.append(RIGHT_PARENTHESIS);
}
return sb.toString();
}
protected abstract void toStringEncapsulatedExpression(StringBuilder sb);
}
/**
* The abstract definition of an {@link ExpressionTester}.
*/
public static abstract class AbstractExpressionTester implements ExpressionTester {
public final AdditionExpressionTester add(ExpressionTester expression) {
return JPQLParserTester.add(this, expression);
}
public final AndExpressionTester and(ExpressionTester expression) {
return JPQLParserTester.and(this, expression);
}
protected final void assertInstance(Expression expression,
Class<? extends Expression> expressionType) {
Class<? extends Expression> expressionClass = expression.getClass();
if (expressionClass != expressionType &&
!expressionType.isAssignableFrom(expressionClass)) {
StringBuilder sb = new StringBuilder();
sb.append("Expecting ");
sb.append(expressionType.getSimpleName());
sb.append(" but was ");
sb.append(expressionClass.getSimpleName());
sb.append(" for [");
sb.append(expression.toParsedText());
sb.append("]");
fail(sb.toString());
}
}
public final BetweenExpressionTester between(ExpressionTester lowerBoundExpression,
ExpressionTester upperBoundExpression) {
return JPQLParserTester.between(this, lowerBoundExpression, upperBoundExpression);
}
public final ComparisonExpressionTester different(ExpressionTester expression) {
return JPQLParserTester.different(this, expression);
}
public final DivisionExpressionTester divide(ExpressionTester expression) {
return JPQLParserTester.division(this, expression);
}
public final ComparisonExpressionTester equal(ExpressionTester expression) {
return JPQLParserTester.equal(this, expression);
}
public final ComparisonExpressionTester greaterThan(ExpressionTester expression) {
return JPQLParserTester.greaterThan(this, expression);
}
public final ComparisonExpressionTester greaterThanOrEqual(ExpressionTester expression) {
return JPQLParserTester.greaterThanOrEqual(this, expression);
}
public final InExpressionTester in(ExpressionTester... inItems) {
if (inItems.length == 1) {
return JPQLParserTester.in(this, inItems[0]);
}
return JPQLParserTester.in(this, inItems);
}
public final InExpressionTester in(String inputParameter) {
return JPQLParserTester.in(this, inputParameter);
}
public final EmptyCollectionComparisonExpressionTester isEmpty() {
return JPQLParserTester.isEmpty(this);
}
public final EmptyCollectionComparisonExpressionTester isNotEmpty() {
return JPQLParserTester.isNotEmpty(this);
}
public boolean isNull() {
return false;
}
public final LikeExpressionTester like(ExpressionTester patternValue) {
return JPQLParserTester.like(this, patternValue);
}
public final LikeExpressionTester like(ExpressionTester patternValue,
ExpressionTester escapeCharacter) {
return JPQLParserTester.like(this, patternValue, escapeCharacter);
}
public final ComparisonExpressionTester lowerThan(ExpressionTester expression) {
return JPQLParserTester.lowerThan(this, expression);
}
public final ComparisonExpressionTester lowerThanOrEqual(ExpressionTester expression) {
return JPQLParserTester.lowerThanOrEqual(this, expression);
}
public final CollectionMemberExpressionTester member(ExpressionTester collectionPath) {
return JPQLParserTester.member(this, collectionPath);
}
public final CollectionMemberExpressionTester memberOf(ExpressionTester collectionPath) {
return JPQLParserTester.memberOf(this, collectionPath);
}
public final MultiplicationExpressionTester multiply(ExpressionTester expression) {
return JPQLParserTester.multiplication(this, expression);
}
public final BetweenExpressionTester notBetween(ExpressionTester lowerBoundExpression,
ExpressionTester upperBoundExpression) {
return JPQLParserTester.notBetween(this, lowerBoundExpression, upperBoundExpression);
}
public final ComparisonExpressionTester notEqual(ExpressionTester expression) {
return JPQLParserTester.notEqual(this, expression);
}
public final InExpressionTester notIn(ExpressionTester... inItems) {
if (inItems.length == 1) {
return JPQLParserTester.notIn(this, inItems[0]);
}
return JPQLParserTester.notIn(this, inItems);
}
public final InExpressionTester notIn(String inputParameter) {
return JPQLParserTester.notIn(this, inputParameter);
}
public final LikeExpressionTester notLike(ExpressionTester expression) {
return JPQLParserTester.notLike(this, expression);
}
public final LikeExpressionTester notLike(ExpressionTester expression,
ExpressionTester escapeCharacter) {
return JPQLParserTester.notLike(this, expression, escapeCharacter);
}
public final ExpressionTester notMember(ExpressionTester collectionPath) {
return JPQLParserTester.notMember(this, collectionPath);
}
public final ExpressionTester notMemberOf(ExpressionTester collectionPath) {
return JPQLParserTester.notMemberOf(this, collectionPath);
}
public final OrExpressionTester or(ExpressionTester expression) {
return JPQLParserTester.or(this, expression);
}
public final RegexpExpressionTester regexp(StringLiteralTester patternValue) {
return JPQLParserTester.regexp(this, patternValue);
}
public final SubtractionExpressionTester subtract(ExpressionTester expression) {
return JPQLParserTester.subtract(this, expression);
}
}
public static abstract class AbstractFromClauseTester extends AbstractExpressionTester {
private ExpressionTester asOfClause;
private ExpressionTester declaration;
private boolean hasSpaceAfterDeclaration;
public boolean hasSpaceAfterFrom;
private boolean hasSpaceAfterHierarchicalQueryClause;
private ExpressionTester hierarchicalQueryClause;
protected AbstractFromClauseTester(ExpressionTester declaration,
ExpressionTester hierarchicalQueryClause,
ExpressionTester asOfClause) {
super();
this.hasSpaceAfterFrom = true;
this.asOfClause = asOfClause;
this.declaration = declaration;
this.hierarchicalQueryClause = hierarchicalQueryClause;
this.hasSpaceAfterDeclaration = !declaration.isNull() && (!hierarchicalQueryClause.isNull() || !asOfClause.isNull());
this.hasSpaceAfterHierarchicalQueryClause = !hierarchicalQueryClause.isNull() && !asOfClause.isNull();
}
public void test(Expression expression) {
assertInstance(expression, AbstractFromClause.class);
AbstractFromClause fromClause = (AbstractFromClause) expression;
assertEquals(toString(), fromClause.toParsedText());
assertEquals(hasSpaceAfterFrom, fromClause.hasSpaceAfterFrom());
assertEquals(!declaration.isNull(), fromClause.hasDeclaration());
assertEquals(hasSpaceAfterDeclaration, fromClause.hasSpaceAfterDeclaration());
assertEquals(!hierarchicalQueryClause.isNull(), fromClause.hasHierarchicalQueryClause());
assertEquals(hasSpaceAfterHierarchicalQueryClause, fromClause.hasSpaceAfterHierarchicalQueryClause());
assertEquals(!asOfClause.isNull(), fromClause.hasAsOfClause());
declaration.test(fromClause.getDeclaration());
hierarchicalQueryClause.test(fromClause.getHierarchicalQueryClause());
asOfClause.test(fromClause.getAsOfClause());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(FROM);
if (hasSpaceAfterFrom) {
sb.append(SPACE);
}
sb.append(declaration);
if (hasSpaceAfterDeclaration) {
sb.append(SPACE);
}
sb.append(hierarchicalQueryClause);
if (hasSpaceAfterHierarchicalQueryClause) {
sb.append(SPACE);
}
sb.append(asOfClause);
return sb.toString();
}
}
public static abstract class AbstractOrderByClauseTester extends AbstractExpressionTester {
public boolean hasSpaceAfterIdentifier;
private ExpressionTester orderByItems;
protected AbstractOrderByClauseTester(ExpressionTester orderByItems) {
super();
this.orderByItems = orderByItems;
this.hasSpaceAfterIdentifier = !orderByItems.isNull();
}
protected abstract String identifier();
public void test(Expression expression) {
assertInstance(expression, AbstractOrderByClause.class);
AbstractOrderByClause orderByClause = (AbstractOrderByClause) expression;
assertEquals(toString(), orderByClause.toParsedText());
assertEquals(!orderByItems.isNull(), orderByClause.hasOrderByItems());
assertEquals(hasSpaceAfterIdentifier, orderByClause.hasSpaceAfterIdentifier());
orderByItems.test(orderByClause.getOrderByItems());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(identifier());
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
sb.append(orderByItems);
return sb.toString();
}
}
public static abstract class AbstractPathExpressionTester extends AbstractExpressionTester {
private boolean endsWithDot;
private ExpressionTester identificationVariable;
private boolean startsWithDot;
private String value;
protected AbstractPathExpressionTester(ExpressionTester identificationVariable, String value) {
super();
this.value = value;
this.identificationVariable = identificationVariable;
this.startsWithDot = (identificationVariable.toString().length() == 0) && (value.indexOf(DOT) > -1);
if (value.length() > 1) {
endsWithDot = value.charAt(value.length() - 1) == DOT;
}
}
public void test(Expression expression) {
assertInstance(expression, AbstractPathExpression.class);
AbstractPathExpression abstractPathExpression = (AbstractPathExpression) expression;
assertEquals(toString(), abstractPathExpression.toParsedText());
assertEquals(!identificationVariable.isNull(), abstractPathExpression.hasIdentificationVariable());
assertEquals(endsWithDot, abstractPathExpression.endsWithDot());
assertEquals(startsWithDot, abstractPathExpression.startsWithDot());
identificationVariable.test(abstractPathExpression.getIdentificationVariable());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(identificationVariable);
if (startsWithDot || (sb.length() > 0)) {
sb.append(DOT);
}
sb.append(value);
return sb.toString();
}
}
public static final class AbstractSchemaNameTester extends AbstractExpressionTester {
private String abstractSchemaName;
protected AbstractSchemaNameTester(String abstractSchemaName) {
super();
this.abstractSchemaName = abstractSchemaName;
}
public void test(Expression expression) {
assertInstance(expression, AbstractSchemaName.class);
AbstractSchemaName abstractSchemaName = (AbstractSchemaName) expression;
assertEquals(toString(), abstractSchemaName.toParsedText());
}
@Override
public String toString() {
return abstractSchemaName;
}
}
public static abstract class AbstractSelectClauseTester extends AbstractExpressionTester {
private boolean hasDistinct;
public boolean hasSpaceAfterDistinct;
public boolean hasSpaceAfterSelect;
private ExpressionTester selectExpression;
protected AbstractSelectClauseTester(ExpressionTester selectExpression, boolean hasDistinct) {
super();
this.hasDistinct = hasDistinct;
this.hasSpaceAfterDistinct = hasDistinct;
this.hasSpaceAfterSelect = hasDistinct || !selectExpression.isNull();
this.selectExpression = selectExpression;
}
public void test(Expression expression) {
assertInstance(expression, AbstractSelectClause.class);
AbstractSelectClause selectClause = (AbstractSelectClause) expression;
assertEquals(toString(), selectClause.toParsedText());
assertEquals(hasSpaceAfterSelect, selectClause.hasSpaceAfterSelect());
assertEquals(hasDistinct, selectClause.hasDistinct());
assertEquals(hasSpaceAfterDistinct, selectClause.hasSpaceAfterDistinct());
assertEquals(!selectExpression.isNull(), selectClause.hasSelectExpression());
selectExpression.test(selectClause.getSelectExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SELECT);
if (hasSpaceAfterSelect) {
sb.append(SPACE);
}
if (hasDistinct) {
sb.append(DISTINCT);
}
if (hasSpaceAfterDistinct) {
sb.append(SPACE);
}
sb.append(selectExpression);
return sb.toString();
}
}
public static abstract class AbstractSelectStatementTester extends AbstractExpressionTester {
private ExpressionTester fromClause;
private ExpressionTester groupByClause;
public boolean hasSpaceAfterFrom;
public boolean hasSpaceAfterGroupBy;
public boolean hasSpaceAfterSelect;
public boolean hasSpaceAfterWhere;
private ExpressionTester havingClause;
private ExpressionTester selectClause;
private ExpressionTester whereClause;
protected AbstractSelectStatementTester(ExpressionTester selectClause,
ExpressionTester fromClause,
ExpressionTester whereClause,
ExpressionTester groupByClause,
ExpressionTester havingClause) {
super();
this.selectClause = selectClause;
this.fromClause = fromClause;
this.whereClause = whereClause;
this.groupByClause = groupByClause;
this.havingClause = havingClause;
hasSpaceAfterSelect = !fromClause.isNull();
hasSpaceAfterFrom = !fromClause.isNull() && (!whereClause.isNull() || !groupByClause.isNull() || !havingClause.isNull());
hasSpaceAfterWhere = !whereClause.isNull() && (!groupByClause.isNull() || !havingClause.isNull());
hasSpaceAfterGroupBy = !groupByClause.isNull() && !havingClause.isNull();
}
protected abstract Class<? extends AbstractSelectStatement> expressionType();
public void test(Expression expression) {
assertInstance(expression, expressionType());
AbstractSelectStatement selectStatement = (AbstractSelectStatement) expression;
assertEquals(toString(), selectStatement.toParsedText());
assertEquals(!selectClause .isNull(), selectStatement.hasSelectClause());
assertEquals(!fromClause .isNull(), selectStatement.hasFromClause());
assertEquals(!whereClause .isNull(), selectStatement.hasWhereClause());
assertEquals(!groupByClause.isNull(), selectStatement.hasGroupByClause());
assertEquals(!havingClause .isNull(), selectStatement.hasHavingClause());
selectClause .test(selectStatement.getSelectClause());
fromClause .test(selectStatement.getFromClause());
whereClause .test(selectStatement.getWhereClause());
groupByClause.test(selectStatement.getGroupByClause());
havingClause .test(selectStatement.getHavingClause());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// SELECT
sb.append(selectClause);
if (hasSpaceAfterSelect && (sb.length() > 0) && (sb.charAt(sb.length() - 1) != ' ')) {
sb.append(SPACE);
}
// FROM
sb.append(fromClause);
if (hasSpaceAfterFrom && sb.charAt(sb.length() - 1) != ' ') {
sb.append(SPACE);
}
// WHERE
sb.append(whereClause);
if (hasSpaceAfterWhere && sb.charAt(sb.length() - 1) != ' ') {
sb.append(SPACE);
}
// GROUP BY
sb.append(groupByClause);
if (hasSpaceAfterGroupBy && sb.charAt(sb.length() - 1) != ' ') {
sb.append(SPACE);
}
// HAVING
sb.append(havingClause);
return sb.toString();
}
}
public static abstract class AbstractSingleEncapsulatedExpressionTester extends AbstractEncapsulatedExpressionTester {
private ExpressionTester expression;
protected AbstractSingleEncapsulatedExpressionTester(ExpressionTester expression) {
super();
this.expression = expression;
}
@Override
protected abstract Class<? extends AbstractSingleEncapsulatedExpression> expressionType();
@Override
protected boolean hasEncapsulatedExpression() {
return !expression.isNull();
}
@Override
public void test(Expression expression) {
super.test(expression);
AbstractSingleEncapsulatedExpression encapsulatedExpression = (AbstractSingleEncapsulatedExpression) expression;
this.expression.test(encapsulatedExpression.getExpression());
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
sb.append(expression);
}
}
public static abstract class AbstractTripleEncapsulatedExpressionTester extends AbstractEncapsulatedExpressionTester {
private ExpressionTester firstExpression;
public boolean hasFirstComma;
public boolean hasSecondComma;
public boolean hasSpaceAfterFirstComma;
public boolean hasSpaceAfterSecondComma;
private ExpressionTester secondExpression;
private ExpressionTester thirdExpression;
protected AbstractTripleEncapsulatedExpressionTester(ExpressionTester firstExpression,
ExpressionTester secondExpression,
ExpressionTester thirdExpression) {
super();
this.firstExpression = firstExpression;
this.secondExpression = secondExpression;
this.thirdExpression = thirdExpression;
hasFirstComma = !secondExpression.isNull();
hasSecondComma = !thirdExpression.isNull();
hasSpaceAfterFirstComma = hasFirstComma;
hasSpaceAfterSecondComma = hasSecondComma;
}
@Override
protected abstract Class<? extends AbstractTripleEncapsulatedExpression> expressionType();
@Override
protected boolean hasEncapsulatedExpression() {
return !firstExpression.isNull() || hasFirstComma || !secondExpression.isNull() || hasSecondComma || !thirdExpression.isNull();
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, AbstractTripleEncapsulatedExpression.class);
AbstractTripleEncapsulatedExpression tripleExpression = (AbstractTripleEncapsulatedExpression) expression;
assertEquals(toString(), tripleExpression.toParsedText());
assertEquals(hasFirstComma, tripleExpression.hasFirstComma());
assertEquals(hasSecondComma, tripleExpression.hasSecondComma());
assertEquals(hasSpaceAfterFirstComma, tripleExpression.hasSpaceAfterFirstComma());
assertEquals(hasSpaceAfterSecondComma, tripleExpression.hasSpaceAfterSecondComma());
assertEquals(!firstExpression.isNull(), tripleExpression.hasFirstExpression());
assertEquals(!secondExpression.isNull(), tripleExpression.hasSecondExpression());
assertEquals(!thirdExpression.isNull(), tripleExpression.hasThirdExpression());
firstExpression.test(tripleExpression.getFirstExpression());
secondExpression.test(tripleExpression.getSecondExpression());
thirdExpression.test(tripleExpression.getThirdExpression());
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
sb.append(firstExpression);
if (hasFirstComma) {
sb.append(COMMA);
}
if (hasSpaceAfterFirstComma) {
sb.append(SPACE);
}
sb.append(secondExpression);
if (hasSecondComma) {
sb.append(COMMA);
}
if (hasSpaceAfterSecondComma) {
sb.append(SPACE);
}
sb.append(thirdExpression);
}
}
public static final class AdditionExpressionTester extends CompoundExpressionTester {
protected AdditionExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
protected Class<? extends CompoundExpression> expressionType() {
return AdditionExpression.class;
}
@Override
protected String identifier() {
return PLUS;
}
}
public static abstract class AggregateFunctionTester extends AbstractSingleEncapsulatedExpressionTester {
public boolean hasDistinct;
public boolean hasSpaceAfterDistinct;
protected AggregateFunctionTester(ExpressionTester expression, boolean hasDistinct) {
super(expression);
this.hasDistinct = hasDistinct;
this.hasSpaceAfterDistinct = hasDistinct;
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
if (hasDistinct) {
sb.append(DISTINCT);
}
if (hasSpaceAfterDistinct) {
sb.append(SPACE);
}
super.toStringEncapsulatedExpression(sb);
}
}
public static final class AllOrAnyExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
private String identifier;
protected AllOrAnyExpressionTester(String identifier, ExpressionTester expression) {
super(expression);
this.identifier = identifier;
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return AllOrAnyExpression.class;
}
@Override
protected String identifier() {
return identifier;
}
}
public static final class AndExpressionTester extends LogicalExpressionTester {
protected AndExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
protected Class<? extends CompoundExpression> expressionType() {
return AndExpression.class;
}
@Override
protected String identifier() {
return AND;
}
}
public static final class ArithmeticFactorTester extends AbstractExpressionTester {
private ExpressionTester expression;
private String sign;
protected ArithmeticFactorTester(String sign, ExpressionTester expression) {
super();
this.sign = sign;
this.expression = expression;
}
public void test(Expression expression) {
assertInstance(expression, ArithmeticFactor.class);
ArithmeticFactor factor = (ArithmeticFactor) expression;
assertEquals(toString(), factor.toParsedText());
assertEquals(sign == MINUS, factor.isNegative());
assertEquals(sign == PLUS, factor.isPositive());
this.expression.test(factor.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(sign);
sb.append(expression);
return sb.toString();
}
}
protected final static class AsOfClauseTester extends AbstractExpressionTester {
private String category;
private ExpressionTester expression;
public boolean hasSpaceAfterCategory;
public boolean hasSpaceAfterIdentifier;
protected AsOfClauseTester(String category, ExpressionTester expression) {
super();
this.category = category;
this.expression = expression;
this.hasSpaceAfterIdentifier = (category != null) || !expression.isNull();
this.hasSpaceAfterCategory = (category != null) && !expression.isNull();
}
public void test(Expression expression) {
assertInstance(expression, AsOfClause.class);
AsOfClause asOfClause = (AsOfClause) expression;
assertEquals(toString(), asOfClause.toParsedText());
assertEquals(!this.expression.isNull(), asOfClause.hasExpression());
assertEquals(hasSpaceAfterIdentifier, asOfClause.hasSpaceAfterIdentifier());
assertEquals(hasSpaceAfterCategory, asOfClause.hasSpaceAfterCategory());
this.expression.test(asOfClause.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(AS_OF);
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
if (category != null) {
sb.append(category);
}
if (hasSpaceAfterCategory) {
sb.append(SPACE);
}
sb.append(expression);
return sb.toString();
}
}
public static final class AvgFunctionTester extends AggregateFunctionTester {
protected AvgFunctionTester(ExpressionTester expression, boolean hasDistinct) {
super(expression, hasDistinct);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return AvgFunction.class;
}
@Override
protected String identifier() {
return AVG;
}
}
public static final class BadExpressionTester extends AbstractExpressionTester {
private ExpressionTester expression;
protected BadExpressionTester(ExpressionTester expression) {
super();
this.expression = expression;
}
public void test(Expression expression) {
assertInstance(expression, BadExpression.class);
BadExpression badExpression = (BadExpression) expression;
assertEquals(toString(), badExpression.toParsedText());
this.expression.test(badExpression.getExpression());
}
@Override
public String toString() {
return expression.toString();
}
}
public static final class BetweenExpressionTester extends AbstractExpressionTester {
private ExpressionTester expression;
public boolean hasAnd;
public boolean hasBetween;
private boolean hasNot;
public boolean hasSpaceAfterAnd;
public boolean hasSpaceAfterBetween;
public boolean hasSpaceAfterLowerBound;
private ExpressionTester lowerBoundExpression;
private ExpressionTester upperBoundExpression;
protected BetweenExpressionTester(ExpressionTester expression,
boolean hasNot,
ExpressionTester lowerBoundExpression,
ExpressionTester upperBoundExpression) {
super();
this.hasNot = hasNot;
this.hasAnd = true;
this.expression = expression;
this.hasSpaceAfterAnd = true;
this.hasSpaceAfterLowerBound = true;
this.hasSpaceAfterBetween = true;
this.lowerBoundExpression = lowerBoundExpression;
this.upperBoundExpression = upperBoundExpression;
}
public void test(Expression expression) {
assertInstance(expression, BetweenExpression.class);
BetweenExpression betweenExpression = (BetweenExpression) expression;
assertEquals(toString(), betweenExpression.toParsedText());
assertEquals(!this.expression.isNull(), betweenExpression.hasExpression());
assertEquals(hasNot, betweenExpression.hasNot());
assertEquals(hasAnd, betweenExpression.hasAnd());
assertEquals(!lowerBoundExpression.isNull(), betweenExpression.hasLowerBoundExpression());
assertEquals(hasSpaceAfterAnd, betweenExpression.hasSpaceAfterAnd());
assertEquals(hasSpaceAfterBetween, betweenExpression.hasSpaceAfterBetween());
assertEquals(hasSpaceAfterLowerBound, betweenExpression.hasSpaceAfterLowerBound());
assertEquals(!upperBoundExpression.isNull(), betweenExpression.hasUpperBoundExpression());
this.expression.test(betweenExpression.getExpression());
lowerBoundExpression.test(betweenExpression.getLowerBoundExpression());
upperBoundExpression.test(betweenExpression.getUpperBoundExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(expression);
if (!expression.isNull()) {
sb.append(SPACE);
}
if (hasNot) {
sb.append(NOT);
sb.append(SPACE);
}
sb.append(BETWEEN);
if (hasSpaceAfterBetween) {
sb.append(SPACE);
}
sb.append(lowerBoundExpression);
if (hasSpaceAfterLowerBound) {
sb.append(SPACE);
}
if (hasAnd) {
sb.append(AND);
}
if (hasSpaceAfterAnd) {
sb.append(SPACE);
}
sb.append(upperBoundExpression);
return sb.toString();
}
}
public static final class CaseExpressionTester extends AbstractExpressionTester {
private ExpressionTester caseOperand;
private ExpressionTester elseExpression;
public boolean hasElse;
public boolean hasEnd;
public boolean hasSpaceAfterCase;
public boolean hasSpaceAfterCaseOperand;
public boolean hasSpaceAfterElse;
public boolean hasSpaceAfterElseExpression;
public boolean hasSpaceAfterWhenClauses;
private ExpressionTester whenClauses;
protected CaseExpressionTester(ExpressionTester caseOperand,
ExpressionTester whenClauses,
ExpressionTester elseExpression) {
super();
this.whenClauses = whenClauses;
this.caseOperand = caseOperand;
this.elseExpression = elseExpression;
this.hasElse = !elseExpression.isNull();
this.hasEnd = true;
this.hasSpaceAfterCase = true;
this.hasSpaceAfterElse = hasElse;
this.hasSpaceAfterElseExpression = hasElse;
this.hasSpaceAfterCaseOperand = !caseOperand.isNull();
this.hasSpaceAfterWhenClauses = !whenClauses.isNull();
}
public void test(Expression expression) {
assertInstance(expression, CaseExpression.class);
CaseExpression caseExpression = (CaseExpression) expression;
assertEquals(toString(), caseExpression.toParsedText());
assertEquals(!caseOperand.isNull(), caseExpression.hasCaseOperand());
assertEquals(hasElse, caseExpression.hasElse());
assertEquals(hasEnd, caseExpression.hasEnd());
assertEquals(hasSpaceAfterCase, caseExpression.hasSpaceAfterCase());
assertEquals(hasSpaceAfterCaseOperand, caseExpression.hasSpaceAfterCaseOperand());
assertEquals(hasSpaceAfterElse, caseExpression.hasSpaceAfterElse());
assertEquals(hasSpaceAfterElseExpression, caseExpression.hasSpaceAfterElseExpression());
assertEquals(hasSpaceAfterWhenClauses, caseExpression.hasSpaceAfterWhenClauses());
assertEquals(!whenClauses.isNull(), caseExpression.hasWhenClauses());
caseOperand.test(caseExpression.getCaseOperand());
whenClauses.test(caseExpression.getWhenClauses());
elseExpression.test(caseExpression.getElseExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(CASE);
if (hasSpaceAfterCase) {
sb.append(SPACE);
}
sb.append(caseOperand);
if (hasSpaceAfterCaseOperand) {
sb.append(SPACE);
}
sb.append(whenClauses);
if (hasSpaceAfterWhenClauses) {
sb.append(SPACE);
}
if (hasElse) {
sb.append(ELSE);
}
if (hasSpaceAfterElse) {
sb.append(SPACE);
}
sb.append(elseExpression);
if (hasSpaceAfterElseExpression) {
sb.append(SPACE);
}
if (hasEnd) {
sb.append(END);
}
return sb.toString();
}
}
public static final class CastExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
private ExpressionTester databaseType;
private boolean hasAs;
public boolean hasSpaceAfterAs;
public boolean hasSpaceAfterExpression;
protected CastExpressionTester(ExpressionTester expression,
boolean hasAs,
ExpressionTester databaseType) {
super(expression);
this.hasAs = hasAs;
this.databaseType = databaseType;
this.hasSpaceAfterAs = hasAs && !databaseType.isNull();
this.hasSpaceAfterExpression = !expression.isNull() && (hasAs || !databaseType.isNull());
}
@Override
protected Class<CastExpression> expressionType() {
return CastExpression.class;
}
@Override
protected boolean hasEncapsulatedExpression() {
return super.hasEncapsulatedExpression() || hasAs || !databaseType.isNull();
}
@Override
protected String identifier() {
return CAST;
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
super.toStringEncapsulatedExpression(sb);
if (hasSpaceAfterExpression) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(databaseType);
}
}
public static final class CoalesceExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected CoalesceExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return CoalesceExpression.class;
}
@Override
protected String identifier(){
return COALESCE;
}
}
public static final class CollectionExpressionTester extends AbstractExpressionTester {
public Boolean[] commas;
private ExpressionTester[] expressionTesters;
public Boolean[] spaces;
protected CollectionExpressionTester(ExpressionTester[] expressionTesters,
Boolean[] commas,
Boolean[] spaces) {
super();
this.expressionTesters = expressionTesters;
this.spaces = spaces;
this.commas = commas;
}
public void test(Expression expression) {
assertInstance(expression, CollectionExpression.class);
CollectionExpression collectionExpression = (CollectionExpression) expression;
assertEquals(toString(), collectionExpression.toParsedText());
assertEquals(spaces.length, collectionExpression.childrenSize());
assertEquals(commas.length, collectionExpression.childrenSize());
assertEquals(expressionTesters.length, collectionExpression.childrenSize());
// Expressions
for (int index = expressionTesters.length; --index >= 0; ) {
expressionTesters[index].test(collectionExpression.getChild(index));
}
// Spaces
for (int index = 0, count = spaces.length; index < count; index++) {
assertEquals(
"The flag for a space at " + index + " does not match",
spaces[index],
collectionExpression.hasSpace(index)
);
}
// Commas
for (int index = 0, count = commas.length; index < count; index++) {
assertEquals(
"The flag for a comma at " + index + " does not match",
commas[index],
collectionExpression.hasComma(index)
);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int index = 0, count = expressionTesters.length; index < count; index++) {
sb.append(expressionTesters[index]);
if ((index < commas.length) && commas[index]) {
sb.append(COMMA);
}
if ((index < spaces.length) && spaces[index]) {
sb.append(SPACE);
}
}
return sb.toString();
}
}
public static final class CollectionMemberDeclarationTester extends AbstractExpressionTester {
private ExpressionTester collectionValuedPath;
public boolean hasAs;
public boolean hasLeftParenthesis;
public boolean hasRightParenthesis;
public boolean hasSpaceAfterAs;
public boolean hasSpaceAfterIn;
public boolean hasSpaceAfterRightParenthesis;
private ExpressionTester identificationVariable;
protected CollectionMemberDeclarationTester(ExpressionTester collectionValuedPath,
boolean hasAs,
ExpressionTester identificationVariable) {
super();
this.hasAs = hasAs;
this.hasSpaceAfterAs = hasAs;
this.hasLeftParenthesis = true;
this.hasRightParenthesis = true;
this.collectionValuedPath = collectionValuedPath;
this.identificationVariable = identificationVariable;
this.hasSpaceAfterRightParenthesis = hasAs || !identificationVariable.isNull();
}
public void test(Expression expression) {
assertInstance(expression, CollectionMemberDeclaration.class);
CollectionMemberDeclaration collectionMemberDeclaration = (CollectionMemberDeclaration) expression;
assertEquals(toString(), collectionMemberDeclaration.toParsedText());
assertEquals(hasAs, collectionMemberDeclaration.hasAs());
assertEquals(!collectionValuedPath.isNull(), collectionMemberDeclaration.hasCollectionValuedPathExpression());
assertEquals(!identificationVariable.isNull(), collectionMemberDeclaration.hasIdentificationVariable());
assertEquals(hasLeftParenthesis, collectionMemberDeclaration.hasLeftParenthesis());
assertEquals(hasRightParenthesis, collectionMemberDeclaration.hasRightParenthesis());
assertEquals(hasSpaceAfterAs, collectionMemberDeclaration.hasSpaceAfterAs());
assertEquals(hasSpaceAfterIn, collectionMemberDeclaration.hasSpaceAfterIn());
assertEquals(hasSpaceAfterRightParenthesis, collectionMemberDeclaration.hasSpaceAfterRightParenthesis());
collectionValuedPath.test(collectionMemberDeclaration.getCollectionValuedPathExpression());
identificationVariable.test(collectionMemberDeclaration.getIdentificationVariable());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(IN);
if (hasSpaceAfterIn) {
sb.append(SPACE);
}
else if (hasLeftParenthesis) {
sb.append(LEFT_PARENTHESIS);
}
sb.append(collectionValuedPath);
if (hasRightParenthesis) {
sb.append(RIGHT_PARENTHESIS);
}
if (hasSpaceAfterRightParenthesis) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(identificationVariable);
return sb.toString();
}
}
public static final class CollectionMemberExpressionTester extends AbstractExpressionTester {
private ExpressionTester collectionPath;
private ExpressionTester entityExpression;
private boolean hasNot;
private boolean hasOf;
public boolean hasSpaceAfterMember;
public boolean hasSpaceAfterOf;
protected CollectionMemberExpressionTester(ExpressionTester entityExpression,
boolean hasNot,
boolean hasOf,
ExpressionTester collectionPath) {
super();
this.hasNot = hasNot;
this.hasOf = hasOf;
this.hasSpaceAfterMember = true;
this.hasSpaceAfterOf = hasOf;
this.entityExpression = entityExpression;
this.collectionPath = collectionPath;
}
public void test(Expression expression) {
assertInstance(expression, CollectionMemberExpression.class);
CollectionMemberExpression collectionMemberExpression = (CollectionMemberExpression) expression;
assertEquals(toString(), collectionMemberExpression.toParsedText());
assertEquals(!collectionPath.isNull(), collectionMemberExpression.hasCollectionValuedPathExpression());
assertEquals(!entityExpression.isNull(), collectionMemberExpression.hasEntityExpression());
assertEquals(hasNot, collectionMemberExpression.hasNot());
assertEquals(hasSpaceAfterMember, collectionMemberExpression.hasSpaceAfterMember());
assertEquals(hasOf, collectionMemberExpression.hasOf());
assertEquals(hasSpaceAfterOf, collectionMemberExpression.hasSpaceAfterOf());
entityExpression.test(collectionMemberExpression.getEntityExpression());
collectionPath.test(collectionMemberExpression.getCollectionValuedPathExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(entityExpression);
if (!entityExpression.isNull()) {
sb.append(SPACE);
}
if (hasNot) {
sb.append(NOT);
sb.append(SPACE);
}
if (hasOf) {
sb.append(MEMBER_OF);
if (hasSpaceAfterOf) {
sb.append(SPACE);
}
}
else {
sb.append(MEMBER);
if (hasSpaceAfterMember) {
sb.append(SPACE);
}
}
sb.append(collectionPath);
return sb.toString();
}
}
public static final class CollectionValuedPathExpressionTester extends AbstractPathExpressionTester {
protected CollectionValuedPathExpressionTester(ExpressionTester identificationVariable,
String value) {
super(identificationVariable, value);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, CollectionValuedPathExpression.class);
}
}
public static final class ComparisonExpressionTester extends AbstractExpressionTester {
private String comparator;
public boolean hasSpaceAfterIdentifier;
private ExpressionTester leftExpression;
private ExpressionTester rightExpression;
protected ComparisonExpressionTester(String comparator,
ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super();
this.comparator = comparator;
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
this.hasSpaceAfterIdentifier = true;
}
public void test(Expression expression) {
assertInstance(expression, ComparisonExpression.class);
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
assertEquals(toString(), comparisonExpression.toParsedText());
assertEquals(!leftExpression.isNull(), comparisonExpression.hasLeftExpression());
assertEquals(!rightExpression.isNull(), comparisonExpression.hasRightExpression());
assertEquals(hasSpaceAfterIdentifier, comparisonExpression.hasSpaceAfterIdentifier());
leftExpression .test(comparisonExpression.getLeftExpression());
rightExpression.test(comparisonExpression.getRightExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(leftExpression);
if (!leftExpression.isNull()) {
sb.append(SPACE);
}
sb.append(comparator);
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
sb.append(rightExpression);
return sb.toString();
}
}
public static abstract class CompoundExpressionTester extends AbstractExpressionTester {
public boolean hasSpaceAfterIdentifier;
private ExpressionTester leftExpression;
private ExpressionTester rightExpression;
protected CompoundExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super();
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
this.hasSpaceAfterIdentifier = !rightExpression.isNull();
}
protected abstract Class<? extends CompoundExpression> expressionType();
protected abstract String identifier();
public void test(Expression expression) {
assertInstance(expression, expressionType());
CompoundExpression compoundExpression = (CompoundExpression) expression;
assertEquals(toString(), compoundExpression.toParsedText());
assertEquals(!leftExpression.isNull(), compoundExpression.hasLeftExpression());
assertEquals(!rightExpression.isNull(), compoundExpression.hasRightExpression());
assertEquals(hasSpaceAfterIdentifier, compoundExpression.hasSpaceAfterIdentifier());
leftExpression .test(compoundExpression.getLeftExpression());
rightExpression.test(compoundExpression.getRightExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (!leftExpression.isNull()) {
sb.append(leftExpression);
if (sb.charAt(sb.length() - 1) != SPACE) {
sb.append(SPACE);
}
}
sb.append(identifier());
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
sb.append(rightExpression);
return sb.toString();
}
}
public static final class ConcatExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected ConcatExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return ConcatExpression.class;
}
@Override
protected String identifier() {
return CONCAT;
}
}
public static final class ConnectByClauseTester extends AbstractExpressionTester {
private ExpressionTester expression;
public boolean hasSpaceAfterConnectBy;
protected ConnectByClauseTester(ExpressionTester expression) {
super();
this.expression = expression;
this.hasSpaceAfterConnectBy = !expression.isNull();
}
public void test(Expression expression) {
assertInstance(expression, ConnectByClause.class);
ConnectByClause priorExpression = (ConnectByClause) expression;
assertEquals(toString(), priorExpression.toParsedText());
assertEquals(hasSpaceAfterConnectBy, priorExpression.hasSpaceAfterConnectBy());
assertEquals(!this.expression.isNull(), priorExpression.hasExpression());
this.expression.test(priorExpression.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(CONNECT_BY);
if (hasSpaceAfterConnectBy) {
sb.append(SPACE);
}
sb.append(expression);
return sb.toString();
}
}
public static final class ConstructorExpressionTester extends AbstractExpressionTester {
private String className;
private ExpressionTester constructorItems;
public boolean hasLeftParenthesis;
public boolean hasRightParenthesis;
public boolean hasSpaceAfterNew;
protected ConstructorExpressionTester(String className, ExpressionTester constructorItems) {
super();
this.className = className;
this.constructorItems = constructorItems;
this.hasSpaceAfterNew = true;
this.hasLeftParenthesis = true;
this.hasRightParenthesis = true;
}
public void test(Expression expression) {
assertInstance(expression, ConstructorExpression.class);
ConstructorExpression constructorExpression = (ConstructorExpression) expression;
assertEquals(toString(), constructorExpression.toParsedText());
assertEquals(!constructorItems.isNull(), constructorExpression.hasConstructorItems());
assertEquals(hasSpaceAfterNew, constructorExpression.hasSpaceAfterNew());
assertEquals(hasLeftParenthesis, constructorExpression.hasLeftParenthesis());
assertEquals(hasRightParenthesis, constructorExpression.hasRightParenthesis());
constructorItems.test(constructorExpression.getConstructorItems());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(NEW);
if (hasSpaceAfterNew) {
sb.append(SPACE);
}
sb.append(className);
if (hasLeftParenthesis) {
sb.append(LEFT_PARENTHESIS);
}
sb.append(constructorItems);
if (hasRightParenthesis) {
sb.append(RIGHT_PARENTHESIS);
}
return sb.toString();
}
}
public static final class CountFunctionTester extends AggregateFunctionTester {
protected CountFunctionTester(ExpressionTester expression, boolean hasDistinct) {
super(expression, hasDistinct);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return CountFunction.class;
}
@Override
protected String identifier() {
return COUNT;
}
}
public static final class DatabaseTypeTester extends AbstractDoubleEncapsulatedExpressionTester {
private String databaseType;
protected DatabaseTypeTester(String databaseType,
ExpressionTester size,
ExpressionTester precision) {
super(size, precision);
this.databaseType = databaseType;
}
@Override
protected Class<DatabaseType> expressionType() {
return DatabaseType.class;
}
@Override
protected String identifier() {
return databaseType;
}
}
public static final class DateTimeTester extends AbstractExpressionTester {
private String dateTime;
protected DateTimeTester(String dateTime) {
super();
this.dateTime = dateTime;
}
public void test(Expression expression) {
assertInstance(expression, DateTime.class);
DateTime dateTime = (DateTime) expression;
assertEquals(toString(), dateTime.toParsedText());
}
@Override
public String toString() {
return dateTime;
}
}
/**
* Tester for {@link DeleteClause}.
*/
public static final class DeleteClauseTester extends AbstractExpressionTester {
public boolean hasFrom;
public boolean hasSpaceAfterDelete;
public boolean hasSpaceAfterFrom;
private ExpressionTester rangeVariableDeclaration;
protected DeleteClauseTester(ExpressionTester rangeVariableDeclaration) {
super();
this.hasFrom = true;
this.hasSpaceAfterFrom = true;
this.hasSpaceAfterDelete = true;
this.rangeVariableDeclaration = rangeVariableDeclaration;
}
public void test(Expression expression) {
assertInstance(expression, DeleteClause.class);
DeleteClause deleteClause = (DeleteClause) expression;
assertEquals(toString(), deleteClause.toParsedText());
assertEquals(hasSpaceAfterDelete, deleteClause.hasSpaceAfterDelete());
assertEquals(hasFrom, deleteClause.hasFrom());
assertEquals(hasSpaceAfterFrom, deleteClause.hasSpaceAfterFrom());
assertEquals(!rangeVariableDeclaration.isNull(), deleteClause.hasRangeVariableDeclaration());
rangeVariableDeclaration.test(deleteClause.getRangeVariableDeclaration());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(DELETE);
if (hasSpaceAfterDelete) {
sb.append(SPACE);
}
if (hasFrom) {
sb.append(FROM);
}
if (hasSpaceAfterFrom) {
sb.append(SPACE);
}
sb.append(rangeVariableDeclaration);
return sb.toString();
}
}
public static final class DeleteStatementTester extends AbstractExpressionTester {
private ExpressionTester deleteClause;
public boolean hasSpaceAfterDeleteClause;
private ExpressionTester whereClause;
protected DeleteStatementTester(ExpressionTester deleteClause, ExpressionTester whereClause) {
super();
this.deleteClause = deleteClause;
this.whereClause = whereClause;
this.hasSpaceAfterDeleteClause = !whereClause.isNull();
}
public void test(Expression expression) {
assertInstance(expression, DeleteStatement.class);
DeleteStatement deleteStatement = (DeleteStatement) expression;
assertEquals(toString(), deleteStatement.toParsedText());
assertEquals(hasSpaceAfterDeleteClause, deleteStatement.hasSpaceAfterDeleteClause());
assertEquals(!whereClause.isNull(), deleteStatement.hasWhereClause());
deleteClause.test(deleteStatement.getDeleteClause());
whereClause .test(deleteStatement.getWhereClause());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(deleteClause);
if (hasSpaceAfterDeleteClause) {
sb.append(SPACE);
}
sb.append(whereClause);
return sb.toString();
}
}
public static final class DivisionExpressionTester extends CompoundExpressionTester {
protected DivisionExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
protected Class<? extends CompoundExpression> expressionType() {
return DivisionExpression.class;
}
@Override
protected String identifier() {
return DIVISION;
}
}
public static final class EmptyCollectionComparisonExpressionTester extends AbstractExpressionTester {
private ExpressionTester collectionPath;
private boolean hasNot;
public boolean hasSpaceAfterIs;
protected EmptyCollectionComparisonExpressionTester(ExpressionTester collectionPath,
boolean hasNot) {
super();
this.hasNot = hasNot;
this.hasSpaceAfterIs = true;
this.collectionPath = collectionPath;
}
public void test(Expression expression) {
assertInstance(expression, EmptyCollectionComparisonExpression.class);
EmptyCollectionComparisonExpression emptyCollection = (EmptyCollectionComparisonExpression) expression;
assertEquals(toString(), emptyCollection.toParsedText());
assertEquals(!collectionPath.isNull(), emptyCollection.hasExpression());
assertEquals(hasNot, emptyCollection.hasNot());
assertEquals(hasSpaceAfterIs, emptyCollection.hasSpaceAfterIs());
collectionPath.test(emptyCollection.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(collectionPath);
if (!collectionPath.isNull()) {
sb.append(SPACE);
}
sb.append(IS);
if (hasSpaceAfterIs) {
sb.append(SPACE);
}
if (hasNot) {
sb.append(NOT);
sb.append(SPACE);
}
sb.append(EMPTY);
return sb.toString();
}
}
public static final class EntityTypeLiteralTester extends AbstractExpressionTester {
private String entityType;
protected EntityTypeLiteralTester(String entityType) {
super();
this.entityType = entityType;
}
public void test(Expression expression) {
assertInstance(expression, EntityTypeLiteral.class);
EntityTypeLiteral entityTypeLiteral = (EntityTypeLiteral) expression;
assertEquals(toString(), entityTypeLiteral.toParsedText());
}
@Override
public String toString() {
return entityType;
}
}
public static final class EntryExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected EntryExpressionTester(ExpressionTester identificationVariable) {
super(identificationVariable);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return EntryExpression.class;
}
@Override
protected String identifier() {
return ENTRY;
}
}
public static final class ExistsExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
private boolean hasNot;
protected ExistsExpressionTester(ExpressionTester subquery, boolean hasNot) {
super(subquery);
this.hasNot = hasNot;
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return ExistsExpression.class;
}
@Override
protected String identifier() {
return hasNot ? NOT_EXISTS : EXISTS;
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, ExistsExpression.class);
ExistsExpression existsExpression = (ExistsExpression) expression;
assertEquals(hasNot, existsExpression.hasNot());
}
}
/**
* This tester tests an {@link Expression} information to make sure it correctly parsed a section
* of the query. This interface also adds helper method for easily creating a parsed tree
* representation of the actual query parsed tree.
*/
public static interface ExpressionTester {
AdditionExpressionTester add(ExpressionTester expression);
AndExpressionTester and(ExpressionTester expression);
BetweenExpressionTester between(ExpressionTester lowerBoundExpression, ExpressionTester upperBoundExpression);
ComparisonExpressionTester different(ExpressionTester expression);
DivisionExpressionTester divide(ExpressionTester expression);
ComparisonExpressionTester equal(ExpressionTester expression);
ComparisonExpressionTester greaterThan(ExpressionTester expression);
ComparisonExpressionTester greaterThanOrEqual(ExpressionTester expression);
InExpressionTester in(ExpressionTester... inItems);
InExpressionTester in(String inputParameter);
EmptyCollectionComparisonExpressionTester isEmpty();
EmptyCollectionComparisonExpressionTester isNotEmpty();
/**
* Determines whether this tester represents the {@link NullExpression}.
*
* @return <code>true</code> if this tester represents a <code>null</code> object;
* <code>false</code> otherwise
*/
boolean isNull();
LikeExpressionTester like(ExpressionTester patternValue);
LikeExpressionTester like(ExpressionTester patternValue, ExpressionTester escapeCharacter);
ComparisonExpressionTester lowerThan(ExpressionTester expression);
ComparisonExpressionTester lowerThanOrEqual(ExpressionTester expression);
ExpressionTester member(ExpressionTester collectionPath);
ExpressionTester memberOf(ExpressionTester collectionPath);
MultiplicationExpressionTester multiply(ExpressionTester expression);
BetweenExpressionTester notBetween(ExpressionTester lowerBoundExpression, ExpressionTester upperBoundExpression);
ComparisonExpressionTester notEqual(ExpressionTester expression);
InExpressionTester notIn(ExpressionTester... inItems);
InExpressionTester notIn(String inputParameter);
LikeExpressionTester notLike(ExpressionTester expression);
LikeExpressionTester notLike(ExpressionTester expression, ExpressionTester escapeCharacter);
ExpressionTester notMember(ExpressionTester collectionPath);
ExpressionTester notMemberOf(ExpressionTester collectionPath);
OrExpressionTester or(ExpressionTester expression);
RegexpExpressionTester regexp(StringLiteralTester patternValue);
SubtractionExpressionTester subtract(ExpressionTester expression);
/**
* Tests the given {@link Expression} internal data.
*/
void test(Expression expression);
}
public static final class ExtractExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
private boolean hasFrom;
public boolean hasSpaceAfterFrom;
public boolean hasSpaceAfterPart;
private String part;
protected ExtractExpressionTester(String part, boolean hasFom, ExpressionTester expression) {
super(expression);
this.hasFrom = hasFom;
this.part = (part != null) ? part : ExpressionTools.EMPTY_STRING;
this.hasSpaceAfterPart = (part != null) && (hasFrom || !expression.isNull());
this.hasSpaceAfterFrom = hasFom && !expression.isNull();
}
@Override
protected Class<ExtractExpression> expressionType() {
return ExtractExpression.class;
}
@Override
protected boolean hasEncapsulatedExpression() {
return super.hasEncapsulatedExpression() || hasFrom || ExpressionTools.stringIsNotEmpty(part);
}
@Override
protected String identifier() {
return EXTRACT;
}
@Override
public void test(Expression expression) {
super.test(expression);
ExtractExpression extractExpression = (ExtractExpression) expression;
assertEquals(part, extractExpression.getDatePart());
assertEquals(hasFrom, extractExpression.hasFrom());
assertSame (hasSpaceAfterFrom, extractExpression.hasSpaceAfterFrom());
assertSame (hasSpaceAfterPart, extractExpression.hasSpaceAfterDatePart());
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
sb.append(part);
if (hasSpaceAfterPart) {
sb.append(SPACE);
}
if (hasFrom) {
sb.append(FROM);
}
if (hasSpaceAfterFrom) {
sb.append(SPACE);
}
super.toStringEncapsulatedExpression(sb);
}
}
public static final class FromClauseTester extends AbstractFromClauseTester {
protected FromClauseTester(ExpressionTester declarations,
ExpressionTester hierarchicalQueryClause,
ExpressionTester asOfClause) {
super(declarations, hierarchicalQueryClause, asOfClause);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, FromClause.class);
}
}
public static final class FunctionExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
private String functionName;
public boolean hasComma;
public boolean hasSpaceAfterComma;
private String identifier;
protected FunctionExpressionTester(String identifier,
String functionName,
ExpressionTester funcItems) {
super(funcItems);
this.identifier = identifier;
this.functionName = functionName;
this.hasSpaceAfterComma = !funcItems.isNull();
this.hasComma = !funcItems.isNull();
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return FunctionExpression.class;
}
@Override
protected boolean hasEncapsulatedExpression() {
return functionName.length() > 0 ||
hasComma ||
hasSpaceAfterComma ||
super.hasEncapsulatedExpression();
}
@Override
protected String identifier() {
return identifier;
}
@Override
public void test(Expression expression) {
super.test(expression);
FunctionExpression funcExpression = (FunctionExpression) expression;
assertEquals(identifier, funcExpression.getIdentifier());
assertEquals(functionName, funcExpression.getFunctionName());
assertEquals(hasComma, funcExpression.hasComma());
assertEquals(hasSpaceAfterComma, funcExpression.hasSpaceAfterComma());
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
if (functionName != null) {
sb.append(functionName);
}
if (hasComma) {
sb.append(COMMA);
}
if (hasSpaceAfterComma) {
sb.append(SPACE);
}
super.toStringEncapsulatedExpression(sb);
}
}
public static final class GroupByClauseTester extends AbstractExpressionTester {
private ExpressionTester groupByItems;
public boolean hasSpaceAfterGroupBy;
protected GroupByClauseTester(ExpressionTester groupByItems) {
super();
this.groupByItems = groupByItems;
this.hasSpaceAfterGroupBy = !groupByItems.isNull();
}
public void test(Expression expression) {
assertInstance(expression, GroupByClause.class);
GroupByClause groupByClause = (GroupByClause) expression;
assertEquals(toString(), groupByClause.toParsedText());
assertEquals(!groupByItems.isNull(), groupByClause.hasGroupByItems());
assertEquals(hasSpaceAfterGroupBy, groupByClause.hasSpaceAfterGroupBy());
groupByItems.test(groupByClause.getGroupByItems());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(GROUP_BY);
if (hasSpaceAfterGroupBy) {
sb.append(SPACE);
}
sb.append(groupByItems);
return sb.toString();
}
}
public static final class HavingClauseTester extends AbstractConditionalClauseTester {
protected HavingClauseTester(ExpressionTester conditionalExpression) {
super(conditionalExpression);
}
@Override
protected Class<? extends AbstractConditionalClause> expressionType() {
return HavingClause.class;
}
@Override
protected String identifier() {
return HAVING;
}
}
public static final class HierarchicalQueryClauseTester extends AbstractExpressionTester {
private ExpressionTester connectByClause;
public boolean hasSpaceAfterConnectByClause;
public boolean hasSpaceAfterStartWithClause;
private ExpressionTester orderSiblingsByClause;
private ExpressionTester startWithClause;
protected HierarchicalQueryClauseTester(ExpressionTester startWithClause,
ExpressionTester connectByClause,
ExpressionTester orderSiblingsByClause) {
super();
this.startWithClause = startWithClause;
this.connectByClause = connectByClause;
this.orderSiblingsByClause = orderSiblingsByClause;
this.hasSpaceAfterStartWithClause = !startWithClause.isNull() && !connectByClause.isNull();
this.hasSpaceAfterConnectByClause = !connectByClause.isNull() && !orderSiblingsByClause.isNull();
}
public void test(Expression expression) {
assertInstance(expression, HierarchicalQueryClause.class);
HierarchicalQueryClause clause = (HierarchicalQueryClause) expression;
assertEquals(toString(), clause.toString());
assertEquals(!startWithClause.isNull(), clause.hasStartWithClause());
assertEquals(!connectByClause.isNull(), clause.hasConnectByClause());
assertEquals(!orderSiblingsByClause.isNull(), clause.hasOrderSiblingsByClause());
assertEquals(hasSpaceAfterStartWithClause, clause.hasSpaceAfterStartWithClause());
assertEquals(hasSpaceAfterConnectByClause, clause.hasSpaceAfterConnectByClause());
startWithClause.test(clause.getStartWithClause());
connectByClause.test(clause.getConnectByClause());
orderSiblingsByClause.test(clause.getOrderSiblingsByClause());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(startWithClause);
if (hasSpaceAfterStartWithClause) {
sb.append(SPACE);
}
sb.append(connectByClause);
if (hasSpaceAfterConnectByClause) {
sb.append(SPACE);
}
sb.append(orderSiblingsByClause);
return sb.toString();
}
}
public static final class IdentificationVariableDeclarationTester extends AbstractExpressionTester {
public boolean hasSpace;
private ExpressionTester joins;
private ExpressionTester rangeVariableDeclaration;
protected IdentificationVariableDeclarationTester(ExpressionTester rangeVariableDeclaration,
ExpressionTester joins) {
super();
this.rangeVariableDeclaration = rangeVariableDeclaration;
this.hasSpace = !joins.isNull();
this.joins = joins;
}
public void test(Expression expression) {
assertInstance(expression, IdentificationVariableDeclaration.class);
IdentificationVariableDeclaration identificationVariableDeclaration = (IdentificationVariableDeclaration) expression;
assertEquals(toString(), identificationVariableDeclaration.toParsedText());
assertEquals(!rangeVariableDeclaration.isNull(), identificationVariableDeclaration.hasRangeVariableDeclaration());
assertEquals(hasSpace, identificationVariableDeclaration.hasSpace());
assertEquals(!joins.isNull(), identificationVariableDeclaration.hasJoins());
rangeVariableDeclaration.test(identificationVariableDeclaration.getRangeVariableDeclaration());
joins.test(identificationVariableDeclaration.getJoins());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(rangeVariableDeclaration);
if (hasSpace) {
sb.append(SPACE);
}
sb.append(joins);
return sb.toString();
}
}
public static final class IdentificationVariableTester extends AbstractExpressionTester {
private String identificationVariable;
private boolean virtual;
private ExpressionTester virtualPathExpression;
protected IdentificationVariableTester(String identificationVariable,
boolean virtual,
ExpressionTester virtualPathExpression) {
super();
this.virtual = virtual;
this.identificationVariable = identificationVariable;
this.virtualPathExpression = virtualPathExpression;
}
@Override
public boolean isNull() {
return virtual && virtualPathExpression.isNull();
}
public void test(Expression expression) {
assertInstance(expression, IdentificationVariable.class);
IdentificationVariable identificationVariable = (IdentificationVariable) expression;
assertEquals(this.identificationVariable, identificationVariable.toParsedText());
assertEquals(virtual, identificationVariable.isVirtual());
if (virtual) {
StateFieldPathExpression pathExpression = identificationVariable.getStateFieldPathExpression();
assertEquals(virtualPathExpression.isNull(), pathExpression == null);
if (pathExpression != null) {
virtualPathExpression.test(pathExpression);
}
}
}
@Override
public String toString() {
return virtual ? virtualPathExpression.toString() : identificationVariable;
}
}
public static final class IndexExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected IndexExpressionTester(ExpressionTester identificationVariable) {
super(identificationVariable);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return IndexExpression.class;
}
@Override
protected String identifier() {
return INDEX;
}
}
public static final class InExpressionTester extends AbstractExpressionTester {
public boolean hasLeftParenthesis;
private boolean hasNot;
public boolean hasRightParenthesis;
public boolean hasSpaceAfterIn;
private ExpressionTester inItems;
private ExpressionTester stateFieldPathExpression;
protected InExpressionTester(ExpressionTester stateFieldPathExpression,
boolean hasNot,
ExpressionTester inItems) {
super();
this.stateFieldPathExpression = stateFieldPathExpression;
this.hasLeftParenthesis = !inItems.isNull();
this.hasRightParenthesis = !inItems.isNull();
this.hasNot = hasNot;
this.inItems = inItems;
this.hasSpaceAfterIn = !hasLeftParenthesis && !inItems.isNull();
}
public void test(Expression expression) {
assertInstance(expression, InExpression.class);
InExpression inExpression = (InExpression) expression;
assertEquals(toString(), inExpression.toParsedText());
assertEquals(hasLeftParenthesis, inExpression.hasLeftParenthesis());
assertEquals(hasRightParenthesis, inExpression.hasRightParenthesis());
assertEquals(hasNot, inExpression.hasNot());
assertEquals(!inItems.isNull(), inExpression.hasInItems());
assertEquals(!stateFieldPathExpression.isNull(), inExpression.hasExpression());
stateFieldPathExpression.test(inExpression.getExpression());
inItems.test(inExpression.getInItems());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(stateFieldPathExpression);
if (!stateFieldPathExpression.isNull()) {
sb.append(SPACE);
}
sb.append(hasNot ? NOT_IN : IN);
if (hasSpaceAfterIn) {
sb.append(SPACE);
}
if (hasLeftParenthesis) {
sb.append(LEFT_PARENTHESIS);
}
sb.append(inItems);
if (hasRightParenthesis) {
sb.append(RIGHT_PARENTHESIS);
}
return sb.toString();
}
}
public static final class InputParameterTester extends AbstractExpressionTester {
private String inputParameter;
protected InputParameterTester(String inputParameter) {
super();
this.inputParameter = inputParameter;
}
public void test(Expression expression) {
assertInstance(expression, InputParameter.class);
InputParameter inputParameter = (InputParameter) expression;
assertEquals(toString(), inputParameter.toParsedText());
assertEquals(this.inputParameter.charAt(0) == '?', inputParameter.isPositional());
assertEquals(this.inputParameter.charAt(0) == ':', inputParameter.isNamed());
assertEquals(this.inputParameter.substring(1), inputParameter.getParameterName());
}
@Override
public String toString() {
return inputParameter;
}
}
public static final class JoinTester extends AbstractExpressionTester {
private boolean hasAs;
public boolean hasSpaceAfterAs;
public boolean hasSpaceAfterIdentificationVariable;
public boolean hasSpaceAfterJoin;
public boolean hasSpaceAfterJoinAssociation;
private ExpressionTester identificationVariable;
private ExpressionTester joinAssociationPath;
private ExpressionTester joinCondition;
private String joinType;
protected JoinTester(String joinType,
ExpressionTester joinAssociationPath,
boolean hasAs,
ExpressionTester identificationVariable,
ExpressionTester joinCondition) {
super();
this.joinType = joinType;
this.hasSpaceAfterJoin = true;
this.joinAssociationPath = joinAssociationPath;
this.hasAs = hasAs;
this.hasSpaceAfterAs = hasAs;
this.identificationVariable = identificationVariable;
this.hasSpaceAfterJoinAssociation = !joinAssociationPath.isNull();
this.hasSpaceAfterIdentificationVariable = !identificationVariable.isNull() && !joinCondition.isNull();
this.joinCondition = joinCondition;
}
public void test(Expression expression) {
assertInstance(expression, Join.class);
Join join = (Join) expression;
assertEquals(toString(), join.toParsedText());
assertEquals(joinType, join.getIdentifier());
assertEquals(hasSpaceAfterJoin, join.hasSpaceAfterJoin());
assertEquals(!joinAssociationPath.isNull(), join.hasJoinAssociationPath());
assertEquals(hasAs, join.hasAs());
assertEquals(hasSpaceAfterAs, join.hasSpaceAfterAs());
assertEquals(hasSpaceAfterJoinAssociation, join.hasSpaceAfterJoinAssociation());
assertEquals(!identificationVariable.isNull(), join.hasIdentificationVariable());
assertEquals(hasSpaceAfterIdentificationVariable, join.hasSpaceAfterIdentificationVariable());
joinAssociationPath.test(join.getJoinAssociationPath());
identificationVariable.test(join.getIdentificationVariable());
joinCondition.test(join.getOnClause());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(joinType);
if (hasSpaceAfterJoin) {
sb.append(SPACE);
}
sb.append(joinAssociationPath);
if (hasSpaceAfterJoinAssociation) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(identificationVariable);
if (hasSpaceAfterIdentificationVariable) {
sb.append(SPACE);
}
sb.append(joinCondition);
return sb.toString();
}
}
public static final class JPQLExpressionTester extends AbstractExpressionTester {
private ExpressionTester queryStatement;
private ExpressionTester unknownExpression;
protected JPQLExpressionTester(ExpressionTester queryStatement,
ExpressionTester unknownExpression) {
super();
this.queryStatement = queryStatement;
this.unknownExpression = unknownExpression;
}
public void test(Expression expression) {
JPQLExpression jpqlExpression = (JPQLExpression) expression;
assertEquals(toString(), jpqlExpression.toParsedText());
assertEquals(!queryStatement.isNull(), jpqlExpression.hasQueryStatement());
assertEquals(!unknownExpression.isNull(), jpqlExpression.hasUnknownEndingStatement());
queryStatement .test(jpqlExpression.getQueryStatement());
unknownExpression.test(jpqlExpression.getUnknownEndingStatement());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(queryStatement);
sb.append(unknownExpression);
return sb.toString();
}
}
public static final class KeywordExpressionTester extends AbstractExpressionTester {
private String keyword;
protected KeywordExpressionTester(String keyword) {
super();
this.keyword = keyword;
}
public void test(Expression expression) {
assertInstance(expression, KeywordExpression.class);
KeywordExpression keywordExpression = (KeywordExpression) expression;
assertEquals(toString(), keywordExpression.toParsedText());
}
@Override
public String toString() {
return keyword;
}
}
public static final class LengthExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected LengthExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return LengthExpression.class;
}
@Override
protected String identifier() {
return LENGTH;
}
}
public static final class LikeExpressionTester extends AbstractExpressionTester {
private ExpressionTester escapeCharacter;
public boolean hasEscape;
private boolean hasNot;
public boolean hasSpaceAfterEscape;
public boolean hasSpaceAfterLike;
public boolean hasSpaceAfterPatternValue;
private ExpressionTester patternValue;
private ExpressionTester stringExpression;
protected LikeExpressionTester(ExpressionTester stringExpression,
boolean hasNot,
ExpressionTester patternValue,
ExpressionTester escapeCharacter) {
super();
this.hasNot = hasNot;
this.hasSpaceAfterLike = true;
this.stringExpression = stringExpression;
this.patternValue = patternValue;
this.escapeCharacter = escapeCharacter;
this.hasEscape = !escapeCharacter.isNull();
this.hasSpaceAfterEscape = hasEscape;
this.hasSpaceAfterPatternValue = !patternValue.isNull() && hasEscape;
}
public void test(Expression expression) {
assertInstance(expression, LikeExpression.class);
LikeExpression likeExpression = (LikeExpression) expression;
assertEquals(toString(), likeExpression.toParsedText());
assertEquals(hasNot, likeExpression.hasNot());
assertEquals(hasSpaceAfterLike, likeExpression.hasSpaceAfterLike());
assertEquals(hasEscape, likeExpression.hasEscape());
assertEquals(!escapeCharacter.isNull(), likeExpression.hasEscapeCharacter());
assertEquals(hasSpaceAfterEscape, likeExpression.hasSpaceAfterEscape());
assertEquals(hasSpaceAfterPatternValue, likeExpression.hasSpaceAfterPatternValue());
assertEquals(!patternValue.isNull(), likeExpression.hasPatternValue());
stringExpression.test(likeExpression.getStringExpression());
patternValue.test(likeExpression.getPatternValue());
escapeCharacter.test(likeExpression.getEscapeCharacter());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(stringExpression);
if (!stringExpression.isNull()) {
sb.append(SPACE);
}
sb.append(hasNot ? NOT_LIKE : LIKE);
if (hasSpaceAfterLike) {
sb.append(SPACE);
}
sb.append(patternValue);
if (hasSpaceAfterPatternValue) {
sb.append(SPACE);
}
if (hasEscape) {
sb.append(ESCAPE);
}
if (hasSpaceAfterEscape) {
sb.append(SPACE);
}
sb.append(escapeCharacter);
return sb.toString();
}
}
public static final class LocateExpressionTester extends AbstractTripleEncapsulatedExpressionTester {
protected LocateExpressionTester(ExpressionTester firstExpression,
ExpressionTester secondExpression,
ExpressionTester thirdExpression) {
super(firstExpression, secondExpression, thirdExpression);
}
@Override
protected Class<? extends AbstractTripleEncapsulatedExpression> expressionType() {
return LocateExpression.class;
}
@Override
protected String identifier() {
return LOCATE;
}
}
public static abstract class LogicalExpressionTester extends CompoundExpressionTester {
protected LogicalExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, LogicalExpression.class);
}
}
public static final class LowerExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected LowerExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return LowerExpression.class;
}
@Override
protected String identifier() {
return LOWER;
}
}
public static final class MaxFunctionTester extends AggregateFunctionTester {
protected MaxFunctionTester(ExpressionTester expression, boolean hasDistinct) {
super(expression, hasDistinct);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return MaxFunction.class;
}
@Override
protected String identifier() {
return MAX;
}
}
public static final class MinFunctionTester extends AggregateFunctionTester {
protected MinFunctionTester(ExpressionTester expression, boolean hasDistinct) {
super(expression, hasDistinct);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return MinFunction.class;
}
@Override
protected String identifier() {
return MIN;
}
}
public static final class ModExpressionTester extends AbstractDoubleEncapsulatedExpressionTester {
protected ModExpressionTester(ExpressionTester firstExpression, ExpressionTester secondExpression) {
super(firstExpression, secondExpression);
}
@Override
protected Class<? extends AbstractDoubleEncapsulatedExpression> expressionType() {
return ModExpression.class;
}
@Override
protected String identifier() {
return MOD;
}
}
public static final class MultiplicationExpressionTester extends CompoundExpressionTester {
protected MultiplicationExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
protected Class<? extends CompoundExpression> expressionType() {
return MultiplicationExpression.class;
}
@Override
protected String identifier() {
return MULTIPLICATION;
}
}
public static final class NotExpressionTester extends AbstractExpressionTester {
private ExpressionTester expression;
public boolean hasSpaceAfterNot;
protected NotExpressionTester(ExpressionTester expression) {
super();
this.expression = expression;
this.hasSpaceAfterNot = true;
}
public void test(Expression expression) {
assertInstance(expression, NotExpression.class);
NotExpression notExpression = (NotExpression) expression;
assertEquals(toString(), notExpression.toParsedText());
assertEquals(hasSpaceAfterNot, notExpression.hasSpaceAfterNot());
assertEquals(!this.expression.isNull(), notExpression.hasExpression());
this.expression.test(notExpression.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(NOT);
if (hasSpaceAfterNot) {
sb.append(SPACE);
}
sb.append(expression);
return sb.toString();
}
}
public static final class NullComparisonExpressionTester extends AbstractExpressionTester {
private ExpressionTester expression;
private boolean hasNot;
protected NullComparisonExpressionTester(ExpressionTester expression, boolean hasNot) {
super();
this.hasNot = hasNot;
this.expression = expression;
}
public void test(Expression expression) {
assertInstance(expression, NullComparisonExpression.class);
NullComparisonExpression nullComparisonExpression = (NullComparisonExpression) expression;
assertEquals(toString(), nullComparisonExpression.toParsedText());
assertEquals(hasNot, nullComparisonExpression.hasNot());
assertEquals(!this.expression.isNull(), nullComparisonExpression.hasExpression());
this.expression.test(nullComparisonExpression.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(expression);
if (!expression.isNull()) {
sb.append(SPACE);
}
sb.append(hasNot ? IS_NOT_NULL : IS_NULL);
return sb.toString();
}
}
public static final class NullExpressionTester extends AbstractExpressionTester {
@Override
public boolean isNull() {
return true;
}
public void test(Expression expression) {
assertInstance(expression, NullExpression.class);
}
@Override
public String toString() {
return ExpressionTools.EMPTY_STRING;
}
}
public static final class NullIfExpressionTester extends AbstractDoubleEncapsulatedExpressionTester {
protected NullIfExpressionTester(ExpressionTester firstExpression,
ExpressionTester secondExpression) {
super(firstExpression, secondExpression);
}
@Override
protected Class<? extends AbstractDoubleEncapsulatedExpression> expressionType() {
return NullIfExpression.class;
}
@Override
protected String identifier() {
return NULLIF;
}
}
public static final class NumericLiteralTester extends AbstractExpressionTester {
private String number;
protected NumericLiteralTester(String number) {
super();
this.number = number;
}
public void test(Expression expression) {
assertInstance(expression, NumericLiteral.class);
assertEquals(toString(), expression.toParsedText());
}
@Override
public String toString() {
return number;
}
}
public static final class ObjectExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected ObjectExpressionTester(ExpressionTester identificationVariable) {
super(identificationVariable);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return ObjectExpression.class;
}
@Override
protected String identifier() {
return OBJECT;
}
}
public static final class OnClauseTester extends AbstractConditionalClauseTester {
protected OnClauseTester(ExpressionTester conditionalExpression) {
super(conditionalExpression);
}
@Override
protected Class<? extends AbstractConditionalClause> expressionType() {
return OnClause.class;
}
@Override
protected String identifier() {
return ON;
}
}
public static final class OrderByClauseTester extends AbstractOrderByClauseTester {
protected OrderByClauseTester(ExpressionTester orderByItems) {
super(orderByItems);
}
@Override
protected String identifier() {
return ORDER_BY;
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, OrderByClause.class);
}
}
public static final class OrderByItemTester extends AbstractExpressionTester {
public boolean hasSpaceAfterExpression;
public boolean hasSpaceAfterNulls;
public boolean hasSpaceAfterOrdering;
private NullOrdering nullOrdering;
public String nulls;
private ExpressionTester orderByItem;
private Ordering ordering;
protected OrderByItemTester(ExpressionTester orderByItem,
Ordering ordering,
NullOrdering nullOrdering) {
super();
this.ordering = ordering;
this.orderByItem = orderByItem;
this.nullOrdering = nullOrdering;
this.hasSpaceAfterExpression = ordering != Ordering.DEFAULT ||
nullOrdering != NullOrdering.DEFAULT;
this.hasSpaceAfterOrdering = ordering != Ordering.DEFAULT &&
nullOrdering != NullOrdering.DEFAULT;
}
public void test(Expression expression) {
assertInstance(expression, OrderByItem.class);
OrderByItem orderByItem = (OrderByItem) expression;
assertEquals(toString(), orderByItem.toParsedText());
assertEquals(!this.orderByItem.isNull(), orderByItem.hasExpression());
assertEquals(hasSpaceAfterExpression, orderByItem.hasSpaceAfterExpression());
assertEquals(hasSpaceAfterOrdering, orderByItem.hasSpaceAfterOrdering());
assertSame (ordering, orderByItem.getOrdering());
if (nulls != null) {
assertEquals(nulls, orderByItem.getActualNullOrdering().toUpperCase());
}
else {
assertSame(nullOrdering, orderByItem.getNullOrdering());
}
this.orderByItem.test(orderByItem.getExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(orderByItem);
if (hasSpaceAfterExpression) {
sb.append(SPACE);
}
if (ordering != Ordering.DEFAULT) {
sb.append(ordering.name());
}
if (hasSpaceAfterOrdering) {
sb.append(SPACE);
}
if (nulls != null) {
sb.append(nulls);
if (hasSpaceAfterNulls) {
sb.append(SPACE);
}
}
else if (nullOrdering != NullOrdering.DEFAULT) {
sb.append(nullOrdering.getIdentifier());
}
return sb.toString();
}
}
public static final class OrderSiblingsByClauseTester extends AbstractOrderByClauseTester {
protected OrderSiblingsByClauseTester(ExpressionTester orderByItems) {
super(orderByItems);
}
@Override
protected String identifier() {
return ORDER_SIBLINGS_BY;
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, OrderSiblingsByClause.class);
}
}
public static final class OrExpressionTester extends LogicalExpressionTester {
protected OrExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
protected Class<? extends CompoundExpression> expressionType() {
return OrExpression.class;
}
@Override
protected String identifier() {
return OR;
}
}
public static final class RangeVariableDeclarationTester extends AbstractExpressionTester {
private ExpressionTester abstractSchemaName;
private boolean hasAs;
public boolean hasSpaceAfterAbstractSchemaName;
public boolean hasSpaceAfterAs;
private ExpressionTester identificationVariable;
protected RangeVariableDeclarationTester(ExpressionTester abstractSchemaName,
boolean hasAs,
ExpressionTester identificationVariable) {
super();
this.hasAs = hasAs;
this.abstractSchemaName = abstractSchemaName;
this.identificationVariable = identificationVariable;
this.hasSpaceAfterAbstractSchemaName = hasAs || !identificationVariable.isNull();
this.hasSpaceAfterAs = hasAs;
if (identificationVariable instanceof IdentificationVariableTester &&
identificationVariable.isNull()) {
this.hasSpaceAfterAbstractSchemaName = true;
}
}
public void test(Expression expression) {
assertInstance(expression, RangeVariableDeclaration.class);
RangeVariableDeclaration rangeVariableDeclaration = (RangeVariableDeclaration) expression;
assertEquals(toString(), rangeVariableDeclaration.toParsedText());
assertEquals(hasAs, rangeVariableDeclaration.hasAs());
assertEquals(hasSpaceAfterAs, rangeVariableDeclaration.hasSpaceAfterAs());
assertEquals(!identificationVariable.isNull(), rangeVariableDeclaration.hasIdentificationVariable());
assertEquals(hasSpaceAfterAbstractSchemaName, rangeVariableDeclaration.hasSpaceAfterRootObject());
abstractSchemaName.test(rangeVariableDeclaration.getRootObject());
identificationVariable.test(rangeVariableDeclaration.getIdentificationVariable());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(abstractSchemaName);
if (hasSpaceAfterAbstractSchemaName) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(identificationVariable);
return sb.toString();
}
}
public static final class RegexpExpressionTester extends AbstractExpressionTester {
public boolean hasSpaceAfterIdentifier;
private ExpressionTester patternValue;
private ExpressionTester stringExpression;
protected RegexpExpressionTester(ExpressionTester stringExpression,
ExpressionTester patternValue) {
super();
this.stringExpression = stringExpression;
this.patternValue = patternValue;
this.hasSpaceAfterIdentifier = !patternValue.isNull();
}
public void test(Expression expression) {
assertInstance(expression, RegexpExpression.class);
RegexpExpression regexpExpression = (RegexpExpression) expression;
assertEquals(toString(), regexpExpression.toParsedText());
assertEquals(!patternValue.isNull(), regexpExpression.hasPatternValue());
assertEquals(hasSpaceAfterIdentifier, regexpExpression.hasSpaceAfterIdentifier());
assertEquals(!stringExpression.isNull(), regexpExpression.hasSpaceAfterStringExpression());
assertEquals(!stringExpression.isNull(), regexpExpression.hasStringExpression());
stringExpression.test(regexpExpression.getStringExpression());
patternValue .test(regexpExpression.getPatternValue());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(stringExpression);
if (!stringExpression.isNull()) {
sb.append(SPACE);
}
sb.append(REGEXP);
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
sb.append(patternValue);
return sb.toString();
}
}
public static final class ResultVariableTester extends AbstractExpressionTester {
private boolean hasAs;
public boolean hasSpaceAfterAs;
private ExpressionTester resultVariable;
private ExpressionTester selectExpression;
protected ResultVariableTester(ExpressionTester selectExpression,
boolean hasAs,
ExpressionTester resultVariable) {
super();
this.hasAs = hasAs;
this.hasSpaceAfterAs = hasAs;
this.selectExpression = selectExpression;
this.resultVariable = resultVariable;
}
public void test(Expression expression) {
assertInstance(expression, ResultVariable.class);
ResultVariable resultVariable = (ResultVariable) expression;
assertEquals(toString(), resultVariable.toParsedText());
assertEquals(hasAs, resultVariable.hasAs());
assertEquals(hasSpaceAfterAs, resultVariable.hasSpaceAfterAs());
assertEquals(!this.resultVariable.isNull(), resultVariable.hasResultVariable());
assertEquals(!selectExpression.isNull(), resultVariable.hasSelectExpression());
this.selectExpression.test(resultVariable.getSelectExpression());
this.resultVariable .test(resultVariable.getResultVariable());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(selectExpression);
if (!selectExpression.isNull()) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(resultVariable);
return sb.toString();
}
}
public static final class SelectClauseTester extends AbstractSelectClauseTester {
protected SelectClauseTester(ExpressionTester selectExpressions, boolean hasDistinct) {
super(selectExpressions, hasDistinct);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, SelectClause.class);
}
}
public static final class SelectStatementTester extends AbstractSelectStatementTester {
public boolean hasSpaceBeforeOrderByClause;
public boolean hasSpaceBeforeUnionClauses;
private ExpressionTester orderByClause;
private ExpressionTester unionClauses;
protected SelectStatementTester(ExpressionTester selectClause,
ExpressionTester fromClause,
ExpressionTester whereClause,
ExpressionTester groupByClause,
ExpressionTester havingClause,
ExpressionTester orderByClause,
ExpressionTester unionClauses) {
super(selectClause,
fromClause,
whereClause,
groupByClause,
havingClause);
this.orderByClause = orderByClause;
this.unionClauses = unionClauses;
this.hasSpaceBeforeOrderByClause = !orderByClause.isNull();
this.hasSpaceBeforeUnionClauses = !unionClauses .isNull();
// hasSpaceAfterFrom |= (!fromClause .isNull() && (!whereClause.isNull() || !groupByClause.isNull() && havingClause .isNull() && !orderByClause.isNull() && !unionClauses.isNull());
// hasSpaceAfterWhere |= (!whereClause .isNull() && groupByClause.isNull() && !havingClause .isNull() && !orderByClause.isNull() && !unionClauses .isNull());
// hasSpaceAfterHierarchicalQueryClause |= (!whereClause .isNull() && groupByClause.isNull() && !havingClause .isNull() && !orderByClause.isNull() && !unionClauses .isNull());
// hasSpaceAfterGroupBy |= (!groupByClause.isNull() && havingClause .isNull() && !orderByClause.isNull() && !unionClauses.isNull());
}
@Override
protected Class<? extends AbstractSelectStatement> expressionType() {
return SelectStatement.class;
}
@Override
public void test(Expression expression) {
super.test(expression);
SelectStatement selectStatement = (SelectStatement) expression;
assertEquals(!orderByClause.isNull(), selectStatement.hasOrderByClause());
// assertEquals(hasSpaceBeforeOrderByClause, selectStatement.hasSpaceBeforeOrderBy());
orderByClause.test(selectStatement.getOrderByClause());
unionClauses .test(selectStatement.getUnionClauses());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
if (hasSpaceBeforeOrderByClause && sb.charAt(sb.length() - 1) != ' ') {
sb.append(SPACE);
}
sb.append(orderByClause);
if (hasSpaceBeforeUnionClauses && sb.charAt(sb.length() - 1) != ' ') {
sb.append(SPACE);
}
sb.append(unionClauses);
return sb.toString();
}
}
public static final class SimpleFromClauseTester extends AbstractFromClauseTester {
protected SimpleFromClauseTester(ExpressionTester declaration,
ExpressionTester hierarchicalQueryClause,
ExpressionTester asOfClause) {
super(declaration, hierarchicalQueryClause, asOfClause);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, SimpleFromClause.class);
}
}
public static final class SimpleSelectClauseTester extends AbstractSelectClauseTester {
protected SimpleSelectClauseTester(ExpressionTester selectExpressions, boolean hasDistinct) {
super(selectExpressions, hasDistinct);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, SimpleSelectClause.class);
}
}
public static final class SimpleSelectStatementTester extends AbstractSelectStatementTester {
protected SimpleSelectStatementTester(ExpressionTester selectClause,
ExpressionTester fromClause,
ExpressionTester whereClause,
ExpressionTester groupByClause,
ExpressionTester havingClause) {
super(selectClause, fromClause, whereClause, groupByClause, havingClause);
}
@Override
protected Class<? extends AbstractSelectStatement> expressionType() {
return SimpleSelectStatement.class;
}
}
public static final class SizeExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected SizeExpressionTester(ExpressionTester collectionPath) {
super(collectionPath);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return SizeExpression.class;
}
@Override
protected String identifier() {
return SIZE;
}
}
public static final class SqrtExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected SqrtExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return SqrtExpression.class;
}
@Override
protected String identifier() {
return SQRT;
}
}
public static final class StartWithClauseTester extends AbstractConditionalClauseTester {
protected StartWithClauseTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<StartWithClause> expressionType() {
return StartWithClause.class;
}
@Override
protected String identifier() {
return START_WITH;
}
}
public static final class StateFieldPathExpressionTester extends AbstractPathExpressionTester {
protected StateFieldPathExpressionTester(ExpressionTester identificationVariable,
String value) {
super(identificationVariable, value);
}
@Override
public void test(Expression expression) {
super.test(expression);
assertInstance(expression, StateFieldPathExpression.class);
}
}
public static final class StringLiteralTester extends AbstractExpressionTester {
private boolean hasCloseQuote;
private String literal;
protected StringLiteralTester(String literal) {
super();
this.literal = literal;
if (literal.length() > 1) {
char lastChar = literal.charAt(literal.length() - 1);
hasCloseQuote = (lastChar == SINGLE_QUOTE) || (lastChar == DOUBLE_QUOTE);
}
}
public void test(Expression expression) {
assertInstance(expression, StringLiteral.class);
StringLiteral stringLiteral = (StringLiteral) expression;
assertEquals(toString(), stringLiteral.toString());
assertEquals(hasCloseQuote, stringLiteral.hasCloseQuote());
}
@Override
public String toString() {
return literal;
}
}
public static final class SubExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected SubExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return SubExpression.class;
}
@Override
protected String identifier() {
return ExpressionTools.EMPTY_STRING;
}
}
public static final class SubstringExpressionTester extends AbstractTripleEncapsulatedExpressionTester {
protected SubstringExpressionTester(ExpressionTester firstExpression,
ExpressionTester firstArithmeticExpression,
ExpressionTester secondArithmeticExpression) {
super(firstExpression, firstArithmeticExpression, secondArithmeticExpression);
}
@Override
protected Class<? extends AbstractTripleEncapsulatedExpression> expressionType() {
return SubstringExpression.class;
}
@Override
protected String identifier() {
return SubstringExpression.SUBSTRING;
}
}
public static final class SubtractionExpressionTester extends CompoundExpressionTester {
protected SubtractionExpressionTester(ExpressionTester leftExpression,
ExpressionTester rightExpression) {
super(leftExpression, rightExpression);
}
@Override
protected Class<? extends CompoundExpression> expressionType() {
return SubtractionExpression.class;
}
@Override
protected String identifier() {
return MINUS;
}
}
public static final class SumFunctionTester extends AggregateFunctionTester {
protected SumFunctionTester(ExpressionTester expression, boolean hasDistinct) {
super(expression, hasDistinct);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return SumFunction.class;
}
@Override
protected String identifier() {
return SUM;
}
}
public static final class TableExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected TableExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<TableExpression> expressionType() {
return TableExpression.class;
}
@Override
protected String identifier() {
return TABLE;
}
}
public static final class TableVariableDeclarationTester extends AbstractExpressionTester {
private boolean hasAs;
public boolean hasSpaceAfterAs;
public boolean hasSpaceAfterTableExpression;
private ExpressionTester identificationVariable;
private TableExpressionTester tableExpression;
protected TableVariableDeclarationTester(TableExpressionTester tableExpression,
boolean hasAs,
ExpressionTester identificationVariable) {
super();
this.tableExpression = tableExpression;
this.hasAs = hasAs;
this.identificationVariable = identificationVariable;
this.hasSpaceAfterTableExpression = hasAs || !identificationVariable.isNull();
this.hasSpaceAfterAs = hasAs && !identificationVariable.isNull();
}
public void test(Expression expression) {
assertInstance(expression, Expression.class);
TableVariableDeclaration tableVariableDeclaration = (TableVariableDeclaration) expression;
assertEquals(toString(), tableVariableDeclaration.toParsedText());
assertEquals(!identificationVariable.isNull(), tableVariableDeclaration.hasIdentificationVariable());
assertEquals(hasAs, tableVariableDeclaration.hasAs());
assertEquals(hasSpaceAfterAs, tableVariableDeclaration.hasSpaceAfterAs());
assertEquals(hasSpaceAfterTableExpression, tableVariableDeclaration.hasSpaceAfterTableExpression());
tableExpression .test(tableVariableDeclaration.getTableExpression());
identificationVariable.test(tableVariableDeclaration.getIdentificationVariable());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(tableExpression);
if (hasSpaceAfterTableExpression) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(identificationVariable);
return sb.toString();
}
}
public static final class TreatExpressionTester extends AbstractEncapsulatedExpressionTester {
private ExpressionTester collectionValuedPathExpression;
private ExpressionTester entityTypeName;
private boolean hasAs;
public boolean hasSpaceAfterAs;
public boolean hasSpaceAfterCollectionValuedPathExpression;
protected TreatExpressionTester(ExpressionTester collectionValuedPathExpression,
boolean hasAs,
ExpressionTester entityTypeName) {
super();
this.hasAs = hasAs;
this.entityTypeName = entityTypeName;
this.hasSpaceAfterAs = hasAs;
this.hasSpaceAfterCollectionValuedPathExpression = true;
this.collectionValuedPathExpression = collectionValuedPathExpression;
}
@Override
protected Class<? extends AbstractEncapsulatedExpression> expressionType() {
return TreatExpression.class;
}
@Override
protected boolean hasEncapsulatedExpression() {
return !collectionValuedPathExpression.isNull() || !entityTypeName.isNull() || hasAs;
}
@Override
protected String identifier() {
return TREAT;
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
sb.append(collectionValuedPathExpression);
if (hasSpaceAfterCollectionValuedPathExpression) {
sb.append(SPACE);
}
if (hasAs) {
sb.append(AS);
}
if (hasSpaceAfterAs) {
sb.append(SPACE);
}
sb.append(entityTypeName);
}
}
public static final class TrimExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
private boolean hasFrom;
public boolean hasSpaceAfterFrom;
public boolean hasSpaceAfterSpecification;
public boolean hasSpaceAfterTrimCharacter;
private Specification specification;
private ExpressionTester trimCharacter;
protected TrimExpressionTester(Specification specification,
ExpressionTester stringPrimary,
ExpressionTester trimCharacter,
boolean hasFrom) {
super(stringPrimary);
this.specification = specification;
this.trimCharacter = trimCharacter;
this.hasFrom = hasFrom;
this.hasSpaceAfterFrom = hasFrom;
this.hasSpaceAfterTrimCharacter = !trimCharacter.isNull();
this.hasSpaceAfterSpecification = specification != Specification.DEFAULT;
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return TrimExpression.class;
}
@Override
protected String identifier() {
return TRIM;
}
@Override
public void test(Expression expression) {
super.test(expression);
TrimExpression trimExpression = (TrimExpression) expression;
assertEquals(hasFrom, trimExpression.hasFrom());
assertEquals(hasSpaceAfterFrom, trimExpression.hasSpaceAfterFrom());
assertEquals(hasSpaceAfterTrimCharacter, trimExpression.hasSpaceAfterTrimCharacter());
assertEquals(!trimCharacter.isNull(), trimExpression.hasTrimCharacter());
assertEquals(specification != Specification.DEFAULT, trimExpression.hasSpecification());
assertEquals(hasSpaceAfterSpecification, trimExpression.hasSpaceAfterSpecification());
trimCharacter.test(trimExpression.getTrimCharacter());
}
@Override
protected void toStringEncapsulatedExpression(StringBuilder sb) {
if (specification != Specification.DEFAULT) {
sb.append(specification);
}
if (hasSpaceAfterSpecification) {
sb.append(SPACE);
}
sb.append(trimCharacter);
if (hasSpaceAfterTrimCharacter) {
sb.append(SPACE);
}
if (hasFrom) {
sb.append(FROM);
}
if (hasSpaceAfterFrom) {
sb.append(SPACE);
}
super.toStringEncapsulatedExpression(sb);
}
}
public static final class TypeExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected TypeExpressionTester(ExpressionTester identificationVariable) {
super(identificationVariable);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return TypeExpression.class;
}
@Override
protected String identifier() {
return TYPE;
}
}
public static final class UnionClauseTester extends AbstractExpressionTester {
private boolean hasAll;
public boolean hasSpaceAfterAll;
public boolean hasSpaceAfterIdentifier;
private String identifier;
private ExpressionTester subquery;
protected UnionClauseTester(String identifier, boolean hasAll, ExpressionTester subquery) {
super();
this.identifier = identifier;
this.hasAll = hasAll;
this.subquery = subquery;
this.hasSpaceAfterIdentifier = hasAll || !subquery.isNull();
this.hasSpaceAfterAll = hasAll && !subquery.isNull();
}
public void test(Expression expression) {
assertInstance(expression, UnionClause.class);
UnionClause unionClause = (UnionClause) expression;
assertEquals(toString(), unionClause.toParsedText());
assertEquals(identifier, unionClause.getIdentifier());
assertEquals(hasSpaceAfterIdentifier, unionClause.hasSpaceAfterIdentifier());
assertEquals(hasAll, unionClause.hasAll());
assertEquals(!subquery.isNull(), unionClause.hasQuery());
assertEquals(hasSpaceAfterAll, unionClause.hasSpaceAfterAll());
subquery.test(unionClause.getQuery());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(identifier);
if (hasSpaceAfterIdentifier) {
sb.append(SPACE);
}
if (hasAll) {
sb.append(ALL);
}
if (hasSpaceAfterAll) {
sb.append(SPACE);
}
sb.append(subquery);
return sb.toString();
}
}
public static final class UnknownExpressionTester extends AbstractExpressionTester {
private final String unknownText;
protected UnknownExpressionTester(String unknownText) {
super();
this.unknownText = unknownText;
}
public void test(Expression expression) {
assertInstance(expression, UnknownExpression.class);
UnknownExpression unknownExpression = (UnknownExpression) expression;
assertEquals(toString(), unknownExpression.toParsedText());
}
@Override
public String toString() {
return unknownText;
}
}
public static final class UpdateClauseTester extends AbstractExpressionTester {
public boolean hasSet;
public boolean hasSpaceAfterRangeVariableDeclaration;
public boolean hasSpaceAfterSet;
public boolean hasSpaceAfterUpdate;
private ExpressionTester rangeVariableDeclaration;
private ExpressionTester updateItems;
protected UpdateClauseTester(ExpressionTester rangeVariableDeclaration,
ExpressionTester updateItems) {
super();
this.hasSet = true;
this.hasSpaceAfterSet = true;
this.hasSpaceAfterUpdate = true;
this.updateItems = updateItems;
this.rangeVariableDeclaration = rangeVariableDeclaration;
this.hasSpaceAfterRangeVariableDeclaration = !rangeVariableDeclaration.isNull();
}
public void test(Expression expression) {
assertInstance(expression, UpdateClause.class);
UpdateClause updateClause = (UpdateClause) expression;
assertEquals(toString(), updateClause.toParsedText());
assertEquals(!rangeVariableDeclaration.isNull(), updateClause.hasRangeVariableDeclaration());
assertEquals(hasSet, updateClause.hasSet());
assertEquals(hasSpaceAfterSet, updateClause.hasSpaceAfterSet());
assertEquals(hasSpaceAfterUpdate, updateClause.hasSpaceAfterUpdate());
assertEquals(!updateItems.isNull(), updateClause.hasUpdateItems());
assertEquals(hasSpaceAfterRangeVariableDeclaration, updateClause.hasSpaceAfterRangeVariableDeclaration());
rangeVariableDeclaration.test(updateClause.getRangeVariableDeclaration());
updateItems.test(updateClause.getUpdateItems());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(UPDATE);
if (hasSpaceAfterUpdate) {
sb.append(SPACE);
}
sb.append(rangeVariableDeclaration);
if (hasSpaceAfterRangeVariableDeclaration) {
sb.append(SPACE);
}
if (hasSet) {
sb.append(SET);
}
if (hasSpaceAfterSet) {
sb.append(SPACE);
}
sb.append(updateItems);
return sb.toString();
}
}
public static final class UpdateItemTester extends AbstractExpressionTester {
public boolean hasEqualSign;
public boolean hasSpaceAfterEqualSign;
public boolean hasSpaceAfterStateFieldPathExpression;
private ExpressionTester newValue;
private ExpressionTester stateFieldPathExpression;
protected UpdateItemTester(ExpressionTester stateFieldPathExpression,
ExpressionTester newValue) {
super();
this.stateFieldPathExpression = stateFieldPathExpression;
this.newValue = newValue;
this.hasSpaceAfterStateFieldPathExpression = true;
this.hasSpaceAfterEqualSign = true;
this.hasEqualSign = true;
}
public void test(Expression expression) {
assertInstance(expression, UpdateItem.class);
UpdateItem updateItem = (UpdateItem) expression;
assertEquals(toString(), updateItem.toParsedText());
assertEquals(hasEqualSign, updateItem.hasEqualSign());
assertEquals(!newValue.isNull(), updateItem.hasNewValue());
assertEquals(hasSpaceAfterEqualSign, updateItem.hasSpaceAfterEqualSign());
assertEquals(hasSpaceAfterStateFieldPathExpression, updateItem.hasSpaceAfterStateFieldPathExpression());
assertEquals(!stateFieldPathExpression.isNull(), updateItem.hasStateFieldPathExpression());
stateFieldPathExpression.test(updateItem.getStateFieldPathExpression());
newValue.test(updateItem.getNewValue());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(stateFieldPathExpression);
if (hasSpaceAfterStateFieldPathExpression) {
sb.append(SPACE);
}
if (hasEqualSign) {
sb.append(EQUAL);
}
if (hasSpaceAfterEqualSign) {
sb.append(SPACE);
}
sb.append(newValue);
return sb.toString();
}
}
public static final class UpdateStatementTester extends AbstractExpressionTester {
public boolean hasSpaceAfterUpdateClause;
private ExpressionTester updateClause;
private ExpressionTester whereClause;
protected UpdateStatementTester(ExpressionTester updateClause, ExpressionTester whereClause) {
super();
this.updateClause = updateClause;
this.whereClause = whereClause;
this.hasSpaceAfterUpdateClause = !whereClause.isNull();
}
public void test(Expression expression) {
assertInstance(expression, UpdateStatement.class);
UpdateStatement updateStatement = (UpdateStatement) expression;
assertEquals(toString(), updateStatement.toParsedText());
assertEquals(hasSpaceAfterUpdateClause, updateStatement.hasSpaceAfterUpdateClause());
assertEquals(!whereClause.isNull(), updateStatement.hasWhereClause());
updateClause.test(updateStatement.getUpdateClause());
whereClause .test(updateStatement.getWhereClause());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(updateClause);
if (hasSpaceAfterUpdateClause) {
sb.append(SPACE);
}
sb.append(whereClause);
return sb.toString();
}
}
public static final class UpperExpressionTester extends AbstractSingleEncapsulatedExpressionTester {
protected UpperExpressionTester(ExpressionTester expression) {
super(expression);
}
@Override
protected Class<? extends AbstractSingleEncapsulatedExpression> expressionType() {
return UpperExpression.class;
}
@Override
protected String identifier() {
return UPPER;
}
}
public static final class WhenClauseTester extends AbstractExpressionTester {
public boolean hasSpaceAfterThen;
public boolean hasSpaceAfterWhen;
public boolean hasSpaceAfterWhenExpression;
public boolean hasThen;
private ExpressionTester thenExpression;
private ExpressionTester whenExpression;
protected WhenClauseTester(ExpressionTester whenExpression, ExpressionTester thenExpression) {
super();
this.hasSpaceAfterWhenExpression = true;
this.hasSpaceAfterThen = true;
this.hasSpaceAfterWhen = true;
this.hasThen = true;
this.thenExpression = thenExpression;
this.whenExpression = whenExpression;
}
public void test(Expression expression) {
assertInstance(expression, WhenClause.class);
WhenClause whenClause = (WhenClause) expression;
assertEquals(toString(), whenClause.toParsedText());
assertEquals(!whenExpression.isNull(), whenClause.hasWhenExpression());
assertEquals(hasSpaceAfterWhenExpression, whenClause.hasSpaceAfterWhenExpression());
assertEquals(hasSpaceAfterThen, whenClause.hasSpaceAfterThen());
assertEquals(hasSpaceAfterWhen, whenClause.hasSpaceAfterWhen());
assertEquals(hasThen, whenClause.hasThen());
assertEquals(!thenExpression.isNull(), whenClause.hasThenExpression());
whenExpression.test(whenClause.getWhenExpression());
thenExpression.test(whenClause.getThenExpression());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(WHEN);
if (hasSpaceAfterWhen) {
sb.append(SPACE);
}
sb.append(whenExpression);
if (hasSpaceAfterWhenExpression) {
sb.append(SPACE);
}
if (hasThen) {
sb.append(THEN);
}
if (hasSpaceAfterWhen) {
sb.append(SPACE);
}
sb.append(thenExpression);
return sb.toString();
}
}
public static final class WhereClauseTester extends AbstractConditionalClauseTester {
protected WhereClauseTester(ExpressionTester conditionalExpression) {
super(conditionalExpression);
}
@Override
protected Class<? extends AbstractConditionalClause> expressionType() {
return WhereClause.class;
}
@Override
protected String identifier() {
return WHERE;
}
}
}
| 40.123005
| 213
| 0.630143
|
bbcb31027852878f290d57277401e0d6466fbdf0
| 296
|
package com.ai.htmlgen;
public interface IBooleanExpressionEvaluator
{
static public String NAME = "Aspire.BooleanExpressionEvaluator";
boolean evaluate(final String expression
,IFormHandler pageData
,IControlHandler loopData
,int curTurn );
}
| 26.909091
| 68
| 0.689189
|
1ec3e274eaad691b7e0beebc519b6cae2e041f2a
| 945
|
/**
*
*/
package com.openthinks.goldeneye.impls.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.openthinks.goldeneye.core.mapper.GoldPriceHistoryMapper;
import com.openthinks.goldeneye.core.model.GoldPriceHistory;
import com.openthinks.goldeneye.core.service.GoldPriceHistoryService;
/**
* @author dailey.yet@outlook.com
*
*/
@Service
public class GoldPriceHistoryServiceImpl implements GoldPriceHistoryService {
@Autowired
GoldPriceHistoryMapper goldPriceHistoryMapper;
/* (non-Javadoc)
* @see com.openthinks.goldeneye.core.service.GoldPriceHistoryService#save(com.openthinks.goldeneye.core.model.GoldPriceHistory)
*/
@Override
public void save(GoldPriceHistory record) {
if(record.getId()==null) {
goldPriceHistoryMapper.insertSelective(record);
}else {
goldPriceHistoryMapper.updateByPrimaryKeySelective(record);
}
}
}
| 25.540541
| 129
| 0.798942
|
d3c63ee67e6eda738b2b0f2217dd2886dcae7ad9
| 107
|
package com.hungry.hotel.hungryhoteladmin.restaurentmenu.listener;
public interface LoadMoreListener {
}
| 17.833333
| 66
| 0.841121
|
edcb8ba2206a3d6cdf46f172b59dc4f2a275a6e3
| 945
|
import java.util.*;
class Main {
public static void main(String[] args) {
Menu menu = new Menu();
Scanner sc = new Scanner(System.in);
while(sc.next().equals("add")) {
String type = sc.next();
String desc = sc.next();
int price = sc.nextInt();
// System.out.println(type + " " + desc + " " + price);
if (type.equals("Burger")) {
Burger b = new Burger(desc, price);
menu.add(b);
} else if (type.equals("Snack")) {
Snack s = new Snack(desc, price);
menu.add(s);
} else {
Drink d = new Drink(desc, price);
menu.add(d);
}
}
System.out.println(menu);
// read order
Order order = new Order(menu);
while (sc.hasNext()) {
order.add(sc.nextInt());
}
System.out.println(order);
}
}
| 26.25
| 67
| 0.459259
|
c215d62bc249c85327a0a6435245177d73b1251d
| 820
|
package com.ywy.jfinal.core.route.controller;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.ywy.jfinal.model.User;
/**
* @author ve
* @data 2019/8/13 18:24
*/
public class Controller3_5 extends Controller {
// http://localhost/controller35?user1.realName=hhhh&user2.real_name=hhhh
public void index(
@Para("str") String str) {
User user1 = getBean(User.class, "user1"); // 表单传递过来的bean对象,通过set方法复制,即user1.realName
User user2 = getModel(User.class, "user2"); // 表单传递过来的moodel对象,与数据库字段相同,即user2.real_name
// user1传入的参数为bean的realName,通过getRealName获取
// user2传入的参数为model的real_name,通过get("real_name")获取
// 综上建议数据库设计不使用蛇形命名(下划线分割),而是使用小驼峰命名realName
// 使用代码生成工具生成model
renderText("controller35");
}
}
| 31.538462
| 96
| 0.69878
|
de13a2c7d121d496f4202edab21cd0ff164fa7a2
| 3,654
|
package com.eliteams.quick4j.web.model;
import com.eliteams.quick4j.core.generic.GenericModel;
import java.util.Date;
public class Customer extends GenericModel {
private Long id;
private String userName;
private String pwd;
private String sex;
private String phone;
private String idCard;
private Date birthday;
private String country;
private String province;
private String city;
private String area;
private String address;
private Date createdTime;
private Date modifiedTime;
private Long createdUser;
private Long modifiedUser;
private String remark;
private String state;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd == null ? null : pwd.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard == null ? null : idCard.trim();
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country == null ? null : country.trim();
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city == null ? null : city.trim();
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area == null ? null : area.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(Date modifiedTime) {
this.modifiedTime = modifiedTime;
}
public Long getCreatedUser() {
return createdUser;
}
public void setCreatedUser(Long createdUser) {
this.createdUser = createdUser;
}
public Long getModifiedUser() {
return modifiedUser;
}
public void setModifiedUser(Long modifiedUser) {
this.modifiedUser = modifiedUser;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state == null ? null : state.trim();
}
}
| 19.540107
| 66
| 0.599343
|
2b52be85db6c142a8ec3684b62471b6d015da77e
| 510
|
package com.edu.config;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInnerInterceptor paginationInterceptor() {
return new PaginationInnerInterceptor();
}
}
| 31.875
| 83
| 0.833333
|
ab4dd22aee218bf47fbd6e3c760599406e47db48
| 5,430
|
package parser.util;
import parser.ast.nodes.Assertion;
import parser.ast.nodes.BinaryExpr;
import parser.ast.nodes.BinaryExprOrFormula;
import parser.ast.nodes.BinaryFormula;
import parser.ast.nodes.Body;
import parser.ast.nodes.Call;
import parser.ast.nodes.CallExpr;
import parser.ast.nodes.CallFormula;
import parser.ast.nodes.Check;
import parser.ast.nodes.Cmd;
import parser.ast.nodes.ConstExpr;
import parser.ast.nodes.ExprOrFormula;
import parser.ast.nodes.Fact;
import parser.ast.nodes.FieldDecl;
import parser.ast.nodes.FieldExpr;
import parser.ast.nodes.Function;
import parser.ast.nodes.ITEExpr;
import parser.ast.nodes.ITEExprOrFormula;
import parser.ast.nodes.ITEFormula;
import parser.ast.nodes.LetExpr;
import parser.ast.nodes.ListExpr;
import parser.ast.nodes.ListExprOrFormula;
import parser.ast.nodes.ListFormula;
import parser.ast.nodes.ModelUnit;
import parser.ast.nodes.ModuleDecl;
import parser.ast.nodes.Node;
import parser.ast.nodes.OpenDecl;
import parser.ast.nodes.Paragraph;
import parser.ast.nodes.ParamDecl;
import parser.ast.nodes.PredOrFun;
import parser.ast.nodes.Predicate;
import parser.ast.nodes.QtExpr;
import parser.ast.nodes.QtExprOrFormula;
import parser.ast.nodes.QtFormula;
import parser.ast.nodes.RelDecl;
import parser.ast.nodes.Run;
import parser.ast.nodes.SigDecl;
import parser.ast.nodes.SigExpr;
import parser.ast.nodes.UnaryExpr;
import parser.ast.nodes.UnaryExprOrFormula;
import parser.ast.nodes.UnaryFormula;
import parser.ast.nodes.VarDecl;
import parser.ast.nodes.VarExpr;
public class NodeUtil {
public static boolean isAssertion(Node node) {
return node instanceof Assertion;
}
public static boolean isBinaryExpr(Node node) {
return node instanceof BinaryExpr;
}
public static boolean isBinaryExprOrFormula(Node node) {
return node instanceof BinaryExprOrFormula;
}
public static boolean isBinaryFormula(Node node) {
return node instanceof BinaryFormula;
}
public static boolean isBody(Node node) {
return node instanceof Body;
}
public static boolean isCall(Node node) {
return node instanceof Call;
}
public static boolean isCallExpr(Node node) {
return node instanceof CallExpr;
}
public static boolean isCallFormula(Node node) {
return node instanceof CallFormula;
}
public static boolean isCheck(Node node) {
return node instanceof Check;
}
public static boolean isCmd(Node node) {
return node instanceof Cmd;
}
public static boolean isConstExpr(Node node) {
return node instanceof ConstExpr;
}
public static boolean isExprOrFormula(Node node) {
return node instanceof ExprOrFormula;
}
public static boolean isFact(Node node) {
return node instanceof Fact;
}
public static boolean isFieldDecl(Node node) {
return node instanceof FieldDecl;
}
public static boolean isFieldExpr(Node node) {
return node instanceof FieldExpr;
}
public static boolean isFunction(Node node) {
return node instanceof Function;
}
public static boolean isITEExpr(Node node) {
return node instanceof ITEExpr;
}
public static boolean isITEExprOrFormula(Node node) {
return node instanceof ITEExprOrFormula;
}
public static boolean isITEFormula(Node node) {
return node instanceof ITEFormula;
}
public static boolean isLetExpr(Node node) {
return node instanceof LetExpr;
}
public static boolean isListExpr(Node node) {
return node instanceof ListExpr;
}
public static boolean isListExprOrFormula(Node node) {
return node instanceof ListExprOrFormula;
}
public static boolean isListFormula(Node node) {
return node instanceof ListFormula;
}
public static boolean isModelUnit(Node node) {
return node instanceof ModelUnit;
}
public static boolean isModuleDecl(Node node) {
return node instanceof ModuleDecl;
}
public static boolean isOpenDecl(Node node) {
return node instanceof OpenDecl;
}
public static boolean isParagraph(Node node) {
return node instanceof Paragraph;
}
public static boolean isParamDecl(Node node) {
return node instanceof ParamDecl;
}
public static boolean isPredicate(Node node) {
return node instanceof Predicate;
}
public static boolean isPredOrFun(Node node) {
return node instanceof PredOrFun;
}
public static boolean isQtExpr(Node node) {
return node instanceof QtExpr;
}
public static boolean isQtExprOrFormula(Node node) {
return node instanceof QtExprOrFormula;
}
public static boolean isQtFormula(Node node) {
return node instanceof QtFormula;
}
public static boolean isRelDecl(Node node) {
return node instanceof RelDecl;
}
public static boolean isRun(Node node) {
return node instanceof Run;
}
public static boolean isSigDecl(Node node) {
return node instanceof SigDecl;
}
public static boolean isSigExpr(Node node) {
return node instanceof SigExpr;
}
public static boolean isUnaryExpr(Node node) {
return node instanceof UnaryExpr;
}
public static boolean isUnaryExprOrFormula(Node node) {
return node instanceof UnaryExprOrFormula;
}
public static boolean isUnaryFormula(Node node) {
return node instanceof UnaryFormula;
}
public static boolean isVarDecl(Node node) {
return node instanceof VarDecl;
}
public static boolean isVarExpr(Node node) {
return node instanceof VarExpr;
}
}
| 25.138889
| 58
| 0.756906
|
cfea10ef741774bc8aecfdba777fd3dc75b3ff02
| 758
|
package com.linxiao.framework.rx;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
/**
* RxJava 工具类
* <p>提供RxJava相关常用工具方法</p>
* Created by linxiao on 2016-07-24.
*/
public class RxJavaUtil {
/**
* 倒计时,单位 s,返回回调在主线程
* @param seconds 倒计时秒数
* */
public static Observable<Integer> countDown(final int seconds) {
return Observable.interval(0, 1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.newThread())
.take(seconds)
.map(increaseTime -> seconds - increaseTime.intValue());
}
}
| 22.969697
| 68
| 0.693931
|
0f0652b74c122e6602e026a5356207b2de24eedf
| 2,946
|
package org.springext.security.jwt.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springext.security.jwt.dto.UserConfirmRequest;
import org.springext.security.jwt.dto.UserRegistrationRequest;
import org.springext.security.jwt.dto.UserRegistrationResult;
import org.springext.security.jwt.dto.UserRegistrationResultMessage;
import org.springext.security.jwt.userdetails.UserAuthenticationDetails;
import org.springext.security.jwt.userdetails.UserAuthenticationDetailsService;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JsonUserConfirmFilter<U extends UserAuthenticationDetails, R extends UserRegistrationRequest> extends GenericFilterBean {
private final RequestMatcher requestMatcher;
private final ObjectMapper objectMapper;
private final UserAuthenticationDetailsService<U,R> userAuthenticationDetailsService;
public JsonUserConfirmFilter(RequestMatcher requestMatcher, ObjectMapper objectMapper, UserAuthenticationDetailsService<U,R> userAuthenticationDetailsService) {
this.requestMatcher = requestMatcher;
this.objectMapper = objectMapper;
this.userAuthenticationDetailsService = userAuthenticationDetailsService;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (requestMatcher.matches(request) && request.getMethod().equals("POST")) {
UserConfirmRequest userConfirmRequest = objectMapper.readValue(request.getInputStream(), UserConfirmRequest.class);
UserRegistrationResult result = confirmTicket(userConfirmRequest);
if (result.getMessage() != UserRegistrationResultMessage.REGISTRATION_CONFIRMED) {
response.setStatus(HttpServletResponse.SC_CONFLICT);
}
objectMapper.writeValue(response.getOutputStream(), result);
} else {
chain.doFilter(request, response);
}
}
private UserRegistrationResult confirmTicket(UserConfirmRequest userConfirmRequest) {
return userAuthenticationDetailsService.confirmRegistrationTicket(userConfirmRequest.getTicketId())
.map(u -> UserRegistrationResult.registrationConfirmed(u.getUsername()))
.orElse(UserRegistrationResult.invalidConfirmTicket());
}
}
| 49.1
| 164
| 0.788527
|
068ad664440998ddb5351edf5fd9e515b031e020
| 999
|
package com.datamify.spring.bean.lifecycle;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class TestSpringBeanDependency implements InitializingBean, DisposableBean {
public TestSpringBeanDependency() {
System.out.println("TestSpringBeanDependency constructor");
}
@Override
public void destroy() {
System.out.println("TestSpringBeanDependency destroy");
}
@Override
public void afterPropertiesSet() {
System.out.println("TestSpringBeanDependency afterPropertiesSet");
}
@PostConstruct
public void postConstruct() {
System.out.println("TestSpringBeanDependency postConstruct");
}
@PreDestroy
public void preDestroy() {
System.out.println("TestSpringBeanDependency preDestroy");
}
}
| 26.289474
| 83
| 0.747748
|
172df8455e15750ff846f2b70251463793d2cd38
| 990
|
package com.wish.controller;
import com.wish.model.ExecuteResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
* @author Pinky Lam 908716835@qq.com
* @date 2017年8月8日 上午9:54:45
*/
@RestController
@RequestMapping("swagger")
public class SwaggerController {
@RequestMapping(value = "testSawgger", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ApiOperation(value = "测试swagger", httpMethod = "POST", notes = "testSawgger")
public ExecuteResult<String> addUser(@ApiParam(value = "参数", required = true) Long id) {
ExecuteResult<String> result = new ExecuteResult<String>();
try {
result.setData("这是一个测试!!");
result.setSuccess(true);
} catch (Exception e) {
result.setSuccess(false);
}
return result;
}
}
| 29.117647
| 114
| 0.754545
|
d51cf6397e55bf2a8e2f6f89456a640b14000494
| 1,436
|
package com.qcl.clickhouse.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Java for ClickHouse连接工具类
*
* @author chunlin.qi@hand-china.com
* @version 1.0
* @description
* @date 2021/8/3
*/
public class ClickhouseUtils {
private static Connection connection = null;
static {
try {
// 驱动包
Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
// url路径
String url = "jdbc:clickhouse://192.168.56.10:8123/system";
// 账号
String user = "default";
// 密码
String password = "";
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from system.functions");
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
System.out.println(metaData.getColumnName(i) + ":" + resultSet.getString(i));
}
}
}
}
| 28.156863
| 93
| 0.607939
|
1c40320c48b09c084a554b680ddf9302e5a8d9b1
| 352
|
package com.wy.build;
import com.wy.entity.StrollSkyJiuGe;
/**
* 建造的使用
*
* @author 飞花梦影
* @date 2021-11-04 13:49:33
* @git {@link https://github.com/dreamFlyingFlower }
*/
public class HeavenHandler {
public StrollSkyJiuGe build(HeavenBuilder builder) {
builder.name();
builder.author();
builder.people();
return builder.build();
}
}
| 17.6
| 53
| 0.690341
|
7f6655b8d92d1eb6456cfd6dd105d7475d7d27b1
| 1,492
|
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.qa.brms.performance.examples.nurserostering.domain.contract;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.jboss.qa.brms.performance.examples.common.domain.AbstractPersistable;
import org.jboss.qa.brms.performance.examples.nurserostering.domain.pattern.Pattern;
@XStreamAlias("PatternContractLine")
public class PatternContractLine extends AbstractPersistable {
private Contract contract;
private Pattern pattern;
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
@Override
public String toString() {
return contract + "-" + pattern;
}
}
| 29.254902
| 84
| 0.725201
|
8a5f612671993de2c4824ba920e6e05206faa7bf
| 1,960
|
package io.github.kgpu.wgpuj.jni;
import io.github.kgpu.wgpuj.util.WgpuJavaStruct;
import jnr.ffi.Runtime;
import jnr.ffi.Struct;
/** NOTE: THIS FILE WAS PRE-GENERATED BY JNR_GEN! */
public class WgpuStencilStateDescriptor extends WgpuJavaStruct {
private final WgpuStencilStateFaceDescriptor front =
inner(WgpuStencilStateFaceDescriptor.createHeap());
private final WgpuStencilStateFaceDescriptor back =
inner(WgpuStencilStateFaceDescriptor.createHeap());
private final Struct.Unsigned32 readMask = new Struct.Unsigned32();
private final Struct.Unsigned32 writeMask = new Struct.Unsigned32();
protected WgpuStencilStateDescriptor(boolean direct) {
if (direct) {
useDirectMemory();
}
}
@Deprecated
public WgpuStencilStateDescriptor(Runtime runtime) {
super(runtime);
}
/**
* Creates this struct on the java heap. In general, this should <b>not</b> be used because
* these structs cannot be directly passed into native code.
*/
public static WgpuStencilStateDescriptor createHeap() {
return new WgpuStencilStateDescriptor(false);
}
/**
* Creates this struct in direct memory. This is how most structs should be created (unless,
* they are members of a nothing struct)
*
* @see WgpuJavaStruct#useDirectMemory
*/
public static WgpuStencilStateDescriptor createDirect() {
return new WgpuStencilStateDescriptor(true);
}
public WgpuStencilStateFaceDescriptor getFront() {
return front;
}
public WgpuStencilStateFaceDescriptor getBack() {
return back;
}
public long getReadMask() {
return readMask.get();
}
public void setReadMask(long x) {
this.readMask.set(x);
}
public long getWriteMask() {
return writeMask.get();
}
public void setWriteMask(long x) {
this.writeMask.set(x);
}
}
| 28
| 96
| 0.678571
|
a0450495c9325edcf1d5bbd8ce4eb3acf5c4ecd2
| 741
|
package com.saim.demo.websocket.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@ConditionalOnWebApplication
public class WebSocketConfig {
/**
* 注入对象ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter getServerEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public MySpringConfigurator getSpringConfigurator() {
return new MySpringConfigurator();
}
}
| 30.875
| 86
| 0.793522
|
3ad49e663681df344d3690c1eed33c9347e47ef0
| 250
|
package com.indvd00m.vaadin.navigator.api.event;
/**
* @author indvd00m (gotoindvdum[at]gmail[dot]com)
* @date Nov 17, 2015 12:57:23 AM
*
*/
public interface IViewStatusChangeListener {
void viewStatusChanged(IViewStatusChangeEvent event);
}
| 19.230769
| 54
| 0.752
|
70f5f3d21a36813cecc513381af1921dc7dd3882
| 6,836
|
/*******************************************************************************
* Copyright 2012 André Rouél
*
* 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 net.sf.uadetector.util;
import org.slf4j.Logger;
import org.slf4j.Marker;
public final class LowestLogLevelTestLogger implements Logger {
@Override
public void debug(final Marker marker, final String msg) {
// do nothing
}
@Override
public void debug(final Marker marker, final String format, final Object arg) {
// do nothing
}
@Override
public void debug(final Marker marker, final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void debug(final Marker marker, final String format, final Object... argArray) {
// do nothing
}
@Override
public void debug(final Marker marker, final String msg, final Throwable t) {
// do nothing
}
@Override
public void debug(final String msg) {
// do nothing
}
@Override
public void debug(final String format, final Object arg) {
// do nothing
}
@Override
public void debug(final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void debug(final String format, final Object... argArray) {
// do nothing
}
@Override
public void debug(final String msg, final Throwable t) {
// do nothing
}
@Override
public void error(final Marker marker, final String msg) {
// do nothing
}
@Override
public void error(final Marker marker, final String format, final Object arg) {
// do nothing
}
@Override
public void error(final Marker marker, final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void error(final Marker marker, final String format, final Object... argArray) {
// do nothing
}
@Override
public void error(final Marker marker, final String msg, final Throwable t) {
// do nothing
}
@Override
public void error(final String msg) {
// do nothing
}
@Override
public void error(final String format, final Object arg) {
// do nothing
}
@Override
public void error(final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void error(final String format, final Object... argArray) {
// do nothing
}
@Override
public void error(final String msg, final Throwable t) {
// do nothing
}
@Override
public String getName() {
return this.getClass().getName();
}
@Override
public void info(final Marker marker, final String msg) {
// do nothing
}
@Override
public void info(final Marker marker, final String format, final Object arg) {
// do nothing
}
@Override
public void info(final Marker marker, final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void info(final Marker marker, final String format, final Object... argArray) {
// do nothing
}
@Override
public void info(final Marker marker, final String msg, final Throwable t) {
// do nothing
}
@Override
public void info(final String msg) {
// do nothing
}
@Override
public void info(final String format, final Object arg) {
// do nothing
}
@Override
public void info(final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void info(final String format, final Object... argArray) {
// do nothing
}
@Override
public void info(final String msg, final Throwable t) {
// do nothing
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public boolean isDebugEnabled(final Marker marker) {
return false;
}
@Override
public boolean isErrorEnabled() {
return false;
}
@Override
public boolean isErrorEnabled(final Marker marker) {
return false;
}
@Override
public boolean isInfoEnabled() {
return false;
}
@Override
public boolean isInfoEnabled(final Marker marker) {
return false;
}
@Override
public boolean isTraceEnabled() {
return false;
}
@Override
public boolean isTraceEnabled(final Marker marker) {
return false;
}
@Override
public boolean isWarnEnabled() {
return false;
}
@Override
public boolean isWarnEnabled(final Marker marker) {
return false;
}
@Override
public void trace(final Marker marker, final String msg) {
// do nothing
}
@Override
public void trace(final Marker marker, final String format, final Object arg) {
// do nothing
}
@Override
public void trace(final Marker marker, final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void trace(final Marker marker, final String format, final Object... argArray) {
// do nothing
}
@Override
public void trace(final Marker marker, final String msg, final Throwable t) {
// do nothing
}
@Override
public void trace(final String msg) {
// do nothing
}
@Override
public void trace(final String format, final Object arg) {
// do nothing
}
@Override
public void trace(final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void trace(final String format, final Object... argArray) {
// do nothing
}
@Override
public void trace(final String msg, final Throwable t) {
// do nothing
}
@Override
public void warn(final Marker marker, final String msg) {
// do nothing
}
@Override
public void warn(final Marker marker, final String format, final Object arg) {
// do nothing
}
@Override
public void warn(final Marker marker, final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void warn(final Marker marker, final String format, final Object... argArray) {
// do nothing
}
@Override
public void warn(final Marker marker, final String msg, final Throwable t) {
// do nothing
}
@Override
public void warn(final String msg) {
// do nothing
}
@Override
public void warn(final String format, final Object arg) {
// do nothing
}
@Override
public void warn(final String format, final Object arg1, final Object arg2) {
// do nothing
}
@Override
public void warn(final String format, final Object... argArray) {
// do nothing
}
@Override
public void warn(final String msg, final Throwable t) {
// do nothing
}
}
| 20.778116
| 100
| 0.691779
|
214424ca7f09ff90f4b47ea6a0963a0b57490fc8
| 1,652
|
// default package
// Generated Jun 18, 2016 6:51:54 PM by Hibernate Tools 4.0.0.Final
package ufsc.bd1.org.model;
import java.util.Date;
/**
* Utiliza generated by hbm2java
*/
public class Utiliza implements java.io.Serializable {
private UtilizaId id;
private Exemplar exemplar;
private Pessoa pessoa;
private Projeto projeto;
private Date dataDevolucao;
private Date dataEmprestimo;
public Utiliza() {
}
public Utiliza(UtilizaId id, Exemplar exemplar) {
this.id = id;
this.exemplar = exemplar;
}
public Utiliza(UtilizaId id, Exemplar exemplar, Pessoa pessoa, Projeto projeto, Date dataDevolucao,
Date dataEmprestimo) {
this.id = id;
this.exemplar = exemplar;
this.pessoa = pessoa;
this.projeto = projeto;
this.dataDevolucao = dataDevolucao;
this.dataEmprestimo = dataEmprestimo;
}
public UtilizaId getId() {
return this.id;
}
public void setId(UtilizaId id) {
this.id = id;
}
public Exemplar getExemplar() {
return this.exemplar;
}
public void setExemplar(Exemplar exemplar) {
this.exemplar = exemplar;
}
public Pessoa getPessoa() {
return this.pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public Projeto getProjeto() {
return this.projeto;
}
public void setProjeto(Projeto projeto) {
this.projeto = projeto;
}
public Date getDataDevolucao() {
return this.dataDevolucao;
}
public void setDataDevolucao(Date dataDevolucao) {
this.dataDevolucao = dataDevolucao;
}
public Date getDataEmprestimo() {
return this.dataEmprestimo;
}
public void setDataEmprestimo(Date dataEmprestimo) {
this.dataEmprestimo = dataEmprestimo;
}
}
| 19.209302
| 100
| 0.728208
|
a95eb5f5fa118b362dc2790ddacb8fcb93fcabab
| 725
|
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package io.v.android.impl.google.services.gcm;
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
/**
* Listens for server token change notifications and initiates token (and services) refresh.
*/
public class GcmTokenRefreshListenerService extends InstanceIDListenerService {
@Override
public void onTokenRefresh() {
Intent intent = new Intent(this, GcmRegistrationService.class);
intent.putExtra(GcmRegistrationService.EXTRA_RESTART_SERVICES, true);
startService(intent);
}
}
| 34.52381
| 92
| 0.764138
|
db56fd443ee51aad3e5bede1ca624540f0b878a7
| 12,752
|
package controller_msgs.msg.dds;
import us.ihmc.communication.packets.Packet;
import us.ihmc.euclid.interfaces.Settable;
import us.ihmc.euclid.interfaces.EpsilonComparable;
import java.util.function.Supplier;
import us.ihmc.pubsub.TopicDataType;
/**
* Should disappear for the ROS equivalent.
*/
public class StereoVisionPointCloudMessage extends Packet<StereoVisionPointCloudMessage> implements Settable<StereoVisionPointCloudMessage>, EpsilonComparable<StereoVisionPointCloudMessage>
{
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public long sequence_id_;
public long timestamp_;
public us.ihmc.euclid.tuple3D.Point3D sensor_position_;
public us.ihmc.euclid.tuple4D.Quaternion sensor_orientation_;
/**
* There are two types of confidence value noticing the quality of the data for sensor pose and point cloud.
* The range of confidence is from 0.0 with the worst quality to 1.0 with the best quality.
* The confidence of the sensor pose represents the quality of the pose estimation.
*/
public double sensor_pose_confidence_ = 1.0;
/**
* There are two types of confidence value noticing the quality of the data for sensor pose and point cloud.
* The range of confidence is from 0.0 with the worst quality to 1.0 with the best quality.
* The confidence of the point cloud represents the quality of the collected point cloud data.
*/
public double point_cloud_confidence_ = 1.0;
/**
* The center location of the bounding box of all the points.
* The location of each point in the pointcloud is with respect to this location.
*/
public us.ihmc.euclid.tuple3D.Point3D point_cloud_center_;
/**
* The pointcloud is compressed by using an octree.
* This indicates the resolution used for the octree, the octree depth is 16.
*/
public double resolution_;
/**
* The number of points in this frame.
*/
public int number_of_points_;
/**
* The compressed pointcloud.
* See us.ihmc.robotEnvironmentAwareness.communication.converters.StereoPointCloudCompression for more info on the compression protocol.
*/
public us.ihmc.idl.IDLSequence.Byte point_cloud_;
/**
* The compressed colors.
* See us.ihmc.robotEnvironmentAwareness.communication.converters.StereoPointCloudCompression for more info on the compression protocol.
*/
public us.ihmc.idl.IDLSequence.Byte colors_;
public StereoVisionPointCloudMessage()
{
sensor_position_ = new us.ihmc.euclid.tuple3D.Point3D();
sensor_orientation_ = new us.ihmc.euclid.tuple4D.Quaternion();
point_cloud_center_ = new us.ihmc.euclid.tuple3D.Point3D();
point_cloud_ = new us.ihmc.idl.IDLSequence.Byte (2000000, "type_9");
colors_ = new us.ihmc.idl.IDLSequence.Byte (700000, "type_9");
}
public StereoVisionPointCloudMessage(StereoVisionPointCloudMessage other)
{
this();
set(other);
}
public void set(StereoVisionPointCloudMessage other)
{
sequence_id_ = other.sequence_id_;
timestamp_ = other.timestamp_;
geometry_msgs.msg.dds.PointPubSubType.staticCopy(other.sensor_position_, sensor_position_);
geometry_msgs.msg.dds.QuaternionPubSubType.staticCopy(other.sensor_orientation_, sensor_orientation_);
sensor_pose_confidence_ = other.sensor_pose_confidence_;
point_cloud_confidence_ = other.point_cloud_confidence_;
geometry_msgs.msg.dds.PointPubSubType.staticCopy(other.point_cloud_center_, point_cloud_center_);
resolution_ = other.resolution_;
number_of_points_ = other.number_of_points_;
point_cloud_.set(other.point_cloud_);
colors_.set(other.colors_);
}
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public void setSequenceId(long sequence_id)
{
sequence_id_ = sequence_id;
}
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public long getSequenceId()
{
return sequence_id_;
}
public void setTimestamp(long timestamp)
{
timestamp_ = timestamp;
}
public long getTimestamp()
{
return timestamp_;
}
public us.ihmc.euclid.tuple3D.Point3D getSensorPosition()
{
return sensor_position_;
}
public us.ihmc.euclid.tuple4D.Quaternion getSensorOrientation()
{
return sensor_orientation_;
}
/**
* There are two types of confidence value noticing the quality of the data for sensor pose and point cloud.
* The range of confidence is from 0.0 with the worst quality to 1.0 with the best quality.
* The confidence of the sensor pose represents the quality of the pose estimation.
*/
public void setSensorPoseConfidence(double sensor_pose_confidence)
{
sensor_pose_confidence_ = sensor_pose_confidence;
}
/**
* There are two types of confidence value noticing the quality of the data for sensor pose and point cloud.
* The range of confidence is from 0.0 with the worst quality to 1.0 with the best quality.
* The confidence of the sensor pose represents the quality of the pose estimation.
*/
public double getSensorPoseConfidence()
{
return sensor_pose_confidence_;
}
/**
* There are two types of confidence value noticing the quality of the data for sensor pose and point cloud.
* The range of confidence is from 0.0 with the worst quality to 1.0 with the best quality.
* The confidence of the point cloud represents the quality of the collected point cloud data.
*/
public void setPointCloudConfidence(double point_cloud_confidence)
{
point_cloud_confidence_ = point_cloud_confidence;
}
/**
* There are two types of confidence value noticing the quality of the data for sensor pose and point cloud.
* The range of confidence is from 0.0 with the worst quality to 1.0 with the best quality.
* The confidence of the point cloud represents the quality of the collected point cloud data.
*/
public double getPointCloudConfidence()
{
return point_cloud_confidence_;
}
/**
* The center location of the bounding box of all the points.
* The location of each point in the pointcloud is with respect to this location.
*/
public us.ihmc.euclid.tuple3D.Point3D getPointCloudCenter()
{
return point_cloud_center_;
}
/**
* The pointcloud is compressed by using an octree.
* This indicates the resolution used for the octree, the octree depth is 16.
*/
public void setResolution(double resolution)
{
resolution_ = resolution;
}
/**
* The pointcloud is compressed by using an octree.
* This indicates the resolution used for the octree, the octree depth is 16.
*/
public double getResolution()
{
return resolution_;
}
/**
* The number of points in this frame.
*/
public void setNumberOfPoints(int number_of_points)
{
number_of_points_ = number_of_points;
}
/**
* The number of points in this frame.
*/
public int getNumberOfPoints()
{
return number_of_points_;
}
/**
* The compressed pointcloud.
* See us.ihmc.robotEnvironmentAwareness.communication.converters.StereoPointCloudCompression for more info on the compression protocol.
*/
public us.ihmc.idl.IDLSequence.Byte getPointCloud()
{
return point_cloud_;
}
/**
* The compressed colors.
* See us.ihmc.robotEnvironmentAwareness.communication.converters.StereoPointCloudCompression for more info on the compression protocol.
*/
public us.ihmc.idl.IDLSequence.Byte getColors()
{
return colors_;
}
public static Supplier<StereoVisionPointCloudMessagePubSubType> getPubSubType()
{
return StereoVisionPointCloudMessagePubSubType::new;
}
@Override
public Supplier<TopicDataType> getPubSubTypePacket()
{
return StereoVisionPointCloudMessagePubSubType::new;
}
@Override
public boolean epsilonEquals(StereoVisionPointCloudMessage other, double epsilon)
{
if(other == null) return false;
if(other == this) return true;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.sequence_id_, other.sequence_id_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.timestamp_, other.timestamp_, epsilon)) return false;
if (!this.sensor_position_.epsilonEquals(other.sensor_position_, epsilon)) return false;
if (!this.sensor_orientation_.epsilonEquals(other.sensor_orientation_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.sensor_pose_confidence_, other.sensor_pose_confidence_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.point_cloud_confidence_, other.point_cloud_confidence_, epsilon)) return false;
if (!this.point_cloud_center_.epsilonEquals(other.point_cloud_center_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.resolution_, other.resolution_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.number_of_points_, other.number_of_points_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsByteSequence(this.point_cloud_, other.point_cloud_, epsilon)) return false;
if (!us.ihmc.idl.IDLTools.epsilonEqualsByteSequence(this.colors_, other.colors_, epsilon)) return false;
return true;
}
@Override
public boolean equals(Object other)
{
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof StereoVisionPointCloudMessage)) return false;
StereoVisionPointCloudMessage otherMyClass = (StereoVisionPointCloudMessage) other;
if(this.sequence_id_ != otherMyClass.sequence_id_) return false;
if(this.timestamp_ != otherMyClass.timestamp_) return false;
if (!this.sensor_position_.equals(otherMyClass.sensor_position_)) return false;
if (!this.sensor_orientation_.equals(otherMyClass.sensor_orientation_)) return false;
if(this.sensor_pose_confidence_ != otherMyClass.sensor_pose_confidence_) return false;
if(this.point_cloud_confidence_ != otherMyClass.point_cloud_confidence_) return false;
if (!this.point_cloud_center_.equals(otherMyClass.point_cloud_center_)) return false;
if(this.resolution_ != otherMyClass.resolution_) return false;
if(this.number_of_points_ != otherMyClass.number_of_points_) return false;
if (!this.point_cloud_.equals(otherMyClass.point_cloud_)) return false;
if (!this.colors_.equals(otherMyClass.colors_)) return false;
return true;
}
@Override
public java.lang.String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("StereoVisionPointCloudMessage {");
builder.append("sequence_id=");
builder.append(this.sequence_id_); builder.append(", ");
builder.append("timestamp=");
builder.append(this.timestamp_); builder.append(", ");
builder.append("sensor_position=");
builder.append(this.sensor_position_); builder.append(", ");
builder.append("sensor_orientation=");
builder.append(this.sensor_orientation_); builder.append(", ");
builder.append("sensor_pose_confidence=");
builder.append(this.sensor_pose_confidence_); builder.append(", ");
builder.append("point_cloud_confidence=");
builder.append(this.point_cloud_confidence_); builder.append(", ");
builder.append("point_cloud_center=");
builder.append(this.point_cloud_center_); builder.append(", ");
builder.append("resolution=");
builder.append(this.resolution_); builder.append(", ");
builder.append("number_of_points=");
builder.append(this.number_of_points_); builder.append(", ");
builder.append("point_cloud=");
builder.append(this.point_cloud_); builder.append(", ");
builder.append("colors=");
builder.append(this.colors_);
builder.append("}");
return builder.toString();
}
}
| 38.065672
| 189
| 0.691735
|
24d280236cffcf72f24ecabfdef27dc474ded2ea
| 3,751
|
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.jupiter.api.AfterEach;
public abstract class AbstractRuleTestCase
{
protected Server _server = new Server();
protected LocalConnector _connector;
protected volatile Request _request;
protected volatile Response _response;
protected volatile CountDownLatch _latch;
protected boolean _isSecure = false;
@AfterEach
public void stopServer() throws Exception
{
stop();
}
protected void start(final boolean isSecure) throws Exception
{
_connector = new LocalConnector(_server);
_connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration().addCustomizer(new HttpConfiguration.Customizer()
{
@Override
public void customize(Connector connector, HttpConfiguration channelConfig, Request request)
{
request.setSecure(isSecure);
}
});
_server.setConnectors(new Connector[]{_connector});
_server.setHandler(new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
_request=baseRequest;
_response=_request.getResponse();
try
{
_latch.await();
}
catch (InterruptedException e)
{
throw new ServletException(e);
}
}
});
_server.start();
_latch=new CountDownLatch(1);
_connector.executeRequest("GET / HTTP/1.0\nCookie: set=already\n\n");
while (_response==null)
Thread.sleep(1);
}
protected void reset()
{
if (_latch!=null)
_latch.countDown();
_request = null;
_response = null;
_latch=new CountDownLatch(1);
_connector.executeRequest("GET / HTTP/1.0\nCookie: set=already\n\n");
while (_response==null)
Thread.yield();
}
protected void stop() throws Exception
{
_latch.countDown();
_server.stop();
_server.join();
_request = null;
_response = null;
}
}
| 32.059829
| 161
| 0.609171
|
d978bf05766a199a7c727d94646b7b14b5d8aea3
| 1,905
|
package com.feihua.framework.rest.modules.common.mvc;
import com.feihua.framework.base.modules.postjob.dto.BasePostDto;
import com.feihua.framework.base.modules.role.dto.BaseRoleDto;
import com.feihua.framework.rest.ResponseJsonRender;
import com.feihua.framework.rest.mvc.SuperController;
import com.feihua.framework.rest.service.AccountServiceImpl;
import com.feihua.framework.shiro.pojo.ShiroUser;
import com.feihua.framework.shiro.utils.ShiroUtils;
import com.feihua.utils.http.httpServletResponse.ResponseCode;
import feihua.jdbc.api.pojo.PageAndOrderbyParamDto;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.utils.OrderbyUtils;
import feihua.jdbc.api.utils.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.List;
/**
* controller基类,负责一些通用处理方法
* Created by yw on 2015/9/23.
*/
public class BaseController extends SuperController{
private static Logger logger = LoggerFactory.getLogger(BaseController.class);
public BaseRoleDto getLoginUserRole(){
ShiroUser su = super.getLoginUser();
if(su != null){
return (BaseRoleDto) su.getRole();
}
return null;
}
public BasePostDto getLoginUserPost(){
ShiroUser su = super.getLoginUser();
if(su != null){
return (BasePostDto) su.getPost();
}
return null;
}
public String getLoginUserRoleId(){
BaseRoleDto roleDto = getLoginUserRole();
if(roleDto != null){
return roleDto.getId();
}
return null;
}
public String getLoginUserPostId(){
BasePostDto postDto = getLoginUserPost();
if(postDto != null){
return postDto.getId();
}
return null;
}
}
| 31.75
| 81
| 0.712861
|
11e49fc9df77f0aac1d5b20848869e91eb8162c1
| 1,403
|
package com.kovuthehusky.sortvisualization;
public class RecursiveMergeSort extends Sort {
// TODO: Rewrite this sort to be cleaner and easier to understand.
public RecursiveMergeSort(Window window) {
super(window);
}
@Override
public void run() {
this.mergeSortRecursive(array, 0, array.length);
}
private void merge(int start, int middle, int end) {
Number[] merge = new Number[end - start];
int l = 0, r = 0, pos = 0;
while (l < middle - start && r < end - middle) {
if (this.stop())
return;
if (array[start + l].lt(array[middle + r]))
merge[pos++] = array[start + l++];
else
merge[pos++] = array[middle + r++];
}
while (r < end - middle)
merge[pos++] = array[middle + r++];
while (l < middle - start)
merge[pos++] = array[start + l++];
for (Number element : merge) {
array[start++] = element;
array[start - 1].dirty();
}
}
private void mergeSortRecursive(Number[] array, int start, int end) {
if (end - start <= 1)
return;
int middle = start + (end - start) / 2;
this.mergeSortRecursive(array, start, middle);
this.mergeSortRecursive(array, middle, end);
this.merge(start, middle, end);
}
}
| 31.886364
| 73
| 0.530292
|
69f7625ab464d63373ba15523a2cf48885d73cbc
| 449
|
package fw.pages;
import fw.utils.DatabaseCaller;
import org.openqa.selenium.WebDriver;
import java.util.HashMap;
public class CommonPage extends Page {
protected DatabaseCaller databaseCaller;
public CommonPage(WebDriver driver) {
super(driver);
}
//databaseCaller = clients().getEszTestInstance();
/**
* В зависимости от указанного стенда инициализирует тестовые данные
*
*
*
*/
}
| 14.483871
| 72
| 0.672606
|
eae2a8557f14eeaf16de9fbcb6a459e7aedf8471
| 3,341
|
package tumor.report;
import java.util.ArrayList;
import java.util.List;
import jam.math.DoubleRange;
import jam.report.ReportRecord;
import tumor.mutation.MutationFrequency;
public final class MutFreqDetailRecord implements ReportRecord {
private final long mutationIndex;
private final double rawFrequency;
private final double normFrequency;
/**
* Base name for the mutation frequency detail report.
*/
public static final String BASE_NAME = "mut-freq-detail.csv";
/**
* Creates a new mutation frequency detail record.
*
* @param mutationIndex the index of the mutation of interest.
*
* @param rawFrequency the fraction of tumor cells carrying the
* mutation.
*
* @param normFrequency the ratio of the raw frequency to the
* maximum raw frequency in the population.
*/
public MutFreqDetailRecord(long mutationIndex, double rawFrequency, double normFrequency) {
DoubleRange.FRACTIONAL.validate("Raw frequency", rawFrequency);
DoubleRange.FRACTIONAL.validate("Normalized frequency", normFrequency);
this.mutationIndex = mutationIndex;
this.rawFrequency = rawFrequency;
this.normFrequency = normFrequency;
}
/**
* Translates a list of mutation frequencies into a list of
* mutation frequency detail records.
*
* @param freqList the mutation frequency list to translate.
*
* @return a list of correponding mutation freqeuency detail
* records.
*/
public static List<MutFreqDetailRecord> create(List<MutationFrequency> freqList) {
double maxFrequency = freqList.get(0).getFrequency();
List<MutFreqDetailRecord> recordList = new ArrayList<MutFreqDetailRecord>(freqList.size());
for (MutationFrequency freq : freqList) {
long mutationIndex = freq.getMutation().getIndex();
double rawFrequency = freq.getFrequency();
double normFrequency = rawFrequency / maxFrequency;
recordList.add(new MutFreqDetailRecord(mutationIndex, rawFrequency, normFrequency));
}
return recordList;
}
/**
* Returns the index of the mutation described by this record.
*
* @return the index of the mutation described by this record.
*/
public long getMutationIndex() {
return mutationIndex;
}
/**
* Returns the fraction of tumor cells carrying the mutation.
*
* @return the fraction of tumor cells carrying the mutation.
*/
public double getRawFrequency() {
return rawFrequency;
}
/**
* Returns the ratio of the raw frequency to the maximum raw
* frequency in the population.
*
* @return the ratio of the raw frequency to the maximum raw
* frequency in the population.
*/
public double getNormFrequency() {
return normFrequency;
}
@Override public String formatLine() {
return String.format("%d,%.4g,%.4g",
mutationIndex,
rawFrequency,
normFrequency);
}
@Override public String getBaseName() {
return BASE_NAME;
}
@Override public String getHeaderLine() {
return "mutationIndex,rawFrequency,normFrequency";
}
}
| 30.372727
| 99
| 0.654894
|
62a20a57d7f6ca81522d3efbbb16960ee2e78c38
| 1,802
|
package com.levigo.jadice.format.jpeg2000.internal.marker;
import com.levigo.jadice.format.jpeg2000.JPEG2000Exception;
import com.levigo.jadice.format.jpeg2000.internal.codestream.Codestream;
import com.levigo.jadice.format.jpeg2000.internal.io.SectorInputStream;
import com.levigo.jadice.format.jpeg2000.internal.param.PropertiesParameterInfo;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.io.IOException;
public class PPT extends AbstractMarkerSegment implements Comparable<PPT> {
public int Lppt;
public int Zppt;
public SectorInputStream Ippt;
@Override
protected void read(ImageInputStream source, Codestream codestream) throws IOException {
Lppt = source.readUnsignedShort();
Zppt = source.readUnsignedByte();
Ippt = new SectorInputStream(source, source.getStreamPosition(), Lppt - 3);
}
@Override
protected void write(ImageOutputStream sink, Codestream codestream) throws IOException {
sink.writeShort(Lppt);
sink.writeByte(Zppt);
int read = 0;
final byte buffer[] = new byte[65535];
while ((read = Ippt.read(buffer)) > 0) {
sink.write(buffer, 0, read);
}
}
@Override
protected void validate(Codestream codestream) throws JPEG2000Exception {
}
@Override
protected void fillMarkerInfo(MarkerInfo markerInfo) {
markerInfo.add(new PropertiesParameterInfo("Lppt", Lppt, "TODO"));
markerInfo.add(new PropertiesParameterInfo("Zppt", Zppt, "TODO"));
markerInfo.add(new PropertiesParameterInfo("Ippt (length)", Ippt.length(), "TODO"));
}
@Override
public Marker getMarker() {
return Marker.PPT;
}
@Override
public int compareTo(PPT ppt) {
return this.Zppt - ppt.Zppt;
}
}
| 31.068966
| 91
| 0.722531
|
c359ae0da5b556bb3427ab132fb4f884dd7c8ae2
| 1,658
|
package com.ossez.xml;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
public class JDomParser {
private File file;
public JDomParser(File file) {
this.file = file;
}
public List<Element> getAllTitles() {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(this.getFile());
Element tutorials = doc.getRootElement();
List<Element> titles = tutorials.getChildren("tutorial");
return titles;
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Element getNodeById(String id) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
String filter = "//*[@tutId='" + id + "']";
XPathFactory xFactory = XPathFactory.instance();
XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
List<Element> node = expr.evaluate(document);
return node.get(0);
} catch (JDOMException | IOException e) {
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
| 26.741935
| 88
| 0.603739
|
d8fb2f17a484be71c9f7b6304e4b636fbdd9c930
| 2,574
|
package com.taotao.search.dao;
import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 〈查询索引库商品dao〉
*
* @author mazhongrong@smeyun.com
* @date 2018/8/20
*/
@Repository
public class SearchDao {
@Autowired
private SolrClient solrClient;
public SearchResult search(SolrQuery query) throws Exception{
//根据query对象进行查询
QueryResponse response = solrClient.query(query);
//取查询结果
SolrDocumentList results = response.getResults();
//取查询结果总记录数
long numFound = results.getNumFound();
SearchResult searchResult = new SearchResult();
searchResult.setRecordCount(numFound);
List<SearchItem> itemList = new ArrayList<>();
for (SolrDocument document : results) {
SearchItem searchItem = new SearchItem();
searchItem.setCategoryName(String.valueOf(document.get("item_category_name")));
searchItem.setId(String.valueOf(document.get("id")));
String image = (String) document.get("item_image");
if (org.apache.commons.lang3.StringUtils.isNotEmpty(image)) {
image = image.split(",")[0];
}
searchItem.setImage(image);
searchItem.setPrice((Long) document.get("item_price"));
searchItem.setSellPoint((String) document.get("item_sell_point"));
// 取高亮显示
Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
List<String> list = highlighting.get(document.get("id")).get("item_title");
String title = "";
if (CollectionUtils.isNotEmpty(list)) {
title = list.get(0);
} else {
title = (String) document.get("item_title");
}
searchItem.setTitle(title);
//把结果封装到searchItem对象中
itemList.add(searchItem);
}
//把结果添加到SearchResult对象中
searchResult.setList(itemList);
//返回
return searchResult;
}
}
| 36.771429
| 93
| 0.659674
|
4cdd921cf23aab309136a0df94e19e9e7cd679ed
| 4,556
|
package kr.ac.shms.common.service.impl;
import java.io.ByteArrayInputStream;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import kr.ac.shms.common.dao.CommonAttachDAO;
import kr.ac.shms.common.service.CommonAttachService;
import kr.ac.shms.common.vo.AttachVO;
import kr.ac.shms.common.vo.IAttachVO;
@Service
public class CommonAttachServiceImpl implements CommonAttachService {
private static final Logger logger = LoggerFactory.getLogger(CommonAttachServiceImpl.class);
@Inject
private CommonAttachDAO commonAttachDAO;
@Value("#{appInfo['ip']}")
private String ip;
@Value("#{appInfo['port']}")
private int port;
@Value("#{appInfo['id']}")
private String id;
@Value("#{appInfo['pw']}")
private String pw;
@Override
public List<AttachVO> attachList(int param) {
return commonAttachDAO.attachList(param);
}
@Override
public int atch_file_seqCount(int atch_file_no) {
return commonAttachDAO.selectAtchFileSeqCount(atch_file_no);
}
@Override
public AttachVO download(AttachVO attachVO, String use_type) {
AttachVO attach = commonAttachDAO.selectAttatch(attachVO);
if(use_type != null) {
attach.setUse_type(use_type);
}
return attach;
}
@Override
public int processes(IAttachVO iattachVO, String dir) {
int cnt = 0;
List<AttachVO> attachList = iattachVO.getAttachList();
if(attachList!=null && attachList.size()>0) {
FTPClient client = new FTPClient();
try {
client.connect(ip, port);
int reply = client.getReplyCode();
logger.info("client Connect : {}", reply);
if(FTPReply.isPositiveCompletion(reply)) { // 접속 연결이 됐을 경우
if(client.login(id, pw)) { // FTP 서버 로그인 성공 했을 경우
System.out.println("Login Success");
client.setBufferSize(1000); // 버퍼 사이즈
client.enterLocalPassiveMode(); // 공유기를 상대로 파일 전송하기 위해 패시브 모드로 지정해줘야함
boolean isDirectory = client.changeWorkingDirectory(dir); // 파일 경로 지정
for(AttachVO attach : attachList) {
attach.setFile_path(dir);
}
logger.info("isDir : {} || {}",isDirectory, dir);
if(!isDirectory) {
client.mkd(dir);
}
client.setFileType(FTP.BINARY_FILE_TYPE);
boolean isUpload = false;
for(AttachVO attvo : iattachVO.getAttachList()) {
logger.info("attvo {}", attvo);
isUpload = client.storeFile(attvo.getSave_file_nm(), new ByteArrayInputStream(attvo.getFile().getBytes()));
logger.info("isUpload {}", isUpload);
if(!isUpload) {
client.logout();
break;
}
}
logger.info("isUpload : {}", isUpload);
if(isUpload) cnt += commonAttachDAO.insertAttatches(iattachVO);
client.logout();
client.disconnect();
} else {
client.disconnect(); // 연결 종료
}
}
} catch(Exception e) {
}
}
return cnt;
}
@Override
public int deleteFileProcesses(IAttachVO iattachVO, String dir) {
logger.info("deleteFileProcesses : {}", iattachVO);
FTPClient client = new FTPClient();
int cnt = 0;
int[] delAttNos = iattachVO.getDelAttNos();
if(delAttNos!=null && delAttNos.length > 0) {
List<String> saveNames = commonAttachDAO.selectSaveNamesForDelete(iattachVO);
logger.info("saveNames : {}", saveNames.size());
try {
client.connect(ip, port);
int reply = client.getReplyCode();
logger.info("client Connect : {}", reply);
if(FTPReply.isPositiveCompletion(reply)) { // 접속 연결이 됐을 경우
if(client.login(id, pw)) { // FTP 서버 로그인 성공 했을 경우
System.out.println("Login Success");
client.setBufferSize(1000); // 버퍼 사이즈
client.enterLocalPassiveMode(); // 공유기를 상대로 파일 전송하기 위해 패시브 모드로 지정해줘야함
boolean isDirectory = client.changeWorkingDirectory(dir); // 파일 경로 지정
logger.info("isDir : {} || {}",isDirectory, dir);
// if(!isDirectory) {
// client.mkd(attatchPath);
// }
client.setFileType(FTP.BINARY_FILE_TYPE);
// 이진 데이터 삭제
for(String saveName : saveNames) {
client.deleteFile(saveName);
}
// 첨부파일의 메타 데이터 삭제
commonAttachDAO.deleteAttathes(iattachVO);
client.logout();
client.disconnect();
} else {
client.disconnect(); // 연결 종료
}
}
} catch(Exception e) {
}
}
return cnt;
}
}
| 29.205128
| 114
| 0.665277
|
fd9eb2635f4ec3070f8ab239239d66b5d7165b39
| 4,844
|
package net.tinetwork.tradingcards.tradingcardsplugin.managers.cards;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import net.tinetwork.tradingcards.tradingcardsplugin.TradingCards;
import net.tinetwork.tradingcards.tradingcardsplugin.card.TradingCard;
import net.tinetwork.tradingcards.tradingcardsplugin.managers.Manager;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author sarhatabaot
*/
public abstract class TradingCardManager extends Manager<CompositeCardKey, TradingCard> {
protected final LoadingCache<String, List<TradingCard>> rarityCardCache;
protected final LoadingCache<String, List<TradingCard>> seriesCardCache;
protected final LoadingCache<CompositeRaritySeriesKey,List<TradingCard>> rarityAndSeriesCardCache;
protected TradingCardManager(final TradingCards plugin) {
super(plugin);
this.rarityCardCache = loadRarityCardCache();
this.seriesCardCache = loadSeriesCardCache();
preLoadRarityCache();
preLoadSeriesCache();
this.rarityAndSeriesCardCache = loadRarityAndSeriesCardCache();
preLoadRarityAndSeriesCache();
}
@Override
public LoadingCache<CompositeCardKey, TradingCard> loadCache() {
return CacheBuilder.newBuilder()
.maximumSize(plugin.getAdvancedConfig().getCards().maxCacheSize())
.refreshAfterWrite(plugin.getAdvancedConfig().getCards().refreshAfterWrite(), TimeUnit.MINUTES)
.build(new CacheLoader<>() {
@Override
public TradingCard load(final CompositeCardKey key) throws Exception {
return plugin.getStorage().getCard(key.cardId(), key.rarityId(), key.seriesId()).get();
}
}
);
}
@Contract(" -> new")
private @NotNull LoadingCache<String, List<TradingCard>> loadSeriesCardCache() {
return CacheBuilder.newBuilder()
.maximumSize(plugin.getAdvancedConfig().getCards().maxCacheSize())
.refreshAfterWrite(plugin.getAdvancedConfig().getCards().refreshAfterWrite(), TimeUnit.MINUTES)
.build(new CacheLoader<>() {
@Override
public List<TradingCard> load(final String key) throws Exception {
return plugin.getStorage().getCardsInSeries(key);
}
}
);
}
private @NotNull LoadingCache<CompositeRaritySeriesKey,List<TradingCard>> loadRarityAndSeriesCardCache() {
return CacheBuilder.newBuilder()
.maximumSize(plugin.getAdvancedConfig().getCards().maxCacheSize())
.refreshAfterWrite(plugin.getAdvancedConfig().getCards().refreshAfterWrite(),TimeUnit.MINUTES)
.build(new CacheLoader<>() {
@Override
public List<TradingCard> load(final CompositeRaritySeriesKey key) throws Exception {
List<TradingCard> cardList = plugin.getStorage().getCardsInRarityAndSeries(key.rarityId(),key.seriesId());
if(cardList == null)
return Collections.emptyList();
return cardList;
}
});
}
private void preLoadRarityAndSeriesCache() {
try {
this.rarityAndSeriesCardCache.getAll(loadRaritySeriesKeys());
} catch (ExecutionException e) {
//ignored
}
}
private @NotNull List<CompositeRaritySeriesKey> loadRaritySeriesKeys() {
List<CompositeRaritySeriesKey> keyList = new ArrayList<>();
for (String seriesId: seriesCardCache.asMap().keySet()) {
for(String rarityId: rarityCardCache.asMap().keySet()) {
keyList.add(new CompositeRaritySeriesKey(rarityId,seriesId));
}
}
return keyList;
}
protected abstract LoadingCache<String, List<TradingCard>> loadRarityCardCache();
public abstract void preLoadRarityCache();
public abstract void preLoadSeriesCache();
public LoadingCache<String, List<TradingCard>> getRarityCardCache() {
return rarityCardCache;
}
public LoadingCache<String, List<TradingCard>> getSeriesCardCache() {
return seriesCardCache;
}
public LoadingCache<CompositeRaritySeriesKey, List<TradingCard>> getRarityAndSeriesCardCache() {
return rarityAndSeriesCardCache;
}
}
| 40.705882
| 130
| 0.653386
|
f816b3f36e4ae9aa806689105b5f6eb681161189
| 364
|
package class9_interface;
public class VMS implements Faculty {
@Override
public String getUniversity() {
return "Assumption University";
}
@Override
public String getName() {
return "Vincent Mary School of Science and Technology";
}
@Override
public String getBuilding() {
return "VMS Building";
}
}
| 19.157895
| 63
| 0.64011
|
086141f855b33c2aaee46e60a2d2d494c56e4489
| 2,441
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.pom.PomTarget;
import com.intellij.pom.PomTargetPsiElement;
import com.intellij.psi.DelegatePsiTarget;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
public class DomDocumentationProvider implements DocumentationProvider {
@Override
public String getQuickNavigateInfo(final PsiElement element, PsiElement originalElement) {
return null;
}
@Override
public List<String> getUrlFor(final PsiElement element, final PsiElement originalElement) {
return null;
}
@Override
public String generateDoc(PsiElement element, final PsiElement originalElement) {
if (element instanceof PomTargetPsiElement) {
PomTarget target = ((PomTargetPsiElement)element).getTarget();
if (target instanceof DelegatePsiTarget) {
element = ((DelegatePsiTarget)target).getNavigationElement();
}
}
final DomElement domElement = DomUtil.getDomElement(element);
if (domElement == null) {
return null;
}
ElementPresentationTemplate template = domElement.getChildDescription().getPresentationTemplate();
if (template != null) {
String documentation = template.createPresentation(domElement).getDocumentation();
if (documentation != null) return documentation;
}
return ElementPresentationManager.getDocumentationForElement(domElement);
}
@Override
public PsiElement getDocumentationElementForLookupItem(final PsiManager psiManager, final Object object, final PsiElement element) {
return null;
}
@Override
public PsiElement getDocumentationElementForLink(final PsiManager psiManager, final String link, final PsiElement context) {
return null;
}
}
| 33.902778
| 134
| 0.758296
|
a4d003002b8ca199826f9c1282ac68142ba7414c
| 1,155
|
package com.example.live;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class MyPostViewModel extends ViewModel {
private PostRepository postRepository;
public MyPostViewModel() {
postRepository = PostRepository.getInstance();
}
public LiveData<List<Post>> getPosts() {
return postRepository.registerToAllMyPosts();
}
public Task<Void> removePost(Post id) {
return postRepository.removePost(id);
}
}
| 28.170732
| 63
| 0.790476
|
262979a554ab8d91415c88776c405eab16c5b051
| 409
|
package io.github.artemy.osipov.thrift.bridge.spring.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@EnableConfigurationProperties(BridgeProperties.class)
@Import(BridgeMvcConfiguration.class)
public class BridgeAutoConfiguration {
}
| 34.083333
| 81
| 0.870416
|
0c2bb329b5db1a190b1f443bed577a11b97f6eee
| 746
|
import java.util.*;
public class ProgramTSG
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int i,j;
//upper part
for(i=n;i>=1;i=i-2)
{
for(j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
//lower part
for(i=i+2;i<=n;i=i+2)
{
for(j=n-i;j>=1;j--)
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
| 19.631579
| 44
| 0.363271
|
5e5eb6a92da860b2dd7951b93d1ccfddabaddad2
| 1,028
|
package org.robolectric.shadows;
import android.content.Context;
import android.preference.EditTextPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.TestRunners;
import static junit.framework.Assert.assertNotNull;
import static org.fest.assertions.api.Assertions.assertThat;
@RunWith(TestRunners.WithDefaults.class)
public class EditTextPreferenceTest {
private static final String SOME_TEXT = "some text";
private EditTextPreference preference;
private Context context;
@Before
public void setup() {
context = Robolectric.application;
preference = new EditTextPreference(context);
}
@Test
public void testConstructor() {
preference = new EditTextPreference(context);
assertNotNull(preference.getEditText());
}
@Test
public void testSetText() {
preference.setText(SOME_TEXT);
assertThat((String) preference.getEditText().getText().toString()).isEqualTo(SOME_TEXT);
}
}
| 25.073171
| 92
| 0.773346
|
81bfb61838f861db801399bca8fdf33c1f00d7f4
| 711
|
package question4;
public class Bus extends Vehicle {
String year;
double manufacturerDiscount;
public Bus(int speed,String colour,double price,String year, double manufacturerDiscount) {
super(speed,price,colour);
this.year = year;
this.manufacturerDiscount = manufacturerDiscount;
}
public double getSalePrice(){
double price = (this.regularPrice * (100-this.manufacturerDiscount) )/100.0;
return price;
}
public void display() {
System.out.println("**********Bus*********");
System.out.println("Speed : "+this.speed);
System.out.println("Sale Price: "+this.getSalePrice());
System.out.println("Colour : "+this.colour);
System.out.println("Year : "+this.year);
}
}
| 24.517241
| 92
| 0.69339
|
8de8451a48d82ccedffe2b233b6de6bac0948411
| 243
|
package behavior.visitor;
public class Main {
public static void main(String[] args) {
Fruit apple = new Apple();
Fruit orange = new Orange();
FruitVisitor visitor = new Eater();
apple.accept(visitor);
orange.accept(visitor);
}
}
| 20.25
| 41
| 0.695473
|
f3e8a6b2fda0349c700168cd250302193e7e66fc
| 1,632
|
package com.infoclinika.mssharing.model.internal.read;
import com.google.common.base.Function;
import com.infoclinika.mssharing.model.internal.entity.ExperimentLabel;
import com.infoclinika.mssharing.model.internal.entity.ExperimentLabelType;
import com.infoclinika.mssharing.model.internal.repository.ExperimentLabelRepository;
import com.infoclinika.mssharing.model.internal.repository.ExperimentLabelTypeRepository;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;
/**
* @author andrii.loboda
*/
@Service
public class ExperimentLabelReaderImpl implements ExperimentLabelReader {
@Inject
private ExperimentLabelRepository experimentLabelRepository;
@Inject
private ExperimentLabelTypeRepository experimentLabelTypeRepository;
@Override
public List<ExperimentLabelItem> readLabels(long type) {
final ExperimentLabelType experimentLabelType = experimentLabelTypeRepository.findOne(type);
checkNotNull(experimentLabelType);
return newArrayList(transform(
experimentLabelRepository.findByType(experimentLabelType),
new Function<ExperimentLabel, ExperimentLabelItem>() {
@Override
public ExperimentLabelItem apply(ExperimentLabel label) {
return new ExperimentLabelItem(label.getId(), label.getAcid(), label.getName());
}
}
));
}
}
| 37.953488
| 100
| 0.76348
|
8d32317bf1ebc00ea18bae7b45d4b01abd60fbe9
| 740
|
package de.clayntech.excelsea.log;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
public class ExcelseaLoggingFactoryTest {
private static final class InnerClass {
public final Logger innerLogger=ExcelseaLoggerFactory.getLogger();
}
@Test
public void testGetLogger() {
InnerClass inner=new InnerClass();
Logger log=ExcelseaLoggerFactory.getLogger();
Assertions.assertNotEquals(inner.innerLogger,log);
Assertions.assertNotSame(inner.innerLogger,log);
Assertions.assertTrue(log.getName().contains("ExcelseaLoggingFactoryTest"));
Assertions.assertTrue(inner.innerLogger.getName().contains("InnerClass"));
}
}
| 32.173913
| 84
| 0.735135
|
93779957f0c0f1b7572db24ac38a114b1191821a
| 4,534
|
package org.intermine.bio.webservice;
/*
* Copyright (C) 2002-2019 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 org.apache.commons.lang.StringUtils;
import org.intermine.api.InterMineAPI;
import org.intermine.bio.web.export.SequenceExporter;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.objectstore.ObjectStore;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.export.Exporter;
import org.intermine.webservice.server.exceptions.BadRequestException;
/**
* A service for exporting query results as fasta.
* @author Alexis Kalderimis.
*
*/
public class FastaQueryService extends BioQueryService
{
private static final String EXT = "extension";
private static final String TOO_MANY_COLUMNS =
"Queries for this webservice may only have one output column";
private static final int COLUMN = 0;
/**
* Constructor.
* @param im A reference to an InterMine API settings bundle.
*/
public FastaQueryService(InterMineAPI im) {
super(im);
}
@Override
protected String getSuffix() {
return ".fa";
}
@Override
protected String getContentType() {
return "text/x-fasta";
}
@Override
protected Exporter getExporter(PathQuery pq) {
int extension = parseExtension(getOptionalParameter(EXT, "0"));
ObjectStore objStore = im.getObjectStore();
return new SequenceExporter(objStore, getOutputStream(), COLUMN,
im.getClassKeys(), extension, getQueryPaths(pq));
}
/**
* Make the path-query to run, and check it has the right number of columns.
* @return A suitable pathquery for getting FASTA data from.
*/
@Override
protected PathQuery getQuery() {
PathQuery pq = super.getQuery();
if (pq.getView().size() > 1) {
throw new BadRequestException(TOO_MANY_COLUMNS);
}
return pq;
}
/**
* A method for parsing the value of the extension parameter. Static and protected for
* testing purposes.
*
* @param extension The extension as provided by the user.
* @return An integer representing the number of base pairs.
* @throws BadRequestException If there is a problem interpreting the extension string.
*/
protected static int parseExtension(final String extension) throws BadRequestException {
if (StringUtils.isBlank(extension)) {
return 0;
}
final String ext = extension.toLowerCase().trim();
if (!ext.matches("^((\\d+)|(\\d+(\\.\\d+)?(k|m)))(bp?)?$")) {
throw new BadRequestException("Illegal extension format: " + ext);
}
final String justTheNumber = ext.replaceAll("[kmbp]", "");
final int scale = (ext.contains("k") ? 1000 : ext.contains("m") ? 1000000 : 1);
final float number;
try {
number = Float.parseFloat(justTheNumber) * scale;
} catch (NumberFormatException e) {
throw new BadRequestException("Illegal number: " + justTheNumber, e);
}
if (number < 0) {
throw new BadRequestException("Negative extensions are not allowed.");
}
if (number != Math.ceil(number)) {
throw new BadRequestException("The extension must be a whole number of base pairs. "
+ "I got: " + number + "bp");
}
return Math.round(number);
}
@Override
protected void checkPathQuery(PathQuery pq) throws Exception {
if (pq.getView().size() > 1) {
throw new BadRequestException("Queries to this service may only have one view.");
}
Path path = pq.makePath(pq.getView().get(0));
ClassDescriptor klazz = path.getLastClassDescriptor();
ClassDescriptor sf = im.getModel().getClassDescriptorByName("SequenceFeature");
ClassDescriptor protein = im.getModel().getClassDescriptorByName("Protein");
if (sf == klazz || protein == klazz || klazz.getAllSuperDescriptors().contains(sf)
|| klazz.getAllSuperDescriptors().contains(protein)) {
return; // OK
} else {
throw new BadRequestException("Unsuitable type for export: " + klazz);
}
}
}
| 34.876923
| 96
| 0.646449
|
bebd5e9131eb52086533851cab7f7e642f0c42dc
| 5,661
|
/**
* RELOAD TOOLS
*
* Copyright (c) 2003 Oleg Liber, Bill Olivier, Phillip Beauvoir
*
* 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.
*
* Project Management Contact:
*
* Oleg Liber
* Bolton Institute of Higher Education
* Deane Road
* Bolton BL3 5AB
* UK
*
* e-mail: o.liber@bolton.ac.uk
*
*
* Technical Contact:
*
* Phillip Beauvoir
* e-mail: p.beauvoir@bolton.ac.uk
*
* Web: http://www.reload.ac.uk
*
*/
package uk.ac.reload.editor.metadata.editor.formview;
import java.awt.Color;
import java.awt.Component;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import uk.ac.reload.editor.gui.widgets.NumberFieldWidget;
import uk.ac.reload.editor.gui.widgets.TextAreaWidget;
import uk.ac.reload.editor.gui.widgets.TextFieldWidget;
import uk.ac.reload.editor.gui.widgets.Widget;
import uk.ac.reload.editor.metadata.xml.Metadata;
import uk.ac.reload.moonunit.SchemaController;
import uk.ac.reload.moonunit.schema.SchemaElement;
/**
* A Text Area widget.
*
* @author Phillip Beauvoir
* @version $Id: MD_TextField.java,v 1.1 1998/03/26 15:40:32 ynsingh Exp $
*/
public class MD_TextField
extends MD_Field
implements DocumentListener
{
/**
* An internal flag
*/
private boolean _allowNotification = true;
/**
* The suitable Component we shall use
*/
private Widget _widget;
/**
* Constructor
*/
public MD_TextField(Metadata metadata, SchemaElement schemaElement) {
super(metadata, schemaElement);
// Determine type of text field
_widget = getMetadataTextFieldWidget(schemaElement);
// Border
((JComponent)_widget).setBorder(BorderFactory.createLineBorder(Color.GRAY));
setElement(metadata.getElement(getSchemaElement()));
if(getElement() != null) setValue(getElement().getText());
// We listen to Text Changes
_widget.addDocumentListener(this);
// We listen to Element changes
metadata.addXMLDocumentListener(this);
}
/**
* @return A Text Widget suitable for the MD Form display
*/
protected Widget getMetadataTextFieldWidget(SchemaElement schemaElement) {
if(schemaElement == null) return getDefaultWidget();
Widget component = null;
SchemaController schemaController = getSchemaDocument().getSchemaController();
String widget_type = schemaController.getWidgetType(schemaElement.getXMLPath());
if(widget_type != null) {
if(widget_type.equals("textpane")) {
component = new TextAreaWidget();
((TextAreaWidget)component).setColumns(50);
}
else if(widget_type.equals("numberfield")) {
component = new NumberFieldWidget();
((NumberFieldWidget)component).setColumns(30);
}
else component = getDefaultWidget();
}
else component = getDefaultWidget();
// Set Max String length
int maxLength = -1;
String value = schemaController.getFacetValue(schemaElement, "maxLength");
if(value != null) maxLength = Integer.parseInt(value);
component.setMaxLength(maxLength);
return component;
}
/**
* @return a default widget
*/
private Widget getDefaultWidget() {
TextFieldWidget textField = new TextFieldWidget();
textField.setColumns(50);
return textField;
}
/**
* Clean up
*/
public void cleanup() {
_widget.removeDocumentListener(this);
getSchemaDocument().removeXMLDocumentListener(this);
}
/**
* Get the value of this Widget
* @return The value contained in the Widget
*/
public String getValue() {
return _widget.getTextValue();
}
/**
* Set the value of the Widget
* @param value The value
*/
public void setValue(String value) {
_allowNotification = false;
_widget.setTextValue(value);
_allowNotification = true;
}
/**
* @return the Component that we're using
*/
public Component getComponent() {
return (Component)_widget;
}
// =============================================================================
// === These events are fired from the JTextArea when the textfield changes ====
// =============================================================================
public void removeUpdate(DocumentEvent evt) {
if(_allowNotification) fireElementChanged();
}
public void changedUpdate(DocumentEvent evt) {
if(_allowNotification) fireElementChanged();
}
public void insertUpdate(DocumentEvent evt) {
if(_allowNotification) fireElementChanged();
}
}
| 28.736041
| 92
| 0.680975
|
242a1d8d5ce5a5730ef3451498a7d57dc17d95c1
| 1,935
|
package edu.msoe.leinoa.androideventer.model.triggers;
import java.util.Calendar;
import edu.msoe.leinoa.androideventer.model.ExternalEventInterface;
/**
* Created by aleino on 11/13/16.
*/
public class Trigger {
private String uuid;
private String title;
private String description;
private String triggerType;
private byte[] triggerData;
private Calendar dateCreated;
public Trigger(String uuid, String title, String description, String triggerType,
byte[] triggerData, Calendar dateCreated) {
this.uuid = uuid;
this.title = title;
this.description = description;
this.triggerType = triggerType;
this.triggerData = triggerData;
this.dateCreated = dateCreated;
}
public String getUuid() {
return uuid;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getTriggerType() {
return triggerType;
}
public byte[] getTriggerData() {
return triggerData;
}
public Calendar getDateCreated() {
return dateCreated;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setTriggerType(String triggerType) {
this.triggerType = triggerType;
}
public void setTriggerData(byte[] triggerData) {
this.triggerData = triggerData;
}
public void setDateCreated(Calendar dateCreated) {
this.dateCreated = dateCreated;
}
public boolean isTriggered(ExternalEventInterface externalEvent) {
return false;
}
@Override
public String toString() {
return this.triggerType + ": " + this.title;
}
}
| 22.5
| 85
| 0.642377
|
b9a7dcbe7da5e7d267e40b883a639793d97dc78f
| 3,913
|
package name.ignat.minerva.io.read;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import name.ignat.commons.exception.UnexpectedCaseException;
import name.ignat.minerva.model.Message;
import name.ignat.minerva.model.address.Address;
import name.ignat.minerva.model.address.AddressPattern;
import name.ignat.minerva.model.address.Domain;
/**
* @author Dan Ignat
*/
public final class ReadMappers
{
/*
* Can't use actual type variables for these, since they have to vary for each call to register() and
* registerFactory().
*/
private static Map<Class<?>, ReadMapper<?>> registry = new LinkedHashMap<>();
/*
* Sometimes a mapper needs to have state, e.g. MessageMapper.messageIndex. So we use a registry for stateless
* mappers, and a factoryRegistry for stateful mappers.
*/
private static Map<Class<?>, Supplier<ReadMapper<?>>> factoryRegistry = new LinkedHashMap<>();
static
{
register(Address.class, ReadMappers::toAddress);
register(Domain.class, ReadMappers::toDomain);
register(AddressPattern.class, ReadMappers::toAddressPattern);
registerFactory(Message.class, MessageMapper::new);
}
// Prevents registering the wrong ReadMapper for a given Class
private static <T> void register(Class<T> clazz, ReadMapper<T> mapper)
{
registry.put(clazz, mapper);
}
/*
* Meant to prevent registering the wrong ReadMapper factory for a given Class. Unfortunately, Java doesn't let me
* use T for the mapperFactory, due to limitations on nested generics:
*
* "The method put(Class<?>, Supplier<ReadMapper<?>>) in the type Map<Class<?>,Supplier<ReadMapper<?>>> is not
* applicable for the arguments (Class<T>, Supplier<ReadMapper<T>>)"
*
* So this method doesn't actually prevent what it's supposed to.
*/
private static <T> void registerFactory(Class<T> clazz, Supplier<ReadMapper<?>> mapperFactory)
{
factoryRegistry.put(clazz, mapperFactory);
}
@SuppressWarnings("unchecked")
public static <T> ReadMapper<T> forClass(Class<T> clazz)
{
ReadMapper<T> objectMapper = (ReadMapper<T>) registry.get(clazz);
if (objectMapper == null)
{
/*
* Can't use T here, due to same nested generics limitations as mentioned above:
*
* "Cannot cast from Supplier<ReadMapper<?>> to Supplier<ReadMapper<T>>"
*/
Supplier<ReadMapper<?>> objectMapperFactory = factoryRegistry.get(clazz);
if (objectMapperFactory == null)
{
throw new UnexpectedCaseException(clazz);
}
objectMapper = (ReadMapper<T>) objectMapperFactory.get();
}
return objectMapper;
}
public static Address toAddress(String[] args)
{
assertThat(args, arrayWithSize(1));
return new Address(args[0]);
}
public static Domain toDomain(String[] args)
{
assertThat(args, arrayWithSize(1));
return new Domain(args[0]);
}
public static AddressPattern toAddressPattern(String[] args)
{
assertThat(args, arrayWithSize(1));
return new AddressPattern(args[0]);
}
public static class MessageMapper implements ReadMapper<Message>
{
private int messageIndex = 2;
@Override
public Message apply(String[] args)
{
assertThat(args, arrayWithSize(3));
return new Message(messageIndex++, args[0], args[1], args[2]);
}
}
private ReadMappers() { }
}
| 31.813008
| 120
| 0.628418
|
d2af9ede75e4a6f56e0dea8c3abea04aee2b07b4
| 32,807
|
/**
* Copyright 2018 Marcus Klang (marcus.klang@cs.lth.se)
* 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 se.lth.cs.docria;
import org.msgpack.core.MessageBufferPacker;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.core.buffer.MessageBuffer;
import org.msgpack.value.ImmutableIntegerValue;
import org.msgpack.value.ImmutableValue;
import se.lth.cs.docria.values.*;
import java.io.IOError;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class MsgpackCodec {
private static class ValueWriter implements ValueVisitor {
private MessagePacker packer;
public ValueWriter(MessagePacker packer) {
this.packer = packer;
}
@Override
public void accept(Value value) {
throw new UnsupportedOperationException("Encoding " + value.type().toString());
}
@Override
public void accept(BoolValue value) {
try {
packer.packBoolean(value.boolValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(IntValue value) {
try {
packer.packInt(value.intValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(LongValue value) {
try {
packer.packLong(value.longValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(DoubleValue value) {
try {
packer.packDouble(value.doubleValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(NullValue value) {
try {
packer.packNil();
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(BinaryValue value) {
try {
byte[] bytes = value.binaryValue();
packer.packBinaryHeader(bytes.length);
packer.writePayload(bytes);
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(StringValue value) {
try {
packer.packString(value.stringValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(Span value) {
try {
packer.packInt(value.startOffset().id);
packer.packInt(value.stopOffset().id);
}
catch(IOException e) {
throw new IOError(e);
}
}
public boolean schemaless = false;
@Override
public void accept(ExtensionValue value) {
try {
byte[] bytes = value.binaryValue();
if(schemaless) {
MessageBufferPacker typePacker = MessagePack.newDefaultBufferPacker();
typePacker.packString("doc");
typePacker.packBinaryHeader(bytes.length);
typePacker.addPayload(bytes);
byte[] data = typePacker.toByteArray();
packer.packExtensionTypeHeader((byte) 0, data.length);
packer.addPayload(data);
} else {
packer.packBinaryHeader(bytes.length);
packer.addPayload(bytes);
}
}
catch(IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(Node value) {
try {
packer.packInt(value.id);
}
catch(IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(NodeArrayValue value) {
try {
Node[] nodes = value.nodeArrayValue();
packer.packArrayHeader(nodes.length);
for (int i = 0; i < nodes.length; i++) {
packer.packInt(nodes[i].id);
}
} catch(IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(NodeSpan value) {
try {
packer.packArrayHeader(2);
packer.packInt(value.left.id);
packer.packInt(value.right.id-value.left.id);
} catch(IOException e) {
throw new IOError(e);
}
}
}
private static class SchemaArgWriter implements ValueVisitor {
private MessagePacker packer;
public SchemaArgWriter(MessagePacker packer) {
this.packer = packer;
}
@Override
public void accept(Value value) {
throw new UnsupportedOperationException();
}
@Override
public void accept(BoolValue value) {
try {
packer.packBoolean(value.boolValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(IntValue value) {
try {
packer.packInt(value.intValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(LongValue value) {
try {
packer.packLong(value.longValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(DoubleValue value) {
try {
packer.packDouble(value.doubleValue());
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(BinaryValue value) {
try {
byte[] bytes = value.binaryValue();
packer.packBinaryHeader(bytes.length);
packer.writePayload(bytes);
} catch (IOException e) {
throw new IOError(e);
}
}
@Override
public void accept(StringValue value) {
try {
packer.packString(value.stringValue());
} catch (IOException e) {
throw new IOError(e);
}
}
}
private static void encodeProperties(Document document, MessagePacker packer) throws IOException {
MessageBufferPacker propPacker = MessagePack.newDefaultBufferPacker();
Map<String, Value> props = document.props();
propPacker.packMapHeader(props.size());
ValueWriter propWriter = new ValueWriter(propPacker);
propWriter.schemaless = true;
props.forEach((key, value) -> {
try {
propPacker.packString(key);
value.visit(propWriter);
} catch (IOException ex) {
throw new IOError(ex);
}
});
packer.packInt((int)propPacker.getTotalWrittenBytes());
packer.addPayload(propPacker.toByteArray());
}
private static void encodeSchema(Document document, MessagePacker packer, List<String> types, Map<String,List<String>> types2columns) {
try {
// Encode layers
document.layerStream().map(Layer::name).forEach(types::add);
packer.packArrayHeader(types.size());
for (String type : types) {
packer.packString(type);
}
SchemaArgWriter argWriter = new SchemaArgWriter(packer);
// Encode fields
for (String type : types) {
Schema.Layer schema = document.layer(type).schema();
List<String> fields = types2columns.computeIfAbsent(type, k -> new ArrayList<>());
packer.packInt(schema.fields().size());
for (Map.Entry<String, DataType> entry : schema.fields().entrySet()) {
packer.packString(entry.getKey());
DataType dtype = entry.getValue();
if(dtype.args().isEmpty()) {
packer.packBoolean(false);
packer.packString(dtype.name().getName());
} else {
packer.packBoolean(true);
packer.packString(dtype.name().getName());
Map<String, Value> args = dtype.args();
packer.packMapHeader(args.size());
for (Map.Entry<String, Value> argsEntry : args.entrySet()) {
packer.packString(argsEntry.getKey());
argsEntry.getValue().visit(argWriter);
}
}
fields.add(entry.getKey());
}
}
} catch (IOException e) {
throw new IOError(e);
}
}
private static void encodeTexts(Document.Compiled compiled, Document document, MessagePacker packer) {
MessageBufferPacker textPacker = MessagePack.newDefaultBufferPacker();
try {
textPacker.packMapHeader(document.texts().size());
for (Text text : document.texts()) {
textPacker.packString(text.name());
List<String> parts = compiled.text2parts.get(text.name());
textPacker.packArrayHeader(parts.size());
for (String part : parts) {
textPacker.packString(part);
}
}
packer.packInt((int)textPacker.getTotalWrittenBytes());
packer.addPayload(textPacker.toByteArray());
} catch (IOException e) {
throw new IOError(e);
}
}
private static void encodeLayerData(MessagePacker packer, Layer layer, List<String> fields) {
try {
MessageBufferPacker layerPacker = MessagePack.newDefaultBufferPacker();
Schema.Layer schema = layer.schema();
ValueWriter writer = new ValueWriter(layerPacker);
layerPacker.packInt(layer.size());
for (String field : fields) {
DataType dataType = schema.fields().get(field);
layerPacker.packBoolean(false); //Future improvement of encoding!
switch (dataType.name()) {
case SPAN:
layerPacker.packArrayHeader(layer.size()*2);
for (Node node : layer) {
Value spanValue = node.get(field);
if(spanValue instanceof NullValue) {
layerPacker.packNil();
layerPacker.packNil();
} else {
Span span = spanValue.spanValue();
layerPacker.packInt(span.startOffset().id);
layerPacker.packInt(span.stopOffset().id);
}
}
break;
default:
layerPacker.packArrayHeader(layer.size());
try {
for (Node node : layer) {
node.get(field).visit(writer);
}
} catch (RuntimeException e) {
throw new RuntimeException(String.format("When processing column %s in layer %s", field, layer.name()), e);
}
break;
}
}
packer.packInt((int)layerPacker.getTotalWrittenBytes());
packer.addPayload(layerPacker.toByteArray());
} catch (IOException e) {
throw new IOError(e);
}
}
public static MessageBuffer encode(Document document) {
try {
document.validateSchema();
MessageBufferPacker packer = MessagePack.newDefaultBufferPacker();
Document.Compiled compiled = document.compile();
//1. Write header
packer.writePayload("DM_1".getBytes());
//2. Write properties
encodeProperties(document, packer);
List<String> types = new ArrayList<>();
Map<String,List<String>> types2columns = new TreeMap<>();
//3. Write schema
encodeSchema(document, packer, types, types2columns);
//4. Write texts
encodeTexts(compiled, document, packer);
//5. Write Layer data
for (String type : types) {
encodeLayerData(packer, document.layer(type), types2columns.get(type));
}
return packer.toMessageBuffer();
} catch (IOException e) {
throw new IOError(e);
}
}
public static Document decode(byte[] data) {
MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(data);
return decode(unpacker, null);
}
public static Document decode(byte[] data, Map<String,NodeFactory> nodeFactories) {
MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(data);
return decode(unpacker, nodeFactories);
}
protected static Map<String,Value> decodeProperties(MessageUnpacker unpacker) throws IOException {
int compartmentSize = unpacker.unpackInt();
TreeMap<String, Value> props = new TreeMap<>();
int numEntries = unpacker.unpackMapHeader();
for(int k = 0; k < numEntries; k++) {
String key = unpacker.unpackString();
ImmutableValue value = unpacker.unpackValue();
switch (value.getValueType()) {
case STRING:
props.put(key, Values.get(value.asStringValue().toString()));
break;
case BOOLEAN:
props.put(key, Values.get(value.asBooleanValue().getBoolean()));
break;
case INTEGER:
ImmutableIntegerValue ivalue = value.asIntegerValue();
if(ivalue.isInIntRange())
props.put(key, Values.get(ivalue.toInt()));
else
props.put(key, Values.get(ivalue.toLong()));
break;
case FLOAT:
props.put(key, Values.get(value.asFloatValue().toDouble()));
break;
case BINARY:
props.put(key, Values.get(value.asBinaryValue().asByteArray()));
break;
case EXTENSION:
if(value.asExtensionValue().getType() == 0) {
MessageUnpacker extensionData = MessagePack.newDefaultUnpacker(value.asExtensionValue().getData());
String type = extensionData.unpackString();
switch (type) {
case "doc":
props.put(key, new DocumentValue(extensionData.unpackValue().asBinaryValue().asByteArray()));
break;
default:
props.put(key, new ExtensionValue(type, extensionData.unpackValue().asBinaryValue().asByteArray()));
break;
}
}
else
throw new UnsupportedOperationException(
"Unsupported extension type: " + value.asExtensionValue().getType() + " for property key: " + key);
default:
throw new UnsupportedOperationException(
"Unsupported property type: " + value.getValueType().toString());
}
}
return props;
}
protected static Schema decodeSchema(
MessageUnpacker unpacker,
Map<String,NodeFactory> nodeFactories,
List<String> types,
Map<String,List<String>> types2fields
) throws IOException {
Schema schema = new Schema();
int numLayers = unpacker.unpackArrayHeader();
for(int i = 0; i < numLayers; i++)
types.add(unpacker.unpackString());
for (String layerName : types) {
List<String> fields = new ArrayList<>();
int numFields = unpacker.unpackInt();
Schema.LayerBuilder layerBuilder = Schema.layer(layerName);
for(int i = 0; i < numFields; i++) {
String fieldName = unpacker.unpackString();
boolean extendedType = unpacker.unpackBoolean();
DataType dtype;
String typeName = unpacker.unpackString();
if(extendedType) {
TreeMap<String,Value> args = new TreeMap<>();
int numEntries = unpacker.unpackMapHeader();
for(int k = 0; k < numEntries; k++) {
String key = unpacker.unpackString();
ImmutableValue value = unpacker.unpackValue();
switch (value.getValueType()) {
case STRING:
args.put(key, Values.get(value.asStringValue().toString()));
break;
case BOOLEAN:
args.put(key, Values.get(value.asBooleanValue().getBoolean()));
break;
case INTEGER:
ImmutableIntegerValue ivalue = value.asIntegerValue();
if(ivalue.isInIntRange())
args.put(key, Values.get(ivalue.toInt()));
else
args.put(key, Values.get(ivalue.toLong()));
break;
case FLOAT:
args.put(key, Values.get(value.asFloatValue().toFloat()));
break;
case BINARY:
args.put(key, Values.get(value.asBinaryValue().asByteArray()));
break;
default:
throw new UnsupportedOperationException(
"Unsupported layer type argument: " + value.getValueType().toString());
}
}
dtype = new DataType.Builder(DataTypeName.from(typeName), args).build();
} else {
switch (DataTypeName.from(typeName)) {
case BINARY:
dtype = DataTypes.BINARY;
break;
case STRING:
dtype = DataTypes.STRING;
break;
case BOOL:
dtype = DataTypes.BOOLEAN;
break;
case DOUBLE:
dtype = DataTypes.FLOAT_64;
break;
case INT:
dtype = DataTypes.INT_32;
break;
case LONG:
dtype = DataTypes.INT_64;
break;
default:
throw new UnsupportedOperationException("Unsupported layer type: " + fieldName);
}
}
fields.add(fieldName);
layerBuilder.addField(fieldName, dtype);
}
types2fields.put(layerName, fields);
if(nodeFactories != null && nodeFactories.containsKey(layerName)) {
layerBuilder.setFactory(nodeFactories.get(layerName));
}
schema.add(layerBuilder.build());
}
return schema;
}
protected static Map<String, List<Offset>> decodeTexts(Document doc, MessageUnpacker unpacker) throws IOException {
TreeMap<String,List<Offset>> text2offsets = new TreeMap<>();
int sz = unpacker.unpackInt();
int numTexts = unpacker.unpackMapHeader();
for(int i = 0; i < numTexts; i++) {
String context = unpacker.unpackString();
int numParts = unpacker.unpackArrayHeader();
StringBuilder sb = new StringBuilder();
int offset = 0;
List<Offset> offsets = new ArrayList<>(numParts);
offsets.add(new Offset(0));
for(int k = 0; k < numParts; k++) {
String part = unpacker.unpackString();
sb.append(part);
offset = sb.length();
offsets.add(new Offset(offset));
}
Text text = new Text(context, sb.toString());
text.initializeOffsets(offsets);
doc.add(text);
text2offsets.put(context, offsets);
}
return text2offsets;
}
protected static class NodeArrayPlaceholder extends Value {
private int[] nodeIds;
public NodeArrayPlaceholder(int[] nodeIds) {
this.nodeIds = nodeIds;
}
@Override
public String stringValue() {
return null;
}
@Override
public DataType type() {
throw new UnsupportedOperationException();
}
}
protected static class NodeSpanPlaceholder extends Value {
private int left;
private int right;
public NodeSpanPlaceholder(int left, int right) {
this.left = left;
this.right = right;
}
@Override
public String stringValue() {
return null;
}
@Override
public DataType type() {
throw new UnsupportedOperationException();
}
}
protected static void decodeLayer(Document document, Layer layer, List<String> fields, Map<String, List<Offset>> offsets, MessageUnpacker unpacker) throws IOException {
int layer_sz = unpacker.unpackInt();
int numNodes = unpacker.unpackInt();
Schema.Layer schema = layer.schema();
ArrayList<Node> nodes = new ArrayList<>(numNodes);
for (int i = 0; i < numNodes; i++) {
nodes.add(layer.create().insert());
}
for (String field : fields) {
DataType fieldType = schema.getFieldType(field);
boolean specialized = unpacker.unpackBoolean();
if(specialized)
throw new UnsupportedOperationException("Specialized encoding not yet implemented.");
int numElements = unpacker.unpackArrayHeader();
switch (fieldType.name()) {
case INT:
case NODE: //Serialized, only ints are used to reference nodes.
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, unpacker.unpackInt());
}
}
break;
case DOUBLE:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, unpacker.unpackDouble());
}
}
break;
case STRING:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, unpacker.unpackString());
}
}
break;
case LONG:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, unpacker.unpackLong());
}
}
break;
case BOOL:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, unpacker.unpackBoolean());
}
}
break;
case BINARY:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
int numBytes = unpacker.unpackArrayHeader();
nodes.get(k).put(field, unpacker.readPayload(numBytes));
}
}
break;
case SPAN:
String context = fieldType.args().get("context").stringValue();
List<Offset> contextOffsets = offsets.get(context);
Text txt = document.text(context);
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
int startOffset = unpacker.unpackInt();
int stopOffset = unpacker.unpackInt();
nodes.get(k).put(field,
txt.unsafeSpanFromOffset(
contextOffsets.get(startOffset)
, contextOffsets.get(stopOffset)));
} else {
unpacker.unpackNil();
}
}
break;
case EXT:
String type = fieldType.args().get("type").stringValue();
if(type.equals("doc")) {
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, new DocumentValue(unpacker.unpackValue().asBinaryValue().asByteArray()));
}
}
} else {
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
nodes.get(k).put(field, new ExtensionValue(type, unpacker.unpackValue().asBinaryValue().asByteArray()));
}
}
}
break;
case NODE_ARRAY:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
int numNodeEntries = unpacker.unpackArrayHeader();
int[] nodeIds = new int[numNodeEntries];
for (int j = 0; j < numNodeEntries; j++) {
nodeIds[j] = unpacker.unpackInt();
}
nodes.get(k).put(field, new NodeArrayPlaceholder(nodeIds));
}
}
break;
case NODE_SPAN:
for (int k = 0; k < numNodes; k++) {
if(!unpacker.tryUnpackNil()) {
int nh = unpacker.unpackArrayHeader();
assert nh == 2;
int left = unpacker.unpackInt();
int right = unpacker.unpackInt()+left;
nodes.get(k).put(field, new NodeSpanPlaceholder(left, right));
}
}
break;
default:
throw new UnsupportedOperationException("Field type not yet implemented: " + fieldType.name().getName());
}
}
}
protected static void resolveReferences(Document document, Layer layer) {
Schema.Layer schema = layer.schema();
for (Map.Entry<String, DataType> entry : schema.fields().entrySet()) {
String field = entry.getKey();
switch (entry.getValue().name()) {
case NODE: {
String targetLayerName = entry.getValue().args().get("layer").stringValue();
Layer targetLayer = document.layer(targetLayerName);
layer.forEach(n -> {
if (n.has(field)) {
int nodeId = n.get(field).intValue();
n.put(field, targetLayer.get(nodeId));
}
});
break;
}
case NODE_ARRAY: {
String targetLayerName = entry.getValue().args().get("layer").stringValue();
Layer targetLayer = document.layer(targetLayerName);
layer.forEach(n -> {
if (n.has(field)) {
int[] nodeIds = ((NodeArrayPlaceholder) n.get(field)).nodeIds;
Node[] nodes = new Node[nodeIds.length];
for (int k = 0; k < nodeIds.length; k++) {
nodes[k] = targetLayer.get(nodeIds[k]);
}
n.put(field, nodes);
}
});
break;
}
case NODE_SPAN: {
String targetLayerName = entry.getValue().args().get("layer").stringValue();
Layer targetLayer = document.layer(targetLayerName);
layer.forEach(n -> {
if (n.has(field)) {
NodeSpanPlaceholder placeholder = (NodeSpanPlaceholder)n.get(field);
Node left = targetLayer.get(placeholder.left);
Node right = targetLayer.get(placeholder.right);
n.put(field, new NodeSpan(left, right));
}
});
break;
}
}
}
}
public static Document decode(MessageUnpacker unpacker, Map<String,NodeFactory> nodeFactories) {
try {
byte[] header = unpacker.readPayload(4);
if(Arrays.equals(header, "DM_1".getBytes())) {
// 1. Decode properties
Map<String,Value> values = decodeProperties(unpacker);
List<String> types = new ArrayList<>();
Map<String,List<String>> types2columns = new TreeMap<>();
// 2. Decode Schema
Schema schema = decodeSchema(unpacker, nodeFactories, types, types2columns);
Document doc = new Document(schema);
doc.props().putAll(values);
// 3. Decode texts
Map<String, List<Offset>> offsets = decodeTexts(doc, unpacker);
// 4. Decode layer data
for (String type : types) {
decodeLayer(doc, doc.layer(type), types2columns.get(type), offsets, unpacker);
}
// 5. Resolve node references and replace placeholders with real node objects.
for (String type : types)
resolveReferences(doc, doc.layer(type));
return doc;
}
else {
throw new IOError(new UnsupportedOperationException("Unsupported document, header does not match expected values: " + new String(header, StandardCharsets.ISO_8859_1)));
}
} catch (IOException e) {
throw new IOError(e);
}
}
}
| 37.622706
| 184
| 0.47752
|
fbdcb078f572a4b0880c9511356e82a3b55061e7
| 303
|
import otherStuff.*;
import java.util.*;
/**
* Does everything
*
* @author Aristocrates, barbecue chef / j̶a̶r̶g̶o̶n̶ ̶s̶p̶o̶u̶t̶i̶n̶g̶ ̶m̶a̶n̶i̶a̶c̶
* part time philosopher
* @version sin(π/2)
*/
public class Main implements Constants
{
public static void main(String[] args)
{
}
}
| 18.9375
| 86
| 0.623762
|
49faca65beb02402891c284a9f6bd2d28654a659
| 214
|
package multiplicity3.csys.items.keyboard.model;
/**
* The Enum KeyModifiers.
*/
public enum KeyModifiers
{
/** The alt. */
ALT,
/** The ctl. */
CTL,
/** The none. */
NONE,
/** The shift. */
SHIFT
}
| 10.190476
| 48
| 0.584112
|
003e3b8cc84d51973b9cb57e576af8bf7c7cff33
| 1,752
|
package de.raik.reporting.spigot;
import de.raik.reporting.spigot.command.ReportCommand;
import org.bukkit.plugin.java.JavaPlugin;
import java.net.URI;
import java.net.http.HttpRequest;
import java.util.Objects;
/**
* The jave plugin needed by spigot to setup
* everything for minecraft
*/
public class ReportPlugin extends JavaPlugin {
/**
* The start string of the uri to
* set builder
*/
private String startURIString;
private String authToken = "Basic ";
/**
* On enable setting up the plugin
*/
@Override
public void onEnable() {
this.saveDefaultConfig();
//Setting start url asserting as it's required to be not null
this.startURIString = this.getConfig().getString("microservice.urn");
assert this.startURIString != null;
this.startURIString = this.startURIString.endsWith("/") ? this.startURIString : this.startURIString + "/";
//Setting auth token
this.authToken += this.getConfig().getString("microservice.authKey");
//Set up command
ReportCommand reportCommand = new ReportCommand(this);
Objects.requireNonNull(this.getCommand("report")).setExecutor(reportCommand);
this.getCommand("report").setTabCompleter(reportCommand);
}
/**
* Method returning already created builder
* with uri and authorization to only set request specific
* stuff in command
*
* @param urlPath The sub path of the url
* @return The prepared builder
*/
public HttpRequest.Builder getPreDefinedHttpBuilder(String urlPath) {
return HttpRequest.newBuilder(URI.create(this.startURIString + urlPath))
.header("Authorization", this.authToken);
}
}
| 30.206897
| 114
| 0.678653
|
ef95ff2b888f96b1ab0770dcfa604ecf3200655b
| 1,232
|
package com.legyver.fenxlib.skins.number;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Skin to auto-append a percent symbol to a number.
*/
public class PercentageFieldSkin extends AbstractNumberSkin {
/**
* Construct a Skin for a Percentage field that appends a percent symbol to the number
* @param skinnable the number field to skin
*/
public PercentageFieldSkin(SkinnableNumberField skinnable) {
super(skinnable, false);
}
@Override
protected DecimalFormat getFormatter(Locale locale) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getPercentInstance(locale);
formatter.setParseBigDecimal(true);
return formatter;
}
@Override
protected String getSymbol(DecimalFormat formatter) {
return "%";
}
@Override
protected Runnable getRunLater(SkinnableNumberField skinnable, DecimalFormat formatter) {
return new Runnable() {
@Override
public void run() {
int caretPosition = skinnable.getCaretPosition();
skinnable.appendText("%");
skinnable.positionCaret(caretPosition);
}
};
}
@Override
protected boolean validateTrailing(DecimalFormat formatter, String text, int decimalSeparatorIndex) {
return true;
}
}
| 24.64
| 102
| 0.758929
|
e45394794772fb90da362e4722f20264885de247
| 672
|
/*
* All content copyright http://www.j2eefast.com, unless
* otherwise indicated. All rights reserved.
* No deletion without permission
*/
package com.j2eefast.common.core.base.entity.annotaion;
import com.j2eefast.common.core.enums.ConvertType;
import java.lang.annotation.*;
/**
* 控制实体类Page分页-字段输出
* @author huanzhou
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JsonListFiledIgnore {
ConvertType convert() default ConvertType.EMPTY;
/**
* 默认不输出
* @return
*/
boolean exist() default true;
/**
* 字段对象需要输出的字段
* @return
*/
String[] objectFiled() default {};
}
| 19.2
| 56
| 0.686012
|
793476484d2a4fdbcf74c2d719915e743ee42cc1
| 14,800
|
package com.tachyon.techlabs.iplauction;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.tachyon.techlabs.iplauction.adapter.MyTeamDataAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class MyTeamActivity extends AppCompatActivity {
FirebaseFirestore db = FirebaseFirestore.getInstance();
String team_name;
FirebaseStorage storage=FirebaseStorage.getInstance();
StorageReference storageRef=storage.getReference();
FirebaseAuth mAuth;
FirebaseUser currentUser;
String userEmail;
ImageView team_img_view;
List<String> list;
int bought,total;
String [] playernameArray;
long [] playerpriceArray;
RecyclerView my_players_view;
int sizes , index;
RecyclerView.LayoutManager layoutManager;
Context context;
int point1,point2,point3;
String id,story;
int phasestate,playerpos;
Map<String,Object> playersData = new HashMap<>();
List<String> playerKey = new ArrayList<>();
List<Long> playerValue = new ArrayList<>();
SharedPreferences sp;
SharedPreferences.Editor ed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_team);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
userEmail = Objects.requireNonNull(currentUser).getEmail();
sp= getApplicationContext().getSharedPreferences("Story", 0); // 0 - for private mode
if(Build.VERSION.SDK_INT>22)
{
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.white));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
my_players_view = findViewById(R.id.my_team_recycler_view);
team_img_view = findViewById(R.id.my_team_img);
context = getApplicationContext();
layoutManager = new LinearLayoutManager(context);
my_players_view.setLayoutManager(layoutManager);
getTeamImg();
}
public void showAlert(int position, final Context c)
{
playerpos = position;
}
public void getTeamImg()
{
DocumentReference team_img_doc = db.collection("Players").document(userEmail);
team_img_doc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists())
{
try
{
team_name = documentSnapshot.getString("myteam");
id = documentSnapshot.getString("roomid");
//Log.d("qwertyuiop",team_name);
getStoryline();
getPhaseState();
setTeamImg();
}
catch(Exception exp)
{
//String error = exp.toString();
// Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void getStoryline()
{
DocumentReference phase_doc = db.collection(id).document("Story");
phase_doc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists())
{
try
{
story = Objects.requireNonNull(documentSnapshot.getString("story"));
Log.d("storyline",story);
ed=sp.edit();
ed.putString("Story",story);
ed.commit();
}
catch(Exception e)
{
// Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void getPhaseState()
{
DocumentReference phase_doc = db.collection(id).document("State");
phase_doc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists())
{
try
{
phasestate = Objects.requireNonNull(documentSnapshot.getLong("phase")).intValue();
Log.d("phasestate",phasestate+"");
}
catch(Exception e)
{
//Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void setTeamImg()
{
// switch (team_name)
// {
// case "MI":
// get_team_img(team_name);
// break;
// // team_img_view.setBackground(getDrawable(R.drawable.mumbai_indians_min));
//
// case "CSK": //team_img_view.setBackground(getDrawable(R.drawable.csk));
// get_team_img(team_name);
// break;
// case "KKR": //team_img_view.setBackground(getDrawable(R.drawable.kkr));
// Glide.with(this).load(userphoto).into(team_img_view);
// break;
// case "RR": //team_img_view.setBackground(getDrawable(R.drawable.mumbai_indians_min));
// Glide.with(this).load(userphoto).into(team_img_view);
// break;
// case "RCB":
// Glide.with(this).load(userphoto).into(team_img_view);
// // team_img_view.setBackground(getDrawable(R.drawable.rcb));
// break;
// case "DC": Glide.with(this).load(userphoto).into(team_img_view);
// break;
// case "KXIP": //team_img_view.setBackground(getDrawable(R.drawable.kings11_min));
// Glide.with(this).load(userphoto).into(team_img_view);
// break;
// case "GL":// team_img_view.setBackground(getDrawable(R.drawable.mumbai_indians_min));
// Glide.with(this).load(userphoto).into(team_img_view);
// break;
// case "SH": //team_img_view.setBackground(getDrawable(R.drawable.mumbai_indians_min));
// Glide.with(this).load(userphoto).into(team_img_view);
// break;
// case "RPS": //team_img_view.setBackground(getDrawable(R.drawable.mumbai_indians_min));
// Glide.with(this).load(userphoto).into(team_img_view);
// break;
// }
//
get_team_img(team_name);
getPlayerBoughtNum();
}
private void get_team_img(String team_name) {
try
{
storageRef.child(team_name+".png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// Log.d("playerimg",uri.toString());
Glide.with(MyTeamActivity.this).load(uri).into(team_img_view);
//GlideApp.with(OngoingPlayer.this).load(storageRef).into(player_img);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Log.d("playerimg","fail");
// Toast.makeText(this, "Not able to load player image", Toast.LENGTH_SHORT).show();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void getPlayerBoughtNum()
{
DocumentReference get_num_doc = db.collection("Players").document(userEmail);
get_num_doc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists())
{
try
{
bought = Objects.requireNonNull(documentSnapshot.getLong("players_bought")).intValue();
getListOfPlayers();
}
catch(Exception e)
{
//Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void getListOfPlayers()
{
/*
db.collection("Players").document(userEmail).collection("MyTeam")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
try
{
list = new ArrayList<>();
for(QueryDocumentSnapshot documentSnapshot : Objects.requireNonNull(task.getResult()))
{
list.add(documentSnapshot.getId());
}
total = list.size();
//Log.d("qwertyuiop",total+"");
playernameArray = new String[bought];
playerpriceArray = new long[bought];
setListOfPlayers(0);
}
catch(Exception ex)
{
Toast.makeText(context, ex.toString(), Toast.LENGTH_SHORT).show();
}
}
}
});
*/
db.collection("Players").document(userEmail).collection("MyTeam").document("1").get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
try
{
playersData = documentSnapshot.getData();
for(Map.Entry<String,Object> entry : Objects.requireNonNull(playersData).entrySet())
{
playerKey.add(entry.getKey());
String v = String.valueOf(entry.getValue());
playerValue.add(Long.parseLong(v));
}
playernameArray = new String[playerKey.size()];
playernameArray = playerKey.toArray(playernameArray);
showPLayerData(story);
//playerpriceArray = new long[playerValue.size()];
//playerpriceArray = playerValue.toArray(playerpriceArray);
//total = list.size();
//playernameArray = new String[bought];
//playerpriceArray = new long[bought];
//setListOfPlayers(0);
Log.d("playerdata",Objects.requireNonNull(playerKey).toString());
Log.d("playerdata",Objects.requireNonNull(playerValue).toString());
}
catch(Exception e)
{
// Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void setListOfPlayers(int size)
{
index = size ;
sizes = size+1;
final String num = sizes+"";
DocumentReference setplayer_doc = db.collection("Players").document(userEmail).collection("MyTeam").document(num);
setplayer_doc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists())
{
try
{
String n = documentSnapshot.getString("1");
//Log.d("qwertyuiop",n);
Long l = Long.parseLong(documentSnapshot.getString("2"));
playernameArray[index] = n;//documentSnapshot.getString("1");
playerpriceArray[index] = l;//Long.parseLong(documentSnapshot.getString("2"));
//Toast.makeText(MyTeamActivity.this, playernameArray[index], Toast.LENGTH_SHORT).show();
if(index<bought-1)
{
setListOfPlayers(index+1);
}
else
{
//showPLayerData();
}
}
catch(Exception exp)
{
// Toast.makeText(context, exp.toString(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void showPLayerData(String sto)
{
//Log.d("storyadapter",sto);
MyTeamDataAdapter myTeamDataAdapter = new MyTeamDataAdapter(getApplicationContext(),playernameArray,playerValue,getResources(),id,story,phasestate,team_name);
my_players_view.setAdapter(myTeamDataAdapter);
}
}
| 38.541667
| 166
| 0.536351
|
029589d95cdc8065f32206cb864a887d59de0b8c
| 1,199
|
package com.ppdai.das.console.enums;
public enum AttributesEnum {
AUTO_RELOAD_DISENABLED(0, "false", "项目自动不reload"),
AUTO_RELOAD_ENABLED(1, "true", "项目自动reload");
private Integer type;
private String name;
private String description;
AttributesEnum(Integer type, String name, String description) {
this.type = type;
this.name = name;
this.description = description;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public static AttributesEnum getPatternTypeEnumByType(int type) {
for (AttributesEnum item : AttributesEnum.values()) {
if (type == item.type) {
return item;
}
}
throw new EnumConstantNotPresentException(AttributesEnum.class, "type " + type + " is not exist!!");
}
}
| 23.057692
| 108
| 0.612177
|
c1cacdeee1b8155abd4b3b0ac6d47e2d7900edc4
| 787
|
// WARNING: THIS FILE IS MANAGED BY SPRING ROO.
package com.packtpub.springsecurity.events.client.proxy;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyForName;
import org.springframework.roo.addon.gwt.RooGwtProxy;
@ProxyForName(value = "com.packtpub.springsecurity.events.server.domain.Event", locator = "com.packtpub.springsecurity.events.server.locator.EventLocator")
@RooGwtProxy(value = "com.packtpub.springsecurity.events.server.domain.Event", readOnly = { "version", "id" }, scaffold = true)
public interface EventProxy extends EntityProxy {
abstract Long getId();
abstract String getDescription();
abstract void setDescription(String description);
abstract Integer getVersion();
}
| 37.47619
| 155
| 0.787802
|
161f3b00e92bc2eb28e1c049e792d9205460eec1
| 161
|
package org.simplify4u.plugins;
class MainTest {
public static void main(String[] args) {
System.out.println("This is a fake test class.");
}
}
| 20.125
| 57
| 0.658385
|
3a8caa5073005cac2e14e681936c7a72acf574e4
| 1,118
|
/*
* 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 eapli.base.export;
import java.util.logging.Level;
import java.util.logging.Logger;
import eapli.base.AppSettings;
import eapli.base.Application;
import eapli.base.messagesmanagement.application.ImportMessagesFactory;
/**
*
* @author Utilizador
*/
public class InformationExporterFactory {
private static final AppSettings SETTINGS = Application.settings();
public InformationExporter build(String format) {
String formatTemp=format.substring(format.length()-3).toLowerCase();
InformationExporter exporter=null;
try {
exporter = (InformationExporter) Class.forName(SETTINGS.getProperty(formatTemp)).newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NullPointerException ex) {
Logger.getLogger(ImportMessagesFactory.class.getName()).log(Level.SEVERE, null, ex);
}
return exporter;
}
}
| 32.882353
| 118
| 0.736136
|
e22d0551906463c110400c396e0cdbb1725eb59e
| 6,144
|
package com.example.qwim.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.example.qwim.R;
import com.example.qwim.adapter.ConversationAdapter;
import com.example.qwim.adapter.IMultipleItem;
import com.example.qwim.adapter.OnRecyclerViewListener;
import com.example.qwim.bean.Conversation;
import com.example.qwim.bean.PrivateConversation;
import com.example.qwim.event.RefreshEvent;
import com.example.qwim.ui.AddFriendActivity;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
/**
* Created by qikaixuan on 17-4-17.
*/
public class ConversationFragment extends Fragment {
private ConversationAdapter mAdapter;
private SwipeRefreshLayout mSwipe;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true); // 配置Actionbar可先的属性
View view = inflater.inflate(R.layout.conversation_fragment, container, false);
mSwipe = (SwipeRefreshLayout) view.findViewById(R.id.conversation_swipe);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.conversation_recycler);
IMultipleItem<Conversation> multipleItem = new IMultipleItem<Conversation>() {
@Override
public int getItemLayoutId(int viewtype) {
return R.layout.item_conversation;
}
@Override
public int getItemViewType(int postion, Conversation conversation) {
return 0;
}
@Override
public int getItemCount(List<Conversation> list) {
return list.size();
}
};
mAdapter = new ConversationAdapter(getContext(), multipleItem, null);
recyclerView.setAdapter(mAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
mSwipe.setEnabled(true);
setListener();
return view;
}
private void setListener() {
mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
query();
}
});
mAdapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
@Override
public void onItemClick(int position) {
mAdapter.getItem(position).onClick(getActivity());
}
@Override
public boolean onItemLongClick(int position) {
mAdapter.getItem(position).onLongClick(getActivity());
mAdapter.remove(position);
return true;
}
});
}
/**
查询本地会话
*/
public void query(){
mAdapter.bindDatas(getConversations());
mAdapter.notifyDataSetChanged();
mSwipe.setRefreshing(false);
}
/**
* 获取会话列表的数据:增加新朋友会话
* @return
*/
private List<Conversation> getConversations(){
//添加会话
List<Conversation> conversationList = new ArrayList<>();
conversationList.clear();
List<BmobIMConversation> list = BmobIM.getInstance().loadAllConversation();
if(list!=null && list.size()>0){
for (BmobIMConversation item:list){
switch (item.getConversationType()){
case 1://私聊
conversationList.add(new PrivateConversation(item));
break;
default:
break;
}
}
}
// //添加新朋友会话-获取好友请求表中最新一条记录
// List<NewFriend> friends = NewFriendManager.getInstance(getActivity()).getAllNewFriend();
// if(friends!=null && friends.size()>0){
// conversationList.add(new NewFriendConversation(friends.get(0)));
// }
//重新排序
Collections.sort(conversationList);
return conversationList;
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
/**注册自定义消息接收事件
* @param event
*/
@Subscribe
public void onEventMainThread(RefreshEvent event){
//因为新增`新朋友`这种会话类型
mAdapter.bindDatas(getConversations());
mAdapter.notifyDataSetChanged();
}
/**注册离线消息接收事件
* @param event
*/
public void onEventMainThread(OfflineMessageEvent event){
//重新刷新列表
mAdapter.bindDatas(getConversations());
mAdapter.notifyDataSetChanged();
}
/**注册消息接收事件
* @param event
* 1、与用户相关的由开发者自己维护,SDK内部只存储用户信息
* 2、开发者获取到信息后,可调用SDK内部提供的方法更新会话
*/
@Subscribe
public void onEventMainThread(MessageEvent event){
//重新获取本地消息并刷新列表
mAdapter.bindDatas(getConversations());
mAdapter.notifyDataSetChanged();
}
//toolbar选项
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_add,menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
startActivity(new Intent(getContext(), AddFriendActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
| 31.187817
| 103
| 0.644043
|
24e0cd5b79f663e1f4ea03015a81ad3b68307b78
| 328
|
package org.bookshop.system.bookshopsystem.repositories;
import org.bookshop.system.bookshopsystem.models.entities.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoryRepository extends JpaRepository<Category,Long> {
}
| 32.8
| 74
| 0.859756
|
d83c162f029845937d86a9021d80df915e310068
| 1,426
|
package ro.atrifan.client.http.util;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
public class HTTPResponse {
private int code;
private String body;
private Set headers;
private long runningTime;
private int contentLength;
private HTTPMethod method;
public HTTPResponse(HTTPMethod method) {
this.method = method;
this.runningTime = -1L;
}
public int getCode() {
return code;
}
void setCode(int code) {
this.code = code;
}
public String getBody() {
return body;
}
void setBody(String body) {
this.body = body;
}
public NameValuePair[] getHeaders() {
NameValuePair[] headers = new NameValuePair[this.headers.size()];
this.headers.toArray(headers);
return headers;
}
void setHeaders(NameValuePair[] headers) {
if (headers == null) {
this.headers = new LinkedHashSet(Arrays.asList(headers));
}
}
public HTTPMethod getMethod() {
return method;
}
public long getRunningTime() {
return this.runningTime;
}
public void setRunningTime(long runningTime) {
this.runningTime = runningTime;
}
public int getContentLength() {
return contentLength;
}
void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
}
| 21.283582
| 73
| 0.621318
|
cc3a80107b2c73012cb41594c9f880d3ebfd298f
| 673
|
package com.mhemmings.lsstorage.test;
import com.mhemmings.lsstorage.LSDatabase;
import com.mhemmings.lsstorage.LSObject;
import com.mhemmings.lsstorage.LSTable;
public class MyDatabase extends LSDatabase {
public static final LSTable<Car> carTable = new CarTable();
public static final LSTable<Manufacturer> manufacturerTable = new ManufacturerTable();
public MyDatabase() {
super("CarsDatabase", 1);
}
@Override
public LSTable<LSObject>[] tables() {
return new LSTable[] { carTable, manufacturerTable };
}
@Override
public String[] onUpgrade(int oldVersion) {
String sql[] = new String[0];
switch (oldVersion) {
case 1:
}
return sql;
}
}
| 20.393939
| 87
| 0.736999
|
ebbe9fe8d97717dfb0af4293d6ddddec76f27c7e
| 214
|
package cl.tiocomegfas.library.hardware.exception;
public class GpsException extends RuntimeException{
public GpsException() {
}
public GpsException(String message) {
super(message);
}
}
| 17.833333
| 51
| 0.705607
|
606c3a3293145a2d4fe00ad7d944531b2c719482
| 2,756
|
package extensions;
import javafx.scene.Node;
import javafx.scene.web.WebView;
import util.PropertiesReader;
import java.io.File;
/**
* Class used for creating and managing webviews for the
* extensions added to the application. Note: This class
* cannot be directly added to a scene; the view component
* of the class can be obtained through the getView() method
*
* @author Walker Willetts
*/
public class ExtensionWebView {
/* Instance Variables */
private WebView myView;
/**
* Creates a new ExtensionWebView with no initial page loaded
* @param height is a {@code double} that specifies the held WebView's height
* @param width is a {@code double} that specifies the held WebView's width
*/
public ExtensionWebView(double height, double width) {
myView = new WebView();
myView.setPrefHeight(height);
myView.setPrefWidth(width);
}
/**
* Creates a new ExtensionWebView with the given page loaded
* @param page is a {@code String} representing the initial page to load
* into the WebView maintained by the ExtensionWebView
* @param height is a {@code double} that specifies the held WebView's height
* @param width is a {@code double} that specifies the held WebView's width
*/
public ExtensionWebView(String page, double height, double width) {
myView = new WebView();
myView.setPrefHeight(height);
myView.setPrefWidth(width);
loadHTML(page);
}
public void goForward() {
myView.getEngine().executeScript("history.forward()");
}
public void goBack() {
myView.getEngine().executeScript("history.back()");
}
/**
* Loads the specified html page into the WebView. If page is not contained
* within the resources/html/ directory then nothing will be loaded.
* @param page is a {@code String} representing the name of the file to load
*/
public void loadHTML(String page) {
File html = new File(PropertiesReader.path("html_files") + page);
if(html.exists()) myView.getEngine().load(html.toURI().toString());
}
/**
* Loads the given URL into the WebView
* @param url is a {@code String} specifying the appropriate URL to load
*/
public void loadSite(String url) {
myView.getEngine().load(url);
}
/**
* Sets the width of the held WebView to the given width
* @param width is a {@code double} specifying the new width of the WebView
*/
public void setWidth(double width) { myView.setPrefWidth(width); }
/**
* Sets the height of the held WebView to the given height
* @param height is a {@code double} specifying the new height of the WebView
*/
public void setHeight(double height) { myView.setPrefHeight(height); }
/**
* @return A {@code Node} object that displays the ExtensionWebView
*/
public Node getView() { return myView; }
}
| 30.622222
| 78
| 0.715167
|
700cfbea3d56f66f0cf8026cd190456587c80f55
| 5,994
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.systemtest.javafeedclient;
import ai.vespa.feed.client.FeedClient;
import ai.vespa.feed.client.FeedClientBuilder;
import ai.vespa.feed.client.OperationStats;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.yahoo.vespa.http.client.config.Cluster;
import com.yahoo.vespa.http.client.config.ConnectionParams;
import com.yahoo.vespa.http.client.config.Endpoint;
import com.yahoo.vespa.http.client.config.FeedParams;
import com.yahoo.vespa.http.client.config.SessionParams;
import javax.net.ssl.HostnameVerifier;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.logging.LogManager;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* @author bjorncs
*/
class Utils {
static {
// Disable java.util.logging
LogManager.getLogManager().reset();
}
static final HostnameVerifier TRUST_ALL_VERIFIER = (hostname, session) -> true;
private Utils() {}
static Path certificate() { return Paths.get(System.getProperty("vespa.test.feed.certificate")); }
static Path privateKey() { return Paths.get(System.getProperty("vespa.test.feed.private-key")); }
static Path caCertificate() { return Paths.get(System.getProperty("vespa.test.feed.ca-certificate")); }
static int connections() { return Integer.parseInt(System.getProperty("vespa.test.feed.connections")); }
static String route() { return System.getProperty("vespa.test.feed.route"); }
static URI endpoint() { return URI.create(System.getProperty("vespa.test.feed.endpoint")); }
static int documents() { return Integer.parseInt(System.getProperty("vespa.test.feed.documents")); }
static int warmupSeconds() { return Integer.parseInt(System.getProperty("vespa.test.feed.warmup.seconds")); }
static int benchmarkSeconds() { return Integer.parseInt(System.getProperty("vespa.test.feed.benchmark.seconds")); }
static int maxConcurrentStreamsPerConnection() {
return Integer.parseInt(System.getProperty("vespa.test.feed.max-concurrent-streams-per-connection"));
}
static String fieldsJson() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (JsonGenerator generator = new JsonFactory().createGenerator(out)) {
generator.writeStartObject();
generator.writeStringField("text", System.getProperty("vespa.test.feed.document-text"));
generator.writeEndObject();
generator.flush();
}
return out.toString(UTF_8);
}
static void printJsonReport(Duration duration, OperationStats stats, String loadgiver) throws IOException {
printJsonReport(duration, stats, loadgiver, System.out);
}
static void printJsonReport(Duration duration, OperationStats stats, String loadgiver, OutputStream out) throws IOException {
JsonFactory factory = new JsonFactory();
try (JsonGenerator generator = factory.createGenerator(out)) {
generator.writeStartObject();
generator.writeNumberField("feeder.runtime", duration.toMillis());
generator.writeNumberField("feeder.okcount", stats.successes());
generator.writeNumberField("feeder.errorcount", stats.exceptions() + stats.responses() - stats.successes());
generator.writeNumberField("feeder.exceptions", stats.exceptions());
generator.writeNumberField("feeder.bytessent", stats.bytesSent());
generator.writeNumberField("feeder.bytesreceived", stats.bytesReceived());
generator.writeNumberField("feeder.throughput", stats.successes() / (double) duration.toMillis() * 1000);
generator.writeNumberField("feeder.minlatency", stats.minLatencyMillis());
generator.writeNumberField("feeder.avglatency", stats.averageLatencyMillis());
generator.writeNumberField("feeder.maxlatency", stats.maxLatencyMillis());
generator.writeStringField("loadgiver", loadgiver);
generator.writeEndObject();
generator.flush();
}
}
static FeedClient createFeedClient() {
int connections = connections();
return FeedClientBuilder.create(endpoint())
.setMaxStreamPerConnection(maxConcurrentStreamsPerConnection())
.setConnectionsPerEndpoint(connections)
.setCaCertificatesFile(caCertificate())
.setCertificate(certificate(), privateKey())
.setHostnameVerifier(TRUST_ALL_VERIFIER)
.build();
}
static SessionParams createSessionParams() {
URI endpoint = endpoint();
return new SessionParams.Builder()
.setFeedParams(new FeedParams.Builder()
.setRoute(route())
.build())
.setConnectionParams(new ConnectionParams.Builder()
.setCaCertificates(caCertificate())
.setCertificateAndPrivateKey(privateKey(), certificate())
.setNumPersistentConnectionsPerEndpoint(connections())
.setHostnameVerifier(TRUST_ALL_VERIFIER)
.build())
.addCluster(new Cluster.Builder()
.addEndpoint(Endpoint.create(endpoint.getHost(), endpoint.getPort(), true))
.build())
.build();
}
}
| 50.369748
| 129
| 0.657491
|
c0c31b3de6f8afc1c4abece98a7ab6f22f8c0eac
| 609
|
package com.jspiders.ds.largestarray;
public class Largestelement {
public static int maxUsingIterator(int a[])
{
int max=a[0];
for(int i=0;i<a.length;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
return max;
}
public static int maxUsingRecurssion(int a[],int index)
{
int max=a[0];
if(a[index]>max)
{
max=a[index];
}
index++;
maxUsingRecurssion(a,index);
return max;
}
public static void main(String[] args) {
int a[] = {10,20,30};
maxUsingIterator(a);
int index = 0;
maxUsingRecurssion(a,index);
}
}
| 14.5
| 57
| 0.55665
|
1fd0a5c4825358fedb3ef85d1b9d401f86b13d5b
| 5,314
|
package is103.lostluggage;
import is103.lostluggage.Database.MyJDBC;
import is103.lostluggage.Model.User;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventType;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
/**
* Main class
*
* @author Michael de Boer
*
*/
public class MainApp extends Application {
private static BorderPane root;
public static int serviceChangeValue = 99;
//Database instance
private static MyJDBC DB;
public static String language = "english";
public static String currentView;
public static User currentUser = null;
public static Stage mainStage;
@Override
public void start(Stage stage) throws Exception {
//Method to set the db property
setDatabase("corendonlostluggage", "root", "admin");
//set root
root = FXMLLoader.load(getClass().getResource("/fxml/MainView.fxml"));
Scene mainScene = new Scene(root);
checkLoggedInStatus(currentUser);
mainScene.getStylesheets().add("/styles/Styles.css");
stage.setTitle("Corendon Lost Luggage");
stage.setScene(mainScene);
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
stage.setX(primaryScreenBounds.getMinX());
stage.setY(primaryScreenBounds.getMinY());
stage.setWidth(primaryScreenBounds.getWidth());
stage.setHeight(primaryScreenBounds.getHeight());
stage.setMinWidth(1000);
stage.setMinHeight(700);
Image logo = new Image("Images/Stage logo.png");
//Image applicationIcon = new Image(getClass().getResourceAsStream("Images/Logo.png"));
stage.getIcons().add(logo);
stage.show();
//Set the mainstage as a property
MainApp.mainStage = stage;
}
//methode voor het switchen van schermen
public static void switchView(String view) throws IOException {
//parent vanuit MainApp laden
Parent fxmlView;
if (language.equals("dutch")) {
ResourceBundle bundle = ResourceBundle.getBundle("resources.Bundle", new Locale("nl"));
fxmlView = FXMLLoader.load(MainApp.class.getResource(view), bundle);
} else {
ResourceBundle bundle = ResourceBundle.getBundle("resources.Bundle");
fxmlView = FXMLLoader.load(MainApp.class.getResource(view), bundle);
}
//scene zetten ( in Center van BorderPane )
//fxmlView.
root.setCenter(fxmlView);
}
public static File selectFileToSave(String defaultFileName) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Specify filename");
//todo: provide the file selection dialog to the user
File file = fileChooser.showSaveDialog(mainStage);
//File selected? return the file, else return null
if (file != null) {
return file;
} else {
return null;
}
}
//set the database instance
public static void setDatabase(String dbname, String user, String password) throws FileNotFoundException {
// //config file
// File file = new File("src/main/resources/config");
//
// //Scanner object
// Scanner input = new Scanner(file);
//
// String dbname = input.next();
// String user = input.next();
// String password = input.next();
//init db
MainApp.DB = new MyJDBC(dbname, user, password);
}
//method to connect to the database
public static MyJDBC getDatabase() {
return MainApp.DB;
}
public static String getLanguage() {
return language;
}
public static void checkLoggedInStatus(User user) throws IOException {
if (user != null) {
currentUser = user;
System.out.println(user);
if (user.getRole().equals("Administrator")) {
switchView("/Views/Admin/HomeUserView.fxml");
System.out.println("The correct user role is selected: " + user);
}
if (user.getRole().equals("Manager")) {
switchView("/Views/ManagerHomeView.fxml");
}
if (user.getRole().equals("Service")) {
switchView("/Views/Service/ServiceHomeView.fxml");
}
} else {
switchView("/Views/Admin/LogInView.fxml");
}
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 28.880435
| 110
| 0.640008
|
57c6849c930f0f4230d5b599649d52b02d92ac62
| 288
|
package cn.torna.web.controller.user.param;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* @author tanghc
*/
@Data
public class UpdateInfoParam {
@NotBlank(message = "nickname can not be null")
private String nickname;
private String email;
}
| 15.157895
| 51
| 0.722222
|
8fc04985aacf533e8ad7f1ed4788298c7d57d8e9
| 3,160
|
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc5756.RecinCrew2020.subsystems;
import org.usfirst.frc5756.RecinCrew2020.Robot;
import edu.wpi.first.wpilibj.command.Subsystem;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
/**
*
*/
public class PowerCellController extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public PowerCellController() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
//Robot.robotMap.powercellCollector.set(ControlMode.PercentOutput, 0);
//Robot.robotMap.powercellCollector.set(ControlMode.PercentOutput, 0);
Robot.robotMap.powercellShooter.set(0);
Robot.robotMap.powercellShooter2.set(0);
//Robot.robotMap.powercellFeeder.set(ControlMode.PercentOutput, 0);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
@Override
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
@Override
public void periodic() {
// Put code here to be run every loop
//TODO: Write else if for a powercellOuttakeButtonSlow, for feeding into low target
if (Robot.oi.powerCellWindowWhiperButton.get()) {
powercellIn(1.0);
//powerCellFeed(1);
powercellOut(0);
} else if (Robot.oi.powercellOuttakeButton.get()) {
powercellIn(0);
//powerCellFeed(0);
powercellOut(0.65);
} else {
powercellIn(0);
//powerCellFeed(0);
powercellOut(0);
}
}
public void powercellIn(double speed) {
//Robot.robotMap.powercellCollector.set(ControlMode.PercentOutput, -speed);
}
public void powerCellFeed(double speed) {
//Robot.robotMap.powercellFeeder.set(ControlMode.PercentOutput, speed);
}
public void powercellOut(double speed) {
Robot.robotMap.powercellShooter.set(-speed);
Robot.robotMap.powercellShooter2.set(speed);
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CMDPIDGETTERS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CMDPIDGETTERS
// Put methods for controlling this subsystem
// here. Call these from Commands.
}
| 31.287129
| 91
| 0.691456
|
5ed2c7db45e9ad6de7b1ee4764fe30456d916f3d
| 937
|
/*******************************************************************************
* Copyright (c) 2021 Microsoft Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*******************************************************************************/
package com.microsoft.java.lsif.core.internal.protocol;
import java.util.List;
import org.eclipse.lsp4j.Diagnostic;
public class DiagnosticResult extends Vertex {
private List<Diagnostic> result;
public DiagnosticResult(String id, List<Diagnostic> result) {
super(id, Vertex.DIAGNOSTICRESULT);
this.result = result;
}
public List<Diagnostic> getResult() {
return this.result;
}
}
| 29.28125
| 80
| 0.63714
|
57dee82b920a6de20b824e5b69784cf5c1ac0f42
| 2,486
|
package com.tencent.wxcloudrun.model;
import com.tencent.wxcloudrun.common.bean.BaseModel;
import com.tencent.wxcloudrun.util.Id;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
*
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user_record
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class UserRecord extends BaseModel {
/**
* Database Column Remarks:
* id
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.id
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
@Id(type = Id.Type.ID_WORKER)
private Long id;
/**
* Database Column Remarks:
* 创建时间
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.create_time
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
private Date createTime;
/**
* Database Column Remarks:
* 修改时间
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.update_time
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
private Date updateTime;
/**
* Database Column Remarks:
* 用户对应AppID
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.open_id
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
private String openId;
/**
* Database Column Remarks:
* 记录信息
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.record
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
private String record;
/**
* Database Column Remarks:
* 执行时间
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.execute_time
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
private Date executeTime;
/**
* Database Column Remarks:
* 是否删除
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_record.deleted
*
* @mbg.generated Mon Mar 14 10:26:52 CST 2022
*/
private Long deleted;
}
| 25.895833
| 77
| 0.649236
|
cbb14b78dcb5a4b035072459f994d944980d9fdb
| 3,300
|
package com.boohee.widgets;
import android.content.Context;
import android.os.Build.VERSION;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.boohee.api.StatusApi;
import com.boohee.database.OnePreference;
import com.boohee.one.R;
import com.boohee.one.http.JsonCallback;
import com.boohee.utils.Helper;
import org.json.JSONObject;
public class CheckView extends RelativeLayout {
@InjectView(2131429211)
Button btnPos;
private Context mContext;
private LayoutParams mLp;
private WindowManager mWindowManager;
@InjectView(2131429208)
TextView txtMsg;
@InjectView(2131429207)
TextView txtTitle;
public CheckView(Context context) {
this(context, null);
}
public CheckView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CheckView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
init();
}
private void init() {
this.mWindowManager = (WindowManager) this.mContext.getSystemService("window");
LayoutInflater.from(getContext()).inflate(R.layout.oi, this);
ButterKnife.inject((View) this);
}
public void attachToWindow() {
if (getParent() == null) {
this.mLp = new LayoutParams();
if (VERSION.SDK_INT >= 19) {
this.mLp.type = 2005;
} else {
this.mLp.type = 2002;
}
this.mLp.format = 1;
this.mLp.flags = 40;
this.mLp.gravity = 8388659;
this.mLp.width = -1;
this.mLp.height = -2;
this.mLp.x = 0;
this.mLp.y = 0;
this.mWindowManager.addView(this, this.mLp);
}
}
@OnClick({2131429211})
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_pos:
postCheckIn();
return;
default:
return;
}
}
public void dismiss() {
if (getParent() != null && this.mWindowManager != null) {
this.mWindowManager.removeView(this);
}
}
public void setMsg(String str) {
if (this.txtMsg != null && !TextUtils.isEmpty(str)) {
this.txtMsg.setText(str);
}
}
private void postCheckIn() {
StatusApi.checkIn(this.mContext, new JsonCallback(this.mContext) {
public void ok(JSONObject object) {
super.ok(object);
CharSequence message = object.optString("message");
if (!TextUtils.isEmpty(message)) {
Helper.showToast(message);
}
OnePreference.setPrefSignRecord();
}
public void onFinish() {
super.onFinish();
CheckView.this.dismiss();
}
});
}
}
| 27.966102
| 87
| 0.59697
|
ce4fd3cd777e7bc7393471201d86b3fee7fc1e39
| 1,182
|
package br.com.alura.tdd.modelo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
public class Employee {
private String name;
private LocalDate admissionDate;
private BigDecimal salary;
public Employee(String name, LocalDate admissionDate, BigDecimal salary) {
this.name = name;
this.admissionDate = admissionDate;
this.salary = salary;
this.setSalaryScale();
}
public void readjustSalary(BigDecimal readjust) {
this.salary = this.salary.add(readjust);
this.setSalaryScale();
}
private void setSalaryScale() {
// Métodos privados não precisam ser testados, eles serão testados indiretamente nos testes dos métodos públicos
this.salary = this.salary.setScale(2, RoundingMode.HALF_UP);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getAdmissionDate() {
return admissionDate;
}
public void setAdmissionDate(LocalDate admissionDate) {
this.admissionDate = admissionDate;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
this.setSalaryScale();
}
}
| 21.490909
| 114
| 0.748731
|
2bfe219d99c3842c629cf9a167b74b2c5a218292
| 1,267
|
package com.dx.jwfm.framework.web.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import com.dx.jwfm.framework.core.RequestContext;
import com.dx.jwfm.framework.util.FastUtil;
public class PropertyTag extends BaseViewTag {
/** */
private static final long serialVersionUID = 1L;
/** HTML中的name属性,同时做为在bean中取值的属性名 */
protected String name;
/** 如果所得值为数字和日期时,所显示的格式化串 */
protected String format;
@Override
public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
try{
Object val = RequestContext.getBeanValue(name);
String value = FastUtil.format(val,format);
if(value!=null && "html".equals(format)){
value = value.replaceAll("\\r*\\n\\r*", "<br/>");
}
if(value!=null){
out.print(value);
}
} catch (IOException ex) {
logger.error(ex);
} catch (Exception e) {
throw new JspException(e);
}
name = null;format=null;
return SKIP_BODY;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
| 23.036364
| 54
| 0.659037
|
69b5323fecf20d627bc7e82e63e314847e8dc2f1
| 2,795
|
package org.lucasbernardo.healthcareinstitution.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author Lucas<sorackb@gmail.com>
*/
@Entity
@Table(name = "exam")
public class Exam implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ManyToOne
@JoinColumn(name = "healthcare_institution_id", nullable = false)
private HealthcareInstitution healthcareInstitution;
@Column(name = "patient_name", nullable = false)
private String patientName;
@Column(name = "patient_age", nullable = false)
private Integer patientAge;
@Column(name = "patient_gender", nullable = false)
private String patientGender;
@Column(name = "physician_name", nullable = false)
private String physicianName;
@Column(name = "physician_crm", nullable = false)
private String physicianCRM;
@Column(name = "procedure_name", nullable = false)
private String procedureName;
@Column(name = "charged", nullable = false)
private Boolean charged = false;
public Integer getId() {
return id;
}
public HealthcareInstitution getHealthcareInstitution() {
return healthcareInstitution;
}
public void setHealthcareInstitution(HealthcareInstitution healthcareInstitution) {
this.healthcareInstitution = healthcareInstitution;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public Integer getPatientAge() {
return patientAge;
}
public void setPatientAge(Integer patientAge) {
this.patientAge = patientAge;
}
public String getPatientGender() {
return patientGender;
}
public void setPatientGender(String patientGender) {
this.patientGender = patientGender;
}
public String getPhysicianName() {
return physicianName;
}
public void setPhysicianName(String physicianName) {
this.physicianName = physicianName;
}
public String getPhysicianCRM() {
return physicianCRM;
}
public void setPhysicianCRM(String physicianCRM) {
this.physicianCRM = physicianCRM;
}
public String getProcedureName() {
return procedureName;
}
public void setProcedureName(String procedureName) {
this.procedureName = procedureName;
}
public Boolean isCharged() {
return charged;
}
public void setCharged(Boolean charged) {
this.charged = charged;
}
}
| 25.409091
| 86
| 0.715206
|
493b00d3b6bafe54f4569fc9a2f764c91be53db6
| 2,074
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.apache.kafka.connect.runtime.rest.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/**
* Standard error format for all REST API failures. These are generated automatically by
* {@link ConnectExceptionMapper} in response to uncaught
* {@link ConnectException}s.
*/
public class ErrorMessage {
private final int errorCode;
private final String message;
@JsonCreator
public ErrorMessage(@JsonProperty("error_code") int errorCode, @JsonProperty("message") String message) {
this.errorCode = errorCode;
this.message = message;
}
@JsonProperty("error_code")
public int errorCode() {
return errorCode;
}
@JsonProperty
public String message() {
return message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ErrorMessage that = (ErrorMessage) o;
return Objects.equals(errorCode, that.errorCode) &&
Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(errorCode, message);
}
}
| 32.40625
| 109
| 0.702989
|
96e283f416ef278c50e38da79d65704c1c44131d
| 156
|
package finergit.ast.token;
public class DECLAREDMETHODNAME extends IDENTIFIER {
public DECLAREDMETHODNAME(final String name) {
super(name);
}
}
| 15.6
| 52
| 0.75
|
d1e0bee09cd8436af9bd1de81b80ed61e4c80aca
| 407
|
package com.javapatterns.observer.watching;
import java.util.Observable;
public class Watched extends Observable
{
private String data = "";
public String retrieveData()
{
return data;
}
public void changeData(String data)
{
if ( !this.data.equals( data) )
{
this.data = data;
setChanged();
}
notifyObservers();
}
}
| 16.28
| 43
| 0.577396
|
2a3c9c740ec58c9b454349729744a613baf40f99
| 1,663
|
package grondag.canvas.shader;
import grondag.canvas.material.MaterialContext;
public class ShaderContext {
private static int indexCounter;
public final int index = ++indexCounter;
public final MaterialContext materialContext;
public final ShaderPass pass;
public final String name;
private ShaderContext(Builder builder) {
materialContext = builder.materialContext;
pass = builder.pass;
name = materialContext == MaterialContext.PROCESS && pass == ShaderPass.PROCESS ? "process" : materialContext.name().toLowerCase() + "-" + pass.name().toLowerCase();
}
public static class Builder {
private MaterialContext materialContext;
private ShaderPass pass = ShaderPass.SOLID;
Builder materialContext(MaterialContext materialContext) {
this.materialContext = materialContext;
return this;
}
Builder pass(ShaderPass pass) {
this.pass = pass == null ? ShaderPass.SOLID : pass;
return this;
}
ShaderContext build() {
return new ShaderContext(this);
}
}
public static Builder builder() {
return new Builder();
}
public static final ShaderContext TERRAIN_SOLID = builder()
.pass(ShaderPass.SOLID)
.materialContext(MaterialContext.TERRAIN)
.build();
public static final ShaderContext TERRAIN_DECAL = builder()
.pass(ShaderPass.DECAL)
.materialContext(MaterialContext.TERRAIN)
.build();
public static final ShaderContext TERRAIN_TRANSLUCENT = builder()
.pass(ShaderPass.TRANSLUCENT)
.materialContext(MaterialContext.TERRAIN)
.build();
public static final ShaderContext PROCESS = builder()
.pass(ShaderPass.PROCESS)
.materialContext(MaterialContext.PROCESS)
.build();
}
| 25.584615
| 167
| 0.747444
|
af6ca02f7254b3a2238e78f64250bc43af3968df
| 3,396
|
/*
* $Id: AbstractExecuteAction.java 421119 2006-07-12 04:49:11Z wsmoak $
*
* Copyright 2000-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.struts.chain.commands;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.chain.contexts.ActionContext;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ForwardConfig;
/**
* <p>Invoke the appropriate <code>Action</code> for this request, and cache
* the returned <code>ActionForward</code>.</p>
*
* @version $Rev: 421119 $ $Date: 2005-06-04 10:58:46 -0400 (Sat, 04 Jun 2005)
* $
*/
public abstract class AbstractExecuteAction extends ActionCommandBase {
// ---------------------------------------------------------- Public Methods
/**
* <p>Invoke the appropriate <code>Action</code> for this request, and
* cache the returned <code>ActionForward</code>.</p>
*
* @param actionCtx The <code>Context</code> for the current request
* @return <code>false</code> so that processing continues
* @throws Exception if thrown by the Action class
*/
public boolean execute(ActionContext actionCtx)
throws Exception {
// Skip processing if the current request is not valid
Boolean valid = actionCtx.getFormValid();
if ((valid == null) || !valid.booleanValue()) {
return (false);
}
// Acquire the resources we will need to send to the Action
Action action = actionCtx.getAction();
if (action == null) {
return (false);
}
ActionConfig actionConfig = actionCtx.getActionConfig();
ActionForm actionForm = actionCtx.getActionForm();
// Execute the Action for this request, caching returned ActionForward
ForwardConfig forwardConfig =
execute(actionCtx, action, actionConfig, actionForm);
actionCtx.setForwardConfig(forwardConfig);
return (false);
}
// ------------------------------------------------------- Protected Methods
/**
* <p>Execute the specified <code>Action</code>, and return the resulting
* <code>ForwardConfig</code>.</p>
*
* @param context The <code>Context</code> for this request
* @param action The <code>Action</code> to be executed
* @param actionConfig The <code>ActionConfig</code> defining this action
* @param actionForm The <code>ActionForm</code> (if any) for this
* action
* @return ForwardConfig The next location, or null
* @throws Exception if thrown by the <code>Action</code>
*/
protected abstract ForwardConfig execute(ActionContext context,
Action action, ActionConfig actionConfig, ActionForm actionForm)
throws Exception;
}
| 37.733333
| 80
| 0.654888
|
7817bbda3389376ed55554bf7f54e3bf46a46019
| 283
|
package business.mission.picturesmanager.service;
import org.springframework.stereotype.Component;
@Component
public interface SaveTagAnswerService {
String saveTagAnswer(Long missionId, Long authorId, Long pictureId, String mark, String tag,Long picTime, Integer tagTime);
}
| 28.3
| 127
| 0.819788
|
5271945ac801212c8ae24405994eb9debc94edf5
| 3,062
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.hadoop.hdfs.protocol
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|protocol
package|;
end_package
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Method
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|server
operator|.
name|protocol
operator|.
name|NamenodeProtocols
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|retry
operator|.
name|AtMostOnce
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|retry
operator|.
name|Idempotent
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Assert
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_comment
comment|/** * Tests to make sure all the protocol class public methods have * either {@link Idempotent} or {@link AtMostOnce} once annotations. */
end_comment
begin_class
DECL|class|TestAnnotations
specifier|public
class|class
name|TestAnnotations
block|{
annotation|@
name|Test
DECL|method|checkAnnotations ()
specifier|public
name|void
name|checkAnnotations
parameter_list|()
block|{
name|Method
index|[]
name|methods
init|=
name|NamenodeProtocols
operator|.
name|class
operator|.
name|getMethods
argument_list|()
decl_stmt|;
for|for
control|(
name|Method
name|m
range|:
name|methods
control|)
block|{
name|Assert
operator|.
name|assertTrue
argument_list|(
literal|"Idempotent or AtMostOnce annotation is not present "
operator|+
name|m
argument_list|,
name|m
operator|.
name|isAnnotationPresent
argument_list|(
name|Idempotent
operator|.
name|class
argument_list|)
operator|||
name|m
operator|.
name|isAnnotationPresent
argument_list|(
name|AtMostOnce
operator|.
name|class
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 17.597701
| 814
| 0.787394
|
cdb250291d36676af533c6f4530929b492b62795
| 1,109
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2012 Ausenco Engineering Canada Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.render;
import java.awt.Frame;
import com.jogamp.opengl.awt.GLCanvas;
public class RenderFrame extends Frame {
/**
* Package level constructor. This will only be created by Renderer
*/
RenderFrame(int width, int height, String title, GLCanvas canvas) {
super(title);
setSize(width, height);
setLayout(new java.awt.BorderLayout());
add(canvas, java.awt.BorderLayout.CENTER);
validate();
setVisible(true);
}
}
| 28.435897
| 75
| 0.735798
|
a3c269d23f2349d184e95079dce9fe276445c191
| 2,141
|
/*
* 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.asterix.replication.functions;
import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
public class ReplicaIndexFlushRequest {
Set<Long> laggingRescouresIds;
public ReplicaIndexFlushRequest(Set<Long> laggingRescouresIds) {
this.laggingRescouresIds = laggingRescouresIds;
}
public void serialize(OutputStream out) throws IOException {
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(laggingRescouresIds.size());
for (Long resourceId : laggingRescouresIds) {
dos.writeLong(resourceId);
}
}
public static ReplicaIndexFlushRequest create(DataInput input) throws IOException {
int numOfResources = input.readInt();
Set<Long> laggingRescouresIds = new HashSet<Long>(numOfResources);
for (int i = 0; i < numOfResources; i++) {
laggingRescouresIds.add(input.readLong());
}
return new ReplicaIndexFlushRequest(laggingRescouresIds);
}
public Set<Long> getLaggingRescouresIds() {
return laggingRescouresIds;
}
public void setLaggingRescouresIds(Set<Long> laggingRescouresIds) {
this.laggingRescouresIds = laggingRescouresIds;
}
}
| 35.098361
| 87
| 0.725829
|
61982fe9a8822e07d9a315d66fbe00911ab9a31d
| 745
|
package io.github.ennuil.boringbackgrounds;
import io.github.ennuil.boringbackgrounds.data.BackgroundSettingsLoader;
import io.github.ennuil.boringbackgrounds.events.RandomizeBackgroundEvent;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.resource.ResourceManagerHelper;
import net.minecraft.resource.ResourceType;
public class BoringBackgroundsMod implements ClientModInitializer {
@Override
public void onInitializeClient() {
// Registers the background loader
ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(new BackgroundSettingsLoader());
// Registers the background-randomizing event
RandomizeBackgroundEvent.registerEvent();
}
}
| 39.210526
| 120
| 0.810738
|
892c3642bd47d4329489f6bdff2b11671b5627cd
| 384
|
//**************************************************
// Value.java Author: Nazmul Hasan
// Demonstrates how to use Do While Loop.
//**************************************************
package DO_WHILE_LOOP_01;
public class Value
{
public static void main(String args[])
{
int i = 5;
do
{
System.out.println("The value of i is: " + i);
i++;
}
while (i < 29);
}
}
| 18.285714
| 52
| 0.447917
|
18e3861433c3369be2362a58ea9844782b718dcf
| 3,118
|
package com.cnfe.quit.config;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* This class is used to configure the project with dynamic values.
*
* @author eclipse20134
* @version 0.1
*/
public class Config {
private static Logger log = LogManager.getLogger(Config.class);
/**
* parameters for the initializing of the builder
*/
private static final Parameters PARAMS = new Parameters();
/**
* builder to load and save a configuration
*/
private static final FileBasedConfigurationBuilder<FileBasedConfiguration> BUILDER;
/**
* configuration of the project
*/
private static final Configuration CONFIG_ORIGIN;
static {
log.info("load configuration");
try {
BUILDER = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(PARAMS.properties().setFileName("config/config.properties"));
CONFIG_ORIGIN = BUILDER.getConfiguration();
} catch (Exception e) {
throw new RuntimeException("properties file cannot be loaded!");
}
}
/**
* Get a configuration value as string.
*
* @param key
* key for the value that can be used from the {@link Keys} interface
* @return value for the given key
*/
public static String getString(String key) {
log.info("get configuration value for {}", key);
return CONFIG_ORIGIN.getString(key);
}
/**
* Get a configuration value as boolean.
*
* @param key
* key for the value that can be used from the {@link Keys} interface
* @return value for the given key
*/
public static boolean getBoolean(String key) {
log.info("get configuration value for {}", key);
return CONFIG_ORIGIN.getBoolean(key);
}
/**
* Set a value for a specific key in the configuration.
*
* @param key
* key for the value that can be used from the {@link Keys} interface
* @param value
* new value
* @throws ConfigurationException
* configuration saving was not successful
*/
public static void set(String key, Object value) throws ConfigurationException {
log.info("set new value {} for {}", value, key);
CONFIG_ORIGIN.setProperty(key, value);
BUILDER.save();
}
/**
* This is class is used to save the keys for the configuration file.
*
* @author eclipse20134
* @version 0.1
*/
public interface Keys {
String LANGUAGE = "quit.language";
String COUNTRY = "quit.country";
String DEFAULT_TARGET_LANGUAGE = "quit.defaultTargetLanguage";
String DEFAULT_SOURCE_LANGUAGE = "quit.defaultSourceLanguage";
String AUTO_COPY_RESULT = "quit.autoCopyResult";
String AUTO_TRANSLATE_STRING = "quit.autoTranslate";
String CSS = "quit.css";
}
}
| 29.415094
| 101
| 0.725144
|
52f4ea7b450cfa12d069ab0d8694f7139a5b3ea7
| 3,251
|
/*
* Copyright (c) 2002-2021 Manorrock.com. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder 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 cloud.piranha.http.webapp;
import cloud.piranha.core.api.Piranha;
import cloud.piranha.http.api.HttpServerProcessor;
import cloud.piranha.http.api.HttpServerProcessorEndState;
import static cloud.piranha.http.api.HttpServerProcessorEndState.COMPLETED;
import cloud.piranha.http.api.HttpServerRequest;
import cloud.piranha.http.api.HttpServerResponse;
import java.lang.System.Logger;
import static java.lang.System.Logger.Level.ERROR;
/**
* The Web Application HttpServerProcessor.
*
* @author Manfred Riem (mriem@manorrock.com)
*/
public class HttpWebApplicationServerProcessor implements HttpServerProcessor {
/**
* Stores the logger.
*/
private static final Logger LOGGER = System.getLogger(HttpWebApplicationServerProcessor.class.getPackageName());
/**
* Stores the Piranha instance.
*/
private final Piranha piranha;
/**
* Constructor.
*
* @param piranha the Piranha instance.
*/
public HttpWebApplicationServerProcessor(Piranha piranha) {
this.piranha = piranha;
}
@Override
public HttpServerProcessorEndState process(HttpServerRequest request, HttpServerResponse response) {
try (HttpWebApplicationRequest servletRequest = new HttpWebApplicationRequest(request)) {
HttpWebApplicationResponse servletResponse = new HttpWebApplicationResponse(response);
piranha.service(servletRequest, servletResponse);
servletResponse.flush();
} catch (Throwable t) {
LOGGER.log(ERROR, "An error occurred while processing the request", t);
}
return COMPLETED;
}
}
| 42.220779
| 116
| 0.741926
|
ab63c997ee5be2f088661cf69301bf9fc8c56982
| 3,307
|
package com.nosebite.matrice;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
/**
* A simple {@link Fragment} subclass that displays the NavBar to the User.
* It is included in other Fragments.
*/
public class NavBarFragment extends Fragment {
private String parentFragmentName;
public NavBarFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_nav_bar, container, false);
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
assert getParentFragment() != null;
parentFragmentName = getParentFragment().getClass().getSimpleName();
/* Adds callback to the Home Button to navigate the user to the Main Screen. */
ImageButton toHomeButton = (ImageButton) view.findViewById(R.id.navBarHomeButton);
toHomeButton.setOnClickListener(view13 -> {
//Uses popUpTo global action to remove Fragment instances from backstack
Navigation.findNavController(view13)
.navigate(MainNavGraphDirections.actionPopUpToMainScreenFragment());
});
/* Displays different destinations upon current parent fragment */
ImageButton levelsButton = (ImageButton) view.findViewById(R.id.navBarLevelsButton);
if(parentFragmentName.equals("LevelsFragment"))
{
levelsButton.setImageResource(R.drawable.ic_play_icon);
}
else {
levelsButton.setImageResource(R.drawable.ic_levels_icon);
}
levelsButton.setOnClickListener(view12 -> {
if(parentFragmentName.equals("LevelsFragment")) {
//TODO Navigate to GameScreen
}
else {
//TODO Navigate to LevelsScreen
}
Toast.makeText(getContext(), getString(R.string.message_feature_coming_soon), Toast.LENGTH_SHORT).show();
});
/* On Click Listener for starting Settings Activity to adjust Preferences */
ImageButton settingsButton = (ImageButton) view.findViewById(R.id.navBarSettingsButton);
settingsButton.setOnClickListener(view1 -> {
//Since it's another Activity we have to use an Intent
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
});
/* Updates displayed fragment title with parent fragments title */
TextView fragmentTitle = (TextView) view.findViewById(R.id.navBarTitle);
if(parentFragmentName.equals("LevelsFragment"))
{
fragmentTitle.setText(R.string.title_levels_fragment);
}
else {
fragmentTitle.setText(R.string.text_menu_authors);
}
}
}
| 37.579545
| 117
| 0.678258
|
a37ae8549e7771d4f3910deb6b8d669b7ba467de
| 15,365
|
/*
* Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose
*
* 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 ca.phon.app.session;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.time.*;
import java.util.*;
import java.util.List;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.table.*;
import org.apache.commons.lang3.*;
import org.jdesktop.swingx.*;
import ca.phon.app.query.*;
import ca.phon.project.*;
import ca.phon.query.db.*;
import ca.phon.session.*;
import ca.phon.session.Record;
import ca.phon.session.filter.*;
import ca.phon.session.format.*;
import ca.phon.ui.*;
import ca.phon.ui.toast.*;
import ca.phon.util.*;
import ca.phon.util.icons.*;
/**
* Displays options for identify records by range,
* speaker, or search results.
*/
public class RecordFilterPanel extends JPanel {
private final static org.apache.logging.log4j.Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger(RangeRecordFilter.class.getName());
/** The transcript */
private Session t;
/* UI */
private ButtonGroup radioGrp;
private JRadioButton allBtn;
private JRadioButton rangeBtn;
private JRadioButton speakerBtn;
private JPanel queryOptsPanel;
private JRadioButton queryBtn;
private OpenResultSetSelector resultSetSelector;
private JTextField rangeField;
private JXTable speakerTbl;
private List<Participant> selectedParticipants =
new ArrayList<Participant>();
private Project project;
/**
* Constructor
*/
public RecordFilterPanel(Project project, Session t) {
this.project = project;
if(t != null)
setSession(t);
}
public RecordFilterPanel(Project project) {
this.project = project;
}
public void setSession(Session session) {
this.t = session;
init();
}
private void init() {
radioGrp = new ButtonGroup();
ButtonAction bAct = new ButtonAction();
allBtn = new JRadioButton("All records");
allBtn.setSelected(true);
allBtn.addActionListener(bAct);
radioGrp.add(allBtn);
JPanel rangePanel = new JPanel(new HorizontalLayout(5));
rangeBtn = new JRadioButton("Record range");
rangeBtn.addActionListener(bAct);
radioGrp.add(rangeBtn);
rangeField = new JTextField();
rangeField.setText("1.." + t.getRecordCount());
rangeField.setInputVerifier(new RangeVerifier());
rangeField.setColumns(10);
rangeField.setEnabled(false);
rangePanel.add(rangeBtn);
rangePanel.add(rangeField);
JPanel speakerPanel = new JPanel(new VerticalLayout());
speakerBtn = new JRadioButton("Records for participant(s)");
speakerBtn.addActionListener(bAct);
radioGrp.add(speakerBtn);
speakerTbl = new JXTable(new ParticipantsTableModel());
speakerTbl.setVisibleRowCount(3);
speakerTbl.setEnabled(false);
speakerPanel.add(speakerBtn);
speakerPanel.add(new JScrollPane(speakerTbl));
queryBtn = new JRadioButton("Records from query results");
queryBtn.addActionListener(bAct);
radioGrp.add(queryBtn);
resultSetSelector = new OpenResultSetSelector(getSession());
resultSetSelector.getResultSetTable().setVisibleRowCount(3);
resultSetSelector.getResultSetTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
queryOptsPanel = new JPanel(new VerticalLayout());
queryOptsPanel.add(queryBtn);
queryOptsPanel.add(resultSetSelector);
setLayout(new VerticalLayout(5));
add(allBtn);
add(rangePanel);
add(speakerPanel);
add(queryOptsPanel);
}
/**
* Table model for speakers
*/
private class ParticipantsTableModel extends AbstractTableModel {
public ParticipantsTableModel() {
super();
for(int i = 0; i < t.getParticipantCount(); i++) {
selectedParticipants.add(t.getParticipant(i));
}
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public int getRowCount() {
return t.getParticipantCount();
}
@Override
public String getColumnName(int col) {
String retVal = "";
if(col == 0) retVal = " ";
else if(col == 1) retVal = "Name";
else if(col == 2) retVal = "Role";
else if(col == 3) retVal = "Age";
return retVal;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object retVal = new String();
Participant p = getSession().getParticipant(rowIndex);
if(columnIndex == 0) {
if(selectedParticipants.contains(p)) {
retVal = Boolean.TRUE;
} else {
retVal = Boolean.FALSE;
}
} else if(columnIndex == 1) {
if(p.getName() == null) return p.getId();
retVal = p.getName();
} else if(columnIndex == 2) {
retVal = p.getRole();
} else if(columnIndex == 3) {
if(p.getBirthDate() != null) {
retVal = AgeFormatter.ageToString(p.getAge(getSession().getDate()));
}
}
return retVal;
}
@Override
public Class<?> getColumnClass(int col) {
Class<?> retVal = null;
if(col == 0) retVal = Boolean.class;
else if(col == 1) retVal = String.class;
else if(col == 2) retVal = ParticipantRole.class;
else if(col == 3) retVal = String.class;
return retVal;
}
@Override
public boolean isCellEditable(int row, int col) {
boolean retVal = false;
if(col == 0) retVal = true;
return retVal;
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
Participant p = getSession().getParticipant(rowIndex);
Boolean selected = (Boolean)value;
if(selected) {
if(!selectedParticipants.contains(p))
selectedParticipants.add(p);
} else {
selectedParticipants.remove(p);
}
}
}
public JPanel getQueryOptionsPanel() {
return this.queryOptsPanel;
}
/**
* Table model for searches
*/
private class SearchTableModel extends AbstractTableModel {
List<FilterPanelCellValue> searches;
List<Integer> openQueryRows = new ArrayList<>();
public SearchTableModel() {
searches = new ArrayList<RecordFilterPanel.FilterPanelCellValue>();
int rowIdx = 0;
// report any currently open result sets
for(CommonModuleFrame cmf:CommonModuleFrame.getOpenWindows()) {
if(cmf instanceof ResultSetEditor) {
ResultSetEditor editor = (ResultSetEditor)cmf;
// check session
final Session editorSession = editor.getSession();
if(editorSession != null && editorSession.getCorpus().equals(t.getCorpus())
&& editorSession.getName().equals(t.getName())) {
// add result set to list
searches.add(new FilterPanelCellValue(editor.getQuery(), editor.getResultSet()));
openQueryRows.add(rowIdx);
}
}
}
final ResultSetManager rsManager = QueryManager.getSharedInstance().createResultSetManager();
for(Query q:rsManager.getQueries(project)) {
for(ResultSet rs:rsManager.getResultSetsForQuery(project, q)) {
if(rs.getCorpus().equals(t.getCorpus()) && rs.getSession().equals(getSession().getName())) {
searches.add(new FilterPanelCellValue(q, rs));
}
}
}
}
public boolean isOpenQuery(int row) {
return openQueryRows.contains(row);
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public int getRowCount() {
return searches.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object retVal = "";
final FilterPanelCellValue rowValue = searches.get(rowIndex);
if(columnIndex == 0) {
retVal = rowValue.getObj1().getName();
} else if (columnIndex == 1) {
retVal = rowValue.getQuery().getDate();
} else if (columnIndex == 2) {
retVal = rowValue.getResultSet().size();
}
return retVal;
}
@Override
public String getColumnName(int col) {
String retVal = "";
if(col == 0) retVal = "Query";
else if(col == 1) retVal = "Date";
else if(col == 2) retVal = "# of Results";
return retVal;
}
@Override
public Class<?> getColumnClass(int col) {
Class<?> retVal = String.class;
if(col == 0) retVal = String.class;
else if(col == 1) retVal = LocalDate.class;
else if(col == 2) retVal = Integer.class;
return retVal;
}
}
/**
* Table cell class
*/
private class FilterPanelCellValue extends Tuple<Query, ResultSet> {
public FilterPanelCellValue(Query q, ResultSet rs) {
super(q, rs);
}
public Query getQuery() { return this.getObj1(); }
public ResultSet getResultSet() { return this.getObj2(); }
}
/**
* Action for enabling/disabling components
*/
private class ButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(allBtn.isSelected()) {
rangeField.setEnabled(false);
speakerTbl.setEnabled(false);
resultSetSelector.getResultSetTable().setEnabled(false);
} else if (rangeBtn.isSelected()) {
rangeField.setEnabled(true);
speakerTbl.setEnabled(false);
resultSetSelector.getResultSetTable().setEnabled(false);
} else if(speakerBtn.isSelected()) {
rangeField.setEnabled(false);
speakerTbl.setEnabled(true);
resultSetSelector.getResultSetTable().setEnabled(false);
} else if(queryBtn.isSelected()) {
rangeField.setEnabled(false);
speakerTbl.setEnabled(false);
resultSetSelector.getResultSetTable().setEnabled(true);
}
}
}
/**
* Range field validator
*/
private class RangeVerifier extends AbstractVerifier implements VerifierListener {
/** Error message */
private String err = "";
/** Range regex */
private String rangeRegex = "([0-9]+)(?:\\.\\.([0-9]+))?";
public RangeVerifier() {
this.addVerificationListener(this);
}
@Override
public boolean verification(JComponent c) {
boolean retVal = true;
Pattern p = Pattern.compile(rangeRegex);
if(c == rangeField) {
// don't validate if we are not enabled
if(!rangeField.isEnabled()) return true;
String rangeString = rangeField.getText();
String[] ranges = rangeString.split(",");
for(String range:ranges) {
range = StringUtils.strip(range);
Matcher m = p.matcher(range);
if(m.matches()) {
// make sure range is valid
if(m.group(2) == null) {
String idxStr = m.group(1);
Integer idx = Integer.parseInt(idxStr);
if(idx < 0 || idx > getSession().getRecordCount()) {
err = "Record out of bounds '" + idx + "'";
retVal = false;
break;
}
} else {
String firstStr = m.group(1);
String secStr = m.group(2);
Integer first = Integer.parseInt(firstStr);
Integer second = Integer.parseInt(secStr);
if(first > second) {
err = "Invalid range '" + range + "'";
retVal = false;
break;
} else if(
first > getSession().getRecordCount() || second > getSession().getRecordCount()) {
err = "Range out of bounds '" + range + "'";
retVal = false;
break;
}
}
} else {
err = "Invalid range string '" + range + "'";
retVal = false;
break;
}
}
} else {
retVal = false;
}
return retVal;
}
@Override
public void verificationFailed(JComponent comp) {
final Toast toast = ToastFactory.makeToast(err);
toast.setMessageBackground(PhonGuiConstants.PHON_ORANGE);
toast.start(comp);
}
@Override
public void verificationPassed(JComponent comp) {
comp.setBackground(Color.white);
}
@Override
public void verificationReset(JComponent comp) {
comp.setBackground(Color.white);
}
}
/**
* Date column formatter
*/
private class DateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
JLabel retVal = (JLabel)super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
LocalDateTime d = (LocalDateTime)value;
String dateStr = DateFormatter.dateTimeToString(d);
retVal.setText(dateStr);
// if(!table.isEnabled()) {
retVal.setEnabled(table.isEnabled());
// }
return retVal;
}
}
/**
* Query name formatter. Displays a star next to starred queries and will show
* open queries in italics
*/
private class QueryNameCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
JLabel retVal = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
SearchTableModel tblModel = (SearchTableModel)table.getModel();
FilterPanelCellValue cellVal = tblModel.searches.get(row);
if(cellVal.getQuery().isStarred()) {
final ImageIcon icon = IconManager.getInstance()
.getIcon("misc/metal-star-on", IconSize.SMALL);
retVal.setIcon(icon);
} else {
retVal.setIcon(null);
}
if(tblModel.isOpenQuery(row)) {
retVal.setFont(retVal.getFont().deriveFont(Font.ITALIC));
}
return retVal;
}
}
/**
* Get the defined filter
*/
public RecordFilter getRecordFilter() {
RecordFilter retVal = null;
if(allBtn.isSelected()) {
retVal = new AbstractRecordFilter() {
@Override
public boolean checkRecord(Record utt) {
return true;
}
};
} else if(rangeBtn.isSelected()) {
try {
retVal = new RangeRecordFilter(t, rangeField.getText());
} catch (ParseException e) {
LOGGER.error( e.getLocalizedMessage(), e);
}
} else if(speakerBtn.isSelected()) {
retVal = new ParticipantRecordFilter(selectedParticipants);
} else if(queryBtn.isSelected() && resultSetSelector.getSelectedResultSets().size() > 0) {
retVal = new ResultSetRecordFilter(t, resultSetSelector.getSelectedResultSets().get(0));
}
return retVal;
}
public Session getSession() {
return t;
}
/**
* Validate panel
*/
public boolean validatePanel() {
boolean retVal = false;
if(allBtn.isSelected()) {
retVal = true;
} else if(speakerBtn.isSelected()) {
// make sure at least one participant is selected
if(selectedParticipants.size() == 0) {
final Toast toast = ToastFactory.makeToast("Choose at least one participant.");
toast.start(speakerBtn);
} else {
retVal = true;
}
} else if(rangeBtn.isSelected()) {
// validate range field
retVal = rangeField.getInputVerifier().verify(rangeField);
} else if(queryBtn.isSelected()) {
// make sure selected search has data
if(resultSetSelector.getSelectedResultSets().size() == 0 ||
resultSetSelector.getSelectedResultSets().get(0).numberOfResults(true) == 0) {
final Toast toast = ToastFactory.makeToast("No results selected.");
toast.start(queryBtn);
} else {
retVal = true;
}
}
return retVal;
}
}
| 25.565724
| 144
| 0.672177
|
48a0ef6e6c048f3df6d8a470613f64415fb22863
| 5,465
|
package org.jboss.hal.testsuite.test.configuration.messaging.remote.activemq.server.connector.remote;
import java.io.IOException;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.dmr.ModelDescriptionConstants;
import org.jboss.hal.testsuite.Console;
import org.jboss.hal.testsuite.CrudOperations;
import org.jboss.hal.testsuite.Random;
import org.jboss.hal.testsuite.creaper.ManagementClientProvider;
import org.jboss.hal.testsuite.creaper.ResourceVerifier;
import org.jboss.hal.testsuite.creaper.command.AddLocalSocketBinding;
import org.jboss.hal.testsuite.creaper.command.RemoveLocalSocketBinding;
import org.jboss.hal.testsuite.dmr.ModelNodeGenerator;
import org.jboss.hal.testsuite.page.configuration.MessagingRemoteActiveMQPage;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.wildfly.extras.creaper.core.CommandFailedException;
import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import org.wildfly.extras.creaper.core.online.operations.Operations;
import org.wildfly.extras.creaper.core.online.operations.Values;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.RemoteActiveMQServer;
@RunWith(Arquillian.class)
public class RemoteConnectorTest {
private static final OnlineManagementClient client = ManagementClientProvider.createOnlineManagementClient();
private static final Operations operations = new Operations(client);
private static final String REMOTE_CONNECTOR_CREATE = "remote-connector-to-create-" + Random.name();
private static final String REMOTE_CONNECTOR_UPDATE = "remote-connector-to-update-" + Random.name();
private static final String REMOTE_CONNECTOR_DELETE = "remote-connector-to-delete-" + Random.name();
private static final String LOCAL_SOCKET_BINDING = "local-socket-binding-" + Random.name();
private static final String LOCAL_SOCKET_BINDING_UPDATE = "local-socket-binding-update-" + Random.name();
@BeforeClass
public static void setUp() throws IOException, CommandFailedException {
client.apply(new AddLocalSocketBinding(LOCAL_SOCKET_BINDING));
client.apply(new AddLocalSocketBinding(LOCAL_SOCKET_BINDING_UPDATE));
createRemoteConnector(REMOTE_CONNECTOR_DELETE, LOCAL_SOCKET_BINDING);
createRemoteConnector(REMOTE_CONNECTOR_UPDATE, LOCAL_SOCKET_BINDING);
}
private static void createRemoteConnector(String name, String socketBinding) throws IOException {
operations.add(RemoteActiveMQServer.remoteConnectorAddress(name), Values.of("socket-binding", socketBinding))
.assertSuccess();
}
@AfterClass
public static void tearDown() throws IOException, OperationException, CommandFailedException {
try {
operations.removeIfExists(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_CREATE));
operations.removeIfExists(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_UPDATE));
operations.removeIfExists(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_DELETE));
client.apply(new RemoveLocalSocketBinding(LOCAL_SOCKET_BINDING));
client.apply(new RemoveLocalSocketBinding(LOCAL_SOCKET_BINDING_UPDATE));
} finally {
client.close();
}
}
@Drone
private WebDriver browser;
@Inject
private Console console;
@Inject
private CrudOperations crudOperations;
@Page
private MessagingRemoteActiveMQPage page;
@Before
public void navigate() {
page.navigate();
console.verticalNavigation().selectSecondary("msg-remote-connector-group-item", "msg-remote-remote-connector-item");
}
@Test
public void create() throws Exception {
crudOperations.create(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_CREATE),
page.getRemoteConnectorTable(),
formFragment -> {
formFragment.text(ModelDescriptionConstants.NAME, REMOTE_CONNECTOR_CREATE);
formFragment.text("socket-binding", LOCAL_SOCKET_BINDING);
}, ResourceVerifier::verifyExists);
}
@Test
public void remove() throws Exception {
crudOperations.delete(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_DELETE),
page.getRemoteConnectorTable(), REMOTE_CONNECTOR_DELETE);
}
@Test
public void editParams() throws Exception {
page.getRemoteConnectorTable().select(REMOTE_CONNECTOR_UPDATE);
crudOperations.update(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_UPDATE),
page.getRemoteConnectorForm(), "params",
new ModelNodeGenerator.ModelNodePropertiesBuilder().addProperty(Random.name(), Random.name()).build());
}
@Test
public void editSocketBinding() throws Exception {
page.getRemoteConnectorTable().select(REMOTE_CONNECTOR_UPDATE);
crudOperations.update(RemoteActiveMQServer.remoteConnectorAddress(REMOTE_CONNECTOR_UPDATE),
page.getRemoteConnectorForm(), "socket-binding", LOCAL_SOCKET_BINDING_UPDATE);
}
}
| 45.165289
| 124
| 0.769442
|
6832b7fb8e0002d62066f699eb6731616f021e70
| 4,027
|
//Title: XM-Miner
//Version:
//Copyright: Copyright (c) 1999
//Author: Yong Uk Song
//Company: DIS
//Description: XM-Miner
package xmminer.xmclient.xmlib;
import xmminer.xmclient.*;
public class XMCORBATable
{
transient String m_columnNames[];
transient int m_nColumns, m_nRows;
transient int m_page;
transient String m_cColumnNames[];
transient int m_cRowNumber;
transient int m_cNColumns, m_cNRows;
transient String m_cRowData[][];
public XMCORBATable(String projectPath, String projectName, String metaFilename, int id) throws Exception
{
try
{
SetCORBA();
System.out.println(projectPath + ", " + projectName + ", " + metaFilename + ", " + id);
m_sCORBATable.Initialize(projectPath, projectName, metaFilename, id);
System.out.println("constructor");
m_columnNames = m_cColumnNames = m_sCORBATable.GetColumnNames();
m_nColumns = m_cNColumns = (m_columnNames == null) ? 0 : m_columnNames.length;
m_nRows = m_sCORBATable.GetNumberOfRows();
}
catch (Exception e)
{
m_columnNames = m_cColumnNames = null;
m_nColumns = m_cNColumns = m_nRows = 0;
throw(e);
}
}
// CORBA
//transient xmminer.xmvbj.xmlib.XMBCORBATable m_sCORBATable = null;
transient xmminer.xmserver.xmlib.XMBCORBATable m_sCORBATable = null;
private void SetCORBA() throws org.omg.CORBA.OBJECT_NOT_EXIST
{
if (m_sCORBATable == null)
{
// Get the manager Id
// Locate an account manager. Give the full POA name and the servant ID.
try
{
//m_sCORBATable = xmminer.xmvbj.xmlib.XMBCORBATableHelper.bind(XMMiner.m_orb, "/xmminer_poa", "XMCORBATable".getBytes());
m_sCORBATable = new xmminer.xmserver.xmlib.XMBCORBATable();
}
catch (org.omg.CORBA.OBJECT_NOT_EXIST e)
{
m_sCORBATable = null;
System.out.println("CORBA object XMCORBATable does not exist.");
throw(e);
}
}
}
public int Initialize(String[] queryColumnNames, int page)
{
System.out.println("initialize");
SetQueryColumns(queryColumnNames);
m_page = page;
m_cRowNumber = 0;
m_cNRows = (m_page <= 0) ? 128 : m_page;
m_cRowData = (m_sCORBATable == null) ? null : m_sCORBATable.GetRows(m_cRowNumber, m_cNRows);
return((m_sCORBATable == null) ? 1 : 0);
}
public void Finalize()
{
if (m_sCORBATable != null)
{
m_sCORBATable.Finalize();
}
}
// No Buffering
public String GetProfile(String name)
{
return((m_sCORBATable == null) ? null : m_sCORBATable.GetProfile(name));
}
public String[] GetProfiles(String name)
{
return((m_sCORBATable == null) ? null : m_sCORBATable.GetProfiles(name));
}
public int SetQueryColumns(String[] columnNames)
{
m_cColumnNames = (columnNames == null) ? m_columnNames : columnNames;
m_cNColumns = m_cColumnNames.length;
return((m_sCORBATable == null) ? -1 : m_sCORBATable.SetQueryColumns(m_cColumnNames));
}
// Buffering
public int GetRowCount()
{
return(m_nRows);
}
public int GetColumnCount()
{
return(m_cNColumns);
}
public String GetColumnName(int col)
{
return(m_cColumnNames[col]);
}
public Class GetColumnClass(int c)
{
return((m_cRowData.length <= 0) ? null : m_cRowData[0][c].getClass());
}
public Object GetValueAt(int row, int col)
{
if (row < m_cRowNumber)
{
int bottom = m_cRowNumber - m_cNRows;
if (bottom < 0) bottom = 0;
m_cRowNumber = (bottom >= row) ? row : bottom;
m_cRowData = m_sCORBATable.GetRows(m_cRowNumber, m_cNRows);
}
else if (row >= m_cRowNumber + m_cNRows)
{
m_cRowNumber = row;
m_cRowData = m_sCORBATable.GetRows(m_cRowNumber, m_cNRows);
}
return(m_cRowData[row - m_cRowNumber][col]);
}
public String[][] GetAllRows(){
return m_sCORBATable.GetAllRows();
}
public String[] GetAllCols(){ return m_columnNames; }
public void SaveAllRows(){
m_sCORBATable.SaveAllRows();
}
}
| 25.16875
| 129
| 0.660293
|
8805a586f33bbee7f51fc1c2f612be1e829f75f7
| 1,865
|
package br.senai.sc.edu.projetomaria.io;
import java.io.FileReader;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import br.senai.sc.edu.projetomaria.model.Familia;
import br.senai.sc.edu.projetomaria.resource.Config;
public class FamiliaReader {
private static final Logger LOGGER = LogManager.getLogger();
private static final String COD_FAMILIA_COMERCIAL = "COD_FAMILIA_COMERCIAL";
private static final String NOME_FAMILIA_COMERCIAL = "NOME_FAMILIA_COMERCIAL";
private static final String[] mapeamentoColunasArquivo = { COD_FAMILIA_COMERCIAL, NOME_FAMILIA_COMERCIAL };
public List<Familia> leitorFamilia(Path pathArquivo) {
CSVParser parseArquivos = null;
CSVFormat formatadorCsv = CSVFormat.DEFAULT.withHeader(mapeamentoColunasArquivo).withDelimiter(Config.CSV_DELIMITADOR);
List <Familia>list = new LinkedList<>();
try (FileReader leitorFamilia = new FileReader(pathArquivo.toFile())) {
parseArquivos = new CSVParser(leitorFamilia, formatadorCsv);
List<CSVRecord> csvRecords = parseArquivos.getRecords();
for (int i = 1; i < csvRecords.size(); i++) {
CSVRecord registro = csvRecords.get(i);
int codigo = Integer.parseInt(registro.get(COD_FAMILIA_COMERCIAL));
String nome = registro.get(NOME_FAMILIA_COMERCIAL);
Familia familia = new Familia();
familia.setCodigo(codigo);
familia.setNome(nome);
list.add(familia);
}
return list;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
}
return Collections.emptyList();
}
}
| 32.719298
| 123
| 0.730295
|
64109bfebf48718b3f5a479d6766a10ed6c58653
| 1,582
|
/*
* Copyright 2006 Jeremias Maerki.
*
* 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.krysalis.barcode4j.impl.datamatrix;
import java.awt.Dimension;
import org.krysalis.barcode4j.impl.ConfigurableBarcodeGenerator;
/**
* This class is an implementation of the DataMatrix barcode.
*
* @version $Id: DataMatrix.java,v 1.4 2008/09/22 08:59:08 jmaerki Exp $
*/
public class DataMatrix extends ConfigurableBarcodeGenerator<DataMatrixBean> {
/** Create a new instance. */
public DataMatrix() {
this.bean = new DataMatrixBean();
}
private Dimension parseSymbolSize(final String size) {
int idx = size.indexOf('x');
Dimension dim;
if (idx > 0) {
dim = new Dimension(Integer.parseInt(size.substring(0, idx)), Integer.parseInt(size.substring(idx + 1)));
} else {
int extent = Integer.parseInt(size);
dim = new Dimension(extent, extent);
}
return dim;
}
/**
* @return the underlying DataMatrix bean
*/
public DataMatrixBean getDataMatrixBean() {
return getBean();
}
}
| 29.849057
| 109
| 0.697851
|
bc6b80eb14c57859d044f55a4141766e0b2d2050
| 2,202
|
package io.connectedcars.authentication;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JwtBody {
@JsonProperty("jti")
private String id;
@JsonProperty("iat")
private long issuedAt;
@JsonProperty("iss")
private String issuer;
@JsonProperty("aud")
private String audience;
@JsonProperty("exp")
private long expires = -1;
@JsonProperty("nbf")
private long notBefore = -1;
@JsonProperty("sub")
private String subject;
/**
* @return the audience
*/
public String getAudience() {
return audience;
}
/**
* @param audience the audience to set
*/
public void setAudience(String audience) {
this.audience = audience;
}
/**
* @return the expires
*/
public long getExpires() {
return expires;
}
/**
* @param expires the expires to set
*/
public void setExpires(long expires) {
this.expires = expires;
}
/**
* @return the notBefore
*/
public long getNotBefore() {
return notBefore;
}
/**
* @param notBefore the notBefore to set
*/
public void setNotBefore(long notBefore) {
this.notBefore = notBefore;
}
/**
* @return the issuer
*/
public String getIssuer() {
return issuer;
}
/**
* @param issuer the issuer to set
*/
public void setIssuer(String issuer) {
this.issuer = issuer;
}
/**
* @return the issuedAt
*/
public long getIssuedAt() {
return issuedAt;
}
/**
* @param issuedAt the Issued At to set
*/
public void setIssuedAt(long issuedAt) {
this.issuedAt = issuedAt;
}
/**
* @return the subject
*/
public String getSubject() {
return subject;
}
/**
* @param subject the subject to set
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
}
| 18.504202
| 53
| 0.550863
|
0ceae73aa87341c58fd517470c183f9b43ca2912
| 3,046
|
package com.fileopr.operations.controller;
import com.fileopr.operations.controller.ApiConstant;
import com.fileopr.operations.models.Employee;
import com.fileopr.operations.models.Storage;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
@RestController
public class MainController {
@RequestMapping(value=ApiConstant.ADD_URL,
method=RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity addEmployee(@RequestBody Employee emp)
{
Storage str = new Storage();
boolean res = str.addEmployee(emp);
if(res)
return new ResponseEntity(HttpStatus.OK);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Unable to Add Employee");
}
@RequestMapping(value=ApiConstant.ADD_FORM_URL,
method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity addEmployee(
@RequestParam(name="id",required = true) int id,
@RequestParam(name="name",required = true) String name,
@RequestParam(name="salary",required = true) double salary,
@RequestParam(name="company",required = true) String company,
@RequestParam(name="dob",required = true) String dob) throws ParseException {
Storage str = new Storage();
Employee emp = new Employee();
emp.setId(id);
emp.setName(name);
emp.setCompany(company);
emp.setSalary(salary);
SimpleDateFormat fs = new SimpleDateFormat("dd-MM-yyyy");
Date date = fs.parse(dob);
emp.setDob(date);
boolean res = str.addEmployee(emp);
if(res)
return new ResponseEntity(HttpStatus.OK);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Unable to Add Employee");
}
@RequestMapping(value=ApiConstant.GET_BY_ID,
method=RequestMethod.GET)
public Employee getEmployee(@PathVariable("id")int id)
{
Storage str = new Storage();
Employee emp = str.getEmployee(id);
return emp;
}
@RequestMapping(value=ApiConstant.GET_ALL_URL,
method=RequestMethod.GET)
public List<Employee> getAll()
{
Storage str = new Storage();
return str.listAll();
}
@RequestMapping(value=ApiConstant.DELETE_URL,
method=RequestMethod.DELETE)
public ResponseEntity delete(@PathVariable("id")int id)
{
Storage str = new Storage();
boolean res = str.deleteEmployee(id);
if(res)
return new ResponseEntity(HttpStatus.OK);
else
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Unable to find resource");
}
}
| 35.418605
| 95
| 0.67761
|
2759ee3a2fe82a38c54c0883dd40f9a14aa56e43
| 1,818
|
package org.rc.inventory.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import org.rc.inventory.R;
import org.rc.inventory.excel.ExcelParser;
import org.rc.inventory.http.FtpResponseCode;
import org.rc.inventory.http.IImageCallback;
import org.rc.inventory.http.ImageEndpoint;
import org.rc.inventory.model.InventoryModel;
import org.rc.inventory.model.LocationModel;
import org.rc.inventory.util.IntentUtil;
import org.rc.inventory.util.InventoryUtil;
import java.util.List;
public class InventoryLocationMainActivity extends AbstractListActivity {
private InventoryModel mInventory = new InventoryModel();
@Override
protected int getToolbarCaption() {
return R.string.title_select_main_location;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getIntent().hasExtra(InventoryUtil.EXTRA_INVENTORY_ITEM)) {
mInventory = (InventoryModel) getIntent()
.getSerializableExtra(InventoryUtil.EXTRA_INVENTORY_ITEM);
}
}
@Override
public void onItemClick(LocationModel location) {
mInventory.setMainLocation(location.getName());
// store the child location list
IntentUtil.getInstance().setExtra(
InventoryUtil.EXTRA_SUB_LOCATION_LIST, location.getSubLocations());
// start the new intent
Intent selectBagLocationIntent = new Intent(this, InventoryLocationSubActivity.class);
selectBagLocationIntent.putExtra(InventoryUtil.EXTRA_INVENTORY_ITEM, mInventory);
startActivity(selectBagLocationIntent);
}
@Override
protected List<LocationModel> loadData() {
return ExcelParser.getInstance().getLocations();
}
}
| 28.857143
| 94
| 0.737074
|
26b0b345602fded04542e7df6b01984711915cd9
| 107
|
package com.example.pgsql.beans;
/**
* Classe réprésentant un médicament
*/
public class Medicament
{
}
| 11.888889
| 36
| 0.728972
|
8f89b13d37164ea77045ab734607635468ebff08
| 377
|
package apycazo.codex.minion.context.properties;
import java.lang.annotation.*;
/**
* Declares additional property source locations. This annotation is only considered when found
* on classes annotated with 'ConfigProvider'.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface PropertySources {
PropertySource [] value();
}
| 23.5625
| 95
| 0.777188
|
16465b4f8aec2c0dae5896666561bf455d9153e1
| 9,388
|
package org.hisp.dhis.importexport.dxf.converter;
/*
* Copyright (c) 2004-2012, 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 java.util.Map;
import org.amplecode.quick.BatchHandler;
import org.amplecode.quick.StatementManager;
import org.amplecode.staxwax.reader.XMLReader;
import org.amplecode.staxwax.writer.XMLWriter;
import org.hisp.dhis.aggregation.AggregatedDataValueService;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.datavalue.DataValue;
import org.hisp.dhis.datavalue.DeflatedDataValue;
import org.hisp.dhis.importexport.ExportParams;
import org.hisp.dhis.importexport.ImportDataValue;
import org.hisp.dhis.importexport.ImportObjectService;
import org.hisp.dhis.importexport.ImportParams;
import org.hisp.dhis.importexport.XMLConverter;
import org.hisp.dhis.importexport.importer.DataValueImporter;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.system.util.DateUtils;
/**
* @author Lars Helge Overland
* @version $Id: DataValueConverter.java 6455 2008-11-24 08:59:37Z larshelg $
*/
public class DataValueConverter
extends DataValueImporter implements XMLConverter
{
public static final String COLLECTION_NAME = "dataValues";
public static final String ELEMENT_NAME = "dataValue";
private static final String FIELD_DATAELEMENT = "dataElement";
private static final String FIELD_PERIOD = "period";
private static final String FIELD_SOURCE = "source";
private static final String FIELD_VALUE = "value";
private static final String FIELD_STOREDBY = "storedBy";
private static final String FIELD_TIMESTAMP = "timeStamp";
private static final String FIELD_COMMENT = "comment";
private static final String FIELD_CATEGORY_OPTION_COMBO = "categoryOptionCombo";
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
private StatementManager statementManager;
private PeriodService periodService;
private Map<Object, Integer> dataElementMapping;
private Map<Object, Integer> periodMapping;
private Map<Object, Integer> sourceMapping;
private Map<Object, Integer> categoryOptionComboMapping;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
/**
* Constructor for write operations.
*/
public DataValueConverter( AggregatedDataValueService aggregatedDataValueService,
StatementManager statementManager,
PeriodService periodService )
{
this.aggregatedDataValueService = aggregatedDataValueService;
this.statementManager = statementManager;
this.periodService = periodService;
}
/**
* Constructor for read operations.
*/
public DataValueConverter( BatchHandler<DataValue> batchHandler,
BatchHandler<ImportDataValue> importDataValueBatchHandler,
AggregatedDataValueService aggregatedDataValueService,
ImportObjectService importObjectService,
ImportParams params,
Map<Object, Integer> dataElementMapping,
Map<Object, Integer> periodMapping,
Map<Object, Integer> sourceMapping,
Map<Object, Integer> categoryOptionComboMapping )
{
this.batchHandler = batchHandler;
this.importDataValueBatchHandler = importDataValueBatchHandler;
this.aggregatedDataValueService = aggregatedDataValueService;
this.importObjectService = importObjectService;
this.params = params;
this.dataElementMapping = dataElementMapping;
this.periodMapping = periodMapping;
this.sourceMapping = sourceMapping;
this.categoryOptionComboMapping = categoryOptionComboMapping;
}
// -------------------------------------------------------------------------
// XMLConverter implementation
// -------------------------------------------------------------------------
public void write( XMLWriter writer, ExportParams params )
{
if ( params.isIncludeDataValues() )
{
if ( params.getStartDate() != null && params.getEndDate() != null )
{
Collection<DeflatedDataValue> values = null;
Collection<Period> periods = periodService.getIntersectingPeriods( params.getStartDate(), params.getEndDate() );
statementManager.initialise();
writer.openElement( COLLECTION_NAME );
for ( final Integer element : params.getDataElements() )
{
for ( final Period period : periods )
{
values = aggregatedDataValueService.getDeflatedDataValues( element, period.getId(), params.getOrganisationUnits() );
for ( final DeflatedDataValue value : values )
{
writer.writeElement( ELEMENT_NAME, EMPTY,
FIELD_DATAELEMENT, String.valueOf( value.getDataElementId() ),
FIELD_PERIOD, String.valueOf( value.getPeriodId() ),
FIELD_SOURCE, String.valueOf( value.getSourceId() ),
FIELD_VALUE, value.getValue(),
FIELD_STOREDBY, value.getStoredBy(),
FIELD_TIMESTAMP, DateUtils.getMediumDateString( value.getTimestamp() ),
FIELD_COMMENT, value.getComment(),
FIELD_CATEGORY_OPTION_COMBO, String.valueOf( value.getCategoryOptionComboId() ) );
}
}
}
writer.closeElement();
statementManager.destroy();
}
}
}
public void read( XMLReader reader, ImportParams params )
{
while ( reader.moveToStartElement( ELEMENT_NAME, COLLECTION_NAME ) )
{
final Map<String, String> values = reader.readElements( ELEMENT_NAME );
final DataValue value = new DataValue();
final DataElement element = new DataElement();
value.setDataElement( element );
final Period period = new Period();
value.setPeriod( period );
final OrganisationUnit source = new OrganisationUnit();
value.setSource( source );
final DataElementCategoryOptionCombo categoryOptionCombo = new DataElementCategoryOptionCombo();
value.setOptionCombo( categoryOptionCombo );
value.getDataElement().setId( dataElementMapping.get( Integer.parseInt( values.get( FIELD_DATAELEMENT ) ) ) );
value.getPeriod().setId( periodMapping.get( Integer.parseInt( values.get( FIELD_PERIOD ) ) ) );
value.getSource().setId( sourceMapping.get( Integer.parseInt( values.get( FIELD_SOURCE ) ) ) );
value.setValue( values.get( FIELD_VALUE ) );
value.setStoredBy( values.get( FIELD_STOREDBY ) );
value.setTimestamp( DateUtils.getMediumDate( values.get( FIELD_TIMESTAMP ) ) );
value.setComment( values.get( FIELD_COMMENT ) );
value.getOptionCombo().setId( categoryOptionComboMapping.get( Integer.parseInt( values.get( FIELD_CATEGORY_OPTION_COMBO ) ) ) );
importObject( value, params );
}
}
}
| 46.019608
| 140
| 0.636877
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.