language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
Java
|
public class ProgramIndicatorServiceTest
extends DhisSpringTest
{
private static final String COL_QUOTE = "\"";
@Autowired
private ProgramIndicatorService programIndicatorService;
@Autowired
private TrackedEntityAttributeService attributeService;
@Autowired
private TrackedEntityInstanceService entityInstanceService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private ProgramService programService;
@Autowired
private ProgramStageService programStageService;
@Autowired
private ProgramInstanceService programInstanceService;
@Autowired
private TrackedEntityDataValueService dataValueService;
@Autowired
private DataElementService dataElementService;
@Autowired
private ProgramStageDataElementService programStageDataElementService;
@Autowired
private TrackedEntityAttributeValueService attributeValueService;
@Autowired
private ProgramStageInstanceService programStageInstanceService;
@Autowired
private ConstantService constantService;
private Date incidentDate;
private Date enrollmentDate;
private ProgramStage psA;
private ProgramStage psB;
private Program programA;
private Program programB;
private ProgramInstance programInstance;
private DataElement deA;
private DataElement deB;
private TrackedEntityAttribute atA;
private TrackedEntityAttribute atB;
private ProgramIndicator indicatorA;
private ProgramIndicator indicatorB;
private ProgramIndicator indicatorC;
private ProgramIndicator indicatorD;
private ProgramIndicator indicatorE;
private ProgramIndicator indicatorF;
@Override
public void setUpTest()
{
OrganisationUnit organisationUnit = createOrganisationUnit( 'A' );
organisationUnitService.addOrganisationUnit( organisationUnit );
// ---------------------------------------------------------------------
// Program
// ---------------------------------------------------------------------
programA = createProgram( 'A', new HashSet<>(), organisationUnit );
programService.addProgram( programA );
psA = new ProgramStage( "StageA", programA );
psA.setSortOrder( 1 );
programStageService.saveProgramStage( psA );
psB = new ProgramStage( "StageB", programA );
psB.setSortOrder( 2 );
programStageService.saveProgramStage( psB );
Set<ProgramStage> programStages = new HashSet<>();
programStages.add( psA );
programStages.add( psB );
programA.setProgramStages( programStages );
programService.updateProgram( programA );
programB = createProgram( 'B', new HashSet<>(), organisationUnit );
programService.addProgram( programB );
// ---------------------------------------------------------------------
// Program Stage DE
// ---------------------------------------------------------------------
deA = createDataElement( 'A' );
deA.setDomainType( DataElementDomain.TRACKER );
deB = createDataElement( 'B' );
deB.setDomainType( DataElementDomain.TRACKER );
dataElementService.addDataElement( deA );
dataElementService.addDataElement( deB );
ProgramStageDataElement stageDataElementA = new ProgramStageDataElement( psA, deA, false, 1 );
ProgramStageDataElement stageDataElementB = new ProgramStageDataElement( psA, deB, false, 2 );
ProgramStageDataElement stageDataElementC = new ProgramStageDataElement( psB, deA, false, 1 );
ProgramStageDataElement stageDataElementD = new ProgramStageDataElement( psB, deB, false, 2 );
programStageDataElementService.addProgramStageDataElement( stageDataElementA );
programStageDataElementService.addProgramStageDataElement( stageDataElementB );
programStageDataElementService.addProgramStageDataElement( stageDataElementC );
programStageDataElementService.addProgramStageDataElement( stageDataElementD );
// ---------------------------------------------------------------------
// TrackedEntityInstance & Enrollment
// ---------------------------------------------------------------------
TrackedEntityInstance entityInstance = createTrackedEntityInstance( 'A', organisationUnit );
entityInstanceService.addTrackedEntityInstance( entityInstance );
incidentDate = DateUtils.getMediumDate( "2014-10-22" );
enrollmentDate = DateUtils.getMediumDate( "2014-12-31" );
programInstance = programInstanceService.enrollTrackedEntityInstance( entityInstance, programA, enrollmentDate,
incidentDate, organisationUnit );
incidentDate = DateUtils.getMediumDate( "2014-10-22" );
enrollmentDate = DateUtils.getMediumDate( "2014-12-31" );
programInstance = programInstanceService.enrollTrackedEntityInstance( entityInstance, programA, enrollmentDate,
incidentDate, organisationUnit );
// TODO enroll twice?
// ---------------------------------------------------------------------
// TrackedEntityAttribute
// ---------------------------------------------------------------------
atA = createTrackedEntityAttribute( 'A', ValueType.NUMBER );
atB = createTrackedEntityAttribute( 'B', ValueType.NUMBER );
attributeService.addTrackedEntityAttribute( atA );
attributeService.addTrackedEntityAttribute( atB );
TrackedEntityAttributeValue attributeValueA = new TrackedEntityAttributeValue( atA, entityInstance, "1" );
TrackedEntityAttributeValue attributeValueB = new TrackedEntityAttributeValue( atB, entityInstance, "2" );
attributeValueService.addTrackedEntityAttributeValue( attributeValueA );
attributeValueService.addTrackedEntityAttributeValue( attributeValueB );
// ---------------------------------------------------------------------
// TrackedEntityDataValue
// ---------------------------------------------------------------------
ProgramStageInstance stageInstanceA = programStageInstanceService.createProgramStageInstance( programInstance,
psA, enrollmentDate, incidentDate, organisationUnit );
ProgramStageInstance stageInstanceB = programStageInstanceService.createProgramStageInstance( programInstance,
psB, enrollmentDate, incidentDate, organisationUnit );
Set<ProgramStageInstance> programStageInstances = new HashSet<>();
programStageInstances.add( stageInstanceA );
programStageInstances.add( stageInstanceB );
programInstance.setProgramStageInstances( programStageInstances );
programInstance.setProgram( programA );
TrackedEntityDataValue dataValueA = new TrackedEntityDataValue( stageInstanceA, deA, "3" );
TrackedEntityDataValue dataValueB = new TrackedEntityDataValue( stageInstanceA, deB, "1" );
TrackedEntityDataValue dataValueC = new TrackedEntityDataValue( stageInstanceB, deA, "5" );
TrackedEntityDataValue dataValueD = new TrackedEntityDataValue( stageInstanceB, deB, "7" );
dataValueService.saveTrackedEntityDataValue( dataValueA );
dataValueService.saveTrackedEntityDataValue( dataValueB );
dataValueService.saveTrackedEntityDataValue( dataValueC );
dataValueService.saveTrackedEntityDataValue( dataValueD );
// ---------------------------------------------------------------------
// Constant
// ---------------------------------------------------------------------
Constant constantA = createConstant( 'A', 7.0 );
constantService.saveConstant( constantA );
// ---------------------------------------------------------------------
// ProgramIndicator
// ---------------------------------------------------------------------
String expressionA = "( d2:daysBetween(" + KEY_PROGRAM_VARIABLE + "{" + ProgramIndicator.VAR_ENROLLMENT_DATE + "}, " + KEY_PROGRAM_VARIABLE + "{"
+ ProgramIndicator.VAR_INCIDENT_DATE + "}) ) / " + ProgramIndicator.KEY_CONSTANT + "{" + constantA.getUid() + "}";
indicatorA = createProgramIndicator( 'A', programA, expressionA, null );
programA.getProgramIndicators().add( indicatorA );
indicatorB = createProgramIndicator( 'B', programA, "70", null );
programA.getProgramIndicators().add( indicatorB );
indicatorC = createProgramIndicator( 'C', programA, "0", null );
programA.getProgramIndicators().add( indicatorC );
String expressionD = "0 + A + 4 + " + ProgramIndicator.KEY_PROGRAM_VARIABLE + "{" + ProgramIndicator.VAR_INCIDENT_DATE + "}";
indicatorD = createProgramIndicator( 'D', programB, expressionD, null );
String expressionE = KEY_DATAELEMENT + "{" + psA.getUid() + "." + deA.getUid() + "} + " + KEY_DATAELEMENT + "{"
+ psB.getUid() + "." + deA.getUid() + "} - " + KEY_ATTRIBUTE + "{" + atA.getUid() + "} + " + KEY_ATTRIBUTE
+ "{" + atB.getUid() + "}";
String filterE = KEY_DATAELEMENT + "{" + psA.getUid() + "." + deA.getUid() + "} + " + KEY_ATTRIBUTE + "{" + atA.getUid() + "} > 10";
indicatorE = createProgramIndicator( 'E', programB, expressionE, filterE );
String expressionF = KEY_DATAELEMENT + "{" + psA.getUid() + "." + deA.getUid() + "}";
String filterF = KEY_DATAELEMENT + "{" + psA.getUid() + "." + deA.getUid() + "} > " +
KEY_ATTRIBUTE + "{" + atA.getUid() + "}";
indicatorF = createProgramIndicator( 'F', AnalyticsType.ENROLLMENT, programB, expressionF, filterF );
indicatorF.getAnalyticsPeriodBoundaries().add( new AnalyticsPeriodBoundary(AnalyticsPeriodBoundary.EVENT_DATE,
AnalyticsPeriodBoundaryType.BEFORE_END_OF_REPORTING_PERIOD, PeriodType.getByNameIgnoreCase( "daily" ), 10) );
}
// -------------------------------------------------------------------------
// CRUD tests
// -------------------------------------------------------------------------
@Test
public void testAddProgramIndicator()
{
int idA = programIndicatorService.addProgramIndicator( indicatorA );
int idB = programIndicatorService.addProgramIndicator( indicatorB );
int idC = programIndicatorService.addProgramIndicator( indicatorC );
assertNotNull( programIndicatorService.getProgramIndicator( idA ) );
assertNotNull( programIndicatorService.getProgramIndicator( idB ) );
assertNotNull( programIndicatorService.getProgramIndicator( idC ) );
}
@Test
public void testDeleteProgramIndicator()
{
int idA = programIndicatorService.addProgramIndicator( indicatorB );
int idB = programIndicatorService.addProgramIndicator( indicatorA );
assertNotNull( programIndicatorService.getProgramIndicator( idA ) );
assertNotNull( programIndicatorService.getProgramIndicator( idB ) );
programIndicatorService.deleteProgramIndicator( indicatorB );
assertNull( programIndicatorService.getProgramIndicator( idA ) );
assertNotNull( programIndicatorService.getProgramIndicator( idB ) );
programIndicatorService.deleteProgramIndicator( indicatorA );
assertNull( programIndicatorService.getProgramIndicator( idA ) );
assertNull( programIndicatorService.getProgramIndicator( idB ) );
}
@Test
public void testUpdateProgramIndicator()
{
int idA = programIndicatorService.addProgramIndicator( indicatorB );
assertNotNull( programIndicatorService.getProgramIndicator( idA ) );
indicatorB.setName( "B" );
programIndicatorService.updateProgramIndicator( indicatorB );
assertEquals( "B", programIndicatorService.getProgramIndicator( idA ).getName() );
}
@Test
public void testGetProgramIndicatorById()
{
int idA = programIndicatorService.addProgramIndicator( indicatorB );
int idB = programIndicatorService.addProgramIndicator( indicatorA );
assertEquals( indicatorB, programIndicatorService.getProgramIndicator( idA ) );
assertEquals( indicatorA, programIndicatorService.getProgramIndicator( idB ) );
}
@Test
public void testGetProgramIndicatorByName()
{
programIndicatorService.addProgramIndicator( indicatorB );
programIndicatorService.addProgramIndicator( indicatorA );
assertEquals( "IndicatorA", programIndicatorService.getProgramIndicator( "IndicatorA" ).getName() );
assertEquals( "IndicatorB", programIndicatorService.getProgramIndicator( "IndicatorB" ).getName() );
}
@Test
public void testGetAllProgramIndicators()
{
programIndicatorService.addProgramIndicator( indicatorB );
programIndicatorService.addProgramIndicator( indicatorA );
assertTrue( equals( programIndicatorService.getAllProgramIndicators(), indicatorB, indicatorA ) );
}
// -------------------------------------------------------------------------
// Logic tests
// -------------------------------------------------------------------------
@Test
public void testGetExpressionDescription()
{
programIndicatorService.addProgramIndicator( indicatorB );
programIndicatorService.addProgramIndicator( indicatorA );
String description = programIndicatorService.getExpressionDescription( indicatorB.getExpression() );
assertEquals( "70", description );
description = programIndicatorService.getExpressionDescription( indicatorA.getExpression() );
assertEquals( "( d2:daysBetween(Enrollment date, Incident date) ) / ConstantA", description );
}
@Test
public void testGetAnyValueExistsFilterEventAnalyticsSQl()
{
String expected = "\"GCyeKSqlpdk\" is not null or \"gAyeKSqlpdk\" is not null";
String expression = "#{OXXcwl6aPCQ.GCyeKSqlpdk} - A{gAyeKSqlpdk}";
assertEquals( expected, programIndicatorService.getAnyValueExistsClauseAnalyticsSql( expression, AnalyticsType.EVENT ) );
}
@Test
public void testGetAnyValueExistsFilterEnrollmentAnalyticsSQl()
{
String expected = "\"gAyeKSqlpdk\" is not null or \"OXXcwl6aPCQ_GCyeKSqlpdk\" is not null";
String expression = "#{OXXcwl6aPCQ.GCyeKSqlpdk} - A{gAyeKSqlpdk}";
assertEquals( expected, programIndicatorService.getAnyValueExistsClauseAnalyticsSql( expression, AnalyticsType.ENROLLMENT ) );
}
@Test
public void testGetAnalyticsSQl()
{
String expected = "coalesce(\"" + deA.getUid() + "\"::numeric,0) + coalesce(\"" + atA.getUid() + "\"::numeric,0) > 10";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( indicatorE.getFilter(), indicatorE, new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSQlRespectMissingValues()
{
String expected = "\"" + deA.getUid() + "\" + \"" + atA.getUid() + "\" > 10";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( indicatorE.getFilter(), indicatorE, false, new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsWithVariables()
{
String expected =
"coalesce(case when \"EZq9VbPWgML\" < 0 then 0 else \"EZq9VbPWgML\" end, 0) + " +
"coalesce(\"GCyeKSqlpdk\"::numeric,0) + " +
"nullif(cast((case when \"EZq9VbPWgML\" >= 0 then 1 else 0 end + case when \"GCyeKSqlpdk\" >= 0 then 1 else 0 end) as double),0)";
String expression =
"d2:zing(#{OXXcwl6aPCQ.EZq9VbPWgML}) + " +
"#{OXXcwl6aPCQ.GCyeKSqlpdk} + " +
"V{zero_pos_value_count}";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsZingA()
{
String col = COL_QUOTE + deA.getUid() + COL_QUOTE;
String expected = "coalesce(case when " + col + " < 0 then 0 else " + col + " end, 0)";
String expression = "d2:zing(" + col + ")";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsZingB()
{
String expected =
"coalesce(case when \"EZq9VbPWgML\" < 0 then 0 else \"EZq9VbPWgML\" end, 0) + " +
"coalesce(case when \"GCyeKSqlpdk\" < 0 then 0 else \"GCyeKSqlpdk\" end, 0) + " +
"coalesce(case when \"hsCmEqBcU23\" < 0 then 0 else \"hsCmEqBcU23\" end, 0)";
String expression =
"d2:zing(#{OXXcwl6aPCQ.EZq9VbPWgML}) + " +
"d2:zing(#{OXXcwl6aPCQ.GCyeKSqlpdk}) + " +
"d2:zing(#{OXXcwl6aPCQ.hsCmEqBcU23})";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsOizp()
{
String col = COL_QUOTE + deA.getUid() + COL_QUOTE;
String expected = "coalesce(case when " + col + " >= 0 then 1 else 0 end, 0)";
String expression = "d2:oizp(" + col + ")";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsZpvc()
{
String expected =
"nullif(cast((" +
"case when \"EZq9VbPWgML\" >= 0 then 1 else 0 end + " +
"case when \"GCyeKSqlpdk\" >= 0 then 1 else 0 end" +
") as double precision),0)";
String expression = "d2:zpvc(#{OXXcwl6aPCQ.EZq9VbPWgML},#{OXXcwl6aPCQ.GCyeKSqlpdk})";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsDaysBetween()
{
String col1 = COL_QUOTE + deA.getUid() + COL_QUOTE;
String col2 = COL_QUOTE + deB.getUid() + COL_QUOTE;
String expected = "(cast(" + col2 + " as date) - cast(" + col1 + " as date))";
String expression = "d2:daysBetween(" + col1 + "," + col2 + ")";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsCondition()
{
String col1 = COL_QUOTE + deA.getUid() + COL_QUOTE;
String expected = "case when (" + col1 + " > 3) then 10 else 5 end";
String expression = "d2:condition('" + col1 + " > 3',10,5)";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithFunctionsComposite()
{
String expected =
"coalesce(case when \"EZq9VbPWgML\" < 0 then 0 else \"EZq9VbPWgML\" end, 0) + " +
"(cast(\"kts5J79K9gA\" as date) - cast(\"GCyeKSqlpdk\" as date)) + " +
"case when (\"GCyeKSqlpdk\" > 70) then 100 else 50 end + " +
"case when (\"HihhUWBeg7I\" < 30) then 20 else 100 end";
String expression =
"d2:zing(#{OXXcwl6aPCQ.EZq9VbPWgML}) + " +
"d2:daysBetween(#{OXXcwl6aPCQ.GCyeKSqlpdk},#{OXXcwl6aPCQ.kts5J79K9gA}) + " +
"d2:condition(\"#{OXXcwl6aPCQ.GCyeKSqlpdk} > 70\",100,50) + " +
"d2:condition('#{OXXcwl6aPCQ.HihhUWBeg7I} < 30',20,100)";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test( expected = IllegalStateException.class )
public void testGetAnalyticsSqlWithFunctionsInvalid()
{
String col = COL_QUOTE + deA.getUid() + COL_QUOTE;
String expected = "case when " + col + " >= 0 then 1 else " + col + " end";
String expression = "d2:xyza(" + col + ")";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testGetAnalyticsSqlWithVariables()
{
String expected = "coalesce(\"EZq9VbPWgML\"::numeric,0) + (executiondate - enrollmentdate)";
String expression = "#{OXXcwl6aPCQ.EZq9VbPWgML} + (V{execution_date} - V{enrollment_date})";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( expression, createProgramIndicator( 'X', programA, expression, null ), new Date(), new Date() ) );
}
@Test
public void testIsEmptyFilter()
{
String expected = "coalesce(\"EZq9VbPWgML\",'') == '' ";
String filter = "#{OXXcwl6aPCQ.EZq9VbPWgML} == ''";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( filter, createProgramIndicator( 'X', programA, null, filter ), new Date(), new Date() ) );
}
@Test
public void testIsZeroFilter()
{
String expected = "coalesce(\"OXXcwl6aPCQ_EZq9VbPWgML\"::numeric,0) == 0 ";
String filter = "#{OXXcwl6aPCQ.EZq9VbPWgML} == 0";
assertEquals( expected, programIndicatorService.getAnalyticsSQl( filter, createProgramIndicator( 'X', AnalyticsType.ENROLLMENT, programA, null, filter ), new Date(), new Date() ) );
}
@Test
public void testIsZeroOrEmptyFilter()
{
String expected = "coalesce(\"OXXcwl6aPCQ_GCyeKSqlpdk\"::numeric,0) == 1 or " +
"(coalesce(\"OXXcwl6aPCQ_GCyeKSqlpdk\",'') == '' and " +
"coalesce(\"kts5J79K9gA\"::numeric,0) == 0 )";
String filter = "#{OXXcwl6aPCQ.GCyeKSqlpdk} == 1 or " +
"(#{OXXcwl6aPCQ.GCyeKSqlpdk} == '' and A{kts5J79K9gA}== 0)";
String actual = programIndicatorService.getAnalyticsSQl( filter, createProgramIndicator( 'X', AnalyticsType.ENROLLMENT, programA, null, filter ), true, new Date(), new Date() );
assertEquals( expected, actual );
}
@Test
public void testEnrollmentIndicatorWithEventBoundaryExpression()
{
String expected = "coalesce((select \"" + deA.getUid() + "\" from analytics_event_" + programB.getUid() + " " +
"where analytics_event_" + indicatorF.getProgram().getUid() +
".pi = ax.pi and \"" + deA.getUid() + "\" is not null " +
"and executiondate < cast( '2018-03-11' as date ) and "+
"ps = '" + psA.getUid() + "' order by executiondate desc limit 1 )::numeric,0)";
Date reportingStartDate = new GregorianCalendar(2018, Calendar.FEBRUARY, 1).getTime();
Date reportingEndDate = new GregorianCalendar(2018, Calendar.FEBRUARY, 28).getTime();
String actual = programIndicatorService.getAnalyticsSQl( indicatorF.getExpression(), indicatorF, true, reportingStartDate, reportingEndDate );
assertEquals( expected, actual );
}
@Test
public void testEnrollmentIndicatorWithEventBoundaryFilter()
{
String expected = "(select \"" + deA.getUid() + "\" from analytics_event_" + programB.getUid() + " " +
"where analytics_event_" + indicatorF.getProgram().getUid() + ".pi " +
"= ax.pi and \"" + deA.getUid() + "\" is not null and executiondate < cast( '2018-03-11' as date ) and " +
"ps = '" + psA.getUid() + "' order by executiondate desc limit 1 ) > \"" + atA.getUid() + "\"";
Date reportingStartDate = new GregorianCalendar(2018, Calendar.FEBRUARY, 1).getTime();
Date reportingEndDate = new GregorianCalendar(2018, Calendar.FEBRUARY, 28).getTime();
String actual = programIndicatorService.getAnalyticsSQl( indicatorF.getFilter(), indicatorF, false, reportingStartDate, reportingEndDate );
assertEquals( expected, actual );
}
@Test
public void testDateFunctions()
{
String expected = "(date_part('year',age(cast('2016-01-01' as date), cast(enrollmentdate as date)))) < 1 " +
"and (date_part('year',age(cast('2016-12-31' as date), cast(enrollmentdate as date)))) >= 1";
String filter = "d2:yearsBetween(V{enrollment_date}, V{analytics_period_start}) < 1 " +
"and d2:yearsBetween(V{enrollment_date}, V{analytics_period_end}) >= 1";
String actual = programIndicatorService.getAnalyticsSQl( filter, createProgramIndicator( 'X', programA, filter, null ), true, DateUtils.parseDate( "2016-01-01" ) , DateUtils.parseDate( "2016-12-31" ) );
assertEquals( expected, actual );
}
@Test
public void testExpressionIsValid()
{
programIndicatorService.addProgramIndicator( indicatorB );
programIndicatorService.addProgramIndicator( indicatorA );
programIndicatorService.addProgramIndicator( indicatorD );
assertEquals( ProgramIndicator.VALID, programIndicatorService.expressionIsValid( indicatorB.getExpression() ) );
assertEquals( ProgramIndicator.VALID, programIndicatorService.expressionIsValid( indicatorA.getExpression() ) );
assertEquals( ProgramIndicator.EXPRESSION_NOT_VALID, programIndicatorService.expressionIsValid( indicatorD.getExpression() ) );
}
@Test
public void testExpressionWithFunctionIsValid()
{
String exprA = "#{" + psA.getUid() + "." + deA.getUid() + "}";
String exprB = "d2:zing(#{" + psA.getUid() + "." + deA.getUid() + "})";
String exprC = "d2:condition('#{" + psA.getUid() + "." + deA.getUid() + "} > 10',2,1)";
assertEquals( ProgramIndicator.VALID, programIndicatorService.expressionIsValid( exprA ) );
assertEquals( ProgramIndicator.VALID, programIndicatorService.expressionIsValid( exprB ) );
assertEquals( ProgramIndicator.VALID, programIndicatorService.expressionIsValid( exprC ) );
}
@Test
public void testFilterIsValid()
{
String filterA = KEY_DATAELEMENT + "{" + psA.getUid() + "." + deA.getUid() + "} - " + KEY_ATTRIBUTE + "{" + atA.getUid() + "} > 10";
String filterB = KEY_ATTRIBUTE + "{" + atA.getUid() + "} == " + KEY_DATAELEMENT + "{" + psA.getUid() + "." + deA.getUid() + "} - 5";
String filterC = KEY_ATTRIBUTE + "{invaliduid} == 100";
String filterD = KEY_ATTRIBUTE + "{" + atA.getUid() + "} + 200";
assertEquals( ProgramIndicator.VALID, programIndicatorService.filterIsValid( filterA ) );
assertEquals( ProgramIndicator.VALID, programIndicatorService.filterIsValid( filterB ) );
assertEquals( ProgramIndicator.INVALID_IDENTIFIERS_IN_EXPRESSION, programIndicatorService.filterIsValid( filterC ) );
assertEquals( ProgramIndicator.FILTER_NOT_EVALUATING_TO_TRUE_OR_FALSE, programIndicatorService.filterIsValid( filterD ) );
}
}
|
Java
|
public final class DelegatingClusterEventProducer extends ClusterEventProducerBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private ClusterEventProducer delegate;
// support for tests to make sure the update is completed
private volatile Phaser phaser;
public DelegatingClusterEventProducer(CoreContainer cc) {
super(cc);
delegate = new NoOpProducer(cc);
}
@Override
public void close() throws IOException {
if (log.isDebugEnabled()) {
log.debug("--closing delegate for CC-{}: {}", Integer.toHexString(cc.hashCode()), delegate);
}
IOUtils.closeQuietly(delegate);
super.close();
}
/**
* A phaser that will advance phases every time {@link #setDelegate(ClusterEventProducer)} is
* called. Useful for allowing tests to know when a new delegate is finished getting set.
*/
@VisibleForTesting
public void setDelegationPhaser(Phaser phaser) {
phaser.register();
this.phaser = phaser;
}
public void setDelegate(ClusterEventProducer newDelegate) {
if (log.isDebugEnabled()) {
log.debug(
"--setting new delegate for CC-{}: {}", Integer.toHexString(cc.hashCode()), newDelegate);
}
this.delegate = newDelegate;
// transfer all listeners to the new delegate
listeners.forEach(
(type, listenerSet) -> {
listenerSet.forEach(
listener -> {
try {
delegate.registerListener(listener, type);
} catch (Exception e) {
log.warn("Exception registering listener with the new event producer", e);
// make sure it's not registered
delegate.unregisterListener(listener, type);
// unregister it here, too
super.unregisterListener(listener, type);
}
});
});
if ((state == State.RUNNING || state == State.STARTING)
&& !(delegate.getState() == State.RUNNING || delegate.getState() == State.STARTING)) {
try {
delegate.start();
if (log.isDebugEnabled()) {
log.debug("--- started delegate {}", delegate);
}
} catch (Exception e) {
log.warn("Unable to start the new delegate {}: {}", delegate.getClass().getName(), e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("--- delegate {} already in state {}", delegate, delegate.getState());
}
}
Phaser localPhaser = phaser; // volatile read
if (localPhaser != null) {
assert localPhaser.getRegisteredParties() == 1;
// we should be the only ones registered, so this will advance phase each time
localPhaser.arrive();
}
}
@Override
public void registerListener(
ClusterEventListener listener, ClusterEvent.EventType... eventTypes) {
super.registerListener(listener, eventTypes);
delegate.registerListener(listener, eventTypes);
}
@Override
public void unregisterListener(
ClusterEventListener listener, ClusterEvent.EventType... eventTypes) {
super.unregisterListener(listener, eventTypes);
delegate.unregisterListener(listener, eventTypes);
}
@Override
public synchronized void start() throws Exception {
if (log.isDebugEnabled()) {
log.debug(
"-- starting CC-{}, Delegating {}, delegate {}",
Integer.toHexString(cc.hashCode()),
Integer.toHexString(hashCode()),
delegate);
}
state = State.STARTING;
if (!(delegate.getState() == State.RUNNING || delegate.getState() == State.STARTING)) {
try {
delegate.start();
if (log.isDebugEnabled()) {
log.debug("--- started delegate {}", delegate);
}
} finally {
state = delegate.getState();
}
} else {
if (log.isDebugEnabled()) {
log.debug("--- delegate {} already in state {}", delegate, delegate.getState());
}
}
}
@Override
public Set<ClusterEvent.EventType> getSupportedEventTypes() {
return NoOpProducer.ALL_EVENT_TYPES;
}
@Override
public synchronized void stop() {
if (log.isDebugEnabled()) {
log.debug(
"-- stopping Delegating {}, delegate {}", Integer.toHexString(hashCode()), delegate);
}
state = State.STOPPING;
delegate.stop();
state = delegate.getState();
}
}
|
Java
|
public class Main {
public static void main(String... args) {
// From regression/mediumbridgeshards.
TestCase3371.test();
TestCase718.test();
TestCase10015.test();
TestCase10020.test();
TestCase10092.test();
TestCase3783.test();
TestCase8166.test();
TestCase10332.test();
TestCase615.test();
TestCase6104.test();
TestCase9366.test();
TestCase5814.test();
TestCase6674.test();
TestCase9226.test();
TestCase55.test();
TestCase3352.test();
TestCase4787.test();
TestCase1596.test();
TestCase2123.test();
TestCase4182.test();
TestCase5828.test();
TestCase6.test();
TestCase8435.test();
TestCase8939.test();
// From allsimplebridges.
Tester5.test();
// Hand rolled.
TestCaseHand1.test();
TestCaseHand2.test();
// Minimal versions of existing tests.
BridgeJsMethodMain.test();
BridgeMethodsMain.test();
MultipleAbstractParentsMain.test();
DefaultMethodsMain.test();
OverwrittenTypeVariablesMain.test();
}
}
|
Java
|
class Solution {
public boolean lemonadeChange(int[] bills) {
if (bills[0] != 5 || bills[1] == 20 || bills[2] == 20){
return false;
}
int cnt_five = 0, cnt_ten = 0;
for (int i = 0; i < bills.length; i++) {
if (bills[i] == 5) {
cnt_five++;
} else if(bills[i] == 10) {
cnt_five--;
cnt_ten++;
if (cnt_five < 0) {
return false;
}
}else{
if (cnt_ten > 0 && cnt_five > 0) {
cnt_ten--;
cnt_five--;
} else if (cnt_ten == 0 && cnt_five >= 3) {
cnt_five -= 3;
} else {
return false;
}
}
}
return true;
}
}
|
Java
|
@Slf4j
public class CommonOperateControllerTests extends DebuggerKingApplicationTests {
// @Test
// public void listSysDictByPageTest()
// throws Exception {
// Map<String, Object> params = Maps.newHashMap();
// params.put("demo", "this is a demo");
//
// HttpHeaders httpHeaders = springBootJunitTestUtil.generateRequestHeaders();
// Cookie[] cookies = springBootJunitTestUtil.buildMockHttpServletRequestCookie();
// springBootJunitTestUtil.execute(params, "/sysDict/listByPage", httpHeaders, HttpTypeEnum.POST_PARAM, cookies);
// }
//
// @Test
// @Rollback(false)
// public void batchInsertWithIdsBackTest()
// throws Exception {
// HttpHeaders httpHeaders = springBootJunitTestUtil.generateRequestHeaders();
// Cookie[] cookies = springBootJunitTestUtil.buildMockHttpServletRequestCookie();
// springBootJunitTestUtil.execute(null, "/sysDict/testBatchInsertWithBackIds", httpHeaders, HttpTypeEnum.POST_BODY, cookies);
// }
}
|
Java
|
@SuppressWarnings( "all" )
public class Activation
implements java.io.Serializable
{
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Flag specifying whether this profile is active as a default.
*/
private boolean activeByDefault = false;
/**
*
* Specifies that this profile will be activated
* when a matching JDK is detected.
*
*/
private String jdk;
/**
*
* Specifies that this profile will be activated
* when matching OS attributes are detected.
*
*/
private ActivationOS os;
/**
*
* Specifies that this profile will be activated
* when this System property is specified.
*
*/
private ActivationProperty property;
/**
*
* Specifies that this profile will be activated
* based on existence of a file.
*
*/
private ActivationFile file;
//-----------/
//- Methods -/
//-----------/
/**
* Get specifies that this profile will be activated based on
* existence of a file.
*
* @return ActivationFile
*/
public ActivationFile getFile()
{
return this.file;
} //-- ActivationFile getFile()
/**
* Get specifies that this profile will be activated when a
* matching JDK is detected.
*
* @return String
*/
public String getJdk()
{
return this.jdk;
} //-- String getJdk()
/**
* Get specifies that this profile will be activated when
* matching OS attributes are detected.
*
* @return ActivationOS
*/
public ActivationOS getOs()
{
return this.os;
} //-- ActivationOS getOs()
/**
* Get specifies that this profile will be activated when this
* System property is specified.
*
* @return ActivationProperty
*/
public ActivationProperty getProperty()
{
return this.property;
} //-- ActivationProperty getProperty()
/**
* Get flag specifying whether this profile is active as a
* default.
*
* @return boolean
*/
public boolean isActiveByDefault()
{
return this.activeByDefault;
} //-- boolean isActiveByDefault()
/**
* Set flag specifying whether this profile is active as a
* default.
*
* @param activeByDefault
*/
public void setActiveByDefault( boolean activeByDefault )
{
this.activeByDefault = activeByDefault;
} //-- void setActiveByDefault( boolean )
/**
* Set specifies that this profile will be activated based on
* existence of a file.
*
* @param file
*/
public void setFile( ActivationFile file )
{
this.file = file;
} //-- void setFile( ActivationFile )
/**
* Set specifies that this profile will be activated when a
* matching JDK is detected.
*
* @param jdk
*/
public void setJdk( String jdk )
{
this.jdk = jdk;
} //-- void setJdk( String )
/**
* Set specifies that this profile will be activated when
* matching OS attributes are detected.
*
* @param os
*/
public void setOs( ActivationOS os )
{
this.os = os;
} //-- void setOs( ActivationOS )
/**
* Set specifies that this profile will be activated when this
* System property is specified.
*
* @param property
*/
public void setProperty( ActivationProperty property )
{
this.property = property;
} //-- void setProperty( ActivationProperty )
}
|
Java
|
@RestController
public class RestServiceAutomationDevice {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
private final FRITZBox fritzBox;
@Autowired
public RestServiceAutomationDevice(@NonNull final FRITZBox fritzBox) {
this.fritzBox = fritzBox;
}
@GetMapping("/api/device")
public ResponseEntity<List<DeviceInfo>> getDevices() {
try {
return new ResponseEntity<>(fritzBox.getDevices(), HttpStatus.OK);
}
catch (Exception exception) {
LOGGER.debug("Problem occurred while retrieving the device list, reason: {}", exception.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("/api/device/{id}")
public ResponseEntity<DeviceInfo> getDevice(@PathVariable final Long id) {
try {
return new ResponseEntity<>(fritzBox.getDevice(id), HttpStatus.OK);
}
catch (Exception exception) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("/api/device/stats/{ain}")
public ResponseEntity<DeviceStats> getDeviceStats(@PathVariable final String ain) {
try {
return new ResponseEntity<>(fritzBox.getDeviceStats(ain), HttpStatus.OK);
}
catch (Exception exception) {
LOGGER.debug("Problem occurred while retrieving the device stats ({}), reason: {}", ain, exception.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("/api/device/{id}/{command}")
public ResponseEntity<Void> executeCommand(@PathVariable final Long id, @PathVariable final String command) {
try {
fritzBox.handleDeviceCommand(id, command);
return new ResponseEntity<>(HttpStatus.OK);
}
catch (Exception exception) {
LOGGER.debug("Problem occurred while executing command, reason: {}", exception.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
}
}
|
Java
|
public final class DynamoDBTableMapper<T extends Object, H extends Object, R extends Object> {
private static final Log LOG = LogFactory.getLog(DynamoDBTableMapper.class);
private final DynamoDBMapperTableModel<T> model;
private final DynamoDBMapperFieldModel<T,H> hk;
private final DynamoDBMapperFieldModel<T,R> rk;
private final DynamoDBMapperConfig config;
private final DynamoDBMapper mapper;
private final AmazonDynamoDB db;
/**
* Constructs a new table mapper for the given class.
* @param model The field model factory.
* @param mapper The DynamoDB mapper.
* @param db The service object to use for all service calls.
*/
protected DynamoDBTableMapper(AmazonDynamoDB db, DynamoDBMapper mapper, final DynamoDBMapperConfig config, final DynamoDBMapperTableModel<T> model) {
this.rk = model.rangeKeyIfExists();
this.hk = model.hashKey();
this.model = model;
this.config = config;
this.mapper = mapper;
this.db = db;
}
/**
* Gets the field model for a given attribute.
* @param <V> The field model's value type.
* @param attributeName The attribute name.
* @return The field model.
*/
public <V> DynamoDBMapperFieldModel<T,V> field(String attributeName) {
return this.model.field(attributeName);
}
/**
* Gets the hash key field model for the specified type.
* @param <H> The hash key type.
* @return The hash key field model.
* @throws DynamoDBMappingException If the hash key is not present.
*/
public DynamoDBMapperFieldModel<T,H> hashKey() {
return this.model.hashKey();
}
/**
* Gets the range key field model for the specified type.
* @param <R> The range key type.
* @return The range key field model.
* @throws DynamoDBMappingException If the range key is not present.
*/
public DynamoDBMapperFieldModel<T,R> rangeKey() {
return this.model.rangeKey();
}
/**
* Retrieves multiple items from the table using their primary keys.
* @param itemsToGet The items to get.
* @return The list of objects.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#batchLoad
*/
public List<T> batchLoad(Iterable<T> itemsToGet) {
final Map<String,List<Object>> results = mapper.batchLoad(itemsToGet);
if (results.isEmpty()) {
return Collections.<T>emptyList();
}
return (List<T>)results.get(mapper.getTableName(model.targetType(), config));
}
/**
* Saves the objects given using one or more calls to the batchWriteItem API.
* @param objectsToSave The objects to save.
* @return The list of failed batches.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#batchSave
*/
public List<DynamoDBMapper.FailedBatch> batchSave(Iterable<T> objectsToSave) {
return mapper.batchWrite(objectsToSave, (Iterable<T>)Collections.<T>emptyList());
}
/**
* Deletes the objects given using one or more calls to the batchWtiteItem API.
* @param objectsToDelete The objects to delete.
* @return The list of failed batches.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#batchDelete
*/
public List<DynamoDBMapper.FailedBatch> batchDelete(Iterable<T> objectsToDelete) {
return mapper.batchWrite((Iterable<T>)Collections.<T>emptyList(), objectsToDelete);
}
/**
* Saves and deletes the objects given using one or more calls to the
* batchWriteItem API.
* @param objectsToWrite The objects to write.
* @param objectsToDelete The objects to delete.
* @return The list of failed batches.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#batchWrite
*/
public List<DynamoDBMapper.FailedBatch> batchWrite(Iterable<T> objectsToWrite, Iterable<T> objectsToDelete) {
return mapper.batchWrite(objectsToWrite, objectsToDelete);
}
/**
* Loads an object with the hash key given.
* @param hashKey The hash key value.
* @return The object.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#load
*/
public T load(H hashKey) {
return mapper.<T>load(model.targetType(), hashKey);
}
/**
* Loads an object with the hash and range key.
* @param hashKey The hash key value.
* @param rangeKey The range key value.
* @return The object.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#load
*/
public T load(H hashKey, R rangeKey) {
return mapper.<T>load(model.targetType(), hashKey, rangeKey);
}
/**
* Saves the object given into DynamoDB.
* @param object The object to save.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#save
*/
public void save(T object) {
mapper.<T>save(object);
}
/**
* Saves the object given into DynamoDB using the specified saveExpression.
* @param object The object to save.
* @param saveExpression The save expression.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#save
*/
public void save(T object, DynamoDBSaveExpression saveExpression) {
mapper.<T>save(object, saveExpression);
}
/**
* Saves the object given into DynamoDB with the condition that the hash
* and if applicable, the range key, does not already exist.
* @param object The object to create.
* @throws ConditionalCheckFailedException If the object exists.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#save
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression
* @see com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue
*/
public void saveIfNotExists(T object) throws ConditionalCheckFailedException {
final DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
for (final DynamoDBMapperFieldModel<T,Object> key : model.keys()) {
saveExpression.withExpectedEntry(key.name(), new ExpectedAttributeValue()
.withExists(false));
}
mapper.<T>save(object, saveExpression);
}
/**
* Saves the object given into DynamoDB with the condition that the hash
* and, if applicable, the range key, already exist.
* @param object The object to update.
* @throws ConditionalCheckFailedException If the object does not exist.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#save
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression
* @see com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue
*/
public void saveIfExists(T object) throws ConditionalCheckFailedException {
final DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
for (final DynamoDBMapperFieldModel<T,Object> key : model.keys()) {
saveExpression.withExpectedEntry(key.name(), new ExpectedAttributeValue()
.withExists(true).withValue(key.convert(key.get(object))));
}
mapper.<T>save(object, saveExpression);
}
/**
* Deletes the given object from its DynamoDB table.
* @param object The object to delete.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#delete
*/
public final void delete(final T object) {
mapper.delete(object);
}
/**
* Deletes the given object from its DynamoDB table using the specified
* deleteExpression.
* @param object The object to delete.
* @param deleteExpression The delete expression.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#delete
*/
public final void delete(final T object, final DynamoDBDeleteExpression deleteExpression) {
mapper.delete(object, deleteExpression);
}
/**
* Deletes the given object from its DynamoDB table with the condition that
* the hash and, if applicable, the range key, already exist.
* @param object The object to delete.
* @throws ConditionalCheckFailedException If the object does not exist.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#delete
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDeleteExpression
* @see com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue
*/
public void deleteIfExists(T object) throws ConditionalCheckFailedException {
final DynamoDBDeleteExpression deleteExpression = new DynamoDBDeleteExpression();
for (final DynamoDBMapperFieldModel<T,Object> key : model.keys()) {
deleteExpression.withExpectedEntry(key.name(), new ExpectedAttributeValue()
.withExists(true).withValue(key.convert(key.get(object))));
}
mapper.delete(object, deleteExpression);
}
/**
* Evaluates the specified query expression and returns the count of matching
* items, without returning any of the actual item data
* @param queryExpression The query expression.
* @return The count.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#count
*/
public int count(DynamoDBQueryExpression<T> queryExpression) {
return mapper.<T>count(model.targetType(), queryExpression);
}
/**
* Queries an Amazon DynamoDB table and returns the matching results as an
* unmodifiable list of instantiated objects.
* @param queryExpression The query expression.
* @return The query results.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#query
*/
public PaginatedQueryList<T> query(DynamoDBQueryExpression<T> queryExpression) {
return mapper.<T>query(model.targetType(), queryExpression);
}
/**
* Queries an Amazon DynamoDB table and returns a single page of matching
* results.
* @param queryExpression The query expression.
* @return The query results.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#query
*/
public QueryResultPage<T> queryPage(DynamoDBQueryExpression<T> queryExpression) {
return mapper.<T>queryPage(model.targetType(), queryExpression);
}
/**
* Evaluates the specified scan expression and returns the count of matching
* items, without returning any of the actual item data.
* @param scanExpression The scan expression.
* @return The count.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#count
*/
public int count(DynamoDBScanExpression scanExpression) {
return mapper.count(model.targetType(), scanExpression);
}
/**
* Scans through an Amazon DynamoDB table and returns the matching results
* as an unmodifiable list of instantiated objects.
* @param scanExpression The scan expression.
* @return The scan results.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#scan
*/
public PaginatedScanList<T> scan(DynamoDBScanExpression scanExpression) {
return mapper.<T>scan(model.targetType(), scanExpression);
}
/**
* Scans through an Amazon DynamoDB table and returns a single page of
* matching results.
* @param scanExpression The scan expression.
* @return The scan results.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#scanPage
*/
public ScanResultPage<T> scanPage(DynamoDBScanExpression scanExpression) {
return mapper.<T>scanPage(model.targetType(), scanExpression);
}
/**
* Scans through an Amazon DynamoDB table on logically partitioned segments
* in parallel and returns the matching results in one unmodifiable list of
* instantiated objects.
* @param scanExpression The scan expression.
* @param totalSegments The total segments.
* @return The scan results.
* @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#parallelScan
*/
public PaginatedParallelScanList<T> parallelScan(DynamoDBScanExpression scanExpression, int totalSegments) {
return mapper.<T>parallelScan(model.targetType(), scanExpression, totalSegments);
}
/**
* Returns information about the table, including the current status of the
* table, when it was created, the primary key schema, and any indexes on
* the table.
* @return The describe table results.
* @see com.amazonaws.services.dynamodbv2.AmazonDynamoDB#describeTable
*/
public TableDescription describeTable() {
return db.describeTable(
mapper.getTableName(model.targetType(), config)
).getTable();
}
/**
* Creates the table with the specified throughput; also populates the same
* throughput for all global secondary indexes.
* @param throughput The provisioned throughput.
* @return The table decription.
* @see com.amazonaws.services.dynamodbv2.AmazonDynamoDB#createTable
* @see com.amazonaws.services.dynamodbv2.model.CreateTableRequest
*/
public TableDescription createTable(ProvisionedThroughput throughput) {
final CreateTableRequest request = mapper.generateCreateTableRequest(model.targetType());
request.setProvisionedThroughput(throughput);
if (request.getGlobalSecondaryIndexes() != null) {
for (final GlobalSecondaryIndex gsi : request.getGlobalSecondaryIndexes()) {
gsi.setProvisionedThroughput(throughput);
}
}
return db.createTable(request).getTableDescription();
}
/**
* Creates the table and ignores the {@code ResourceInUseException} if it
* ialready exists.
* @param throughput The provisioned throughput.
* @return True if created, or false if the table already existed.
* @see com.amazonaws.services.dynamodbv2.AmazonDynamoDB#createTable
* @see com.amazonaws.services.dynamodbv2.model.CreateTableRequest
*/
public boolean createTableIfNotExists(ProvisionedThroughput throughput) {
try {
createTable(throughput);
} catch (final ResourceInUseException e) {
if (LOG.isTraceEnabled()) {
LOG.trace("Table already exists, no need to create", e);
}
return false;
}
return true;
}
/**
* Deletes the table.
* @return The table decription.
* @see com.amazonaws.services.dynamodbv2.AmazonDynamoDB#deleteTable
* @see com.amazonaws.services.dynamodbv2.model.DeleteTableRequest
*/
public TableDescription deleteTable() {
return db.deleteTable(
mapper.generateDeleteTableRequest(model.targetType())
).getTableDescription();
}
/**
* Deletes the table and ignores the {@code ResourceNotFoundException} if
* it does not already exist.
* @return True if the table was deleted, or false if the table did not exist.
* @see com.amazonaws.services.dynamodbv2.AmazonDynamoDB#deleteTable
* @see com.amazonaws.services.dynamodbv2.model.DeleteTableRequest
*/
public boolean deleteTableIfExists() {
try {
deleteTable();
} catch (final ResourceNotFoundException e) {
if (LOG.isTraceEnabled()) {
LOG.trace("Table does not exist, no need to delete", e);
}
return false;
}
return true;
}
}
|
Java
|
public class Node {
/**
* Described in http://bittorrent.org/beps/bep_0005.html#routing-table
*/
public enum Status {
good, questionable, bad
}
private byte[] id;
private InetAddress ip;
private int port;
private int token;
private boolean isBad;
private long lastChanged;
static final int FRESH_LIMIT = 15*60*1000; // in milliseconds
/**
* Create a new node with id, ip, port as specified
*/
public Node(byte[] id, InetAddress ip, int port) {
this.id = new byte[160/8];
System.arraycopy(id, 0, this.id, 0, 160/8);
this.ip = ip;
this.port = port;
this.lastChanged = System.currentTimeMillis();
this.token = -1;
this.isBad = false;
}
/**
* Create a new node with id, ip, port as specified
*/
public Node(byte[] id, byte[] ip, byte[] port) throws UnknownHostException {
this(id, InetAddress.getByAddress(ip),
((port[0] & 0xFF) << 8) | (port[1] & 0xFF));
}
/**
* Returns this node id
*/
public byte[] id() {
return this.id;
}
/**
* Returns this node ip
*/
public InetAddress ip() {
return this.ip;
}
/**
* Return this node peer
*/
public int port() {
return this.port;
}
/**
* Return this node token if it was set, -1 otherwise
*/
public int token() {
return this.token;
}
/**
* Set this node token, normally the value comes from
* the "token" key in a "get_peers" response.
*/
public void setToken(int token) {
this.token = token;
}
/**
* Set a node status to be bad. From BEP5: "Nodes become bad when they fail
* to respond to multiple queries in a row.
*/
public void setBad(boolean bad) {
this.isBad = bad;
}
/**
* Return this node status, as described in:
* http://bittorrent.org/beps/bep_0005.html#routing-table
*/
public Status status() {
if (this.isBad) {
return Status.bad;
}
if ((System.currentTimeMillis() - this.lastChanged) <= FRESH_LIMIT) {
return Status.questionable;
}
return Status.good;
}
/**
* Refresh this node as described in:
* http://bittorrent.org/beps/bep_0005.html#routing-table
*/
public void refresh() {
this.lastChanged = System.currentTimeMillis();
}
}
|
Java
|
@Value(staticConstructor = "of")
@EqualsAndHashCode(callSuper = true)
public final class Version extends ValueObject {
public static final Version INITIAL_VERSION = Version.of(0);
private final int version;
public int get() {
return version;
}
}
|
Java
|
public class AddTagCommandParser implements Parser<AddTagCommand> {
/**
* Parses the given {@code String} of arguments in the context of the AddTagCommand
* and returns a AddTagCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public AddTagCommand parse(String args) throws ParseException {
final int indexLowerLimit = 0;
final int indexUpperLimit = 1;
final int indexIsTag = 2;
final int indexIsRange = 3;
Set<Tag> toAddSet = new HashSet<>();
Set<Index> index = new HashSet<>();
String indexInput;
List<String> indexSet = new ArrayList<>();
if (args.trim().isEmpty()) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
StringTokenizer st = new StringTokenizer(args.trim(), " ");
List<String> firstItemArray;
String firstItem = st.nextToken();
firstItemArray = fillCheckArray(firstItem);
boolean firstTag;
boolean isRange;
String lowerLimit = firstItemArray.get(indexLowerLimit);
String upperLimit = firstItemArray.get(indexUpperLimit);
String checkFirstTag = firstItemArray.get(indexIsTag);
String checkIsRange = firstItemArray.get(indexIsRange);
if (checkIsRange.equals("true")) {
isRange = true;
} else {
isRange = false;
}
if (checkFirstTag.equals("true")) {
firstTag = true;
} else {
firstTag = false;
}
// Check if first keyword is tag or index
if (firstTag) {
throw new ParseException("Please provide an input for index.\n"
+ String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
} else {
if (isRange) {
// Check if any of the limit is empty
boolean isLowerValid = lowerLimit.isEmpty();
boolean isUpperValid = upperLimit.isEmpty();
if (isLowerValid || isUpperValid) {
throw new ParseException("Invalid index range provided.\n"
+ String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
// Check if range is appropriate
int lower = Integer.parseInt(lowerLimit);
int upper = Integer.parseInt(upperLimit);
if (lower > upper) {
throw new ParseException("Invalid index range provided.\n"
+ String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
// Adding of range of indexes
for (int i = lower; i <= upper; i++) {
String toAdd = String.valueOf(i);
indexSet.add(toAdd);
try {
Index indexFromRangeToAdd = ParserUtil.parseIndex(toAdd);
index.add(indexFromRangeToAdd);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
} else {
// Adding of an index
indexSet.add(firstItem);
try {
Index indexToAdd = ParserUtil.parseIndex(firstItem);
index.add(indexToAdd);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
}
boolean tagAdded = false;
while (st.hasMoreTokens()) {
String newToken = st.nextToken();
firstItemArray = fillCheckArray(newToken);
boolean isTag;
boolean isRangeAgain;
String lowerLimit2 = firstItemArray.get(indexLowerLimit);
String upperLimit2 = firstItemArray.get(indexUpperLimit);
String checkIsTag = firstItemArray.get(indexIsTag);
String checkIsRangeAgain = firstItemArray.get(indexIsRange);
if (checkIsRangeAgain.equals("true")) {
isRangeAgain = true;
} else {
isRangeAgain = false;
}
if (checkIsTag.equals("true")) {
isTag = true;
} else {
isTag = false;
}
// Adding of tag with no overlap
if (isTag) {
Tag toAdd;
try {
toAdd = new Tag(newToken);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
if (!toAddSet.contains(toAdd)) {
toAddSet.add(toAdd);
tagAdded = true;
}
} else {
if (tagAdded) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
} else {
if (isRangeAgain) {
// Check if any of the limit is empty
boolean isLowerValidAgain = lowerLimit2.isEmpty();
boolean isUpperValidAgain = upperLimit2.isEmpty();
if (isLowerValidAgain || isUpperValidAgain) {
throw new ParseException("Invalid index range provided.\n"
+ String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
// Check if range is appropriate
int lower = Integer.parseInt(lowerLimit2);
int upper = Integer.parseInt(upperLimit2);
if (lower > upper) {
throw new ParseException("Invalid index range provided.\n"
+ String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
// Adding of range of indexes
for (int i = lower; i <= upper; i++) {
String toAdd = String.valueOf(i);
if (!indexSet.contains(toAdd)) {
indexSet.add(toAdd);
try {
Index indexFromRangeToAdd = ParserUtil.parseIndex(toAdd);
index.add(indexFromRangeToAdd);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
}
} else {
// Adding of an index with no overlap
if (!indexSet.contains(newToken)) {
indexSet.add(newToken);
try {
Index indexToAdd = ParserUtil.parseIndex(newToken);
index.add(indexToAdd);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
}
}
}
}
if (toAddSet.isEmpty()) {
throw new ParseException("Please provide an input for tag\n"
+ String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
List<Integer> numList = new ArrayList<>();
Iterator<String> it = indexSet.iterator();
while (it.hasNext()) {
int numToAdd = Integer.parseInt(it.next());
numList.add(numToAdd);
}
Collections.sort(numList);
indexSet.clear();
for (Integer i : numList) {
String strToAdd = String.valueOf(i);
indexSet.add(strToAdd);
}
indexInput = indexSet.stream().collect(Collectors.joining(", "));
return new AddTagCommand(toAddSet, index, indexInput);
}
/**
*
* @param token
* @return checkArray containing values for checking
*/
private List<String> fillCheckArray(String token) {
List<String> checkArray = new ArrayList<>();
boolean startUpper = false;
String isRange = "false";
String isTag = "false";
String lowerLimit = "";
String upperLimit = "";
char[] itemArray = token.toCharArray();
if (token.contains("-")) {
isRange = "true";
}
// Check character of first keyword of input
for (char c : itemArray) {
if (!Character.isDigit(c)) {
if (c == '-') {
startUpper = true;
} else {
if (isRange.equals("false")) {
isTag = "true";
break;
} else {
if (startUpper) {
upperLimit = "";
break;
} else {
lowerLimit = "";
break;
}
}
}
} else {
if (startUpper) {
upperLimit += c;
} else {
lowerLimit += c;
}
}
}
checkArray.add(0, lowerLimit);
checkArray.add(1, upperLimit);
checkArray.add(2, isTag);
checkArray.add(3, isRange);
return checkArray;
}
}
|
Java
|
public class LEAPCodec extends ByteArrayCodec {
public static final String NAME = "LEAP";
private transient ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
private transient DataOutputStream outStream = new DataOutputStream(outBuffer);
private transient Vector stringReferences = new Vector();
//#MIDP_EXCLUDE_BEGIN
private void readObject(java.io.ObjectInputStream oin) throws java.io.IOException, ClassNotFoundException {
oin.defaultReadObject();
outBuffer = new ByteArrayOutputStream();
outStream = new DataOutputStream(outBuffer);
stringReferences = new Vector();
}
//#MIDP_EXCLUDE_END
// Types
private static final byte PRIMITIVE = 0;
private static final byte AGGREGATE = 1;
private static final byte CONTENT_ELEMENT_LIST = 2;
private static final byte OBJECT = 3;
// Markers for structured types
private static final byte ELEMENT = 4;
private static final byte END = 5;
// Primitive types
private static final byte STRING = 6;
private static final byte BOOLEAN = 7;
private static final byte INTEGER = 8;
private static final byte LONG = 9;
private static final byte FLOAT = 10;
private static final byte DOUBLE = 11;
private static final byte DATE = 12;
private static final byte BYTE_SEQUENCE = 13;
private static final byte BIG_STRING = 14;
// Modifiers
private static final byte MODIFIER = (byte) 0x10; // Only bit five set to 1
private static final byte UNMODIFIER = (byte) 0xEF; // Only bit five cleared to 1
/* LEAP Language operators
public static final String INSTANCEOF = "INSTANCEOF";
public static final String INSTANCEOF_ENTITY = "entity";
public static final String INSTANCEOF_TYPE = "type";
public static final String IOTA = "IOTA";
*/
/**
* Construct a LEAPCodec object i.e. a Codec for the LEAP language
*/
public LEAPCodec() {
super(NAME);
}
/**
* Encodes an abstract descriptor holding a content element
* into a byte array.
* @param content the content as an abstract descriptor.
* @return the content as a byte array.
* @throws CodecException
*/
public synchronized byte[] encode(AbsContentElement content) throws CodecException {
try {
outBuffer.reset();
stringReferences.removeAllElements();
write(outStream, content);
return outBuffer.toByteArray();
}
catch (Throwable t) {
throw new CodecException("Error encoding content", t);
}
}
/**
* Encodes a content into a byte array.
* @param ontology the ontology
* @param content the content as an abstract descriptor.
* @return the content as a byte array.
* @throws CodecException
*/
public byte[] encode(Ontology ontology, AbsContentElement content) throws CodecException {
return encode(content);
}
/**
* Decodes the content to an abstract descriptor.
* @param content the content as a byte array.
* @return the content as an abstract description.
* @throws CodecException
*/
public AbsContentElement decode(byte[] content) throws CodecException {
throw new CodecException("Not supported");
}
/**
* Decodes the content to an abstract description.
* @param ontology the ontology.
* @param content the content as a byte array.
* @return the content as an abstract description.
* @throws CodecException
*/
public synchronized AbsContentElement decode(Ontology ontology, byte[] content) throws CodecException {
if (content.length == 0) {
return null;
}
try {
ByteArrayInputStream inpBuffer = new ByteArrayInputStream(content);
DataInputStream inpStream = new DataInputStream(inpBuffer);
stringReferences.removeAllElements();
AbsObject obj = read(inpStream, ontology);
inpStream.close();
return (AbsContentElement) obj;
}
catch (Throwable t) {
throw new CodecException("Error decoding content", t);
}
}
private void write(DataOutputStream stream, AbsObject abs) throws Throwable {
// PRIMITIVE
if (abs instanceof AbsPrimitive) {
//stream.writeByte(PRIMITIVE);
Object obj = ((AbsPrimitive) abs).getObject();
if (obj instanceof String) {
String s = (String) obj;
if (s.length() >= 65535) {
writeBigString(stream, BIG_STRING, s);
}
else {
writeString(stream, STRING, s);
}
}
else if (obj instanceof Boolean) {
stream.writeByte(BOOLEAN);
stream.writeBoolean(((Boolean) obj).booleanValue());
}
else if (obj instanceof Integer) {
stream.writeByte(INTEGER);
stream.writeInt(((Integer) obj).intValue());
}
else if (obj instanceof Long) {
stream.writeByte(LONG);
stream.writeLong(((Long) obj).longValue());
}
//#MIDP_EXCLUDE_BEGIN
else if (obj instanceof Float) {
stream.writeByte(FLOAT);
stream.writeFloat(((Float) obj).floatValue());
}
else if (obj instanceof Double) {
stream.writeByte(DOUBLE);
stream.writeDouble(((Double) obj).doubleValue());
}
//#MIDP_EXCLUDE_END
else if (obj instanceof Date) {
stream.writeByte(DATE);
stream.writeLong(((Date) obj).getTime());
}
else if (obj instanceof byte[]) {
stream.writeByte(BYTE_SEQUENCE);
byte[] b = (byte[]) obj;
stream.writeInt(b.length);
stream.write(b, 0, b.length);
}
return;
}
// AGGREGATE
if (abs instanceof AbsAggregate) {
writeString(stream, AGGREGATE, abs.getTypeName());
AbsAggregate aggregate = (AbsAggregate) abs;
for (int i = 0; i < aggregate.size(); i++) {
stream.writeByte(ELEMENT);
write(stream, aggregate.get(i));
}
stream.writeByte(END);
return;
}
// CONTENT_ELEMENT_LIST
if (abs instanceof AbsContentElementList) {
stream.writeByte(CONTENT_ELEMENT_LIST);
AbsContentElementList acel = (AbsContentElementList) abs;
for (int i = 0; i < acel.size(); i++) {
stream.writeByte(ELEMENT);
write(stream, acel.get(i));
}
stream.writeByte(END);
return;
}
// If we get here it must be a complex OBJECT
writeString(stream, OBJECT, abs.getTypeName());
String[] names = abs.getNames();
for (int i = 0; i < abs.getCount(); i++) {
writeString(stream, ELEMENT, names[i]);
AbsObject child = abs.getAbsObject(names[i]);
write(stream, child);
}
stream.writeByte(END);
}
private AbsObject read(DataInputStream stream, Ontology ontology) throws Throwable {
byte type = stream.readByte();
// PRIMITIVE
//if (type == PRIMITIVE) {
// byte primitiveType = stream.readByte();
// AbsPrimitive abs = null;
if ((type&UNMODIFIER) == STRING) {
return AbsPrimitive.wrap(readString(stream, type));
}
if ((type&UNMODIFIER) == BIG_STRING) {
return AbsPrimitive.wrap(readBigString(stream, type));
}
if (type == BOOLEAN) {
boolean value = stream.readBoolean();
return AbsPrimitive.wrap(value);
}
if (type == INTEGER) {
int value = stream.readInt();
return AbsPrimitive.wrap(value);
}
if (type == LONG) {
long value = stream.readLong();
return AbsPrimitive.wrap(value);
}
//#MIDP_EXCLUDE_BEGIN
if (type == FLOAT) {
float value = stream.readFloat();
return AbsPrimitive.wrap(value);
}
if (type == DOUBLE) {
double value = stream.readDouble();
return AbsPrimitive.wrap(value);
}
//#MIDP_EXCLUDE_END
if (type == DATE) {
long value = stream.readLong();
return AbsPrimitive.wrap(new Date(value));
}
if (type == BYTE_SEQUENCE) {
byte[] value = new byte[stream.readInt()];
stream.read(value, 0, value.length);
return AbsPrimitive.wrap(value);
}
//return abs;
//}
// AGGREGATE
if ((type&UNMODIFIER) == AGGREGATE) {
String typeName = readString(stream, type);
AbsAggregate abs = new AbsAggregate(typeName);
byte marker = stream.readByte();
do {
if (marker == ELEMENT) {
AbsObject elementValue = read(stream, ontology);
if (elementValue != null) {
try {
abs.add((AbsTerm) elementValue);
}
catch (ClassCastException cce) {
throw new CodecException("Non term element in aggregate");
}
}
marker = stream.readByte();
}
}
while (marker != END);
return abs;
}
// CONTENT_ELEMENT_LIST
if (type == CONTENT_ELEMENT_LIST) {
AbsContentElementList abs = new AbsContentElementList();
byte marker = stream.readByte();
do {
if (marker == ELEMENT) {
AbsObject elementValue = read(stream, ontology);
if (elementValue != null) {
try {
abs.add((AbsContentElement) elementValue);
}
catch (ClassCastException cce) {
throw new CodecException("Non content-element element in content-element-list");
}
}
marker = stream.readByte();
}
}
while (marker != END);
return abs;
}
// If we get here it must be a complex OBJECT
String typeName = readString(stream, type);
// DEBUG System.out.println("Type is "+typeName);
ObjectSchema schema = ontology.getSchema(typeName);
// DEBUG System.out.println("Schema is "+schema);
AbsObject abs = schema.newInstance();
byte marker = stream.readByte();
do {
if ((marker&UNMODIFIER) == ELEMENT) {
String attributeName = readString(stream, marker);
AbsObject attributeValue = read(stream, ontology);
if (attributeValue != null) {
AbsHelper.setAttribute(abs, attributeName, attributeValue);
}
marker = stream.readByte();
}
}
while (marker != END);
return abs;
}
private final void writeString(DataOutputStream stream, byte tag, String s) throws Throwable {
int index = stringReferences.indexOf(s);
if (index >= 0) {
// Write the tag modified and just put the index
//System.out.println("String "+s+" already encoded");
stream.writeByte(tag|MODIFIER);
stream.writeByte(index);
}
else {
stream.writeByte(tag);
stream.writeUTF(s);
if ((s.length() > 1) && (stringReferences.size() < 256)) {
stringReferences.addElement(s);
}
}
}
// This method is equal to writeString, but is used to encode String whose
// length is >= 65535. Therefore the string is not encoded using writeUTF().
private final void writeBigString(DataOutputStream stream, byte tag, String s) throws Throwable {
int index = stringReferences.indexOf(s);
if (index >= 0) {
// Write the tag modified and just put the index
//System.out.println("String "+s+" already encoded");
stream.writeByte(tag|MODIFIER);
stream.writeByte(index);
}
else {
stream.writeByte(tag);
byte[] bytes = s.getBytes();
stream.writeInt(bytes.length);
stream.write(bytes, 0, bytes.length);
if ((s.length() > 1) && (stringReferences.size() < 256)) {
stringReferences.addElement(s);
}
}
}
private final String readString(DataInputStream stream, byte tag) throws Throwable {
String s = null;
if ((tag&MODIFIER) != 0) {
int index = stream.readUnsignedByte();
if (index < stringReferences.size()) {
s= (String) stringReferences.elementAt(index);
}
}
else {
s = stream.readUTF();
if ((s.length() > 1) && (stringReferences.size() < 256)) {
stringReferences.addElement(s);
}
}
return s;
}
// This method is equal to readString, but is used to decode String whose
// length is >= 65535. Therefore the string is not decoded using writeUTF().
private final String readBigString(DataInputStream stream, byte tag) throws Throwable {
String s = null;
if ((tag&MODIFIER) != 0) {
int index = stream.readUnsignedByte();
if (index < stringReferences.size()) {
s= (String) stringReferences.elementAt(index);
}
}
else {
byte[] bytes = new byte[stream.readInt()];
stream.read(bytes, 0, bytes.length);
s = new String(bytes);
if ((s.length() > 1) && (stringReferences.size() < 256)) {
stringReferences.addElement(s);
}
}
return s;
}
}
|
Java
|
class TestNetwork extends NetworkConfig
{
TestNetwork()
{
this("test-network");
}
private TestNetwork(final String name)
{
super(name);
try
{
//
// orderer org: three orderers.
//
final OrganizationConfig ordererOrg =
new OrganizationConfig("OrdererOrg",
"OrdererMSP",
new MSPDescriptor("msp-com.example",
new File("config/crypto-config/ordererOrganizations/example.com")));
ordererOrg.getOrderers()
.add(new OrdererConfig("orderer1",
loadEnvironment("orderer1.properties"),
new MSPDescriptor("msp-com.example.orderer1",
new File("config/crypto-config/ordererOrganizations/example.com/orderers/orderer1.example.com"))));
ordererOrg.getOrderers()
.add(new OrdererConfig("orderer2",
loadEnvironment("orderer2.properties"),
new MSPDescriptor("msp-com.example.orderer2",
new File("config/crypto-config/ordererOrganizations/example.com/orderers/orderer2.example.com"))));
ordererOrg.getOrderers()
.add(new OrdererConfig("orderer3",
loadEnvironment("orderer3.properties"),
new MSPDescriptor("msp-com.example.orderer3",
new File("config/crypto-config/ordererOrganizations/example.com/orderers/orderer3.example.com"))));
//
// org1 : two peers + admin context in peer1
//
final OrganizationConfig org1 =
new OrganizationConfig("Org1",
"Org1MSP",
new MSPDescriptor("msp-com.example.org1",
new File("config/crypto-config/peerOrganizations/org1.example.com")));
//
// This is an awful hack but org1-peer1 needs an org Admin context MSP in order to run the CLI (cc query from shell)
/// AND it needs the orderer1 tls/ca.crt...
// todo: what's the correct way to specify users, enrollments, admin contexts? Figure this out when switching to the CA.
// todo: doesn't the admin MSP User context belong up on the org?
// todo: we don't need the entire MSP for distributing the TLS certificates
//
org1.getPeers()
.add(new PeerConfig("org1-peer1",
loadEnvironment("org1-peer1.properties"),
new MSPDescriptor("msp-com.example.org1.org1-peer1",
new File("config/crypto-config/peerOrganizations/org1.example.com/peers/org1-peer1.org1.example.com")),
new MSPDescriptor("msp-com.example.org1.user.admin",
new File("config/crypto-config/peerOrganizations/org1.example.com/users/[email protected]")),
new MSPDescriptor("msp-com.example.orderer1",
new File("config/crypto-config/ordererOrganizations/example.com/orderers/orderer1.example.com"))));
org1.getPeers()
.add(new PeerConfig("org1-peer2",
loadEnvironment("org1-peer2.properties"),
new MSPDescriptor("msp-com.example.org1.org1-peer2",
new File("config/crypto-config/peerOrganizations/org1.example.com/peers/org1-peer2.org1.example.com"))));
//
// org2 : two peers
//
final OrganizationConfig org2 =
new OrganizationConfig("Org2",
"Org1MSP",
new MSPDescriptor("msp-com.example.org2",
new File("config/crypto-config/peerOrganizations/org2.example.com")));
org2.getPeers()
.add(new PeerConfig("org2-peer1",
loadEnvironment("org2-peer1.properties"),
new MSPDescriptor("msp-com.example.org2.org2-peer1",
new File("config/crypto-config/peerOrganizations/org2.example.com/peers/org2-peer1.org2.example.com"))));
org2.getPeers()
.add(new PeerConfig("org2-peer2",
loadEnvironment("org2-peer2.properties"),
new MSPDescriptor("msp-com.example.org2.org2-peer2",
new File("config/crypto-config/peerOrganizations/org2.example.com/peers/org2-peer2.org2.example.com"))));
organizations.add(ordererOrg);
organizations.add(org1);
organizations.add(org2);
}
catch (Exception ex)
{
fail("Could not load test network config", ex);
}
}
/**
* This can be improved, but it's not super relevant HOW the context is initialized. Just experimenting here...
*/
protected static Environment loadEnvironment(final String name)
{
final String path = "/config/v1/networks/test-network/" + name;
final Properties props = new Properties();
try
{
props.load(CryptoXYZZYConfigMapTest.class.getResourceAsStream(path));
}
catch (IOException ex)
{
fail("Could not load resource bundle " + path, ex);
}
final Environment environment = new Environment();
for (Object o : props.keySet())
{
final String key = o.toString();
environment.put(key, props.getProperty(key));
}
return environment;
}
}
|
Java
|
public abstract class AbstractPamLoginModule extends AbstractSharedLoginModule {
public static final Logger logger = Logger.getLogger(AbstractPamLoginModule.class.getName());
private String serviceName;
private UnixUser unixUser;
private boolean useUnixGroups;
private List<String> supplementalRoles;
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map shared, Map options) {
super.initialize(subject, callbackHandler, shared, options);
Object service = options.get("service");
if (null == service) {
throw new IllegalStateException("service is required");
}
this.serviceName = service.toString();
Object useUnixGroups1 = options.get("useUnixGroups");
if (null != useUnixGroups1) {
this.useUnixGroups = Boolean.parseBoolean(useUnixGroups1.toString());
} else {
this.useUnixGroups = false;
}
Object supplementalRoles1 = options.get("supplementalRoles");
if (null != supplementalRoles1) {
this.supplementalRoles = new ArrayList<String>();
this.supplementalRoles.addAll(Arrays.asList(supplementalRoles1.toString().split(", *")));
}
}
/**
* Authenticates using PAM
* @param name
* @param password
* @return
* @throws LoginException
*/
protected boolean authenticate(String name, char[] password) throws LoginException {
try {
if ((name == null) || (password == null)) {
debug("user or pass is null");
return false;
}
debug("PAM authentication trying (" + serviceName + ") for: " + name);
UnixUser authenticate = new PAM(serviceName).authenticate(name, new String(password));
debug("PAM authentication succeeded for: " + name);
this.unixUser = authenticate;
return true;
} catch (PAMException e) {
debug(e.getMessage());
if (isDebug()) {
e.printStackTrace();
}
return false;
}
}
/**
* Emit Debug message via System.err by default
*
* @param message
*/
protected void debug(String message) {
logger.log(Level.INFO, message);
}
@Override
protected List<Principal> createRolePrincipals() {
return createRolePrincipals(unixUser);
}
@Override
protected Principal createUserPrincipal() {
return createUserPrincipal(unixUser);
}
/**
* Create a Principal for the user
*
* @param user
*
* @return
*/
protected abstract Principal createUserPrincipal(UnixUser user);
/**
* Create a role Principal
*
* @param role
*
* @return
*/
protected abstract Principal createRolePrincipal(String role);
/**
* Create Principals for any roles
*
* @param username
*
* @return
*/
protected List<Principal> createRolePrincipals(UnixUser username) {
ArrayList<Principal> principals = new ArrayList<Principal>();
if (null != supplementalRoles) {
for (String supplementalRole : supplementalRoles) {
Principal rolePrincipal = createRolePrincipal(supplementalRole);
if (null != rolePrincipal) {
principals.add(rolePrincipal);
}
}
}
if (useUnixGroups) {
for (String s : username.getGroups()) {
Principal rolePrincipal = createRolePrincipal(s);
if (null != rolePrincipal) {
principals.add(rolePrincipal);
}
}
}
return principals;
}
@Override
public boolean commit() throws LoginException {
if (!isAuthenticated()) {
unixUser = null;
}
return super.commit();
}
@Override
public boolean abort() throws LoginException {
unixUser = null;
return super.abort();
}
@Override
public boolean logout() throws LoginException {
unixUser = null;
return super.logout();
}
public boolean isUseUnixGroups() {
return useUnixGroups;
}
}
|
Java
|
public class RecipientAlternatesAdapter extends CursorAdapter {
static final int MAX_LOOKUPS = 50;
private final LayoutInflater mLayoutInflater;
private final long mCurrentId;
private int mCheckedItemPosition = -1;
private OnCheckedItemChangedListener mCheckedItemChangedListener;
private static final String TAG = "RecipAlternates";
public static final int QUERY_TYPE_EMAIL = 0;
public static final int QUERY_TYPE_PHONE = 1;
private Query mQuery;
public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
ArrayList<String> inAddresses) {
return getMatchingRecipients(context, inAddresses, QUERY_TYPE_EMAIL);
}
/**
* Get a HashMap of address to RecipientEntry that contains all contact
* information for a contact with the provided address, if one exists. This
* may block the UI, so run it in an async task.
*
* @param context Context.
* @param inAddresses Array of addresses on which to perform the lookup.
* @return HashMap<String,RecipientEntry>
*/
public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
ArrayList<String> inAddresses, int addressType) {
Queries.Query query;
if (addressType == QUERY_TYPE_EMAIL) {
query = Queries.EMAIL;
} else {
query = Queries.PHONE;
}
int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.size());
String[] addresses = new String[addressesSize];
StringBuilder bindString = new StringBuilder();
// Create the "?" string and set up arguments.
for (int i = 0; i < addressesSize; i++) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses.get(i).toLowerCase());
addresses[i] = (tokens.length > 0 ? tokens[0].getAddress() : inAddresses.get(i));
bindString.append("?");
if (i < addressesSize - 1) {
bindString.append(",");
}
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
}
HashMap<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
Cursor c = context.getContentResolver().query(
query.getContentUri(),
query.getProjection(),
query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString()
+ ")", addresses, null);
if (c != null) {
try {
if (c.moveToFirst()) {
do {
String address = c.getString(Queries.Query.DESTINATION);
recipientEntries.put(address, RecipientEntry.constructTopLevelEntry(
c.getString(Queries.Query.NAME),
c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
c.getString(Queries.Query.DESTINATION),
c.getInt(Queries.Query.DESTINATION_TYPE),
c.getString(Queries.Query.DESTINATION_LABEL),
c.getLong(Queries.Query.CONTACT_ID),
c.getLong(Queries.Query.DATA_ID),
c.getString(Queries.Query.PHOTO_THUMBNAIL_URI)));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Received reverse look up information for " + address
+ " RESULTS: "
+ " NAME : " + c.getString(Queries.Query.NAME)
+ " CONTACT ID : " + c.getLong(Queries.Query.CONTACT_ID)
+ " ADDRESS :" + c.getString(Queries.Query.DESTINATION));
}
} while (c.moveToNext());
}
} finally {
c.close();
}
}
return recipientEntries;
}
public RecipientAlternatesAdapter(Context context, long contactId, long currentId, int viewId,
OnCheckedItemChangedListener listener) {
this(context, contactId, currentId, viewId, QUERY_TYPE_EMAIL, listener);
}
public RecipientAlternatesAdapter(Context context, long contactId, long currentId, int viewId,
int queryMode, OnCheckedItemChangedListener listener) {
super(context, getCursorForConstruction(context, contactId, queryMode), 0);
mLayoutInflater = LayoutInflater.from(context);
mCurrentId = currentId;
mCheckedItemChangedListener = listener;
if (queryMode == QUERY_TYPE_EMAIL) {
mQuery = Queries.EMAIL;
} else if (queryMode == QUERY_TYPE_PHONE) {
mQuery = Queries.PHONE;
} else {
mQuery = Queries.EMAIL;
Log.e(TAG, "Unsupported query type: " + queryMode);
}
}
private static Cursor getCursorForConstruction(Context context, long contactId, int queryType) {
final Cursor cursor;
if (queryType == QUERY_TYPE_EMAIL) {
cursor = context.getContentResolver().query(
Queries.EMAIL.getContentUri(),
Queries.EMAIL.getProjection(),
Queries.EMAIL.getProjection()[Queries.Query.CONTACT_ID] + " =?", new String[] {
String.valueOf(contactId)
}, null);
} else {
cursor = context.getContentResolver().query(
Queries.PHONE.getContentUri(),
Queries.PHONE.getProjection(),
Queries.PHONE.getProjection()[Queries.Query.CONTACT_ID] + " =?", new String[] {
String.valueOf(contactId)
}, null);
}
return removeDuplicateDestinations(cursor);
}
/**
* @return a new cursor based on the given cursor with all duplicate destinations removed.
*
* It's only intended to use for the alternate list, so...
* - This method ignores all other fields and dedupe solely on the destination. Normally,
* if a cursor contains multiple contacts and they have the same destination, we'd still want
* to show both.
* - This method creates a MatrixCursor, so all data will be kept in memory. We wouldn't want
* to do this if the original cursor is large, but it's okay here because the alternate list
* won't be that big.
*/
// Visible for testing
/* package */ static Cursor removeDuplicateDestinations(Cursor original) {
final MatrixCursor result = new MatrixCursor(
original.getColumnNames(), original.getCount());
final HashSet<String> destinationsSeen = new HashSet<String>();
original.moveToPosition(-1);
while (original.moveToNext()) {
final String destination = original.getString(Query.DESTINATION);
if (destinationsSeen.contains(destination)) {
continue;
}
destinationsSeen.add(destination);
result.addRow(new Object[] {
original.getString(Query.NAME),
original.getString(Query.DESTINATION),
original.getInt(Query.DESTINATION_TYPE),
original.getString(Query.DESTINATION_LABEL),
original.getLong(Query.CONTACT_ID),
original.getLong(Query.DATA_ID),
original.getString(Query.PHOTO_THUMBNAIL_URI),
original.getInt(Query.DISPLAY_NAME_SOURCE)
});
}
return result;
}
@Override
public long getItemId(int position) {
Cursor c = getCursor();
if (c.moveToPosition(position)) {
c.getLong(Queries.Query.DATA_ID);
}
return -1;
}
public RecipientEntry getRecipientEntry(int position) {
Cursor c = getCursor();
c.moveToPosition(position);
return RecipientEntry.constructTopLevelEntry(
c.getString(Queries.Query.NAME),
c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
c.getString(Queries.Query.DESTINATION),
c.getInt(Queries.Query.DESTINATION_TYPE),
c.getString(Queries.Query.DESTINATION_LABEL),
c.getLong(Queries.Query.CONTACT_ID),
c.getLong(Queries.Query.DATA_ID),
c.getString(Queries.Query.PHOTO_THUMBNAIL_URI));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Cursor cursor = getCursor();
cursor.moveToPosition(position);
if (convertView == null) {
convertView = newView();
}
if (cursor.getLong(Queries.Query.DATA_ID) == mCurrentId) {
mCheckedItemPosition = position;
if (mCheckedItemChangedListener != null) {
mCheckedItemChangedListener.onCheckedItemChanged(mCheckedItemPosition);
}
}
bindView(convertView, convertView.getContext(), cursor);
return convertView;
}
// TODO: this is VERY similar to the BaseRecipientAdapter. Can we combine
// somehow?
@Override
public void bindView(View view, Context context, Cursor cursor) {
int position = cursor.getPosition();
TextView display = (TextView) view.findViewById(android.R.id.title);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
RecipientEntry entry = getRecipientEntry(position);
if (position == 0) {
display.setText(cursor.getString(Queries.Query.NAME));
display.setVisibility(View.VISIBLE);
// TODO: see if this needs to be done outside the main thread
// as it may be too slow to get immediately.
imageView.setImageURI(entry.getPhotoThumbnailUri());
imageView.setVisibility(View.VISIBLE);
} else {
display.setVisibility(View.GONE);
imageView.setVisibility(View.GONE);
}
TextView destination = (TextView) view.findViewById(android.R.id.text1);
destination.setText(cursor.getString(Queries.Query.DESTINATION));
TextView destinationType = (TextView) view.findViewById(android.R.id.text2);
if (destinationType != null) {
destinationType.setText(mQuery.getTypeLabel(context.getResources(),
cursor.getInt(Queries.Query.DESTINATION_TYPE),
cursor.getString(Queries.Query.DESTINATION_LABEL)).toString().toUpperCase());
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return newView();
}
private View newView() {
return mLayoutInflater.inflate(R.layout.chips_recipient_dropdown_item, null);
}
/*package*/ static interface OnCheckedItemChangedListener {
public void onCheckedItemChanged(int position);
}
}
|
Java
|
public class Aether {
/**
* Stores the local repository directory.
*/
@Getter
private File localRepositoryDirectory;
/**
* Stores a list of remote repositories to check.
*/
private final List<RemoteRepository> repositories = new ArrayList<> ();
/**
* Stores the currently active repository system.
*/
@Getter (AccessLevel.PROTECTED)
private final RepositorySystem repositorySystem;
/**
* Stores the system session.
*/
@Getter (AccessLevel.PROTECTED)
private RepositorySystemSession session;
/**
* Constructs a new Aether instance.
*
* @param localRepositoryDirectory The local repository directory.
*/
public Aether (File localRepositoryDirectory) {
// create a new Aether Session
this.repositorySystem = this.prepareSystem ();
// update local repository & initialize session
this.setLocalRepository (localRepositoryDirectory);
}
/**
* Constructs a new Aether instance.
*
* @param localRepositoryDirectory The local repository directory.
* @param repositories The remote repository list.
*/
public Aether (File localRepositoryDirectory, Collection<RemoteRepository> repositories) {
this (localRepositoryDirectory);
this.addRepository (repositories);
}
/**
* Adds a new remote repository to the list.
*
* @param repository The repository.
*/
public void addRepository (@NonNull RemoteRepository repository) {
if (this.repositories.contains (repository)) return;
this.repositories.add (repository);
}
/**
* Adds a list of new remote repositories to the list.
*
* @param repositories The repository.
*/
public void addRepository (@NonNull Collection<RemoteRepository> repositories) {
for (RemoteRepository repository : repositories) {
this.addRepository (repository);
}
}
/**
* Clears the repository list.
*/
public void clearRepositories () {
this.repositories.clear ();
}
/**
* Prepares the repository system implementation.
*
* @return The system.
*/
protected RepositorySystem prepareSystem () {
DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils.newServiceLocator ();
serviceLocator.addService (RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
serviceLocator.addService (TransporterFactory.class, FileTransporterFactory.class);
serviceLocator.addService (TransporterFactory.class, HttpTransporterFactory.class);
return serviceLocator.getService (RepositorySystem.class);
}
/**
* Registers all repositories with a new request.
*
* @param request The request.
*/
protected void registerRepositories (CollectRequest request) {
for (RemoteRepository repository : this.repositories) request.addRepository (repository);
}
/**
* Removes a repository.
*
* @param repository The repository.
*/
public void removeRepository (@NonNull RemoteRepository repository) {
this.repositories.remove (repository);
}
/**
* Removes a collection of repositories.
*
* @param repositories The repository collection.
*/
public void removeRepository (@NonNull Collection<RemoteRepository> repositories) {
for (RemoteRepository repository : repositories) {
this.removeRepository (repository);
}
}
/**
* Resolves a dependency.
*
* @param artifact The artifact.
* @param type The type.
* @return The node list generator.
* @throws org.eclipse.aether.collection.DependencyCollectionException Occurs if collecting the dependency tree fails.
* @throws org.eclipse.aether.resolution.DependencyResolutionException Occurs if resolving the dependency tree fails.
*/
public PreorderNodeListGenerator resolve (String artifact, String type) throws DependencyCollectionException, DependencyResolutionException {
return this.resolve (new Dependency (new DefaultArtifact (artifact), type));
}
/**
* Resolves a dependency.
*
* @param artifact The artifact.
* @param type The type.
* @return The artifact list.
* @throws org.eclipse.aether.collection.DependencyCollectionException Occurs if collecting the dependency tree fails.
* @throws org.eclipse.aether.resolution.DependencyResolutionException Occurs if resolving the dependency tree fails.
*/
public List<Artifact> resolveArtifacts (Artifact artifact, String type) throws DependencyCollectionException, DependencyResolutionException {
return this.resolve (artifact, type).getArtifacts (false);
}
/**
* Resolves a dependency.
*
* @param artifact The artifact.
* @param type The type.
* @return The artifact list.
* @throws org.eclipse.aether.collection.DependencyCollectionException Occurs if collecting the dependency tree fails.
* @throws org.eclipse.aether.resolution.DependencyResolutionException Occurs if resolving the dependency tree fails.
*/
public List<Artifact> resolveArtifacts (String artifact, String type) throws DependencyCollectionException, DependencyResolutionException {
return this.resolve (artifact, type).getArtifacts (false);
}
/**
* Resolves a dependency.
*
* @param artifact The artifact.
* @param type The type.
* @return The node list generator.
* @throws org.eclipse.aether.collection.DependencyCollectionException Occurs if collecting the dependency tree fails.
* @throws org.eclipse.aether.resolution.DependencyResolutionException Occurs if resolving the dependency tree fails.
*/
public PreorderNodeListGenerator resolve (Artifact artifact, String type) throws DependencyCollectionException, DependencyResolutionException {
return this.resolve (new Dependency (artifact, type));
}
/**
* Resolves a dependency.
*
* @param dependency The dependency.
* @return The node list generator.
* @throws org.eclipse.aether.collection.DependencyCollectionException Occurs if collecting the dependency tree fails.
* @throws org.eclipse.aether.resolution.DependencyResolutionException Occurs if resolving the dependency tree fails.
*/
public PreorderNodeListGenerator resolve (Dependency dependency) throws DependencyCollectionException, DependencyResolutionException {
CollectRequest collectRequest = new CollectRequest ();
collectRequest.setRoot (dependency);
this.registerRepositories (collectRequest);
DependencyNode node = this.getRepositorySystem ().collectDependencies (this.getSession (), collectRequest).getRoot ();
DependencyRequest request = new DependencyRequest ();
request.setRoot (node);
this.getRepositorySystem ().resolveDependencies (this.getSession (), request);
PreorderNodeListGenerator generator = new PreorderNodeListGenerator ();
node.accept (generator);
return generator;
}
/**
* Sets the local repository directory.
*
* @param localRepositoryDirectory The directory.
*/
public void setLocalRepository (@NonNull File localRepositoryDirectory) {
this.localRepositoryDirectory = localRepositoryDirectory;
this.updateSession ();
}
/**
* Updates the session instance.
*/
protected void updateSession () {
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession ();
LocalRepository repository = new LocalRepository (this.getLocalRepositoryDirectory ());
session.setLocalRepositoryManager (this.getRepositorySystem ().newLocalRepositoryManager (session, repository));
this.session = session;
}
}
|
Java
|
public class TouchHandlerOld implements ITouchHandler {
/** The chart renderer. */
private DefaultRenderer mRenderer;
/** The old x coordinate. */
private float oldX;
/** The old y coordinate. */
private float oldY;
/** The zoom buttons rectangle. */
private RectF zoomR = new RectF();
/** The pan tool. */
private Pan mPan;
/** The graphical view. */
private GraphicalView graphicalView;
/**
* Creates an implementation of the old version of the touch handler.
*
* @param view the graphical view
* @param chart the chart to be drawn
*/
public TouchHandlerOld(GraphicalView view, AbstractChart chart) {
graphicalView = view;
zoomR = graphicalView.getZoomRectangle();
if (chart instanceof XYChart) {
mRenderer = ((XYChart) chart).getRenderer();
} else {
mRenderer = ((RoundChart) chart).getRenderer();
}
if (mRenderer.isPanEnabled()) {
mPan = new Pan(chart);
}
}
public boolean handleTouch(MotionEvent event) {
int action = event.getAction();
if (mRenderer != null && action == MotionEvent.ACTION_MOVE) {
if (oldX >= 0 || oldY >= 0) {
float newX = event.getX();
float newY = event.getY();
if (mRenderer.isPanEnabled()) {
mPan.apply(oldX, oldY, newX, newY);
}
oldX = newX;
oldY = newY;
graphicalView.repaint();
return true;
}
} else if (action == MotionEvent.ACTION_DOWN) {
oldX = event.getX();
oldY = event.getY();
if (mRenderer != null && mRenderer.isZoomEnabled() && zoomR.contains(oldX, oldY)) {
if (oldX < zoomR.left + zoomR.width() / 3) {
graphicalView.zoomIn();
} else if (oldX < zoomR.left + zoomR.width() * 2 / 3) {
graphicalView.zoomOut();
} else {
graphicalView.zoomReset();
}
return true;
}
} else if (action == MotionEvent.ACTION_UP) {
oldX = 0;
oldY = 0;
}
return !mRenderer.isClickEnabled();
}
/**
* Adds a new zoom listener.
*
* @param listener zoom listener
*/
public void addZoomListener(ZoomListener listener) {
}
/**
* Removes a zoom listener.
*
* @param listener zoom listener
*/
public void removeZoomListener(ZoomListener listener) {
}
/**
* Adds a new pan listener.
*
* @param listener pan listener
*/
public void addPanListener(PanListener listener) {
if (mPan != null) {
mPan.addPanListener(listener);
}
}
/**
* Removes a pan listener.
*
* @param listener pan listener
*/
public void removePanListener(PanListener listener) {
if (mPan != null) {
mPan.removePanListener(listener);
}
}
}
|
Java
|
public class StreamingExecutionControl implements ExecutionControl {
private final ObjectOutput out;
private final ObjectInput in;
/**
* Creates an instance.
*
* @param out the output for commands
* @param in the input for command responses
*/
public StreamingExecutionControl(ObjectOutput out, ObjectInput in) {
this.out = out;
this.in = in;
}
@Override
public void load(ClassBytecodes[] cbcs)
throws ClassInstallException, NotImplementedException, EngineTerminationException {
try {
// Send a load command to the remote agent.
writeCommand(CMD_LOAD);
out.writeObject(cbcs);
out.flush();
// Retrieve and report results from the remote agent.
readAndReportClassInstallResult();
} catch (IOException ex) {
throw new EngineTerminationException("Exception writing remote load: " + ex);
}
}
@Override
public void redefine(ClassBytecodes[] cbcs)
throws ClassInstallException, NotImplementedException, EngineTerminationException {
try {
// Send a load command to the remote agent.
writeCommand(CMD_REDEFINE);
out.writeObject(cbcs);
out.flush();
// Retrieve and report results from the remote agent.
readAndReportClassInstallResult();
} catch (IOException ex) {
throw new EngineTerminationException("Exception writing remote redefine: " + ex);
}
}
@Override
public String invoke(String classname, String methodname)
throws RunException, EngineTerminationException, InternalException {
try {
// Send the invoke command to the remote agent.
writeCommand(CMD_INVOKE);
out.writeUTF(classname);
out.writeUTF(methodname);
out.flush();
// Retrieve and report results from the remote agent.
readAndReportExecutionResult();
String result = in.readUTF();
return result;
} catch (IOException ex) {
throw new EngineTerminationException("Exception writing remote invoke: " + ex);
}
}
@Override
public String varValue(String classname, String varname)
throws RunException, EngineTerminationException, InternalException {
try {
// Send the variable-value command to the remote agent.
writeCommand(CMD_VAR_VALUE);
out.writeUTF(classname);
out.writeUTF(varname);
out.flush();
// Retrieve and report results from the remote agent.
readAndReportExecutionResult();
String result = in.readUTF();
return result;
} catch (IOException ex) {
throw new EngineTerminationException("Exception writing remote varValue: " + ex);
}
}
@Override
public void addToClasspath(String path)
throws EngineTerminationException, InternalException {
try {
// Send the classpath addition command to the remote agent.
writeCommand(CMD_ADD_CLASSPATH);
out.writeUTF(path);
out.flush();
// Retrieve and report results from the remote agent.
readAndReportClassSimpleResult();
} catch (IOException ex) {
throw new EngineTerminationException("Exception writing remote add to classpath: " + ex);
}
}
@Override
public void stop()
throws EngineTerminationException, InternalException {
try {
// Send the variable-value command to the remote agent.
writeCommand(CMD_STOP);
out.flush();
} catch (IOException ex) {
throw new EngineTerminationException("Exception writing remote stop: " + ex);
}
}
@Override
public Object extensionCommand(String command, Object arg)
throws RunException, EngineTerminationException, InternalException {
try {
writeCommand(command);
out.writeObject(arg);
out.flush();
// Retrieve and report results from the remote agent.
readAndReportExecutionResult();
Object result = in.readObject();
return result;
} catch (IOException | ClassNotFoundException ex) {
throw new EngineTerminationException("Exception transmitting remote extensionCommand: "
+ command + " -- " + ex);
}
}
/**
* Closes the execution engine. Send an exit command to the remote agent.
*/
@Override
public void close() {
try {
writeCommand(CMD_CLOSE);
out.flush();
} catch (IOException ex) {
// ignore;
}
}
private void writeCommand(String cmd) throws IOException {
out.writeInt(COMMAND_PREFIX);
out.writeUTF(cmd);
}
/**
* Read a UTF or a null encoded as a null marker.
* @return a string or null
* @throws IOException passed through from readUTF()
*/
private String readNullOrUTF() throws IOException {
String s = in.readUTF();
return s.equals(NULL_MARKER) ? null : s;
}
/**
* Reports results from a remote agent command that does not expect
* exceptions.
*/
private void readAndReportClassSimpleResult() throws EngineTerminationException, InternalException {
try {
int status = in.readInt();
switch (status) {
case RESULT_SUCCESS:
return;
case RESULT_NOT_IMPLEMENTED: {
String message = in.readUTF();
throw new NotImplementedException(message);
}
case RESULT_INTERNAL_PROBLEM: {
String message = in.readUTF();
throw new InternalException(message);
}
case RESULT_TERMINATED: {
String message = in.readUTF();
throw new EngineTerminationException(message);
}
default: {
throw new EngineTerminationException("Bad remote result code: " + status);
}
}
} catch (IOException ex) {
throw new EngineTerminationException(ex.toString());
}
}
/**
* Reports results from a remote agent command that does not expect
* exceptions.
*/
private void readAndReportClassInstallResult() throws ClassInstallException,
NotImplementedException, EngineTerminationException {
try {
int status = in.readInt();
switch (status) {
case RESULT_SUCCESS:
return;
case RESULT_NOT_IMPLEMENTED: {
String message = in.readUTF();
throw new NotImplementedException(message);
}
case RESULT_CLASS_INSTALL_EXCEPTION: {
String message = in.readUTF();
boolean[] loaded = (boolean[]) in.readObject();
throw new ClassInstallException(message, loaded);
}
case RESULT_TERMINATED: {
String message = in.readUTF();
throw new EngineTerminationException(message);
}
default: {
throw new EngineTerminationException("Bad remote result code: " + status);
}
}
} catch (IOException | ClassNotFoundException ex) {
throw new EngineTerminationException(ex.toString());
}
}
/**
* Reports results from a remote agent command that expects runtime
* exceptions.
*
* @return true if successful
* @throws IOException if the connection has dropped
* @throws JShellException {@link jdk.jshell.EvalException}, if a user
* exception was encountered on invoke;
* {@link jdk.jshell.UnresolvedReferenceException}, if an unresolved
* reference was encountered
* @throws java.lang.ClassNotFoundException
*/
private void readAndReportExecutionResult() throws RunException,
EngineTerminationException, InternalException {
try {
int status = in.readInt();
switch (status) {
case RESULT_SUCCESS:
return;
case RESULT_NOT_IMPLEMENTED: {
String message = in.readUTF();
throw new NotImplementedException(message);
}
case RESULT_USER_EXCEPTION: {
// A user exception was encountered. Handle pre JDK 11 back-ends
throw readUserException();
}
case RESULT_CORRALLED: {
// An unresolved reference was encountered.
throw readResolutionException();
}
case RESULT_USER_EXCEPTION_CHAINED: {
// A user exception was encountered -- transmit chained.
in.readInt(); // always RESULT_USER_EXCEPTION
UserException result = readUserException();
RunException caused = result;
// Loop through the chained causes (if any) building a chained exception
loop: while (true) {
RunException ex;
int cstatus = in.readInt();
switch (cstatus) {
case RESULT_USER_EXCEPTION: {
// A user exception was the proximal cause.
ex = readUserException();
break;
}
case RESULT_CORRALLED: {
// An unresolved reference was the underlying cause.
ex = readResolutionException();
break;
}
case RESULT_SUCCESS: {
// End of chained exceptions
break loop;
}
default: {
throw new EngineTerminationException("Bad chained remote result code: " + cstatus);
}
}
caused.initCause(ex);
caused = ex;
}
caused.initCause(null); // root cause has no cause
throw result;
}
case RESULT_STOPPED: {
// Execution was aborted by the stop()
throw new StoppedException();
}
case RESULT_INTERNAL_PROBLEM: {
// An internal error has occurred.
String message = in.readUTF();
throw new InternalException(message);
}
case RESULT_TERMINATED: {
String message = in.readUTF();
throw new EngineTerminationException(message);
}
default: {
throw new EngineTerminationException("Bad remote result code: " + status);
}
}
} catch (EOFException ex) {
throw new EngineTerminationException("Terminated.");
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
throw new EngineTerminationException(ex.toString());
}
}
private UserException readUserException() throws IOException, ClassNotFoundException {
String message = readNullOrUTF();
String exceptionClassName = in.readUTF();
StackTraceElement[] elems = (StackTraceElement[]) in.readObject();
return new UserException(message, exceptionClassName, elems);
}
private ResolutionException readResolutionException() throws IOException, ClassNotFoundException {
int id = in.readInt();
StackTraceElement[] elems = (StackTraceElement[]) in.readObject();
return new ResolutionException(id, elems);
}
}
|
Java
|
@ApplicationScoped
class ValidationServiceBean implements ValidationService {
@Inject
TicketService ticketService;
@Inject
ServiceResponseBuilderFactory builderFactory;
@Override
public ServiceResponse validate(ValidationRequest request) {
final TicketState state = ticketService.validate(request.getTicket());
if (state == null) {
return builderFactory.createAuthenticationFailureBuilder()
.code(ProtocolError.INVALID_TICKET)
.message("invalid ticket")
.build();
}
return builderFactory.createAuthenticationSuccessBuilder()
.user(state.getUsername())
.build();
}
}
|
Java
|
public class StudentDb {
/**
* Strings for the database connection
*/
String driver = "com.mysql.jdbc.Driver";
String connUrl = "jdbc:mysql://localhost/";
String database = "recreation";
String user = "root";
String pass = "PROG32758";
/**
* These constants represent the field names in the Student table
*/
private final String TABLE_NAME = "student";
private final String ID = "id";
private final String FIRST_NAME = "firstName";
private final String LAST_NAME = "lastName";
private final String AGE = "age";
/**
* This method will return a positive integer if the query was successful
* and the student was added, otherwise an error message will be displayed.
* This method takes in a student object as a parameter.
* @param student
* @return an integer to validate if the query was successful or not
* @throws java.lang.Exception
*/
public int addStudent(Student student) throws Exception{
String formatSql = "INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)";
String sql = String.format(formatSql,TABLE_NAME,FIRST_NAME,LAST_NAME,
AGE);
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try {
conn = DBConnector.getConnection(
driver, connUrl, database, user, pass
);
ps = conn.prepareStatement(sql);
ps.setString(1, student.getFirstName());
ps.setString(2, student.getLastName());
ps.setInt(3, student.getAge());
result = ps.executeUpdate();
} catch (Exception ex) {
throw(ex);
} finally{
DBConnector.closeJDBCObjects(conn, ps);
}
return result;
}
/**
* This method will return a positive integer if the query was successful
* and the student was removed, otherwise an error message will be displayed.
* This method takes in a student object as a parameter.
* @param studentId
* @return an integer to validate if the query was successful or not
* @throws Exception
*/
public int removeStudent(String studentId) throws Exception{
String sqlQuery = "DELETE FROM %s WHERE %s = ?";
String formatSql = String.format(sqlQuery, TABLE_NAME, ID);
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try {
conn = DBConnector.getConnection(
driver, connUrl, database, user, pass
);
ps = conn.prepareStatement(formatSql);
ps.setString(1, studentId);
result = ps.executeUpdate();
} catch (Exception ex) {
throw(ex);
} finally{
DBConnector.closeJDBCObjects(conn, ps);
}
return result;
}
/**
* This method will return an array of student and their details
* @return an ArrayList<Student>
*/
public ArrayList<Student> getStudents(){
String formatSql = "SELECT * FROM %s";
String sql = String.format(formatSql, TABLE_NAME);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Student> students = new ArrayList<>();
try {
conn = DBConnector.getConnection(
driver, connUrl, database, user, pass
);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
Student student = new Student(
rs.getInt(ID),
rs.getString(FIRST_NAME),
rs.getString(LAST_NAME),
rs.getInt(AGE)
);
students.add(student);
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
DBConnector.closeJDBCObjects(conn, ps, rs);
}
return students;
}
}
|
Java
|
public class ImmutableUnflavoredBuildTargetView extends AbstractUnflavoredBuildTargetView {
private final UnconfiguredBuildTarget data;
private final Path cellPath;
private final int hash;
private ImmutableUnflavoredBuildTargetView(Path cellPath, UnconfiguredBuildTarget data) {
this.data = data;
this.cellPath = cellPath;
// always precompute hash because we intern object anyways
hash = Objects.hash(cellPath, data);
}
/** Interner for instances of UnflavoredBuildTargetView. */
private static final Interner<ImmutableUnflavoredBuildTargetView> interner =
Interners.newWeakInterner();
@Override
public UnconfiguredBuildTarget getData() {
return data;
}
@Override
public Path getCellPath() {
return cellPath;
}
@Override
public CanonicalCellName getCell() {
return data.getCell();
}
@Override
public String getBaseName() {
return data.getBaseName();
}
@Override
public String getShortName() {
return data.getName();
}
@Override
public String toString() {
return getFullyQualifiedName();
}
/**
* Create new instance of {@link UnflavoredBuildTargetView}
*
* @param cellPath Absolute path to the cell root that owns this build target
* @param cellName Name of the cell that owns this build target
* @param baseName Base part of build target name, like "//some/target"
* @param shortName Last part of build target name after colon
*/
public static ImmutableUnflavoredBuildTargetView of(
Path cellPath, CanonicalCellName cellName, String baseName, String shortName) {
return of(
cellPath,
ImmutableUnconfiguredBuildTarget.of(
cellName, baseName, shortName, UnconfiguredBuildTarget.NO_FLAVORS));
}
/**
* Create new instance of {@link UnflavoredBuildTargetView}
*
* @param cellPath Absolute path to the cell root that owns this build target
* @param data {@link UnconfiguredBuildTarget} which encapsulates build target data
*/
public static ImmutableUnflavoredBuildTargetView of(Path cellPath, UnconfiguredBuildTarget data) {
return interner.intern(new ImmutableUnflavoredBuildTargetView(cellPath, data));
}
@Override
public int compareTo(UnflavoredBuildTargetView o) {
if (this == o) {
return 0;
}
int cmp = getCell().compareTo(o.getCell());
if (cmp != 0) {
return cmp;
}
cmp = MoreStrings.compareStrings(getBaseName(), o.getBaseName());
if (cmp != 0) {
return cmp;
}
return MoreStrings.compareStrings(getShortName(), o.getShortName());
}
@Override
public boolean equals(Object another) {
if (this == another) {
return true;
}
return another instanceof ImmutableUnflavoredBuildTargetView
&& equalTo((ImmutableUnflavoredBuildTargetView) another);
}
private boolean equalTo(ImmutableUnflavoredBuildTargetView another) {
if (hash != another.hash) {
return false;
}
return cellPath.equals(another.cellPath) && data.equals(another.data);
}
@Override
public int hashCode() {
return hash;
}
}
|
Java
|
public class BackwardsCompatibilityTest extends HudsonTestCase {
/**
* Tests that a build containing version 1 of {@link FailureCauseBuildAction} can be done.
*/
@LocalData
public void testReadResolveFromVersion1() {
FreeStyleProject job = (FreeStyleProject)Jenkins.getInstance().getItem("bfa");
assertNotNull(job);
FailureCauseBuildAction action = job.getBuilds().getFirstBuild().getAction(FailureCauseBuildAction.class);
List<FoundFailureCause> foundFailureCauses = Whitebox.getInternalState(action, "foundFailureCauses");
List<FailureCause> failureCauses = Whitebox.getInternalState(action, "failureCauses");
assertNotNull(foundFailureCauses);
assertTrue(foundFailureCauses.isEmpty());
assertNull(failureCauses);
action = job.getBuilds().getLastBuild().getAction(FailureCauseBuildAction.class);
foundFailureCauses = Whitebox.getInternalState(action, "foundFailureCauses");
failureCauses = Whitebox.getInternalState(action, "failureCauses");
assertNotNull(foundFailureCauses);
assertEquals(1, foundFailureCauses.size());
assertNull(failureCauses);
}
/**
* Tests that legacy causes in {@link PluginImpl#causes} gets converted during startup to a {@link
* com.sonyericsson.jenkins.plugins.bfa.db.LocalFileKnowledgeBase}.
*
* @throws Exception if so.
*/
@LocalData
public void testLoadVersion1ConfigXml() throws Exception {
KnowledgeBase knowledgeBase = PluginImpl.getInstance().getKnowledgeBase();
Collection<FailureCause> causes = knowledgeBase.getCauses();
assertEquals(3, causes.size());
Indication indication = null;
for (FailureCause c : causes) {
assertNotNull(c.getName() + " should have an id", fixEmpty(c.getId()));
if ("The Wrong".equals(c.getName())) {
indication = c.getIndications().get(0);
}
}
assertNotNull("Missing a cause!", indication);
assertEquals(".+wrong.*", Whitebox.getInternalState(indication, "pattern").toString());
}
/**
* Tests that a legacy FoundFailureCause can be loaded by the annotator.
*
* @throws Exception if so.
*/
@LocalData
public void testLoadOldFailureCauseWithOnlyLineNumbers() throws Exception {
FreeStyleProject job = (FreeStyleProject)Jenkins.getInstance().getItem("MyProject");
assertNotNull(job);
FreeStyleBuild build = job.getBuilds().getFirstBuild();
OldDataConverter.getInstance().waitForInitialCompletion();
FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class);
List<FoundFailureCause> foundFailureCauses = Whitebox.getInternalState(action, "foundFailureCauses");
FoundFailureCause foundFailureCause = foundFailureCauses.get(0);
FoundIndication indication = foundFailureCause.getIndications().get(0);
assertTrue(indication.getMatchingString().matches(indication.getPattern()));
IndicationAnnotator annotator = new IndicationAnnotator(foundFailureCauses);
Map<String, AnnotationHelper> helperMap = Whitebox.getInternalState(annotator, "helperMap");
//since the old FoundIndication doesn't contain a matchingString from the start, we check it.
AnnotationHelper annotationHelper = helperMap.get(indication.getMatchingString());
assertNotNull(annotationHelper);
}
/**
* Tests if a {@link MatrixBuild} gets loaded and converted correctly from a version 1.2.0 save.
*
* @throws InterruptedException if it is not allowed to sleep in the beginning.
*/
@LocalData
public void testMatrix120() throws InterruptedException {
MatrixProject project = (MatrixProject)jenkins.getItem("mymatrix");
MatrixBuild build = project.getBuildByNumber(1);
OldDataConverter.getInstance().waitForInitialCompletion();
FailureCauseMatrixBuildAction matrixBuildAction = build.getAction(FailureCauseMatrixBuildAction.class);
assertNotNull(matrixBuildAction);
List<MatrixRun> runs = Whitebox.getInternalState(matrixBuildAction, "runs");
assertNotNull(runs);
List<String> runIds = null;
runIds = Whitebox.getInternalState(matrixBuildAction, "runIds");
assertEquals(runs.size(), runIds.size());
assertNotNull(runs.get(3).getProject());
assertEquals(runs.get(3).getProject().getCombination().toString(), runIds.get(3));
assertNotNull(Whitebox.getInternalState(matrixBuildAction, "build"));
MatrixBuild build2 = project.getBuildByNumber(2);
List<MatrixRun> aggregatedRuns2 = FailureCauseMatrixAggregator.getRuns(build2);
FailureCauseMatrixBuildAction matrixBuildAction2 = build2.getAction(FailureCauseMatrixBuildAction.class);
assertNotNull(matrixBuildAction2);
List<MatrixRun> runs2 = Whitebox.getInternalState(matrixBuildAction2, "runs");
assertSame(aggregatedRuns2.get(5), runs2.get(5));
}
}
|
Java
|
public class SymbolicAdsStringField extends SymbolicAdsField implements AdsStringField {
private static final Pattern SYMBOLIC_ADDRESS_STRING_PATTERN = Pattern.compile("^(?<symbolicAddress>.+):(?<adsDataType>'STRING'|'WSTRING')\\((?<stringLength>\\d{1,3})\\)(\\[(?<numberOfElements>\\d)])?");
private final int stringLength;
private SymbolicAdsStringField(String symbolicAddress, AdsDataType adsDataType, int stringLength, Integer numberOfElements) {
super(symbolicAddress, adsDataType, numberOfElements);
this.stringLength = stringLength;
}
public static SymbolicAdsStringField of(String address) {
Matcher matcher = SYMBOLIC_ADDRESS_STRING_PATTERN.matcher(address);
if (!matcher.matches()) {
throw new PlcInvalidFieldException(address, SYMBOLIC_ADDRESS_STRING_PATTERN, "{address}");
}
String symbolicAddress = matcher.group("symbolicAddress");
String adsDataTypeString = matcher.group("adsDataType");
AdsDataType adsDataType = AdsDataType.valueOf(adsDataTypeString);
String stringLengthString = matcher.group("stringLength");
Integer stringLength = stringLengthString != null ? Integer.valueOf(stringLengthString) : null;
String numberOfElementsString = matcher.group("numberOfElements");
Integer numberOfElements = numberOfElementsString != null ? Integer.valueOf(numberOfElementsString) : null;
return new SymbolicAdsStringField(symbolicAddress, adsDataType, stringLength, numberOfElements);
}
public static boolean matches(String address) {
return SYMBOLIC_ADDRESS_STRING_PATTERN.matcher(address).matches();
}
@Override
public int getStringLength() {
return stringLength;
}
@Override
public String toString() {
return "SymbolicAdsStringField{" +
"symbolicAddress='" + getSymbolicAddress() + '\'' +
", stringLength=" + stringLength +
'}';
}
@Override
public void xmlSerialize(Element parent) {
Document doc = parent.getOwnerDocument();
Element messageElement = doc.createElement(getClass().getSimpleName());
parent.appendChild(messageElement);
Element symbolicAddressElement = doc.createElement("symbolicAddress");
symbolicAddressElement.appendChild(doc.createTextNode(getSymbolicAddress()));
messageElement.appendChild(symbolicAddressElement);
Element numberOfElementsElement = doc.createElement("numberOfElements");
numberOfElementsElement.appendChild(doc.createTextNode(Integer.toString(getNumberOfElements())));
messageElement.appendChild(numberOfElementsElement);
Element datatypeElement = doc.createElement("dataType");
datatypeElement.appendChild(doc.createTextNode(getPlcDataType()));
messageElement.appendChild(datatypeElement);
}
}
|
Java
|
public abstract class BaseGenericBinaryMessageReaderImpl<HK, HV> extends BaseBinaryMessageReader {
private final SpecVersion version;
private final byte[] body;
protected BaseGenericBinaryMessageReaderImpl(SpecVersion version, byte[] body) {
Objects.requireNonNull(version);
this.version = version;
this.body = body;
}
@Override
public <T extends CloudEventWriter<V>, V> V read(CloudEventWriterFactory<T, V> visitorFactory) throws CloudEventRWException, IllegalStateException {
CloudEventWriter<V> visitor = visitorFactory.create(this.version);
// Grab from headers the attributes and extensions
// This implementation avoids to use visitAttributes and visitExtensions
// in order to complete the visit in one loop
this.forEachHeader((key, value) -> {
if (isContentTypeHeader(key)) {
visitor.setAttribute("datacontenttype", toCloudEventsValue(value));
} else if (isCloudEventsHeader(key)) {
String name = toCloudEventsKey(key);
if (name.equals("specversion")) {
return;
}
if (this.version.getAllAttributes().contains(name)) {
visitor.setAttribute(name, toCloudEventsValue(value));
} else {
visitor.setExtension(name, toCloudEventsValue(value));
}
}
});
// Set the payload
if (this.body != null && this.body.length != 0) {
return visitor.end(this.body);
}
return visitor.end();
}
@Override
public void readAttributes(CloudEventAttributesWriter visitor) throws RuntimeException {
this.forEachHeader((key, value) -> {
if (isContentTypeHeader(key)) {
visitor.setAttribute("datacontenttype", toCloudEventsValue(value));
} else if (isCloudEventsHeader(key)) {
String name = toCloudEventsKey(key);
if (name.equals("specversion")) {
return;
}
if (this.version.getAllAttributes().contains(name)) {
visitor.setAttribute(name, toCloudEventsValue(value));
}
}
});
}
@Override
public void readExtensions(CloudEventExtensionsWriter visitor) throws RuntimeException {
// Grab from headers the attributes and extensions
this.forEachHeader((key, value) -> {
if (isCloudEventsHeader(key)) {
String name = toCloudEventsKey(key);
if (!this.version.getAllAttributes().contains(name)) {
visitor.setExtension(name, toCloudEventsValue(value));
}
}
});
}
protected abstract boolean isContentTypeHeader(HK key);
protected abstract boolean isCloudEventsHeader(HK key);
protected abstract String toCloudEventsKey(HK key);
protected abstract void forEachHeader(BiConsumer<HK, HV> fn);
protected abstract String toCloudEventsValue(HV value);
}
|
Java
|
public abstract class Camera {
/**
* The Point3 object of the camera, which represents the position (x,y,z coordinates)
*/
final Point3 e;
/**
* The Vector3 object of the camera, which represents the perspective (gaze direction)
*/
final Vector3 g;
/**
* The Vector3 object of the camera, which represents the up-Vector.
*/
final Vector3 t;
/**
* The Vector3 object, which represents the u-axis of the transformed coordinate system.
*/
final Vector3 u;
/**
* The Vector3 object, which represents the v-axis of the transformed coordinate system.
*/
final Vector3 v;
/**
* The Vector3 object, which represents the w-axis of the transformed coordinate system.
*/
final Vector3 w;
/**
* the SamplingPattern component of the camera.
*/
final SamplingPattern samplingPattern;
/**
* The constructor needs the 3 vectors of the camera position and generates a new coordinate
* system with the origin e and the new axial vectors u, w and v.
* These three vectors are needed to to generate the rays of the camera.
* @param e position of camera (eye position)
* @param g gaze direction
* @param t Up-Vector
*/
public Camera(final Point3 e, final Vector3 g, final Vector3 t, final SamplingPattern samplingPattern){
if(e==null)throw new IllegalArgumentException("e have to be not null");
if(g==null)throw new IllegalArgumentException("g have to be not null");
if(t==null)throw new IllegalArgumentException("t have to be not null");
if(samplingPattern==null)throw new IllegalArgumentException("samplingPattern have to be not null");
this.e=e;
this.g=g;
this.t=t;
this.samplingPattern=samplingPattern;
this.w = this.g.normalized().mul(-1.0);
this.u = this.t.x(this.w).normalized();
this.v = this.w.x(this.u);
}
/**
* This method returns the ray for certain pixel
* @param width The width of the screen.
* @param height The height of the screen.
* @param x The x-coordinate of the pixel.
* @param y The y-coordinate of the pixel
* @return abstract no return
*/
public abstract Set<Ray> rayFor(final int width,final int height,final int x,final int y);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Camera camera = (Camera) o;
if (!e.equals(camera.e)) return false;
if (!g.equals(camera.g)) return false;
if (!t.equals(camera.t)) return false;
if (!u.equals(camera.u)) return false;
if (!v.equals(camera.v)) return false;
return !(w != null ? !w.equals(camera.w) : camera.w != null);
}
@Override
public int hashCode() {
int result = e.hashCode();
result = 31 * result + g.hashCode();
result = 31 * result + t.hashCode();
result = 31 * result + u.hashCode();
result = 31 * result + v.hashCode();
result = 31 * result + (w != null ? w.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Camera{" +
"e=" + e +
", g=" + g +
", t=" + t +
", u=" + u +
", v=" + v +
", w=" + w +
'}';
}
}
|
Java
|
public class CoupangTest {
private int[] nums;
private int target;
private int[] expectedResult;
private static final int NOT_FOUND_INDEX = -1;
@Before
public void initializeUnit() {
nums = new int[]{ 2, 7, 11, 5 };
target = 9;
expectedResult = new int[] {0, 1};
}
@Test
public void testSolution1() {
assertArrayEquals(expectedResult, findSolution1(nums, target));
}
/**
* n^2 solution
*/
private static int[] findSolution1(int[] nums, int target) {
int size = nums.length;
for (int i = 0; i < size; ++i) {
for (int j = i + 1; j < size; ++j) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[]{ NOT_FOUND_INDEX, NOT_FOUND_INDEX };
}
@Test
public void testSolution2() {
assertArrayEquals(expectedResult, findSolution2(nums, target));
}
/**
* 2*n solution
*/
private static int[] findSolution2(int[] nums, int target) {
int size = nums.length;
Map<Integer, Integer> indexAndValueMapper = new HashMap<>();
for (int i = 0; i < size; ++i) {
indexAndValueMapper.put(nums[i], i);
}
for (int i = 0; i < size; ++i) {
int value1 = nums[i];
if (value1 < target) {
int value2 = target - value1;
if (indexAndValueMapper.containsKey(value2)) {
int value2Index = indexAndValueMapper.get(value2);
if (i != value2Index) {
return new int[] {i, value2Index};
}
}
}
}
return new int[]{ NOT_FOUND_INDEX, NOT_FOUND_INDEX };
}
}
|
Java
|
@ServiceClient(builder = StorageManagementClientBuilder.class)
public final class TableAsyncClient {
private TablesImpl serviceClient;
/** Initializes an instance of Tables client. */
TableAsyncClient(TablesImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Table>> createWithResponse(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.createWithResponseAsync(resourceGroupName, accountName, tableName);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Table>> createWithResponse(
String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.createWithResponseAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Table> create(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.createAsync(resourceGroupName, accountName, tableName);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Table> create(String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.createAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Table>> updateWithResponse(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.updateWithResponseAsync(resourceGroupName, accountName, tableName);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Table>> updateWithResponse(
String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.updateWithResponseAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Table> update(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.updateAsync(resourceGroupName, accountName, tableName);
}
/**
* Creates a new table with the specified table name, under the specified account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the table, including Id, resource name, resource type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Table> update(String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.updateAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Gets the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the table with the specified table name, under the specified account if it exists.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Table>> getWithResponse(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.getWithResponseAsync(resourceGroupName, accountName, tableName);
}
/**
* Gets the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the table with the specified table name, under the specified account if it exists.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Table>> getWithResponse(
String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.getWithResponseAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Gets the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the table with the specified table name, under the specified account if it exists.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Table> get(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.getAsync(resourceGroupName, accountName, tableName);
}
/**
* Gets the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the table with the specified table name, under the specified account if it exists.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Table> get(String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.getAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Deletes the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.deleteWithResponseAsync(resourceGroupName, accountName, tableName);
}
/**
* Deletes the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(
String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.deleteWithResponseAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Deletes the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete(String resourceGroupName, String accountName, String tableName) {
return this.serviceClient.deleteAsync(resourceGroupName, accountName, tableName);
}
/**
* Deletes the table with the specified table name, under the specified account if it exists.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param tableName A table name must be unique within a storage account and must be between 3 and 63 characters.The
* name must comprise of only alphanumeric characters and it cannot begin with a numeric character.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete(String resourceGroupName, String accountName, String tableName, Context context) {
return this.serviceClient.deleteAsync(resourceGroupName, accountName, tableName, context);
}
/**
* Gets a list of all the tables under the specified storage account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all the tables under the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public Mono<PagedResponse<Table>> listSinglePage(String resourceGroupName, String accountName) {
return this.serviceClient.listSinglePageAsync(resourceGroupName, accountName);
}
/**
* Gets a list of all the tables under the specified storage account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all the tables under the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public Mono<PagedResponse<Table>> listSinglePage(String resourceGroupName, String accountName, Context context) {
return this.serviceClient.listSinglePageAsync(resourceGroupName, accountName, context);
}
/**
* Gets a list of all the tables under the specified storage account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all the tables under the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<Table> list(String resourceGroupName, String accountName) {
return this.serviceClient.listAsync(resourceGroupName, accountName);
}
/**
* Gets a list of all the tables under the specified storage account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all the tables under the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<Table> list(String resourceGroupName, String accountName, Context context) {
return this.serviceClient.listAsync(resourceGroupName, accountName, context);
}
/**
* Get the next page of items.
*
* @param nextLink null
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response schema.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public Mono<PagedResponse<Table>> listNextSinglePage(String nextLink) {
return this.serviceClient.listNextSinglePageAsync(nextLink);
}
/**
* Get the next page of items.
*
* @param nextLink null
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response schema.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public Mono<PagedResponse<Table>> listNextSinglePage(String nextLink, Context context) {
return this.serviceClient.listNextSinglePageAsync(nextLink, context);
}
}
|
Java
|
@Component
public class ReinstateIneligibleApplicationModelPopulator {
public ReinstateIneligibleApplicationViewModel populateModel(final ApplicationResource applicationResource) {
return new ReinstateIneligibleApplicationViewModel(applicationResource.getCompetition(),
applicationResource.getId(), applicationResource.getName());
}
}
|
Java
|
public class DefaultRowSet implements RowSet {
private final Sheet sheet;
private final RowSetMetaData metaData;
private int currentRowIndex = -1;
private String[] currentRow;
DefaultRowSet(Sheet sheet, RowSetMetaData metaData) {
this.sheet = sheet;
this.metaData = metaData;
}
@Override
public RowSetMetaData getMetaData() {
return metaData;
}
@Override
public boolean next() {
currentRow = null;
currentRowIndex++;
if (currentRowIndex < sheet.getNumberOfRows()) {
currentRow = sheet.getRow(currentRowIndex);
return true;
}
return false;
}
@Override
public int getCurrentRowIndex() {
return currentRowIndex;
}
@Override
public String[] getCurrentRow() {
return currentRow;
}
@Override
public String getColumnValue(int idx) {
return currentRow[idx];
}
@Override
public Properties getProperties() {
final String[] names = metaData.getColumnNames();
if (names == null) {
throw new IllegalStateException("Cannot create properties without meta data");
}
Properties props = new Properties();
for (int i = 0; i < currentRow.length; i++) {
String value = currentRow[i];
if (value != null) {
props.setProperty(names[i], value);
}
}
return props;
}
}
|
Java
|
public class Chord {
/**
* root notes array for each chord (I, V, vi, IV) in all keys (C..B)
*/
private static final int[][] ROOT_NOTES = {
{48, 43, 45, 41}, /* C3 G2 A2 F2 */
{49, 44, 46, 42}, /* C#3 G#2 Bb2 F#2 */
{50, 45, 47, 43}, /* D3 A2 B2 G2 */
{51, 46, 48, 44}, /* D#3 Bb2 C3 G#2 */
{52, 47, 49, 45}, /* E3 B2 C#3 A2 */
{53, 48, 50, 46}, /* F3 C3 D3 Bb2 */
{54, 49, 51, 47}, /* F#3 C#3 D#3 B2 */
{43, 50, 52, 48}, /* G2 D3 E3 C3 */
{44, 51, 53, 49}, /* G#2 D#3 F3 C#3 */
{45, 52, 54, 50}, /* A2 E3 F#3 D3 */
{46, 41, 43, 39}, /* Bb2 F2 G2 D#2 */
{47, 42, 44, 40} /* B2 F#2 G#2 E2 */
};
/**
* list of offsets to the chord's major (I, V, IV) or minor (vi) third
*/
private static final int[] THIRD_OFFSET = {4, 4, 3, 4};
/**
* offset to the chord's perfect fifth, same for all
*/
private static final int FIFTH_OFFSET = 7;
/**
* offset to the root octave
*/
private static final int OCTAVE_OFFSET = 12;
public final int root;
public final int third;
public final int fifth;
public final int octave;
public final int key;
public final int chord_num;
public Chord(int key, int chord_num) {
if (key >= ROOT_NOTES.length) throw new AssertionError();
if (chord_num >= 4) throw new AssertionError();
root = ROOT_NOTES[key][chord_num];
third = root + THIRD_OFFSET[chord_num];
fifth = root + FIFTH_OFFSET;
octave = root + OCTAVE_OFFSET;
this.key = key;
this.chord_num = chord_num;
}
}
|
Java
|
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
name = "",
propOrder = {"realarray"})
@XmlRootElement(name = "Seasonality_ExpoSmooth")
public class SeasonalityExpoSmooth {
@XmlElement(name = "REAL-ARRAY", required = true)
protected REALARRAY realarray;
@XmlAttribute(name = "type", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String type;
@XmlAttribute(name = "period", required = true)
protected BigInteger period;
@XmlAttribute(name = "unit")
protected String unit;
@XmlAttribute(name = "phase")
protected BigInteger phase;
@XmlAttribute(name = "delta")
protected Double delta;
/**
* Gets the value of the realarray property.
*
* @return possible object is {@link REALARRAY }
*/
public REALARRAY getREALARRAY() {
return realarray;
}
/**
* Sets the value of the realarray property.
*
* @param value allowed object is {@link REALARRAY }
*/
public void setREALARRAY(REALARRAY value) {
this.realarray = value;
}
/**
* Gets the value of the type property.
*
* @return possible object is {@link String }
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value allowed object is {@link String }
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the period property.
*
* @return possible object is {@link BigInteger }
*/
public BigInteger getPeriod() {
return period;
}
/**
* Sets the value of the period property.
*
* @param value allowed object is {@link BigInteger }
*/
public void setPeriod(BigInteger value) {
this.period = value;
}
/**
* Gets the value of the unit property.
*
* @return possible object is {@link String }
*/
public String getUnit() {
return unit;
}
/**
* Sets the value of the unit property.
*
* @param value allowed object is {@link String }
*/
public void setUnit(String value) {
this.unit = value;
}
/**
* Gets the value of the phase property.
*
* @return possible object is {@link BigInteger }
*/
public BigInteger getPhase() {
return phase;
}
/**
* Sets the value of the phase property.
*
* @param value allowed object is {@link BigInteger }
*/
public void setPhase(BigInteger value) {
this.phase = value;
}
/**
* Gets the value of the delta property.
*
* @return possible object is {@link Double }
*/
public Double getDelta() {
return delta;
}
/**
* Sets the value of the delta property.
*
* @param value allowed object is {@link Double }
*/
public void setDelta(Double value) {
this.delta = value;
}
}
|
Java
|
public class Pastel {
public static Map<String, Object> defaultMetadata = Map.ofEntries(
entry("title", "API Documentation"),
entry("language_tabs", new ArrayList<String>()),
entry("toc_footers", new ArrayList<String>()),
entry("logo", Boolean.valueOf(false)),
entry("includes", new ArrayList<String>()),
entry("last_updated", "")
);
/**
* Generate the API documentation using the markdown and include files
*/
public void generate(String sourceFolder, String destinationFolder, Map<String, Object> metadataOverrides) {
String sourceMarkdownFilePath;
File source = new File(sourceFolder);
if (sourceFolder.endsWith(".md")) {
// We're given just the path to a file, we'll use default assets
sourceMarkdownFilePath = source.getAbsolutePath();
sourceFolder = source.getParent();///dirname($sourceMarkdownFilePath);
} else {
if (!source.isDirectory()) {
throw new IllegalArgumentException("Source folder sourceFolder is not a directory.");
}
// Valid source directory
sourceMarkdownFilePath = sourceFolder + "/index.md";
}
if (destinationFolder == null) {
// If no destination is supplied, place it in the source folder
destinationFolder = sourceFolder;
}
try {
String content = Files.readString(Path.of(sourceMarkdownFilePath));
List<Extension> extensions = Arrays.asList(YamlFrontMatterExtension.create());
Parser parser = Parser.builder().extensions(extensions).build();
Node document = parser.parse(content);
Node firstChild = document.getFirstChild();
Map<String, Object> frontMatterData = new HashMap<>();
if (firstChild instanceof YamlFrontMatterBlock) {
YamlFrontMatterBlock frontmatter = (YamlFrontMatterBlock) firstChild;
//handle the frontmatter
YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor();
frontmatter.accept(visitor);
Map<String, List<String>> frontData = visitor.getData();
List<String> filePathsToInclude = new ArrayList<>();
for (Entry<String, List<String>> item: frontData.entrySet()) {
List<String> values = item.getValue();
if (values.size() == 1) {
frontMatterData.put(item.getKey(), values.get(0));
} else {
frontMatterData.put(item.getKey(), values);
}
}
if (frontData.containsKey("includes")) {//isset($frontmatter['includes'])) {
for (String include: frontData.get("includes")) {
filePathsToInclude.add(sourceFolder.trim() + "/" + include.trim());
}
for (String filename: filePathsToInclude) {
Path path = Path.of(filename);
if (!path.toFile().exists()) {
Shotput.getLogger().info("Include file " + filename + " not found.");
} else if (path.toFile().isDirectory()) {
for( File f: path.toFile().listFiles()) {
if (f.isFile() && f.getName().endsWith(".md")) {
Node item = parser.parse(Files.readString(f.toPath()));
item.accept(new CopyVisitor(document));
}
}
} else {
Node item = parser.parse(Files.readString(path));
item.accept(new CopyVisitor(document));
}
}
}
if (!frontData.containsKey("last_updated")) {
// Set last_updated to most recent time main or include files was modified
long time = 0l;
for (String file: filePathsToInclude) {
Path path = Path.of(file);
long timeModified = path.toFile().lastModified();
if (timeModified > time) {
time = timeModified;
}
}
long mTime = Path.of(sourceMarkdownFilePath).toFile().lastModified();
time = mTime > time ? mTime : time;
Date date = new Date(time);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
String dateText = df2.format(date);
frontMatterData.put("last_updated", dateText);
}
}
HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
String htmlContent = renderer.render(document);
Map<String, Object> metadata = this.getPageMetadata(frontMatterData, metadataOverrides);
VelocityEngine engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
engine.init();
Template t = engine.getTemplate("views/index.vtl");
VelocityContext context = new VelocityContext();
PastelUtil utils = new PastelUtil();
context.put("page", metadata);
context.put("util", utils);
context.put("content", htmlContent);
StringWriter writer = new StringWriter();
t.merge(context, writer);
File dest = new File(destinationFolder);
if (!dest.exists()) {
dest.mkdirs();
}
BufferedWriter indexWriter = new BufferedWriter(new FileWriter(dest.getAbsolutePath() + "/index.html"));
indexWriter.write(writer.toString());
indexWriter.close();
copyRecursively("css/", destinationFolder);
copyRecursively("js/", destinationFolder);
copyRecursively("fonts/", destinationFolder);
copyRecursively("images/", destinationFolder);
} catch (IOException ex) {
Shotput.getLogger().error("Failed to generate Documentation", ex);
}
}
protected Map<String, Object> getPageMetadata(Map<String, Object> frontmatter, Map<String, Object> metadataOverrides)
{
Map<String, Object> metadata = new HashMap<>(Pastel.defaultMetadata);//Pastel.defaultMetadata.clone();//Pastel::$defaultMetadata;
for (Entry<String, Object> row : metadata.entrySet()) {
// Override default with values from front matter
String key = row.getKey();
if (frontmatter != null && frontmatter.containsKey(key)) {
metadata.put(key, frontmatter.get(key));
}
// And override that with values from config
if (metadataOverrides != null && metadataOverrides.containsKey(key)) {
metadata.put(key, metadataOverrides.get(key));
}
}
return metadata;
}
private boolean copyRecursively(String src, String dest) {
Path destinationDir = Paths.get(dest);
URL dirURL = getClass().getClassLoader().getResource(src);
if (dirURL != null && dirURL.getProtocol().equals("file")) {
// Traverse the file tree and copy each file/directory.
try {
for (File f: new File(dirURL.toURI()).listFiles()) {
if (f.isFile()) {
Path targetPath = destinationDir.resolve(src + f.getName()).toAbsolutePath();
targetPath.toFile().mkdirs();
Files.copy(new FileInputStream(f), targetPath, StandardCopyOption.REPLACE_EXISTING);
} else {
copyRecursively(src + f.getName(), dest);
}
}
} catch (IOException | URISyntaxException ex) {
return false;
}
return true;
}
if (dirURL == null) {
/*
* In case of a jar file, we can't actually find a directory.
* Have to assume the same jar as clazz.
*/
String me = getClass().getName().replace(".", "/")+".class";
dirURL = getClass().getClassLoader().getResource(me);
}
if (dirURL.getProtocol().equals("jar")) {
/* A JAR path */
try {
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while(entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.startsWith(src)) { //filter according to the path
Path targetPath = destinationDir.resolve(name).toAbsolutePath();
if (name.equals(src)) {
targetPath.toFile().mkdirs();
} else {
jar.getInputStream(jarEntry).transferTo(new FileOutputStream(targetPath.toFile()));
}
}
}
} catch (Exception e) {
return false;
}
return true;
}
return false;
}
public static void main(String[] args) {
Pastel pastel = new Pastel();
pastel.generate("index.md", "docs/", null);
}
}
|
Java
|
public class NewsTask extends AsyncTask<String, Void, ArrayList<News>> {
private NewsCallback callback;
public NewsTask(NewsCallback callback) {
this.callback = callback;
}
@Override
protected ArrayList<News> doInBackground(String... params) {
ArrayList<News> items = new ArrayList<>();
Document doc = null;
if (params.length == 0) {
try {
doc = Jsoup.connect("https://het-erasmus.nl/nieuws").get();
Elements newsItems = doc.getElementsByClass("news-list-item");
for (Element newsItem : newsItems) {
Element item = newsItem.getElementsByClass("news-list-item-right").get(0);
String title = item.getElementsByTag("a").get(1).text();
String shortText = item.getElementsByClass("bodytext").get(0).text();
String category = item.getElementsByTag("a").get(0).text();
String date = item.getElementsByClass("news-list-date").get(0).text().replace(".", " ");
String url = item.getElementsByTag("a").get(0).attr("href");
String image = "https://het-erasmus.nl/" + newsItem.getElementsByClass("news-list-item-left").get(0).getElementsByTag("img").get(0).attr("src");
News news = new News(title, shortText, category, date, url, image);
items.add(news);
Log.d("News item", news.toString());
}
} catch (IOException e) {
if (callback != null) callback.onNewsLoadingFailed();
// e.printStackTrace();
}
} else {
try {
doc = Jsoup.connect("https://het-erasmus.nl/" + params[0]).get();
Element item = doc.getElementsByClass("news-single-item").get(0);
String title = item.getElementsByTag("h1").get(0).text();
String shortText = item.getElementsByTag("h2").get(0).getElementsByClass("bodytext").get(0).text();
String category = "";
if (item.getElementsByClass("news-list-category").size() > 0) {
category = item.getElementsByClass("news-list-category").get(0).text();
}
String date = item.getElementsByClass("news-single-date").get(0).text().replace(".", " ");
String text = "";
int count = item.getElementsByTag("p").size();
Log.d("DetailFragment", "count texts: " + count);
for (int i = 1; i < count; i++) {
text += item.getElementsByTag("p").get(i).text();
if (i < count - 1) text += "\n";
}
String url = item.baseUri();
String image = "https://het-erasmus.nl/" + item.getElementsByClass("news-single-img").get(0).getElementsByTag("img").get(0).attr("src");
News news = new News(title, shortText, text, category, date, url, image);
items.add(news);
Log.d("News single item", news.toString());
} catch (IOException e) {
if (callback != null) callback.onNewsLoadingFailed();
// e.printStackTrace();
}
}
if (callback != null && items.size() > 0) callback.onNewsLoaded(items);
return items;
}
}
|
Java
|
public class CMMParser {
String filename;
public final CMMGrammar Grammar;
CMMTokenName[] tokenNames;
/**
* Maps each Grammar terminal to it's token code.
*/
CMMGrammar.Terminal[] terminalCodeMap;
/**
* The LL(1) predict table maps:
* NonTerminal X LookAheadToken => ProductionRule
* This way, we can determine at any point what production rule applies to the current context.
*/
private LL1PredictTable predictTable;
Stack<CMMGrammar.Symbol> stack;
Stack<Integer> indexStack = new Stack<Integer>();
Scanner scanner;
CMMGrammar.AST tree;
CompilerContext Context;
public CMMParser(String filename, CMMTokenName[] tokenNames) throws Exception {
this.filename = filename;
this.tokenNames = tokenNames;
Context = new CompilerContext();
// fill terminal - code map
// We put them into an array, indexed by their code, since we assume that the code is usually a small number.
// Of course a hash map can be used instead.
// find max code
int maxCode = 0;
for (CMMTokenName name : tokenNames) {
if (name.isSyntaxElement()) {
int code = name.getCode();
maxCode = Math.max(maxCode, code);
if (code < 0) {
throw new ParserException("This parser is not suitable for tokens with a code range < 0 or > 1 million");
}
}
}
if (maxCode > 1e6) {
throw new ParserException("This parser is not suitable for tokens with a code range < 0 or > 1 million");
}
// create scanner
try {
scanner = new Scanner<CMMTokenName>(filename, tokenNames);
}
catch (Exception e) {
logError("Could not open file \"%s\": " + e.getMessage(), filename);
}
// create Grammar & PredictTable
Grammar = new CMMGrammar(Context, scanner);
predictTable = Grammar.createPredictTable();
// fill map
terminalCodeMap = new CMMGrammar.Terminal[maxCode+1];
//Map<String, CMMGrammar.Terminal> terminals = grammar.Terminals;
for (CMMGrammar.Terminal terminal : Grammar.Terminals) {
if (!terminal.TokenName.isSyntaxElement() || terminal.TokenName.isEOF()) continue;
if (terminal.TokenName.isSyntaxElement()) {
terminalCodeMap[terminal.TokenName.getCode()] = terminal;
}
}
}
/**
* @return The first Terminal that represents the given token.
*/
public CMMGrammar.Terminal getTerminal(CMMTokenName token) {
return terminalCodeMap[token.getCode()];
}
public boolean isLastChildOfParent(CMMGrammar.Node node) {
return node.Parent == null || // Start symbol only has one rule with a single symbol
node.index() == node.Parent.Rule.getSymbolCount() - 1;
}
/**
* Drives the AST creation and then starts the pass propagation
*/
public CMMGrammar.AST parse() throws ParserException {
try {
// create AST
tree = Grammar.createAST();
CMMGrammar.Node currentNode = tree.Root;
// create stack and push the start symbol
stack = new Stack<CMMGrammar.Symbol>();
stack.push(Grammar.NonTerminals[1]); // skip over "Start
indexStack.push(1); // next index of start symbol
indexStack.push(0); // next index of first symbol
// advance to the first token
scanner.nextSyntaxElement();
stackLoop: while (!stack.isEmpty() && !scanner.current().isFinalToken()) {
// getTerminal always works because the scanner uses the exact same tokens whose
// codes have been added to the terminalCodeMap.
CMMGrammar.Terminal currentTerminal = getTerminal((CMMTokenName)scanner.current().Name);
CMMGrammar.Symbol stackTop = stack.peek();
int nextIndex = indexStack.pop();
if (stackTop == currentTerminal) {
// match a terminal
stack.pop();
// add terminal node to AST
// need to use previousNode to identify which terminal we found
CMMGrammar.Node node = currentNode.newChild(nextIndex, currentTerminal, scanner.current());
// push increased index back on index stack
indexStack.push(++nextIndex);
scanner.nextSyntaxElement();
while (isLastChildOfParent(node)) {
// we generated the entire sub tree -> go back up
currentNode = currentNode.Parent;
node = node.Parent;
indexStack.pop();
if (currentNode == null) {
// generated the Start symbol -> stack should be empty -> done parsing
assert(stack.isEmpty());
break stackLoop;
}
}
}
else if (stackTop instanceof CMMGrammar.Terminal) {
// unexpected terminal
logError("Unexpected Token: \"%s\" - Expected: \"%s\"", currentTerminal, stackTop);
return null;
}
else {
// stackTop is non-terminal
if (!(stackTop instanceof CMMGrammar.NonTerminal)) {
throw new ParserException("Error in grammar - Found symbol that is neither Terminal nor Non-Terminal: " + stackTop);
}
CMMGrammar.NonTerminal var = (CMMGrammar.NonTerminal)stackTop;
CMMGrammar.Rule rule = predictTable.lookup(var, currentTerminal);
if (rule == null) {
logError("Unexpected Token: \"%s\" in \"%s\"", currentTerminal.TokenName, var);
return null;
}
// pop the top and replace it with the symbols of the predicted production rule
stack.pop();
// push symbols in reverse order
for (int i = rule.getSymbolCount()-1; i >= 0; i--) {
CMMGrammar.Symbol sym = rule.getSymbol(i);
stack.push(sym);
}
onPredict(rule, currentNode);
// add child to AST
CMMGrammar.Node node = currentNode.newChild(nextIndex, rule);
// push increased index back on index stack
indexStack.push(++nextIndex);
if (!node.isLambda()) {
// push new index for nodes of new parent
indexStack.push(0);
// step down the tree
currentNode = node;
}
else {
while (isLastChildOfParent(node)) {
// we generated the entire sub tree -> go back up
currentNode = currentNode.Parent;
node = node.Parent;
indexStack.pop();
if (currentNode == null) {
// generated the Start symbol -> stack should be empty -> done parsing
assert(stack.isEmpty());
// skip until EOF (or unexpected token)
scanner.nextSyntaxElement();
break stackLoop;
}
}
}
}
}
if (!stack.isEmpty()) {
logError("Parse stack not empty - Expected: " + Arrays.asList(stack.toArray()));
return null;
}
else if (!scanner.current().isFinalToken()) {
logError("Symbols found after end of Program.");
return null;
}
CompilerLog.println("Parsed file successfully: " + scanner.FileName);
return tree;
}
catch (Exception otherEx) {
logError("Error while parsing file: " + otherEx);
otherEx.printStackTrace();
return null;
}
}
void logError(String msg, Object... args) {
if (scanner != null) {
msg += String.format(" @ %s(%d:%d)", scanner.FileName, scanner.getLineNo(), scanner.getColumnNo());
}
CompilerLog.error(msg, args);
}
void onPredict(CMMGrammar.Rule rule, CMMGrammar.Node currentNode) {
if (true) return;
String indent = "";
while (currentNode.Parent != null) {
indent += " ";
currentNode = currentNode.Parent;
}
List<String> stackStr = new ArrayList<String>();
for (CMMGrammar.Symbol sym : stack) {
if (sym instanceof CMMGrammar.NonTerminal) {
stackStr.add(((CMMGrammar.NonTerminal)sym).Name);
}
else {
stackStr.add(((CMMGrammar.Terminal)sym).TokenName.CanonicalName);
}
}
CompilerLog.println("%sPredict %s: %s %s", indent, scanner.current(), rule.NonTerminal.Name + " #" + rule.Index, stackStr);
}
}
|
Java
|
static final class ChannelIoSharedBuffer extends ChannelIoBuffer {
private final ThreadLocal<ByteBuffer> bufRef;
private ChannelIoSharedBuffer(final ByteBuffer buf) {
super(buf.capacity());
this.bufRef = new VicariousThreadLocal<ByteBuffer>() {
@Override
protected ByteBuffer initialValue() {
return buf.duplicate();
}
};
}
private ChannelIoSharedBuffer(ChannelIoBuffer parent, final ByteBuffer buf) {
super(parent);
this.bufRef = new VicariousThreadLocal<ByteBuffer>() {
@Override
protected ByteBuffer initialValue() {
return buf.duplicate();
}
};
}
// ensure thread-local for final write since we no longer duplicate every write inside NETTY
@Override
public ByteBuffer buf() {
return bufRef.get();
}
@Override
public void buf(ByteBuffer buf) {
bufRef.set(buf);
}
@Override
public int flags() {
return IoBufferEx.FLAG_SHARED;
}
@Override
public byte[] array() {
return buf().array();
}
@Override
public int arrayOffset() {
return buf().arrayOffset();
}
@Override
public boolean hasArray() {
return buf().hasArray();
}
@Override
protected ChannelIoSharedBuffer asSharedBuffer0() {
return this;
}
@Override
protected ChannelIoBuffer asUnsharedBuffer0() {
return new ChannelIoUnsharedBuffer(buf());
}
@Override
protected ChannelIoUnsharedBuffer duplicate0() {
return new ChannelIoUnsharedBuffer(this, buf().duplicate());
}
@Override
protected ChannelIoUnsharedBuffer slice0() {
return new ChannelIoUnsharedBuffer(this, buf().slice());
}
@Override
protected ChannelIoUnsharedBuffer asReadOnlyBuffer0() {
return new ChannelIoUnsharedBuffer(this, buf().asReadOnlyBuffer());
}
}
|
Java
|
public class ApplicationEventDistributionServiceImplTest extends AbstractServicesUnitTest {
/* Test subject and mocks */
@TestSubject
private ApplicationEventDistributionServiceImpl applicationEventDistributionService = new ApplicationEventDistributionServiceImpl();
@Mock
private ApplicationEventListener applicationEventListener;
@Mock
private PersistenceUtilityService persistenceUtilityService;
@Mock
private ExecutorService executorService;
/* Constructors */
public ApplicationEventDistributionServiceImplTest() {
}
/* Test methods */
@Test
public void testPublishSynchronousEventWithInvalidArguments() {
// Reset
resetAll();
// Replay
replayAll();
// Run test scenario
try {
applicationEventDistributionService.publishSynchronousEvent(null);
fail("Exception should be thrown");
} catch (final IllegalArgumentException ex) {
// Expected
}
// Verify
verifyAll();
}
@Test
public void testPublishSynchronousEvent() {
// Test data
final Long stationId = 1l;
final ApplicationEvent applicationEvent = new MockApplicationEvent();
// Reset
resetAll();
// Expectation
expect(applicationEventListener.subscribed(eq(applicationEvent))).andReturn(true).once();
applicationEventListener.process(eq(applicationEvent));
expectLastCall().once();
persistenceUtilityService.runInNewTransaction(isA(Runnable.class));
expectLastCall().andAnswer(() -> {
final Runnable runnable = (Runnable) getCurrentArguments()[0];
runnable.run();
return null;
}).once();
// Replay
replayAll();
// Run test scenario
applicationEventDistributionService.subscribe(applicationEventListener);
applicationEventDistributionService.publishSynchronousEvent(applicationEvent);
// Verify
verifyAll();
}
@Test
public void testSubscribeWithInvalidArguments() {
// Reset
resetAll();
// Replay
replayAll();
// Run test scenario
try {
applicationEventDistributionService.subscribe(null);
fail("Exception should be thrown");
} catch (final IllegalArgumentException ex) {
// Expected
}
// Verify
verifyAll();
}
@Test
public void testSubscribe() {
// Reset
resetAll();
// Replay
replayAll();
// Run test scenario
applicationEventDistributionService.subscribe(new ApplicationEventListener() {
@Nonnull
@Override
public boolean subscribed(@Nonnull ApplicationEvent applicationEvent) {
return false;
}
@Override
public void process(@Nonnull ApplicationEvent applicationEvent) {
}
});
// Verify
verifyAll();
}
@Test
public void testPublishAsynchronousEventWithInvalidArguments() {
// Reset
resetAll();
// Replay
replayAll();
// Run test scenario
try {
applicationEventDistributionService.publishAsynchronousEvent(null);
fail("Exception should be thrown");
} catch (final IllegalArgumentException ex) {
// Expected
}
// Verify
verifyAll();
}
@Test
public void testPublishAsynchronousEvent() {
// Test data
final Long stationId = 1l;
final ApplicationEvent applicationEvent = new MockApplicationEvent();
// Reset
resetAll();
// Expectation
expect(executorService.submit(isA(Runnable.class))).andAnswer(() -> {
final Runnable runnable = (Runnable) getCurrentArguments()[0];
runnable.run();
return null;
}).times(2);
expect(applicationEventListener.subscribed(eq(applicationEvent))).andReturn(true).once();
applicationEventListener.process(eq(applicationEvent));
expectLastCall().once();
persistenceUtilityService.runInPersistenceSession(isA(Runnable.class));
expectLastCall().andAnswer(() -> {
final Runnable runnable = (Runnable) getCurrentArguments()[0];
runnable.run();
return null;
}).once();
// Replay
replayAll();
// Run test scenario
applicationEventDistributionService.subscribe(applicationEventListener);
applicationEventDistributionService.publishAsynchronousEvent(applicationEvent);
// Verify
verifyAll();
}
/* Inner class */
private static class MockApplicationEvent implements ApplicationEvent {
/* Constructors */
public MockApplicationEvent() {
}
}
}
|
Java
|
public class GraphNode {
String word;
ArrayList<String> neighbours;
GraphNode(String s)
{
word=s;
neighbours=new ArrayList<>();
}
}
|
Java
|
public final class CRegisterProvider implements IRegisterModel {
/**
* Listeners that are notified about changes in the register values that come from the debug
* client.
*/
private final ListenerProvider<IRegistersChangedListener> reglisteners =
new ListenerProvider<>();
/**
* Listeners that are notified about changes in the register values that come from user input in
* the GUI.
*/
private final ListenerProvider<IDataEnteredListener> enterlisteners =
new ListenerProvider<>();
/**
* Register information that is currently displayed in the register view.
*/
private RegisterInformationInternal[] registerInformation = new RegisterInformationInternal[0];
/**
* Gives information about the registers shown in the view.
*/
private List<RegisterDescription> m_information = null;
/**
* Makes sure to highlight a register if its value changed between the last update and the current
* update.
*
* @param counter Index of the register.
* @param registerValue New value of the register.
* @param oldRegisterInformation Register information from previous update.
* @param newRegisterInformation Register information from current update.
*/
private static void highlightChangedRegister(final int counter,
final RegisterValue registerValue,
final RegisterInformationInternal[] oldRegisterInformation,
final RegisterInformationInternal[] newRegisterInformation) {
if (counter < oldRegisterInformation.length) {
// Highlight if the new value is different from
// the old value of the register.
if (!oldRegisterInformation[counter].getValue().equals(registerValue.getValue())) {
newRegisterInformation[counter].setModified(true);
}
} else {
// If the register is new, highlight it.
newRegisterInformation[counter].setModified(true);
}
}
/**
* Returns the index of a register identified by name.
*
* @param registerName Name of the register.
*
* @return The index of the specified register or -1 if no such register exists.
*/
private int findRegisterIndex(final String registerName) {
int counter = 0;
for (final RegisterInformationInternal info : registerInformation) {
if (info.getRegisterName().equals(registerName)) {
return counter;
}
++counter;
}
return -1;
}
/**
* Returns the register description of a register identified by a name.
*
* @param name The name of the register.
*
* @return The register description of the register or null if the register is unknown.
*/
private RegisterDescription getDescription(final String name) {
for (final RegisterDescription description : m_information) {
if (description.getName().equals(name)) {
return description;
}
}
return null;
}
/**
* Notifies the register listeners about changes in the register values.
*/
private void notifyRegisterChanged() {
for (final IRegistersChangedListener listener : reglisteners) {
listener.registerDataChanged();
}
}
/**
* Notifies listeners about changes in the register values that came from the GUI (aka user
* input).
*
* @param index Index of the register.
* @param previousValue Old value of the register.
* @param newValue New value of the register.
*/
private void notifyRegisterEntered(
final int index, final BigInteger previousValue, final BigInteger newValue) {
for (final IDataEnteredListener listener : enterlisteners) {
listener.registerChanged(index, previousValue, newValue);
}
}
/**
* Adds a listener that is notified when the user enters register values through the GUI.
*
* @param listener The listener that is notified when the user enters register values.
*/
public void addListener(final IDataEnteredListener listener) {
enterlisteners.addListener(listener);
}
@Override
public void addListener(final IRegistersChangedListener listener) {
reglisteners.addListener(listener);
}
@Override
public int getNumberOfRegisters() {
return registerInformation.length;
}
@Override
public RegisterInformationInternal[] getRegisterInformation() {
return registerInformation.clone();
}
@Override
public RegisterInformationInternal getRegisterInformation(final int index) {
return registerInformation[index];
}
/**
* Changes the register description information.
*
* @param information The new register information.
*/
public void setRegisterDescription(final List<RegisterDescription> information) {
m_information = information;
}
/**
* Updates the register information.
*
* @param information The new register information to display.
*/
public void setRegisterInformation(final List<RegisterValue> information) {
Preconditions.checkNotNull(information, "IE01475: Information argument can not be null");
if (!information.isEmpty() && (m_information == null)) {
throw new IllegalStateException(
"IE01124: Can not set register values if no target information is given");
}
final RegisterInformationInternal[] oldRegisterInformation = registerInformation;
final RegisterInformationInternal[] newRegisterInformation =
new RegisterInformationInternal[information.size()];
int counter = 0;
if (!information.isEmpty()) {
Preconditions.checkNotNull(
m_information, "IE01125: Target information should not be null at this point");
for (final RegisterValue registerValue : information) {
final RegisterDescription regInfo = getDescription(registerValue.getName());
Preconditions.checkNotNull(regInfo, "IE01476: Unknown register");
newRegisterInformation[counter] =
new RegisterInformationInternal(regInfo.getName(), regInfo.getSize());
newRegisterInformation[counter].setValue(registerValue.getValue());
// Make sure to highlight modified register values.
highlightChangedRegister(
counter, registerValue, oldRegisterInformation, newRegisterInformation);
counter++;
}
}
registerInformation = newRegisterInformation;
notifyRegisterChanged();
}
@Override
public void setValue(final String registerName, final BigInteger editValue) {
// This function overwrites register values with a new value. Listeners are
// notified about the change and receive the old value and the new value of
// the register to roll back the changes if necessary.
final int index = findRegisterIndex(registerName);
if ((index == -1) || (index >= registerInformation.length)) {
// Fail silently if the index is out of bounds
return;
}
// Save the old value of the register
final BigInteger oldValue = registerInformation[index].getValue();
// Update the register with the new value
registerInformation[index].setValue(editValue);
// Notify the listeners about the change
notifyRegisterEntered(index, oldValue, editValue);
}
}
|
Java
|
@Schema(
name = "ResourceMetadata",
description = "Metadata of a resource",
oneOf = ResourceMetadata.class,
example = "{\n" +
" \"title\": \"Sample Resource\",\n" +
" \"description\": \"This is an example resource containing weather data.\",\n" +
" \"keywords\": [\n" +
" \"weather\",\n" +
" \"data\",\n" +
" \"sample\"\n" +
" ],\n" +
" \"owner\": \"https://openweathermap.org/\",\n" +
" \"license\": \"ODbL\",\n" +
" \"version\": \"1.0\"\n" +
"}\n"
)
public class ResourceMetadata implements Serializable {
@JsonProperty("title")
private String title;
@JsonProperty("description")
private String description;
@ElementCollection
@JsonProperty("keywords")
private List<String> keywords;
@Column(columnDefinition = "BYTEA")
@JsonProperty("policy")
private String policy;
@JsonProperty("owner")
private URI owner;
@JsonProperty("license")
private URI license;
@JsonProperty("version")
private String version;
@NotNull
@ElementCollection
@Column(columnDefinition = "BYTEA")
@JsonProperty("representations")
private List<ResourceRepresentation> representations;
/**
* <p>Constructor for ResourceMetadata.</p>
*/
public ResourceMetadata() {
}
/**
* <p>Constructor for ResourceMetadata.</p>
*
* @param title a {@link java.lang.String} object.
* @param description a {@link java.lang.String} object.
* @param keywords a {@link java.util.List} object.
* @param policy a {@link java.lang.String} object.
* @param owner a {@link java.net.URI} object.
* @param license a {@link java.net.URI} object.
* @param version a {@link java.lang.String} object.
* @param representations a {@link java.util.List} object.
*/
public ResourceMetadata(String title, String description, List<String> keywords, String policy,
URI owner, URI license, String version, List<ResourceRepresentation> representations) {
this.title = title;
this.description = description;
this.keywords = keywords;
this.policy = policy;
this.owner = owner;
this.license = license;
this.version = version;
this.representations = representations;
}
/**
* <p>Getter for the field <code>title</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getTitle() {
return title;
}
/**
* <p>Setter for the field <code>title</code>.</p>
*
* @param title a {@link java.lang.String} object.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* <p>Getter for the field <code>description</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getDescription() {
return description;
}
/**
* <p>Setter for the field <code>description</code>.</p>
*
* @param description a {@link java.lang.String} object.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>Getter for the field <code>keywords</code>.</p>
*
* @return a {@link java.util.List} object.
*/
public List<String> getKeywords() {
return keywords;
}
/**
* <p>Setter for the field <code>keywords</code>.</p>
*
* @param keywords a {@link java.util.List} object.
*/
public void setKeywords(List<String> keywords) {
this.keywords = keywords;
}
/**
* <p>Getter for the field <code>policy</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getPolicy() {
return policy;
}
/**
* <p>Setter for the field <code>policy</code>.</p>
*
* @param policy a {@link java.lang.String} object.
*/
public void setPolicy(String policy) {
this.policy = policy;
}
/**
* <p>Getter for the field <code>owner</code>.</p>
*
* @return a {@link java.net.URI} object.
*/
public URI getOwner() {
return owner;
}
/**
* <p>Setter for the field <code>owner</code>.</p>
*
* @param owner a {@link java.net.URI} object.
*/
public void setOwner(URI owner) {
this.owner = owner;
}
/**
* <p>Getter for the field <code>license</code>.</p>
*
* @return a {@link java.net.URI} object.
*/
public URI getLicense() {
return license;
}
/**
* <p>Setter for the field <code>license</code>.</p>
*
* @param license a {@link java.net.URI} object.
*/
public void setLicense(URI license) {
this.license = license;
}
/**
* <p>Getter for the field <code>version</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getVersion() {
return version;
}
/**
* <p>Setter for the field <code>version</code>.</p>
*
* @param version a {@link java.lang.String} object.
*/
public void setVersion(String version) {
this.version = version;
}
/**
* <p>Getter for the field <code>representations</code>.</p>
*
* @return a {@link java.util.List} object.
*/
public List<ResourceRepresentation> getRepresentations() {
return representations;
}
/**
* <p>Setter for the field <code>representations</code>.</p>
*
* @param representations a {@link java.util.List} object.
*/
public void setRepresentations(List<ResourceRepresentation> representations) {
this.representations = representations;
}
/** {@inheritDoc} */
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
String jsonString = null;
try {
jsonString = mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return jsonString;
}
}
|
Java
|
public class SignalFxMetricsReporterServiceConfig extends AbstractConfig {
private static final ConfigDef CONFIG;
public static final String REPORT_METRICS_CONFIG = "report.metrics.list";
public static final String REPORT_METRICS_DOC = CommonServiceConfig.REPORT_METRICS_DOC;
public static final String REPORT_INTERVAL_SEC_CONFIG = CommonServiceConfig.REPORT_INTERVAL_SEC_CONFIG;
public static final String REPORT_INTERVAL_SEC_DOC = CommonServiceConfig.REPORT_INTERVAL_SEC_DOC;
public static final String REPORT_SIGNALFX_URL = "report.signalfx.url";
public static final String REPORT_SIGNALFX_URL_DOC = "The url of signalfx server which SignalFxMetricsReporterService will report the metrics values.";
public static final String SIGNALFX_METRIC_DIMENSION = "report.metric.dimensions";
public static final String SIGNALFX_METRIC_DIMENSION_DOC = "Dimensions added to each metric. Example: {\"key1:value1\", \"key2:value2\"} ";
public static final String SIGNALFX_TOKEN = "report.signalfx.token";
public static final String SIGNALFX_TOKEN_DOC = "SignalFx access token";
static {
CONFIG = new ConfigDef().define(REPORT_METRICS_CONFIG,
ConfigDef.Type.LIST,
Arrays.asList("kmf.services:*:*"),
ConfigDef.Importance.MEDIUM,
REPORT_METRICS_DOC)
.define(REPORT_INTERVAL_SEC_CONFIG,
ConfigDef.Type.INT,
1,
ConfigDef.Importance.LOW,
REPORT_INTERVAL_SEC_DOC)
.define(REPORT_SIGNALFX_URL,
ConfigDef.Type.STRING,
"",
ConfigDef.Importance.LOW,
REPORT_SIGNALFX_URL_DOC)
.define(SIGNALFX_TOKEN,
ConfigDef.Type.STRING,
"",
ConfigDef.Importance.HIGH,
SIGNALFX_TOKEN_DOC);
}
public SignalFxMetricsReporterServiceConfig(Map<?, ?> props) {
super(CONFIG, props);
}
}
|
Java
|
public class UniformNearShadowDistance extends BaseUniform implements KVStorage.OnChangeListener {
public static final String UNIFORM_NEAR_SHADOW_DISTANCE = "u_nearShadowDistance";
private static final float SHADOW_OFFSET = 2;
private float distance;
public UniformNearShadowDistance() {
super();
ForgE.config.addListener(this);
updateDistance();
}
@Override
public void defineUniforms() {
define(UNIFORM_NEAR_SHADOW_DISTANCE, Float.class);
}
@Override
public void bind(ShaderProgram shader, LevelEnv env, RenderContext context, Camera camera) {
shader.setUniformf(UNIFORM_NEAR_SHADOW_DISTANCE, distance);
}
@Override
public void dispose() {
ForgE.config.removeListener(this);
}
@Override
public void onKeyChange(Object key, KVStorage storage) {
updateDistance();
}
private void updateDistance() {
this.distance = ForgE.config.getInt(Config.Key.NearShadowDistance) + SHADOW_OFFSET;
}
}
|
Java
|
public class BranchCoverageFactory extends
AbstractFitnessFactory<BranchCoverageTestFitness> {
private static final Logger logger = LoggerFactory.getLogger(BranchCoverageFactory.class);
/**
* return coverage goals of the target class or of all the contextual branches, depending on the limitToCUT parameter
* @param limitToCUT whether to consider the class under test only ({@code true}) or all known
* classes ({@code false})
* @return
*/
private List<BranchCoverageTestFitness> computeCoverageGoals(boolean limitToCUT){
long start = System.currentTimeMillis();
List<BranchCoverageTestFitness> goals = new ArrayList<>();
// logger.info("Getting branches");
for (String className : BranchPool.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()).knownClasses()) {
//when limitToCUT== true, if not the class under test of a inner/anonymous class, continue
if(limitToCUT && !isCUT(className)) continue;
//when limitToCUT==false, consider all classes, but excludes libraries ones according the INSTRUMENT_LIBRARIES property
if(!limitToCUT && (!Properties.INSTRUMENT_LIBRARIES && !DependencyAnalysis.isTargetProject(className))) continue;
final MethodNameMatcher matcher = new MethodNameMatcher();
// Branchless methods
for (String method : BranchPool.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()).getBranchlessMethods(className)) {
if (matcher.fullyQualifiedMethodMatches(method)) {
goals.add(createRootBranchTestFitness(className, method));
}
}
// Branches
for (String methodName : BranchPool.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()).knownMethods(className)) {
if (!matcher.methodMatches(methodName)) {
logger.info("Method " + methodName + " does not match criteria. ");
continue;
}
for (Branch b : BranchPool.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()).retrieveBranchesInMethod(className,
methodName)) {
if(!b.isInstrumented()) {
goals.add(createBranchCoverageTestFitness(b, true));
goals.add(createBranchCoverageTestFitness(b, false));
}
}
}
}
goalComputationTime = System.currentTimeMillis() - start;
return goals;
}
/*
* (non-Javadoc)
*
* @see
* org.evosuite.coverage.TestCoverageFactory#getCoverageGoals()
*/
/** {@inheritDoc} */
@Override
public List<BranchCoverageTestFitness> getCoverageGoals() {
return computeCoverageGoals(true);
}
public List<BranchCoverageTestFitness> getCoverageGoalsForAllKnownClasses() {
return computeCoverageGoals(false);
}
/**
* Create a fitness function for branch coverage aimed at executing the
* given ControlDependency.
*
* @param cd
* a {@link org.evosuite.graphs.cfg.ControlDependency} object.
* @return a {@link org.evosuite.coverage.branch.BranchCoverageTestFitness}
* object.
*/
public static BranchCoverageTestFitness createBranchCoverageTestFitness(
ControlDependency cd) {
return createBranchCoverageTestFitness(cd.getBranch(),
cd.getBranchExpressionValue());
}
/**
* Create a fitness function for branch coverage aimed at executing the
* Branch identified by b as defined by branchExpressionValue.
*
* @param b
* a {@link org.evosuite.coverage.branch.Branch} object.
* @param branchExpressionValue
* a boolean.
* @return a {@link org.evosuite.coverage.branch.BranchCoverageTestFitness}
* object.
*/
public static BranchCoverageTestFitness createBranchCoverageTestFitness(
Branch b, boolean branchExpressionValue) {
return new BranchCoverageTestFitness(new BranchCoverageGoal(b,
branchExpressionValue, b.getClassName(), b.getMethodName()));
}
/**
* Create a fitness function for branch coverage aimed at covering the root
* branch of the given method in the given class. Covering a root branch
* means entering the method.
*
* @param className
* a {@link java.lang.String} object.
* @param method
* a {@link java.lang.String} object.
* @return a {@link org.evosuite.coverage.branch.BranchCoverageTestFitness}
* object.
*/
public static BranchCoverageTestFitness createRootBranchTestFitness(
String className, String method) {
return new BranchCoverageTestFitness(new BranchCoverageGoal(className,
method.substring(method.lastIndexOf(".") + 1)));
}
/**
* Convenience method calling createRootBranchTestFitness(class,method) with
* the respective class and method of the given BytecodeInstruction.
*
* @param instruction
* a {@link org.evosuite.graphs.cfg.BytecodeInstruction} object.
* @return a {@link org.evosuite.coverage.branch.BranchCoverageTestFitness}
* object.
*/
public static BranchCoverageTestFitness createRootBranchTestFitness(
BytecodeInstruction instruction) {
if (instruction == null)
throw new IllegalArgumentException("null given");
return createRootBranchTestFitness(instruction.getClassName(),
instruction.getMethodName());
}
}
|
Java
|
@WebuiProcess(layoutType = PanelLayoutType.SingleOverlayField)
public class WEBUI_M_HU_SecurPharmScan extends HUEditorProcessTemplate implements IProcessPrecondition
{
@Autowired
private SecurPharmService securPharmService;
static final String PARAM_Barcode = "Barcode";
@Param(mandatory = true, parameterName = PARAM_Barcode)
private String dataMatrixString;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!securPharmService.hasConfig())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no SecurPharm config");
}
if (!selectedRowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final HUEditorRow row = getSingleSelectedRow();
final HuId huId = row.getHuId();
final SecurPharmHUAttributesScanner scanner = securPharmService.newHUScanner();
if (!scanner.isEligible(huId))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("HU not eligible");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final SecurPharmHUAttributesScanner scanner = securPharmService.newHUScanner();
final SecurPharmHUAttributesScannerResult result = scanner.scanAndUpdateHUAttributes(getDataMatrix(), getSelectedHuId());
//
// Update view
final HUEditorView view = getView();
if (result.getExtractedCUId() != null)
{
view.addHUId(result.getExtractedCUId());
}
view.invalidateAll();
return result.getResultMessageAndCode();
}
private HuId getSelectedHuId()
{
return getSingleSelectedRow().getHuId();
}
private final DataMatrixCode getDataMatrix()
{
return DataMatrixCode.ofString(dataMatrixString);
}
}
|
Java
|
@DataEntry
@ObjectClass(value = "cibaRequest")
public class CIBARequest implements Serializable {
@DN
private String dn;
@AttributeName(name = "authReqId")
private String authReqId;
@AttributeName(name = "clnId", consistency = true)
private String clientId;
@AttributeName(name = "usrId", consistency = true)
private String userId;
@AttributeName(name = "creationDate")
private Date creationDate;
@AttributeName(name = "exp")
private Date expirationDate;
@AttributeName(name = "oxStatus")
private String status;
public String getDn() {
return dn;
}
public void setDn(String dn) {
this.dn = dn;
}
public String getAuthReqId() {
return authReqId;
}
public void setAuthReqId(String authReqId) {
this.authReqId = authReqId;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CIBARequest that = (CIBARequest) o;
if (!dn.equals(that.dn)) return false;
if (!authReqId.equals(that.authReqId)) return false;
return true;
}
@Override
public int hashCode() {
int result = dn.hashCode();
result = 31 * result + authReqId.hashCode();
return result;
}
}
|
Java
|
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CustomFiltersLiveTest {
@LocalServerPort
String port;
@Autowired
private WebTestClient client;
@BeforeEach
public void clearLogList() {
LoggerListAppender.clearEventList();
client = WebTestClient.bindToServer()
.baseUrl("http://localhost:" + port)
.build();
}
@Test
public void whenCallServiceThroughGateway_thenAllConfiguredFiltersGetExecuted() {
ResponseSpec response = client.get()
.uri("/service/resource")
.exchange();
response.expectStatus()
.isOk()
.expectHeader()
.doesNotExist("Bael-Custom-Language-Header")
.expectBody(String.class)
.isEqualTo("Service Resource");
assertThat(LoggerListAppender.getEvents())
// Global Pre Filter
.haveAtLeastOne(eventContains("Global Pre Filter executed"))
// Global Post Filter
.haveAtLeastOne(eventContains("Global Post Filter executed"))
// Global Pre and Post Filter
.haveAtLeastOne(eventContains("First Pre Global Filter"))
.haveAtLeastOne(eventContains("Last Post Global Filter"))
// Logging Filter Factory
.haveAtLeastOne(eventContains("Pre GatewayFilter logging: My Custom Message"))
.haveAtLeastOne(eventContains("Post GatewayFilter logging: My Custom Message"))
// Modify Request
.haveAtLeastOne(eventContains("Modify request output - Request contains Accept-Language header:"))
.haveAtLeastOne(eventContainsExcept("Removed all query params: ", "locale"))
// Modify Response
.areNot(eventContains("Added custom header to Response"))
// Chain Request
.haveAtLeastOne(eventContains("Chain Request output - Request contains Accept-Language header:"));
}
@Test
public void givenRequestWithLocaleQueryParam_whenCallServiceThroughGateway_thenAllConfiguredFiltersGetExecuted() {
ResponseSpec response = client.get()
.uri("/service/resource?locale=en")
.exchange();
response.expectStatus()
.isOk()
.expectHeader()
.exists("Bael-Custom-Language-Header")
.expectBody(String.class)
.isEqualTo("Service Resource");
assertThat(LoggerListAppender.getEvents())
// Modify Response
.haveAtLeastOne(eventContains("Added custom header to Response"))
.haveAtLeastOne(eventContainsExcept("Removed all query params: ", "locale"));
}
/**
* This condition will be successful if the event contains a substring
*/
private Condition<ILoggingEvent> eventContains(String substring) {
return new Condition<ILoggingEvent>(entry -> (substring == null || (entry.getFormattedMessage() != null && entry.getFormattedMessage()
.contains(substring))), String.format("entry with message '%s'", substring));
}
/**
* This condition will be successful if the event contains a substring, but not another one
*/
private Condition<ILoggingEvent> eventContainsExcept(String substring, String except) {
return new Condition<ILoggingEvent>(entry -> (substring == null || (entry.getFormattedMessage() != null && entry.getFormattedMessage()
.contains(substring)
&& !entry.getFormattedMessage()
.contains(except))),
String.format("entry with message '%s'", substring));
}
}
|
Java
|
public class GUIUtil {
/**
* Create file chooser file chooser.
*
* @param selectedFile the selected file
* @param supportedTypes the supported types
* @param operation the operation
* @return the file chooser
*/
public static FileChooser createFileChooser(
File selectedFile, FileTypeSupport supportedTypes, FileOperation operation) {
FileChooser chooser;
if (SystemInfo.isMacOsx()) {
chooser = new AwtFileChooser(null, operation, supportedTypes);
} else {
chooser = new SwingFileChooser(supportedTypes, operation);
}
if (selectedFile != null && selectedFile.exists()) {
if (selectedFile.isDirectory()) {
chooser.setCurrentDirectory(selectedFile);
} else {
chooser.setSelectedFile(selectedFile);
}
}
return chooser;
}
/**
* Take screenshot.
*
* @param fileName the file name
* @param formatName the format name
* @throws IOException the io exception
* @throws AWTException the awt exception
*/
public static void takeScreenshot(String fileName, String formatName) throws IOException, AWTException {
Rectangle screenBounds = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage image = new Robot().createScreenCapture(screenBounds);
ImageIO.write(image, formatName, new File(fileName));
}
}
|
Java
|
public abstract class DynamixelMotor {
protected int id;
protected int motorType;
protected int mMaxPosition;
protected int mRotationMode;
protected boolean flipped;
protected static ArrayList<int[]> syncMoveList;
protected static int syncDataLength = -1;
//TODO fix xl320
protected final double encoderPerSecPerUnit = 1.58;
protected int currentPosition = 0;
protected boolean D = true;
protected final byte[] mxHeader = new byte[] {(byte) 0xFF, (byte) 0xFF};
protected final byte[] xlHeader = new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFD, (byte) 0x00};
public DynamixelMotor(int id, int motorType) {
this.id = id; // not verifying if the id is in use
this.motorType = motorType;
this.mMaxPosition = getMotorMaxPosition();
this.currentPosition = getZeroPosition();
if (syncMoveList != null) {syncMoveList = new ArrayList<>();}
}
protected abstract byte[] sendMessage(byte[] message) throws IOException;
protected byte[] readAddress(int id, int address, int length) {
ByteBuffer buffer = ByteBuffer.allocate(13);
int messageLength = 0x04;
byte[] params;
try {
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (messageLength + 2), (byte) 0x00, (byte) 0x02,
(byte) address, (byte) 0x00, (byte) length};
buffer.put(xlHeader);
buffer.put(params);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) messageLength, (byte) 0x02, (byte) address, (byte) length};
byte checksum = DynamixelUtil.generateChecksum(params);
buffer.put(mxHeader);
buffer.put(params);
buffer.put(checksum);
break;
}
return sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected byte[] writeAddress(int id, int address, int value) {
ByteBuffer buffer = ByteBuffer.allocate(13);
int length = 0x04;
byte[] params;
try {
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (length + 2), (byte) 0x00, (byte) 0x03, (byte) address,
(byte) 0x00, (byte) value};
buffer.put(xlHeader);
buffer.put(params);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) length, (byte) 0x03, (byte) address, (byte) value};
byte checksum = DynamixelUtil.generateChecksum(params);
buffer.put(mxHeader);
buffer.put(params);
buffer.put(checksum);
break;
}
sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected byte[] writeAddress(int id, int address, int lowByte, int highByte) {
ByteBuffer buffer = ByteBuffer.allocate(14);
int length = 0x05;
byte[] params;
try {
//System.out.println("Motor " + id + " Type " + motorType + " / " + this.hashCode());
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (length + 2), (byte) 0x00, (byte) 0x03,
(byte) address, (byte) 0x00, (byte) lowByte, (byte) highByte};
buffer.put(xlHeader);
buffer.put(params);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) length, (byte) 0x03, (byte) address,
(byte) lowByte, (byte) highByte};
byte checksum = DynamixelUtil.generateChecksum(params);
buffer.put(mxHeader);
buffer.put(params);
buffer.put(checksum);
break;
}
if (D) DynamixelUtil.printHexByteArray(buffer.array());
sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected byte[] writeAddress(int id, int address, byte[] dataArr) {
ByteBuffer buffer = ByteBuffer.allocate(12 + dataArr.length);
int length = 0x03 + dataArr.length;
byte[] params;
try {
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (length + 2), (byte) 0x00, (byte) 0x03,
(byte) address, (byte) 0x00};
buffer.put(xlHeader);
buffer.put(params);
buffer.put(dataArr);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) length, (byte) 0x03, (byte) address};
buffer.put(mxHeader);
buffer.put(params);
buffer.put(dataArr);
byte checksum = DynamixelUtil.generateChecksum(buffer, 2, buffer.position());
buffer.put(checksum);
break;
}
if (D) DynamixelUtil.printHexByteArray(dataArr);
if (D) DynamixelUtil.printHexByteArray(buffer.array());
sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] syncWriteAddress() {
int[] length = getMotorPerController();
// ((L + 1) * N) + headers (L: Data Length per motor [2], N: the number of motors[2 / 3])
ByteBuffer xlBuffer = ByteBuffer.allocate((length[0] * (syncDataLength + 1)) + 9); // 2 motors
ByteBuffer mxBuffer = ByteBuffer.allocate((length[1] * (syncDataLength + 1)) + 8); // 3 motors
byte[] xlSyncHeader = new byte[] {(byte) 0xFE, (byte) 0x1E, (byte) 0x00,
(byte)((length[1] * (syncDataLength + 1)) % 256), (byte) 0x00};
byte[] mxSyncHeader = new byte[] {(byte) 0xFE, (byte)(((length[0] * (syncDataLength + 1)) + 4) % 256),
(byte) 0X83, (byte) 0x1E, (byte) 0x02};
xlBuffer.put(xlHeader).put(xlSyncHeader);
xlBuffer.put(mxHeader).put(mxSyncHeader);
int motorType;
try {
for (int[] arr : syncMoveList) {
motorType = DynamixelMotorType.getMotorType(arr[0]);
switch (motorType) {
case DynamixelMotorType.XL_320:
xlBuffer.put((byte) arr[0]); // motor id
for (int i = 2; i < syncMoveList.size(); i++) {
xlBuffer.put((byte) arr[i]);
}
break;
default:
mxBuffer.put((byte) arr[0]); // motor id
for (int i = 2; i < syncMoveList.size(); i++) {
xlBuffer.put((byte) arr[i]);
}
break;
}
}
// calc checksum / crc16
int crc16 = DynamixelUtil.generateDynamixelCRC16(xlBuffer, xlBuffer.position());
xlBuffer.put((byte)(crc16 & 0x00FF)); // CRC low
xlBuffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
byte checksum = DynamixelUtil.generateChecksum(mxBuffer, 2, mxBuffer.position());
mxBuffer.put(checksum);
sendMessage(xlBuffer.array());
DynamixelUtil.sleep(12); // todo: shrink if possible
sendMessage(mxBuffer.array());
} catch (IOException e) {
e.printStackTrace();
} finally {
syncMoveList.clear();
syncDataLength = 0;
}
return null;
}
public byte[] ping() {
ByteBuffer buffer = ByteBuffer.allocate(10);
int length = 0x02;
byte[] params;
try {
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (length + 1), (byte) 0x00, (byte) 0x01};
buffer.put(xlHeader);
buffer.put(params);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) length, (byte) 0x01};
byte checksum = DynamixelUtil.generateChecksum(params);
buffer.put(mxHeader);
buffer.put(params);
buffer.put(checksum);
break;
}
return sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void reset() {
ByteBuffer buffer = ByteBuffer.allocate(10);
int length = 0x02;
byte[] params;
try {
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (length + 1), (byte) 0x00, (byte) 0x06};
buffer.put(xlHeader);
buffer.put(params);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) length, (byte) 0x06};
byte checksum = DynamixelUtil.generateChecksum(params);
buffer.put(mxHeader);
buffer.put(params);
buffer.put(checksum);
break;
}
sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
}
public void reboot() {
ByteBuffer buffer = ByteBuffer.allocate(10);
int length = 0x02;
byte[] params;
try {
switch (motorType) {
case DynamixelMotorType.XL_320:
params = new byte[] {(byte) id, (byte) (length + 1), (byte) 0x00, (byte) 0x08};
buffer.put(xlHeader);
buffer.put(params);
int crc16 = DynamixelUtil.generateDynamixelCRC16(buffer, buffer.position());
buffer.put((byte)(crc16 & 0x00FF)); // CRC low
buffer.put((byte)((crc16 >> 8) & 0x00FF)); // CRC high
break;
default:
params = new byte[] {(byte) id, (byte) length, (byte) 0x08};
byte checksum = DynamixelUtil.generateChecksum(params);
buffer.put(mxHeader);
buffer.put(params);
buffer.put(checksum);
break;
}
sendMessage(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* SETTERS
*/
public void setID(int newID) {
writeAddress(id, 0x03, newID);
this.id = newID;
}
public void setFlipped(boolean shouldFlip) { this.flipped = shouldFlip; }
public void setMotorType(int motor) {
this.motorType = motor;
}
public void setLEDColor(int color) {
writeAddress(id, 0x19, color);
}
public void addSyncMove(int position) {
addSyncMove(position, -1);
}
public void addSyncMove(int position, int speed) {
if (position < 0 || position > mMaxPosition) {
System.out.println("Position [" + position + "] out of bounds!");
return;
}
if (speed > 1023) { speed = 1023; }
// make sure all the data is in the same length
if (syncMoveList.isEmpty()) {
syncDataLength = (speed == -1) ? 2 : 4;
} else if ((syncDataLength == 2 && speed != -1) || (syncDataLength == 4 && speed == -1)) {
System.out.println("Sync move data length mismatch, it will not be added!");
return;
} else if (syncDataLength == 4) {
syncMoveList.add(new int[] {id, 0x1E, position % 256, position / 256, speed % 256, speed / 256});
} else {
syncMoveList.add(new int[] {id, 0x1E, position % 256, position / 256});
}
// update current position
this.currentPosition = position;
}
public void syncMove() {
if (syncMoveList != null && !syncMoveList.isEmpty()) {
syncWriteAddress();
}
}
public void moveToPosition(int position) {
if (position < 0 || position > mMaxPosition) {
System.out.println("Position [" + position + "] out of bounds!");
return;
}
this.currentPosition = position;
if (D) {
System.out.println("Move to position " + position
+ "; low: " + position % 256 + ", hi: " + position / 256);
}
writeAddress(id, 0x1E, position % 256, position / 256);
}
public void moveToPosition(int position, int speed) {
if (position < 0 || position > mMaxPosition) {
System.out.println("Position [" + position + "] out of bounds!");
return;
}
if (speed > 1023) { speed = 1023; }
if (speed <= 0) { speed = 1; }
this.currentPosition = position;
if (D) {
System.out.println("Move to position " + position
+ "; low: " + position % 256 + ", hi: " + position / 256
+ " at speed " + speed + "; low: " + speed % 256 + ", hi: " + speed / 256);
}
writeAddress(id, 0x1E, new byte[] {(byte) (position % 256), (byte) (position / 256),
(byte) (speed % 256), (byte) (speed / 256)});
}
public void moveToPositionInTime(int newPos, double time) {
System.out.println("currentPosition: " + currentPosition);
System.out.println("newPosition: " + newPos);
System.out.println("distance: " + (currentPosition - newPos));
System.out.println("time: " +time);
System.out.println("speedFromEnc: " + getSpeedFromEncoder(currentPosition - newPos, time));
setSpeed(getSpeedFromEncoder(currentPosition - newPos, time));
//moveToPosition(getEncoderFromCoefficient(newPosition));
moveToPosition(newPos);
}
public void moveContinuously(int offset, int position) {
if (offset < -24576 || offset > 24576) {
System.out.println("Offset [" + offset + "] out of bounds!");
return;
}
this.currentPosition = position; // new position after the offset
if (D) {
System.out.println("Move with offset " + offset
+ "; low: " + offset % 256 + ", hi: " + offset / 256);
}
// todo cng mode
writeAddress(id, 0x14, offset % 256, offset / 256);
}
public void setSpeed(int speed) {
if (speed > 1023) {
speed = 1023;
} else if (speed <= 0) {
speed = 1;
}
if (D) { System.out.println("Move at speed " + speed + "; low: " + speed % 256 + ", hi: " + speed / 256); }
writeAddress(id, 0x20, speed % 256, speed / 256);
}
public void setAcceleration(int acceleration) {
if (acceleration > 254) {
acceleration = 254;
} else if (acceleration < 0) {
return;
}
if (D) {
System.out.println("Move at acceleration " + acceleration
+ "; low: " + acceleration % 256 + ", hi: " + acceleration / 256);
}
writeAddress(id, 0x49, acceleration);
}
public void setResponseType(int type) {
// 0 = no return, 1 = return only read, 2 = return all
if (type >= 0 && type <= 2) {
writeAddress(id, 0x10, (byte) type);
String responseType = "";
switch (type) {
case 0:
responseType = "No response";
break;
case 1:
responseType = "Read only";
break;
case 2:
responseType = "All";
break;
}
if (D) { System.out.println("ResponseType: " + responseType); }
}
}
public void setTorqueEnable(boolean enable) {
if (D) { System.out.println("EnableTorque: " + (enable ? "True" : "False")); }
writeAddress(id, 0x18, enable ? 1 : 0);
}
public void setMinAngle(int angle) {
writeAddress(id, 0x06, angle % 256, angle / 256);
}
public void setMaxAngle(int angle) {
writeAddress(id, 0x08, angle % 256, angle / 256);
}
public void setContinousRotation(int enable) {
if (enable == 0) {
setMinAngle(1);
setMaxAngle(mMaxPosition);
} else {
setMinAngle(0);
setMaxAngle(0);
}
}
public void setBaudRate(int newBaudRate) {
writeAddress(id, 0x04, convertBaudRate(newBaudRate));
}
// converts BaudRate from integer to byte
private byte convertBaudRate(int rate) {
if (motorType == DynamixelMotorType.XL_320) {
switch (rate) {
case 9600:
return 0;
case 57600:
return 1;
case 115200:
return 2;
case 1000000:
return 3;
default:
return 3;
}
} else {
switch (rate) {
case 9600:
return (byte) 207;
case 19200:
return 103;
case 38400:
return 51;
case 57600:
return 34;
case 115200:
return 16;
case 200000:
return 9;
case 250000:
return 7;
case 400000:
return 4;
case 500000:
return 3;
case 1000000:
return 1;
default:
return 1;
}
}
}
public void setRotationMode(int rotationMode) {
if (isRotationModeSupported(motorType, rotationMode)) {
switch (rotationMode) {
case DynamixelMotorType.JOINT_MODE:
writeAddress(id, 0x1E, new byte[] {(byte) (2047 % 256), (byte) (2047 / 256),
(byte) (2047 % 256), (byte) (2047 / 256)});
mRotationMode = rotationMode;
break;
case DynamixelMotorType.WHEEL_MODE:
writeAddress(id, 0x1E, new byte[] {(byte) 0, (byte) 0, (byte) 0, (byte) 0});
mRotationMode = rotationMode;
break;
case DynamixelMotorType.MULTI_TURN_MODE:
writeAddress(id, 0x1E, new byte[] {(byte) (4095 % 256), (byte) (4095 / 256),
(byte) (4095 % 256), (byte) (4095 / 256)});
mRotationMode = rotationMode;
break;
}
}
}
public boolean isRotationModeSupported(int motorType, int rotationMode) {
if (rotationMode == DynamixelMotorType.JOINT_MODE || rotationMode == DynamixelMotorType.WHEEL_MODE) {
switch (motorType) {
case DynamixelMotorType.XL_320:
case DynamixelMotorType.AX_12W:
case DynamixelMotorType.AX_12:
case DynamixelMotorType.AX_18:
case DynamixelMotorType.MX_12:
case DynamixelMotorType.MX_28:
case DynamixelMotorType.MX_64:
case DynamixelMotorType.MX_106:
return true;
}
} else if (rotationMode == DynamixelMotorType.MULTI_TURN_MODE) {
switch (motorType) {
case DynamixelMotorType.XL_320:
case DynamixelMotorType.AX_12:
case DynamixelMotorType.AX_18:
return false;
case DynamixelMotorType.AX_12W:
case DynamixelMotorType.MX_12:
case DynamixelMotorType.MX_28:
case DynamixelMotorType.MX_64:
case DynamixelMotorType.MX_106:
return true;
}
}
return false;
}
/*
* GETTERS
*/
public int getId() {
return id;
}
public int getMotorType() {
return motorType;
}
private int[] getMotorPerController() {
// returns array: idx0 = mxCtrl count, idx1 = xlCtrl count
int[] counter = new int[2];
for (int[] arr : syncMoveList) {
if (DynamixelMotorType.getMotorType(arr[0]) == DynamixelMotorType.MX_28) {
counter[0]++;
} else if (DynamixelMotorType.getMotorType(arr[0]) == DynamixelMotorType.XL_320) {
counter[1]++;
}
}
return counter;
}
private int getEncoderFromCoefficient(double coefficient) {
return (int) ((1 + coefficient) * getMotorMaxEncoder() / 2);
}
private int getSpeedFromCoeficient(double coefficient, double time) {
time *= getMotorMaxEncoder();
time /= 1000000;
double encodePerSec = coefficient * getMotorMaxEncoder() / time;
encodePerSec = Math.abs(encodePerSec);
return (int) (encodePerSec / encoderPerSecPerUnit);
}
private int getSpeedFromEncoder(int encoderDistance, double time) {
time *= getMotorMaxEncoder();
time /= 1000000;
double encodePerSec = encoderDistance / time;
encodePerSec = Math.abs(encodePerSec);
return (int) (encodePerSec / encoderPerSecPerUnit);
}
private int getMotorMaxEncoder() {
return getMotorMaxPosition();
}
private int getZeroPosition() {
switch (motorType) {
case DynamixelMotorType.XL_320:
case DynamixelMotorType.AX_12W:
case DynamixelMotorType.AX_12:
case DynamixelMotorType.AX_18:
return 511;
case DynamixelMotorType.MX_12:
case DynamixelMotorType.MX_28:
case DynamixelMotorType.MX_64:
case DynamixelMotorType.MX_106:
return 2047;
default:
return 511;
}
}
private int getMotorMaxAngle() {
switch (motorType) {
case DynamixelMotorType.XL_320:
case DynamixelMotorType.AX_12W:
case DynamixelMotorType.AX_12:
case DynamixelMotorType.AX_18:
return 300;
case DynamixelMotorType.MX_12:
case DynamixelMotorType.MX_28:
case DynamixelMotorType.MX_64:
case DynamixelMotorType.MX_106:
return 360;
default:
return 300;
}
}
private int getMotorMaxPosition() {
switch (motorType) {
case DynamixelMotorType.XL_320:
case DynamixelMotorType.AX_12W:
case DynamixelMotorType.AX_12:
case DynamixelMotorType.AX_18:
return 1024;
case DynamixelMotorType.MX_12:
case DynamixelMotorType.MX_28:
case DynamixelMotorType.MX_64:
case DynamixelMotorType.MX_106:
return 4096;
default:
return 1024;
}
}
public int readPosition() {
byte[] data = readAddress(id, 0x24, 2);
if (data != null) {
if (data.length != 2) {
return -1;
}
return data[0] + 256 * data[1];
}
return -1;
}
@Override
public String toString() {
return "DynamixelMotor{" +
"id=" + id +
", motorType=" + motorType +
", mMaxPosition=" + mMaxPosition +
'}';
}
}
|
Java
|
public class TestStreamingTaskLog extends TestCase {
String input = "the dummy input";
Path inputPath = new Path("inDir");
Path outputPath = new Path("outDir");
String map = null;
MiniMRCluster mr = null;
FileSystem fs = null;
final long USERLOG_LIMIT_KB = 5;//consider 5kb as logSize
String[] genArgs() {
return new String[] {
"-input", inputPath.toString(),
"-output", outputPath.toString(),
"-mapper", map,
"-reducer", StreamJob.REDUCE_NONE,
"-jobconf", "mapred.job.tracker=" + "localhost:" + mr.getJobTrackerPort(),
"-jobconf", "fs.default.name=" + fs.getUri().toString(),
"-jobconf", "mapred.map.tasks=1",
"-jobconf", "keep.failed.task.files=true",
"-jobconf", "mapred.userlog.limit.kb=" + USERLOG_LIMIT_KB,
"-jobconf", "stream.tmpdir="+System.getProperty("test.build.data","/tmp")
};
}
/**
* This test validates the setting of HADOOP_ROOT_LOGGER to 'INFO,TLA' and the
* dependent properties
* (a) hadoop.tasklog.taskid and
* (b) hadoop.tasklog.totalLogFileSize
* for the children of java tasks in streaming jobs.
*/
public void testStreamingTaskLogWithHadoopCmd() {
try {
final int numSlaves = 1;
Configuration conf = new Configuration();
fs = FileSystem.getLocal(conf);
Path testDir = new Path(System.getProperty("test.build.data","/tmp"));
if (fs.exists(testDir)) {
fs.delete(testDir, true);
}
fs.mkdirs(testDir);
File scriptFile = createScript(
testDir.toString() + "/testTaskLog.sh");
mr = new MiniMRCluster(numSlaves, fs.getUri().toString(), 1);
writeInputFile(fs, inputPath);
map = scriptFile.getAbsolutePath();
runStreamJobAndValidateEnv();
fs.delete(outputPath, true);
assertFalse("output not cleaned up", fs.exists(outputPath));
mr.waitUntilIdle();
} catch(IOException e) {
fail(e.toString());
} finally {
if (mr != null) {
mr.shutdown();
}
}
}
private File createScript(String script) throws IOException {
File scriptFile = new File(script);
UtilTest.recursiveDelete(scriptFile);
FileOutputStream in = new FileOutputStream(scriptFile);
in.write(("cat > /dev/null 2>&1\n" +
"echo $HADOOP_ROOT_LOGGER $HADOOP_CLIENT_OPTS").getBytes());
in.close();
Shell.execCommand(new String[]{"chmod", "+x",
scriptFile.getAbsolutePath()});
return scriptFile;
}
private void writeInputFile(FileSystem fs, Path dir) throws IOException {
DataOutputStream out = fs.create(new Path(dir, "part0"));
out.writeBytes(input);
out.close();
}
/**
* Runs the streaming job and validates the output.
* @throws IOException
*/
private void runStreamJobAndValidateEnv() throws IOException {
int returnStatus = -1;
boolean mayExit = false;
StreamJob job = new StreamJob(genArgs(), mayExit);
returnStatus = job.go();
assertEquals("StreamJob failed.", 0, returnStatus);
// validate environment variables set for the child(script) of java process
String env = TestMiniMRWithDFS.readOutput(outputPath, mr.createJobConf());
long logSize = USERLOG_LIMIT_KB * 1024;
assertTrue("environment set for child is wrong", env.contains("INFO,TLA")
&& env.contains("-Dhadoop.tasklog.taskid=attempt_")
&& env.contains("-Dhadoop.tasklog.totalLogFileSize=" + logSize)
&& env.contains("-Dhadoop.tasklog.iscleanup=false"));
}
}
|
Java
|
@FieldOrder({ "frame_id", "timestamp", "nPoints", "pPoints", "pIDs" })
public class LEAP_POINT_MAPPING extends Structure
{
/** The ID of the frame corresponding to the source of the currently tracked points. */
public long frame_id;
/**
* The timestamp of the frame, in microseconds, referenced against
* {@link LeapC#LeapGetNow()}.
*/
public long timestamp;
/** The number of points being tracked. */
public int nPoints;
/**
* A pointer to the array of 3D points being mapped. Use {@link #getPoints()} to obtain
* the array itself.
*/
public Pointer pPoints;
/**
* A pointer an array with the IDs of the points being mapped. Use {@link #getIds()} to
* obtain the array itself.
*/
public Pointer pIDs;
private LEAP_VECTOR[] points;
private int[] ids;
public LEAP_POINT_MAPPING()
{
super(ALIGN_NONE);
}
public LEAP_POINT_MAPPING(int size)
{
super(ALIGN_NONE);
allocateMemory(size);
}
public LEAP_VECTOR[] getPoints()
{
return points;
}
public int[] getIds()
{
return ids;
}
@Override
public void read()
{
super.read();
points = new LEAP_VECTOR[nPoints];
ids = new int[nPoints];
int pointOffset = 0;
int idOffset = 0;
for (int i = 0; i < nPoints; i++)
{
points[i] = new LEAP_VECTOR(pPoints.share(pointOffset));
ids[i] = pIDs.getInt(idOffset);
pointOffset += points[i].size();
idOffset += 4;
}
}
}
|
Java
|
public class InstanceField {
private final Field field;
private final Object instance;
private FieldReader fieldReader;
/**
* Create a new InstanceField.
*
* @param field The field that should be accessed, note that no checks are performed to ensure
* the field belong to this instance class.
* @param instance The instance from which the field shall be accessed.
*/
public InstanceField(Field field, Object instance) {
this.field = Checks.checkNotNull(field, "field");
this.instance = Checks.checkNotNull(instance, "instance");
}
/**
* Safely read the field.
*
* @return the field value.
* @see FieldReader
*/
public Object read() {
return reader().read();
}
/**
* Set the given value to the field of this instance.
*
* @param value The value that should be written to the field.
* @see FieldSetter
*/
public void set(Object value) {
setField(instance, field, value);
}
/**
* Check that the field is not null.
*
* @return <code>true</code> if <code>null</code>, else <code>false</code>.
*/
public boolean isNull() {
return reader().isNull();
}
/**
* Check if the field is annotated by the given annotation.
*
* @param annotationClass The annotation type to check.
* @return <code>true</code> if the field is annotated by this annotation, else <code>false</code>.
*/
public boolean isAnnotatedBy(Class<? extends Annotation> annotationClass) {
return field.isAnnotationPresent(annotationClass);
}
/**
* Check if the field is synthetic.
*
* @return <code>true</code> if the field is synthetic, else <code>false</code>.
*/
public boolean isSynthetic() {
return field.isSynthetic();
}
/**
* Returns the annotation instance for the given annotation type.
*
* @param annotationClass Tha annotation type to retrieve.
* @param <A> Type of the annotation.
* @return The annotation instance.
*/
public <A extends Annotation> A annotation(Class<A> annotationClass) {
return field.getAnnotation(annotationClass);
}
/**
* Returns the JDK {@link Field} instance.
*
* @return The actual {@link Field} instance.
*/
public Field jdkField() {
return field;
}
private FieldReader reader() {
if (fieldReader == null) {
fieldReader = new FieldReader(instance, field);
}
return fieldReader;
}
/**
* Returns the name of the field.
*
* @return Name of the field.
*/
public String name() {
return field.getName();
}
@Override
public String toString() {
return name();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InstanceField that = (InstanceField) o;
return field.equals(that.field) && instance.equals(that.instance);
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + instance.hashCode();
return result;
}
}
|
Java
|
public class BasicMathFunctions {
/**
* Cache for the base used for the log.
*/
private static double logBase = 0;
/**
* Cache for the logarithm value of the base used for the log.
*/
private static double logBaseValue;
/**
* Cache for factorials.
*/
private static final long[] FACTORIALS_CACHE = getFactorialsCache();
/**
* Empty default constructor.
*/
public BasicMathFunctions() {
}
/**
* Returns factorial 0 to 20 in an array.
*
* @return Factorial 0 to 20 in an array.
*/
public static long[] getFactorialsCache() {
long[] result = new long[21];
result[0] = 1;
for (int i = 1; i <= 20; i++) {
result[i] = result[i - 1] * i;
}
return result;
}
/**
* Returns n! as a double. Accuracy decreases if the capacity of a long is
* not sufficient (i.e. n higher than 20).
*
* @param n a given integer
*
* @return the corresponding factorial
*/
public static double factorialDouble(
int n
) {
if (n <= 20) {
return factorial(n);
} else {
double result = factorial(20);
for (int i = 21; i <= n; i++) {
result *= i;
}
return result;
}
}
/**
* Returns n! as a long. Throws an error if the capacity of a long is not
* sufficient (i.e. n higher than 20).
*
* @param n a given integer
*
* @return the corresponding factorial
*/
public static long factorial(
int n
) {
if (n == 0) {
return 0L;
} else if (n == 1) {
return 1L;
} else if (n <= 20) {
return FACTORIALS_CACHE[n];
} else if (n > 20) {
throw new IllegalArgumentException("Reached the maximal capacity of a long.");
} else if (n < 0) {
throw new ArithmeticException("Attempting to calculate the factorial of a negative number.");
}
throw new UnsupportedOperationException("Factorial not implemented for n = " + n + ".");
}
/**
* Returns n!/k! as double. Accuracy decreases if the capacity of a long is
* not sufficient
*
* @param n n
* @param k k
*
* @return n!/k!.
*/
public static double factorialDouble(
int n,
int k
) {
if (n < k) {
throw new ArithmeticException("n < k in n!/k!.");
}
if (n == k) {
return 1L;
} else {
if (n <= 20) {
return factorial(n, k);
}
double result = factorialDouble(20) / factorialDouble(k);
for (int i = 21; i <= n; i++) {
result *= i;
}
return result;
}
}
/**
* Returns n!/k!, an error is thrown if it cannot fit in a long.
*
* @param n n
* @param k k
*
* @return n!/k!.
*/
public static long factorial(
int n,
int k
) {
if (n < k) {
throw new ArithmeticException("n < k in n!/k!.");
}
if (n == k) {
return 1L;
} else {
if (n <= 20) {
return factorial(n) / factorial(k);
}
long nMinusOne = factorial(n - 1, k);
if (nMinusOne == -1L || nMinusOne > Long.MAX_VALUE / n) {
throw new IllegalArgumentException("Reached the maximal capacity of a long.");
} else {
return nMinusOne * n;
}
}
}
/**
* Returns the number of k-combinations in a set of n elements. Accuracy
* decreases if the capacity of a long is not sufficient
*
* @param k the number of k-combinations
* @param n the number of elements
*
* @return The number of k-combinations in a set of n elements.
*/
public static double getCombinationDouble(
int k,
int n
) {
if (k < n) {
double kInN = factorialDouble(n, k);
double nMinK = factorialDouble(n - k);
return kInN / nMinK;
} else if (k == n || k == 0) {
return 1;
} else {
throw new IllegalArgumentException("n>k in combination.");
}
}
/**
* Returns the invert of the number of k-combinations in a set of n
* elements. Accuracy decreases if the capacity of a long is not sufficient
*
* @param k the number of k-combinations
* @param n the number of elements
*
* @return The number of k-combinations in a set of n elements.
*/
public static double getOneOverCombinationDouble(
int k,
int n
) {
if (k < n) {
double kInN = factorialDouble(n, k);
double nMinK = factorialDouble(n - k);
return nMinK / kInN;
} else if (k == 0 || k == n) {
return 1;
} else {
throw new IllegalArgumentException("n>k in combination.");
}
}
/**
* Returns the number of k-combinations in a set of n elements. If n!/k!
* cannot fit in a long, an error is thrown.
*
* @param k the number of k-combinations
* @param n the number of elements
*
* @return The number of k-combinations in a set of n elements.
*/
public static long getCombination(
int k,
int n
) {
if (k < n) {
long kInN = factorial(n, k);
long nMinK = factorial(n - k);
return kInN / nMinK;
} else if (k == n || k == 0) {
return 1L;
} else {
throw new IllegalArgumentException("n>k in combination.");
}
}
/**
* Method to estimate the median for an unsorted list.
*
* @param input array of double
*
* @return median of the input
*/
public static double median(double[] input) {
ArrayList<Double> tempValues = new ArrayList<>(input.length);
for (double tempValue : input) {
tempValues.add(tempValue);
}
Collections.sort(tempValues);
return medianSorted(tempValues);
}
/**
* Method to estimate the median for a sorted list.
*
* @param input array of double
*
* @return median of the input
*/
public static double medianSorted(double[] input) {
int length = input.length;
if (input.length == 1) {
return input[0];
}
if (length % 2 == 1) {
return input[(length - 1) / 2];
} else {
return (input[length / 2] + input[(length) / 2 - 1]) / 2;
}
}
/**
* Method to estimate the median of an unsorted list.
*
* @param input ArrayList of double
* @return median of the input
*/
public static double median(ArrayList<Double> input) {
return percentile(input, 0.5);
}
/**
* Method to estimate the median of a sorted list.
*
* @param input ArrayList of double
* @return median of the input
*/
public static double medianSorted(ArrayList<Double> input) {
return percentileSorted(input, 0.5);
}
/**
* Returns the desired percentile in a given array of unsorted double
* values. If the percentile is between two values a linear interpolation is
* done. Note: When calculating multiple percentiles on the same list, it is
* advised to sort it and use percentileSorted.
*
* @param input the input array
* @param percentile the desired percentile. 0.01 returns the first
* percentile. 0.5 returns the median.
*
* @return the desired percentile
*/
public static double percentile(double[] input, double percentile) {
ArrayList<Double> tempValues = new ArrayList<>(input.length);
for (double tempValue : input) {
tempValues.add(tempValue);
}
Collections.sort(tempValues);
return percentileSorted(tempValues, percentile);
}
/**
* Returns the desired percentile in an array of sorted double values. If
* the percentile is between two values a linear interpolation is done. The
* list must be sorted prior to submission.
*
* @param input the input array
* @param percentile the desired percentile. 0.01 returns the first
* percentile. 0.5 returns the median.
*
* @return the desired percentile
*/
public static double percentileSorted(double[] input, double percentile) {
if (percentile < 0 || percentile > 1) {
throw new IllegalArgumentException(
"Incorrect input for percentile: "
+ percentile + ". Input must be between 0 and 1.");
}
int length = input.length;
if (length == 0) {
throw new IllegalArgumentException(
"Attempting to estimate the percentile of an empty list.");
}
if (length == 1) {
return input[0];
}
double indexDouble = percentile * (length - 1);
int index = (int) (indexDouble);
double valueAtIndex = input[index];
double rest = indexDouble - index;
if (index == input.length - 1 || rest == 0) {
return valueAtIndex;
}
return valueAtIndex + rest * (input[index + 1] - valueAtIndex);
}
/**
* Returns the desired percentile in a list of unsorted double values. If
* the percentile is between two values a linear interpolation is done.
* Note: When calculating multiple percentiles on the same list, it is
* advised to sort it and use percentileSorted.
*
* @param input the input list
* @param percentile the desired percentile. 0.01 returns the first
* percentile. 0.5 returns the median.
*
* @return the desired percentile
*/
public static double percentile(ArrayList<Double> input, double percentile) {
if (input == null) {
throw new IllegalArgumentException(
"Attempting to estimate the percentile of a null object.");
}
int length = input.size();
if (length == 0) {
throw new IllegalArgumentException(
"Attempting to estimate the percentile of an empty list.");
}
ArrayList<Double> sortedInput = new ArrayList<>(input);
Collections.sort(sortedInput);
return percentileSorted(sortedInput, percentile);
}
/**
* Returns the desired percentile in a list of sorted double values. If the
* percentile is between two values a linear interpolation is done. The list
* must be sorted prior to submission.
*
* @param input the input list
* @param percentile the desired percentile. 0.01 returns the first
* percentile. 0.5 returns the median.
*
* @return the desired percentile
*/
public static double percentileSorted(ArrayList<Double> input, double percentile) {
if (percentile < 0 || percentile > 1) {
throw new IllegalArgumentException(
"Incorrect input for percentile: "
+ percentile + ". Input must be between 0 and 1.");
}
if (input == null) {
throw new IllegalArgumentException(
"Attempting to estimate the percentile of a null object.");
}
int length = input.size();
if (length == 0) {
throw new IllegalArgumentException(
"Attempting to estimate the percentile of an empty list.");
}
if (length == 1) {
return input.get(0);
}
double indexDouble = percentile * (length - 1);
int index = (int) (indexDouble);
double valueAtIndex = input.get(index);
double rest = indexDouble - index;
if (index == input.size() - 1 || rest == 0) {
return valueAtIndex;
}
return valueAtIndex + rest * (input.get(index + 1) - valueAtIndex);
}
/**
* Method estimating the median absolute deviation.
*
* @param ratios array of doubles
* @return the mad of the input
*/
public static double mad(double[] ratios) {
double[] deviations = new double[ratios.length];
double med = median(ratios);
for (int i = 0; i < ratios.length; i++) {
deviations[i] = Math.abs(ratios[i] - med);
}
return median(deviations);
}
/**
* Method estimating the median absolute deviation.
*
* @param ratios array of doubles
* @return the mad of the input
*/
public static double mad(ArrayList<Double> ratios) {
double[] deviations = new double[ratios.size()];
double med = median(ratios);
for (int i = 0; i < ratios.size(); i++) {
deviations[i] = Math.abs(ratios.get(i) - med);
}
return median(deviations);
}
/**
* Returns the log of the input in the desired base.
*
* @param input the input
* @param base the log base
*
* @return the log value of the input in the desired base.
*/
public static double log(double input, double base) {
if (base <= 0) {
throw new IllegalArgumentException("Attempting to comupute logarithm of base " + base + ".");
} else if (base != logBase) {
logBase = base;
logBaseValue = FastMath.log(base);
}
return FastMath.log(input) / logBaseValue;
}
/**
* Convenience method returning the standard deviation of a list of doubles.
* Returns 0 if the list is null or of size < 2.
*
* @param input input list
* @return the corresponding standard deviation
*/
public static double std(ArrayList<Double> input) {
if (input == null || input.size() < 2) {
return 0;
}
double result = 0;
double mean = mean(input);
for (Double x : input) {
result += Math.pow(x - mean, 2);
}
result = result / (input.size() - 1);
result = Math.sqrt(result);
return result;
}
/**
* Convenience method returning the mean of a list of doubles.
*
* @param input input list
* @return the corresponding mean
*/
public static double mean(ArrayList<Double> input) {
return sum(input) / input.size();
}
/**
* Convenience method returning the sum of a list of doubles.
*
* @param input input list
* @return the corresponding mean
*/
public static double sum(ArrayList<Double> input) {
double result = 0;
for (Double x : input) {
result += x;
}
return result;
}
/**
* Returns the population Pearson correlation r between series1 and series2.
*
* @param series1 first series to compare
* @param series2 second series to compare
*
* @return the Pearson correlation factor
*/
public static double getCorrelation(ArrayList<Double> series1, ArrayList<Double> series2) {
if (series1.size() != series2.size()) {
throw new IllegalArgumentException("Series must be of same size for correlation analysis (series 1: " + series1.size() + " elements, series 1: " + series2.size() + " elements).");
}
int n = series1.size();
if (n <= 1) {
throw new IllegalArgumentException("At least two values are required for the estimation of correlation factors (" + n + " elements).");
}
double std1 = std(series1);
double std2 = std(series2);
if (std1 == 0 && std2 == 0) {
return 1;
}
if (std1 == 0) {
std1 = std2;
}
if (std2 == 0) {
std2 = std1;
}
double mean1 = mean(series1);
double mean2 = mean(series2);
double corr = 0;
for (int i = 0; i < n; i++) {
corr += (series1.get(i) - mean1) * (series2.get(i) - mean2);
}
corr = corr / (std1 * std2);
corr = corr / (n - 1);
return corr;
}
/**
* Returns the population Pearson correlation r between series1 and series2.
* Here the correlation factor is estimated using median and percentile
* distance instead of mean and standard deviation.
*
* @param series1 the first series to inspect
* @param series2 the second series to inspect
*
* @return a robust version of the Pearson correlation factor
*/
public static double getRobustCorrelation(ArrayList<Double> series1, ArrayList<Double> series2) {
if (series1.size() != series2.size()) {
throw new IllegalArgumentException(
"Series must be of same size for correlation analysis (series 1: "
+ series1.size() + " elements, series 1: " + series2.size() + " elements).");
}
int n = series1.size();
if (n <= 1) {
throw new IllegalArgumentException(
"At least two values are required for the estimation of correlation factors (" + n + " elements).");
}
double std1 = (percentile(series1, 0.841) - percentile(series1, 0.159)) / 2;
double std2 = (percentile(series2, 0.841) - percentile(series2, 0.159)) / 2;
if (std1 == 0 && std2 == 0) {
return 1;
}
if (std1 == 0) {
std1 = std2;
}
if (std2 == 0) {
std2 = std1;
}
double mean1 = median(series1);
double mean2 = median(series2);
double corr = 0;
for (int i = 0; i < n; i++) {
corr += (series1.get(i) - mean1) * (series2.get(i) - mean2);
}
corr = corr / (std1 * std2);
corr = corr / (n - 1);
return corr;
}
/**
* Checks that a probability is between 0 and 1 and throws an
* IllegalArgumentException otherwise. 0.5 represents a probability of 50%.
*
* @param p the probability
*/
public static void checkProbabilityRange(double p) {
if (p < 0.0) {
throw new IllegalArgumentException("Probability <0%.");
} else if (p > 1.0) {
throw new IllegalArgumentException("Probability >100%.");
}
}
/**
* Checks that a probability is between 0 % and 100 % and throws an
* IllegalArgumentException otherwise. 50 represents a probability of 50%.
*
* @param p the probability
*/
public static void checkProbabilityRangeInPercent(double p) {
if (p < 0.0) {
throw new IllegalArgumentException("Probability <0%.");
} else if (p > 100.0) {
throw new IllegalArgumentException("Probability >100%.");
}
}
/**
* Returns an integer randomly chosen between min and max included.
*
* @param min the lower limit
* @param max the higher limit
*
* @return a random integer
*/
public static int getRandomInteger(int min, int max) {
double randomDouble = min + (Math.random() * (max - min));
if (randomDouble > max) {
return max;
}
if (randomDouble < min) {
return min;
}
return (int) Math.round(randomDouble);
}
/**
* Returns a list of n random indexes between min and max included. The list
* is not sorted.
*
* @param n the number of indexes to return
* @param min the lower limit
* @param max the higher limit
*
* @return a list of n random indexes between min and max included
*/
public static ArrayList<Integer> getRandomIndexes(int n, int min, int max) {
ArrayList<Integer> result = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
result.add(getRandomInteger(min, max));
}
return result;
}
}
|
Java
|
public class TieDyeTShirtsSR extends ModelElement {
private final EventGenerator myOrderGenerator;
private RandomVariable myTBOrders;
private RandomVariable myOrderSize;
private RandomVariable myOrderType;
private RandomVariable myShirtMakingTime;
private RandomVariable myPaperWorkTime;
private RandomVariable myPackagingTime;
private SingleQueueStation myShirtMakingStation;
private SingleQueueStation myPWStation;
private SingleQueueStation myPackagingStation;
private SResource myShirtMakers;
private SResource myPackager;
private ResponseVariable mySystemTime;
private TimeWeighted myNumInSystem;
public TieDyeTShirtsSR(ModelElement parent) {
this(parent, null);
}
public TieDyeTShirtsSR(ModelElement parent, String name) {
super(parent, name);
RVariableIfc tbOrdersRV = new ExponentialRV(60);
myTBOrders = new RandomVariable(this, tbOrdersRV);
myOrderGenerator = new EventGenerator(this, new OrderArrivals(), tbOrdersRV, tbOrdersRV);
RVariableIfc type = new DEmpiricalRV(new double[] {1, 2}, new double[] {0.7, 1.0});
RVariableIfc size = new DEmpiricalRV(new double[] {3, 5}, new double[] {0.75, 1.0});
myOrderSize = new RandomVariable(this, size);
myOrderType = new RandomVariable(this, type);
myShirtMakingTime = new RandomVariable(this, new UniformRV(15, 25));
myPaperWorkTime = new RandomVariable(this, new UniformRV(8, 10));
myPackagingTime = new RandomVariable(this, new TriangularRV(5, 10, 15));
myShirtMakers = new SResource(this, 2, "ShirtMakers_R");
myPackager = new SResource(this, 1, "Packager_R");
myShirtMakingStation = new SingleQueueStation(this, myShirtMakers,
myShirtMakingTime, "Shirt_Station");
myPWStation = new SingleQueueStation(this, myPackager,
myPaperWorkTime, "PW_Station");
myPackagingStation = new SingleQueueStation(this, myPackager,
myPackagingTime, "Packing_Station");
// need to set senders/receivers
myShirtMakingStation.setNextReceiver(new AfterShirtMaking());
myPWStation.setNextReceiver(new AfterPaperWork());
myPackagingStation.setNextReceiver(new Dispose());
mySystemTime = new ResponseVariable(this, "System Time");
myNumInSystem = new TimeWeighted(this, "Num in System");
}
private class OrderArrivals implements EventGeneratorActionIfc {
@Override
public void generate(EventGenerator generator, JSLEvent event) {
myNumInSystem.increment();
Order order = new Order();
List<Order.Shirt> shirts = order.getShirts();
for(Order.Shirt shirt: shirts){
myShirtMakingStation.receive(shirt);
}
myPWStation.receive(order.getPaperWork());
}
}
protected class AfterShirtMaking implements ReceiveQObjectIfc {
@Override
public void receive(QObject qObj) {
Order.Shirt shirt = (Order.Shirt) qObj;
shirt.setDoneFlag();
}
}
protected class AfterPaperWork implements ReceiveQObjectIfc {
@Override
public void receive(QObject qObj) {
Order.PaperWork pw = (Order.PaperWork) qObj;
pw.setDoneFlag();
}
}
protected class Dispose implements ReceiveQObjectIfc {
@Override
public void receive(QObject qObj) {
// collect final statistics
myNumInSystem.decrement();
mySystemTime.setValue(getTime() - qObj.getCreateTime());
Order o = (Order) qObj;
o.dispose();
}
}
/**
* Handles the completion of an order
*
*/
private void orderCompleted(Order order) {
myPackagingStation.receive(order);
}
private class Order extends QObject {
private int myType;
private int mySize;
private PaperWork myPaperWork;
private List<Shirt> myShirts;
private int myNumCompleted;
private boolean myPaperWorkDone;
public Order() {
this(getTime());
this.myNumCompleted = 0;
this.myPaperWorkDone = false;
}
public Order(double creationTime) {
this(creationTime, null);
this.myNumCompleted = 0;
this.myPaperWorkDone = false;
}
public Order(double creationTime, String name) {
super(creationTime, name);
myNumCompleted = 0;
myPaperWorkDone = false;
myType = (int) myOrderType.getValue();
mySize = (int) myOrderSize.getValue();
myShirts = new ArrayList<>();
for (int i = 1; i <= mySize; i++) {
myShirts.add(new Shirt());
}
myPaperWork = new PaperWork();
}
public int getType() {
return myType;
}
public void dispose() {
myPaperWork = null;
myShirts.clear();
myShirts = null;
}
public List<Shirt> getShirts() {
List<Shirt> list = new ArrayList<>(myShirts);
return list;
}
public PaperWork getPaperWork() {
return myPaperWork;
}
/**
* The order is complete if it has all its shirts and its paperwork
*
* @return
*/
public boolean isComplete() {
return ((areShirtsDone()) && (isPaperWorkDone()));
}
public boolean areShirtsDone() {
return (myNumCompleted == mySize);
}
public boolean isPaperWorkDone() {
return (myPaperWorkDone);
}
public int getNumShirtsCompleted() {
return myNumCompleted;
}
private void shirtCompleted() {
if (areShirtsDone()) {
throw new IllegalStateException("The order already has all its shirts.");
}
// okay not complete, need to add shirt
myNumCompleted = myNumCompleted + 1;
if (isComplete()) {
TieDyeTShirtsSR.this.orderCompleted(this);
}
}
private void paperWorkCompleted() {
if (isPaperWorkDone()) {
throw new IllegalStateException("The order already has paperwork.");
}
myPaperWorkDone = true;
if (isComplete()) {
TieDyeTShirtsSR.this.orderCompleted(this);
}
}
protected class Shirt extends QObject {
protected boolean myDoneFlag = false;
public Shirt() {
this(getTime());
}
public Shirt(double creationTime) {
this(creationTime, null);
}
public Shirt(double creationTime, String name) {
super(creationTime, name);
}
public Order getOrder() {
return Order.this;
}
public void setDoneFlag() {
if (myDoneFlag == true) {
throw new IllegalStateException("The shirt is already done.");
}
myDoneFlag = true;
Order.this.shirtCompleted();
}
public boolean isCompleted() {
return myDoneFlag;
}
}
protected class PaperWork extends Shirt {
@Override
public void setDoneFlag() {
if (myDoneFlag == true) {
throw new IllegalStateException("The paperwork is already done.");
}
myDoneFlag = true;
Order.this.paperWorkCompleted();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Simulation sim = new Simulation("Tie-Dye T-Shirts");
// get the model
Model m = sim.getModel();
// add system to the main model
TieDyeTShirtsSR system = new TieDyeTShirtsSR(m);
// set the parameters of the experiment
sim.setNumberOfReplications(50);
//sim.setNumberOfReplications(2);
sim.setLengthOfReplication(200000.0);
sim.setLengthOfWarmUp(50000.0);
SimulationReporter r = sim.makeSimulationReporter();
System.out.println("Simulation started.");
sim.run();
System.out.println("Simulation completed.");
r.printAcrossReplicationSummaryStatistics();
}
}
|
Java
|
public class NativeAdSDK {
/**
* Only one of the registerTracking methods below should be called for any single
* ad response, If you wish to reuse the view object you must call unRegisterTracking before
* registering the view(s) with a new NativeAdResponse.
*/
/**
* Register the developer view that will track impressions and respond to clicks
* for the native ad.
*
* @param response A NativeAdResponse
* @param view can be a single view, or container, or a view group
* @param listener A NativeAdEventListener
* @param friendlyObstructionsList a list of Friendly Obstruction
*/
public static void registerTracking(final NativeAdResponse response, final View view, final NativeAdEventListener listener, final List<View> friendlyObstructionsList) {
if (isValid(response)) {
if (view == null) {
Clog.e(Clog.nativeLogTag, "View is not valid for registering");
return;
}
// use a handler to always post register runnable to the main looper in the UI thread
// should not use View.post() because the method posts runnables to different queues based on the view's attachment status
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (view.getTag(R.string.native_tag) != null) {
Clog.e(Clog.nativeLogTag, "View has already been registered, please unregister before reuse");
return;
}
if (((BaseNativeAdResponse) response).registerView(view, listener)) {
((BaseNativeAdResponse) response).registerViewforOMID(view, friendlyObstructionsList);
WeakReference<NativeAdResponse> reference = new WeakReference<NativeAdResponse>(response);
view.setTag(R.string.native_tag, reference);
} else {
Clog.e(Clog.nativeLogTag, "failed at registering the View");
}
}
});
}
}
/**
* Register a list developer views that will track impressions and respond to clicks
* for the native ad.
*
* @param container view/view group that will show native ad
* @param response that contains the meta data of native ad
* @param views a list of clickables
* @param listener called when Ad event happens, can be null
* @param friendlyObstructionsList a list of Friendly Obstruction
*/
public static void registerTracking(final NativeAdResponse response, final View container, final List<View> views, final NativeAdEventListener listener, final List<View> friendlyObstructionsList) {
if (isValid(response)) {
if (container == null || views == null || views.isEmpty()) {
Clog.e(Clog.nativeLogTag, "Views are not valid for registering");
return;
}
// see comment above
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (container.getTag(R.string.native_tag) != null) {
Clog.e(Clog.nativeLogTag, "View has already been registered, please unregister before reuse");
return;
}
if (((BaseNativeAdResponse)response).registerViewList(container, views, listener)) {
((BaseNativeAdResponse)response).registerViewforOMID(container, friendlyObstructionsList);
WeakReference<NativeAdResponse> reference = new WeakReference<NativeAdResponse>(response);
container.setTag(R.string.native_tag, reference);
Clog.d(Clog.nativeLogTag, "View has been registered.");
} else {
Clog.e(Clog.nativeLogTag, "failed at registering the View");
}
}
});
}
}
/**
* Only one of the registerTracking methods below should be called for any single
* ad response, If you wish to reuse the view object you must call unRegisterTracking before
* registering the view(s) with a new NativeAdResponse.
*/
/**
* Register the developer view that will track impressions and respond to clicks
* for the native ad.
*
* @param response A NativeAdResponse
* @param view can be a single view, or container, or a view group
* @param listener A NativeAdEventListener
*/
public static void registerTracking(final NativeAdResponse response, final View view, final NativeAdEventListener listener) {
registerTracking(response, view, listener, null);
}
/**
* Register a list developer views that will track impressions and respond to clicks
* for the native ad.
*
* @param container view/view group that will show native ad
* @param response that contains the meta data of native ad
* @param views a list of clickables
* @param listener called when Ad event happens, can be null
*/
public static void registerTracking(final NativeAdResponse response, final View container, final List<View> views, final NativeAdEventListener listener) {
registerTracking(response, container, views, listener, null);
}
/**
* Called when you are finished with the views for the response or wish to reuse the
* view object(s) for a new NativeAdResponse.
* The old NativeAdResponse will be destroyed once it is unregistered.
*
* @param view can be a single view, or container, or a view group
*/
public static void unRegisterTracking(final View view) {
if (view == null) {
return;
}
// see comment above
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (view.getTag(R.string.native_tag) != null) {
WeakReference reference = (WeakReference) view.getTag(R.string.native_tag);
NativeAdResponse response = (NativeAdResponse)reference.get();
if (response != null) {
Clog.d(Clog.nativeLogTag, "Unregister native ad response, assets will be destroyed.");
((BaseNativeAdResponse)response).unregisterViews();
}
view.setTag(R.string.native_tag, null);
}
}
});
}
/**
* Register the NativeAdResponse to listen to Native Ad events
*
* @param response that contains the meta data of native ad
* @param listener called when Ad event happens, can be null
*/
public static void registerNativeAdEventListener(final NativeAdResponse response, final NativeAdEventListener listener) {
if (isValid(response)) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (!((BaseNativeAdResponse)response).registerNativeAdEventListener(listener)) {
Clog.e(Clog.nativeLogTag, "failed at registering the Listener. Already registered.");
}
}
});
}
}
static boolean isValid(NativeAdResponse response) {
if (response != null && !response.hasExpired()) {
return true;
}
Clog.d(Clog.nativeLogTag, "NativeAdResponse is not valid");
return false;
}
}
|
Java
|
public final class GrpcInteropTestClient {
private int serverPort;
private static String HOST = "localhost";
private static final Logger logger = Logger.getLogger(GrpcInteropTestClient.class.getName());
private static final Tagger tagger = Tags.getTagger();
private static final Tracer tracer = Tracing.getTracer();
private static final String SPAN_NAME = "gRPC-client-span";
private static final TagKey OPERATION_KEY = TagKey.create("operation");
private static final TagKey PROJECT_KEY = TagKey.create("project");
private static final TagValue OPERATION_VALUE = TagValue.create("interop-test");
private static final TagValue PROJECT_VALUE = TagValue.create("open-census");
private GrpcInteropTestClient(int serverPort) {
this.serverPort = serverPort;
}
private void run() {
ExecutorService executor = Executors.newFixedThreadPool(1);
ManagedChannel channel =
ManagedChannelBuilder.forAddress(HOST, serverPort)
.executor(executor)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext(true)
.build();
SpanBuilder spanBuilder =
tracer.spanBuilderWithExplicitParent(SPAN_NAME, null).setSampler(Samplers.alwaysSample());
TagContextBuilder tagContextBuilder =
tagger.emptyBuilder().put(OPERATION_KEY, OPERATION_VALUE).put(PROJECT_KEY, PROJECT_VALUE);
boolean succeeded = false;
try (Scope scopedSpan = spanBuilder.startScopedSpan();
Scope scopedTags = tagContextBuilder.buildScoped()) {
EchoServiceBlockingStub stub = EchoServiceGrpc.newBlockingStub(channel);
EchoResponse response = stub.echo(EchoRequest.getDefaultInstance());
SpanContext expectedSpanContext = tracer.getCurrentSpan().getContext();
TagContext expectedTagContext = tagger.currentBuilder().build();
succeeded = TestUtils.verifyResponse(expectedSpanContext, expectedTagContext, response);
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception thrown when sending request.", e);
} finally {
if (succeeded) {
logger.info("PASSED.");
} else {
logger.info("FAILED.");
}
channel.shutdownNow();
}
}
/** Main launcher of the test client. */
public static void main(String[] args) {
for (Entry<String, Integer> setup : GrpcInteropTestUtils.SETUP_MAP.entrySet()) {
int port = TestUtils.getPortOrDefault(setup.getKey(), setup.getValue());
new GrpcInteropTestClient(port).run();
}
}
}
|
Java
|
public abstract class NettyStreamTestBase<T extends Stream> {
protected static final String MESSAGE = "hello world";
protected static final int STREAM_ID = 1;
@Mock
protected Channel channel;
@Mock
private ChannelHandlerContext ctx;
@Mock
private ChannelPipeline pipeline;
// ChannelFuture has too many methods to implement; we stubbed all necessary methods of Future.
@SuppressWarnings("DoNotMock")
@Mock
protected ChannelFuture future;
@Mock
protected EventLoop eventLoop;
// ChannelPromise has too many methods to implement; we stubbed all necessary methods of Future.
@SuppressWarnings("DoNotMock")
@Mock
protected ChannelPromise promise;
@Mock
protected Http2Stream http2Stream;
@Mock
protected WriteQueue writeQueue;
protected T stream;
/** Set up for test. */
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockFuture(true);
when(channel.write(any())).thenReturn(future);
when(channel.writeAndFlush(any())).thenReturn(future);
when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(channel.pipeline()).thenReturn(pipeline);
when(channel.eventLoop()).thenReturn(eventLoop);
when(channel.newPromise()).thenReturn(new DefaultChannelPromise(channel));
when(channel.voidPromise()).thenReturn(new DefaultChannelPromise(channel));
when(pipeline.firstContext()).thenReturn(ctx);
when(eventLoop.inEventLoop()).thenReturn(true);
when(http2Stream.id()).thenReturn(STREAM_ID);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = (Runnable) invocation.getArguments()[0];
runnable.run();
return null;
}
}).when(eventLoop).execute(any(Runnable.class));
stream = createStream();
}
@Test
public void inboundMessageShouldCallListener() throws Exception {
stream.request(1);
if (stream instanceof NettyServerStream) {
((NettyServerStream) stream).transportState()
.inboundDataReceived(messageFrame(MESSAGE), false);
} else {
((NettyClientStream) stream).transportState()
.transportDataReceived(messageFrame(MESSAGE), false);
}
InputStream message = listenerMessageQueue().poll();
// Verify that inbound flow control window update has been disabled for the stream.
assertEquals(MESSAGE, NettyTestUtil.toString(message));
assertNull("no additional message expected", listenerMessageQueue().poll());
}
@Test
public void shouldBeImmediatelyReadyForData() {
assertTrue(stream.isReady());
}
@Test
public void closedShouldNotBeReady() throws IOException {
assertTrue(stream.isReady());
closeStream();
assertFalse(stream.isReady());
}
@Test
public void notifiedOnReadyAfterWriteCompletes() throws IOException {
sendHeadersIfServer();
assertTrue(stream.isReady());
byte[] msg = largeMessage();
// The future is set up to automatically complete, indicating that the write is done.
stream.writeMessage(new ByteArrayInputStream(msg));
stream.flush();
assertTrue(stream.isReady());
verify(listener()).onReady();
}
@Test
public void shouldBeReadyForDataAfterWritingSmallMessage() throws IOException {
sendHeadersIfServer();
// Make sure the writes don't complete so we "back up"
reset(future);
assertTrue(stream.isReady());
byte[] msg = smallMessage();
stream.writeMessage(new ByteArrayInputStream(msg));
stream.flush();
assertTrue(stream.isReady());
verify(listener(), never()).onReady();
}
@Test
public void shouldNotBeReadyForDataAfterWritingLargeMessage() throws IOException {
sendHeadersIfServer();
// Make sure the writes don't complete so we "back up"
reset(future);
assertTrue(stream.isReady());
byte[] msg = largeMessage();
stream.writeMessage(new ByteArrayInputStream(msg));
stream.flush();
assertFalse(stream.isReady());
verify(listener(), never()).onReady();
}
protected byte[] smallMessage() {
return MESSAGE.getBytes(US_ASCII);
}
protected byte[] largeMessage() {
byte[] smallMessage = smallMessage();
int size = smallMessage.length * 10 * 1024;
byte[] largeMessage = new byte[size];
for (int ix = 0; ix < size; ix += smallMessage.length) {
System.arraycopy(smallMessage, 0, largeMessage, ix, smallMessage.length);
}
return largeMessage;
}
protected abstract T createStream();
protected abstract void sendHeadersIfServer();
protected abstract StreamListener listener();
protected abstract Queue<InputStream> listenerMessageQueue();
protected abstract void closeStream();
private void mockFuture(boolean succeeded) {
when(future.isDone()).thenReturn(true);
when(future.isCancelled()).thenReturn(false);
when(future.isSuccess()).thenReturn(succeeded);
when(future.awaitUninterruptibly(anyLong(), any(TimeUnit.class))).thenReturn(true);
if (!succeeded) {
when(future.cause()).thenReturn(new Exception("fake"));
}
}
}
|
Java
|
public class RecipeCategoryCraftingItems implements IShowsRecipeFocuses {
private final IRecipeRegistry recipeRegistry;
private final IDrawable topDrawable;
private final IDrawable middleDrawable;
private final IDrawable bottomDrawable;
private GuiItemStackGroup craftingItems;
private int left = 0;
private int top = 0;
public RecipeCategoryCraftingItems(IRecipeRegistry recipeRegistry) {
this.recipeRegistry = recipeRegistry;
IFocus<ItemStack> focus = recipeRegistry.createFocus(IFocus.Mode.NONE, null);
craftingItems = new GuiItemStackGroup(focus, 0);
ResourceLocation recipeBackgroundResource = new ResourceLocation(Constants.RESOURCE_DOMAIN, Constants.TEXTURE_RECIPE_BACKGROUND_PATH);
IGuiHelper guiHelper = Internal.getHelpers().getGuiHelper();
topDrawable = guiHelper.createDrawable(recipeBackgroundResource, 196, 65, 26, 6);
middleDrawable = guiHelper.createDrawable(recipeBackgroundResource, 196, 71, 26, 16);
bottomDrawable = guiHelper.createDrawable(recipeBackgroundResource, 196, 87, 26, 6);
}
public void updateLayout(List<ItemStack> itemStacks, GuiProperties guiProperties) {
IFocus<ItemStack> focus = recipeRegistry.createFocus(IFocus.Mode.NONE, null);
craftingItems = new GuiItemStackGroup(focus, 0);
if (!itemStacks.isEmpty()) {
int totalHeight = topDrawable.getHeight() + middleDrawable.getHeight() + bottomDrawable.getHeight();
int ingredientCount = 1;
final int extraBoxHeight = middleDrawable.getHeight();
for (int i = 1; i < itemStacks.size(); i++) {
if (totalHeight + extraBoxHeight <= (guiProperties.getGuiYSize() - 8)) {
totalHeight += extraBoxHeight;
ingredientCount++;
} else {
break;
}
}
top = guiProperties.getGuiTop();
left = guiProperties.getGuiLeft() - topDrawable.getWidth() + 4; // overlaps the recipe gui slightly
ListMultimap<Integer, ItemStack> itemStacksForSlots = ArrayListMultimap.create();
for (int i = 0; i < itemStacks.size(); i++) {
ItemStack itemStack = itemStacks.get(i);
if (i < ingredientCount) {
itemStacksForSlots.put(i, itemStack);
} else {
// start from the end and work our way back, do not override the first one
int index = ingredientCount - (i % ingredientCount);
itemStacksForSlots.put(index, itemStack);
}
}
for (int i = 0; i < ingredientCount; i++) {
craftingItems.init(i, true, left + 5, top + 5 + (i * middleDrawable.getHeight()));
List<ItemStack> itemStacksForSlot = itemStacksForSlots.get(i);
craftingItems.set(i, itemStacksForSlot);
}
}
}
@Nullable
public GuiIngredient<ItemStack> draw(Minecraft minecraft, int mouseX, int mouseY) {
int ingredientCount = craftingItems.getGuiIngredients().keySet().size();
if (ingredientCount > 0) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.disableDepth();
GlStateManager.enableAlpha();
{
int top = this.top;
topDrawable.draw(minecraft, this.left, top);
top += topDrawable.getHeight();
while (ingredientCount-- > 0) {
middleDrawable.draw(minecraft, this.left, top);
top += middleDrawable.getHeight();
}
bottomDrawable.draw(minecraft, this.left, top);
}
GlStateManager.disableAlpha();
GlStateManager.enableDepth();
return craftingItems.draw(minecraft, 0, 0, mouseX, mouseY);
}
return null;
}
@Nullable
@Override
public IClickedIngredient<?> getIngredientUnderMouse(int mouseX, int mouseY) {
ItemStack ingredientUnderMouse = craftingItems.getIngredientUnderMouse(0, 0, mouseX, mouseY);
if (ingredientUnderMouse != null) {
return new ClickedIngredient<Object>(ingredientUnderMouse);
}
return null;
}
@Override
public boolean canSetFocusWithMouse() {
return true;
}
}
|
Java
|
public class DoctrineDbalQbGotoCompletionRegistrar implements GotoCompletionRegistrar {
@Override
public void register(@NotNull GotoCompletionRegistrarParameter registrar) {
// table name completion on method eg:
// Doctrine\DBAL\Connection::insert
// Doctrine\DBAL\Query\QueryBuilder::update
registrar.register(PhpElementsUtil.getParameterInsideMethodReferencePattern(), psiElement -> {
PsiElement context = psiElement.getContext();
if (!(context instanceof StringLiteralExpression)) {
return null;
}
if (!isTableNameRegistrar(context)) {
return null;
}
return new DbalTableGotoCompletionProvider(context);
});
// simple flat field names eg:
// Doctrine\DBAL\Connection::update('foo', ['<caret>'])
registrar.register(PlatformPatterns.psiElement().withParent(StringLiteralExpression.class).withLanguage(PhpLanguage.INSTANCE), psiElement -> {
PsiElement context = psiElement.getContext();
if (!(context instanceof StringLiteralExpression)) {
return null;
}
MethodMatcher.MethodMatchParameter methodMatchParameter = new MethodMatcher.ArrayParameterMatcher(context, 1)
.withSignature("\\Doctrine\\DBAL\\Connection", "insert")
.withSignature("\\Doctrine\\DBAL\\Connection", "update")
.match();
if (methodMatchParameter == null) {
return null;
}
PsiElement[] parameters = methodMatchParameter.getParameters();
if(parameters.length < 2) {
return null;
}
String stringValue = PhpElementsUtil.getStringValue(parameters[0]);
if(StringUtils.isBlank(stringValue)) {
return null;
}
return new DbalFieldGotoCompletionProvider(context, stringValue);
});
// simple word alias completion
// join('foo', 'foo', 'bar')
registrar.register(PhpElementsUtil.getParameterInsideMethodReferencePattern(), psiElement -> {
PsiElement context = psiElement.getContext();
if (!(context instanceof StringLiteralExpression)) {
return null;
}
MethodMatcher.MethodMatchParameter methodMatchParameter = new MethodMatcher.StringParameterRecursiveMatcher(context, 2)
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "innerJoin")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "leftJoin")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "join")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "rightJoin")
.match();
if (methodMatchParameter == null) {
return null;
}
PsiElement[] parameters = methodMatchParameter.getParameters();
if(parameters.length < 2) {
return null;
}
String stringValue = PhpElementsUtil.getStringValue(parameters[1]);
if(StringUtils.isBlank(stringValue)) {
return null;
}
return new MyDbalAliasGotoCompletionProvider(context, stringValue, PhpElementsUtil.getStringValue(parameters[0]));
});
}
private static class MyDbalAliasGotoCompletionProvider extends GotoCompletionProvider {
@NotNull
private final String value;
@Nullable
private final String fromAlias;
public MyDbalAliasGotoCompletionProvider(PsiElement psiElement, @NotNull String value, @Nullable String fromAlias) {
super(psiElement);
this.value = value;
this.fromAlias = fromAlias;
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
Set<String> aliasSet = new HashSet<>();
aliasSet.add(value);
aliasSet.add(fr.adrienbrault.idea.symfony2plugin.util.StringUtils.camelize(value, true));
String underscore = fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore(value);
aliasSet.add(underscore);
if(value.length() > 0) {
aliasSet.add(value.substring(0, 1));
}
if(underscore.contains("_")) {
String[] split = underscore.split("_");
if(split.length > 1) {
aliasSet.add(split[0].substring(0, 1) + split[1].substring(0, 1));
}
List<String> i = new ArrayList<>();
for (String s : split) {
i.add(s.substring(0, 1));
}
aliasSet.add(StringUtils.join(i, ""));
}
if(StringUtils.isNotBlank(this.fromAlias)) {
aliasSet.add(fr.adrienbrault.idea.symfony2plugin.util.StringUtils.camelize(this.fromAlias + "_" + value, true));
aliasSet.add(fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore(this.fromAlias + "_" + value));
}
Collection<LookupElement> lookupElements = new ArrayList<>();
for (String s : aliasSet) {
lookupElements.add(LookupElementBuilder.create(s).withIcon(Symfony2Icons.DOCTRINE));
}
return lookupElements;
}
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(PsiElement element) {
return Collections.emptyList();
}
}
private boolean isTableNameRegistrar(PsiElement context) {
MethodMatcher.MethodMatchParameter methodMatchParameter = new MethodMatcher.StringParameterRecursiveMatcher(context, 0)
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "update")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "insert")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "from")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "delete")
.withSignature("Doctrine\\DBAL\\Connection", "insert")
.withSignature("Doctrine\\DBAL\\Connection", "update")
.match();
if(methodMatchParameter != null) {
return true;
}
methodMatchParameter = new MethodMatcher.StringParameterRecursiveMatcher(context, 1)
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "innerJoin")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "leftJoin")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "join")
.withSignature("Doctrine\\DBAL\\Query\\QueryBuilder", "rightJoin")
.match();
return methodMatchParameter != null;
}
private static class DbalTableGotoCompletionProvider extends GotoCompletionProvider {
public DbalTableGotoCompletionProvider(PsiElement element) {
super(element);
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
Collection<LookupElement> elements = new ArrayList<>();
for (Pair<String, PsiElement> pair : DoctrineMetadataUtil.getTables(getProject())) {
elements.add(LookupElementBuilder.create(pair.getFirst()).withIcon(Symfony2Icons.DOCTRINE));
}
return elements;
}
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(PsiElement element) {
String contents = GotoCompletionUtil.getStringLiteralValue(element);
if(contents == null) {
return Collections.emptyList();
}
Collection<PsiElement> psiElements = new ArrayList<>();
for (Pair<String, PsiElement> pair : DoctrineMetadataUtil.getTables(getProject())) {
if(!contents.equals(pair.getFirst())) {
continue;
}
PsiElement second = pair.getSecond();
if(second == null) {
continue;
}
psiElements.add(second);
}
return psiElements;
}
}
private static class DbalFieldGotoCompletionProvider extends GotoCompletionProvider {
private final String stringValue;
public DbalFieldGotoCompletionProvider(PsiElement element, String stringValue) {
super(element);
this.stringValue = stringValue;
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
DoctrineMetadataModel model = DoctrineMetadataUtil.getMetadataByTable(getProject(), this.stringValue);
if(model == null) {
return Collections.emptyList();
}
Collection<LookupElement> elements = new ArrayList<>();
for (DoctrineModelField field : model.getFields()) {
String column = field.getColumn();
// use "column" else fallback to field name
if(column != null && StringUtils.isNotBlank(column)) {
elements.add(LookupElementBuilder.create(column).withIcon(Symfony2Icons.DOCTRINE));
} else {
String name = field.getName();
if(StringUtils.isNotBlank(name)) {
elements.add(LookupElementBuilder.create(name).withIcon(Symfony2Icons.DOCTRINE));
}
}
}
return elements;
}
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(PsiElement element) {
String contents = GotoCompletionUtil.getStringLiteralValue(element);
if(contents == null) {
return Collections.emptyList();
}
DoctrineMetadataModel model = DoctrineMetadataUtil.getMetadataByTable(getProject(), this.stringValue);
if(model == null) {
return Collections.emptyList();
}
Collection<PsiElement> elements = new ArrayList<>();
for (DoctrineModelField field : model.getFields()) {
if(contents.equals(field.getColumn()) || contents.equals(field.getName())) {
elements.addAll(field.getTargets());
}
}
return elements;
}
}
}
|
Java
|
public class JiraConnectionProperties extends PropertiesImpl {
private static final String INITIAL_HOST = "https://jira.atlassian.com";
/**
* Host URL
*/
public StringProperty hostUrl = PropertyFactory.newString("hostUrl");
/**
* User id and password properties for Basic Authentication
*/
public BasicAuthenticationProperties basicAuthentication = new BasicAuthenticationProperties("basicAuthentication");
/**
* Constructor sets properties name
*
* @param name properties name
*/
public JiraConnectionProperties(String name) {
super(name);
}
/**
* {@inheritDoc}
*/
@Override
public void setupProperties() {
super.setupProperties();
hostUrl.setValue(INITIAL_HOST);
}
/**
* {@inheritDoc}
*/
@Override
public void setupLayout() {
super.setupLayout();
Form mainForm = Form.create(this, Form.MAIN);
mainForm.addRow(hostUrl);
mainForm.addRow(basicAuthentication.getForm(Form.MAIN));
}
}
|
Java
|
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LabelCountersForWorkteam implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The total number of data objects labeled by a human worker.
* </p>
*/
private Integer humanLabeled;
/**
* <p>
* The total number of data objects that need to be labeled by a human worker.
* </p>
*/
private Integer pendingHuman;
/**
* <p>
* The total number of tasks in the labeling job.
* </p>
*/
private Integer total;
/**
* <p>
* The total number of data objects labeled by a human worker.
* </p>
*
* @param humanLabeled
* The total number of data objects labeled by a human worker.
*/
public void setHumanLabeled(Integer humanLabeled) {
this.humanLabeled = humanLabeled;
}
/**
* <p>
* The total number of data objects labeled by a human worker.
* </p>
*
* @return The total number of data objects labeled by a human worker.
*/
public Integer getHumanLabeled() {
return this.humanLabeled;
}
/**
* <p>
* The total number of data objects labeled by a human worker.
* </p>
*
* @param humanLabeled
* The total number of data objects labeled by a human worker.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public LabelCountersForWorkteam withHumanLabeled(Integer humanLabeled) {
setHumanLabeled(humanLabeled);
return this;
}
/**
* <p>
* The total number of data objects that need to be labeled by a human worker.
* </p>
*
* @param pendingHuman
* The total number of data objects that need to be labeled by a human worker.
*/
public void setPendingHuman(Integer pendingHuman) {
this.pendingHuman = pendingHuman;
}
/**
* <p>
* The total number of data objects that need to be labeled by a human worker.
* </p>
*
* @return The total number of data objects that need to be labeled by a human worker.
*/
public Integer getPendingHuman() {
return this.pendingHuman;
}
/**
* <p>
* The total number of data objects that need to be labeled by a human worker.
* </p>
*
* @param pendingHuman
* The total number of data objects that need to be labeled by a human worker.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public LabelCountersForWorkteam withPendingHuman(Integer pendingHuman) {
setPendingHuman(pendingHuman);
return this;
}
/**
* <p>
* The total number of tasks in the labeling job.
* </p>
*
* @param total
* The total number of tasks in the labeling job.
*/
public void setTotal(Integer total) {
this.total = total;
}
/**
* <p>
* The total number of tasks in the labeling job.
* </p>
*
* @return The total number of tasks in the labeling job.
*/
public Integer getTotal() {
return this.total;
}
/**
* <p>
* The total number of tasks in the labeling job.
* </p>
*
* @param total
* The total number of tasks in the labeling job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public LabelCountersForWorkteam withTotal(Integer total) {
setTotal(total);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHumanLabeled() != null)
sb.append("HumanLabeled: ").append(getHumanLabeled()).append(",");
if (getPendingHuman() != null)
sb.append("PendingHuman: ").append(getPendingHuman()).append(",");
if (getTotal() != null)
sb.append("Total: ").append(getTotal());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof LabelCountersForWorkteam == false)
return false;
LabelCountersForWorkteam other = (LabelCountersForWorkteam) obj;
if (other.getHumanLabeled() == null ^ this.getHumanLabeled() == null)
return false;
if (other.getHumanLabeled() != null && other.getHumanLabeled().equals(this.getHumanLabeled()) == false)
return false;
if (other.getPendingHuman() == null ^ this.getPendingHuman() == null)
return false;
if (other.getPendingHuman() != null && other.getPendingHuman().equals(this.getPendingHuman()) == false)
return false;
if (other.getTotal() == null ^ this.getTotal() == null)
return false;
if (other.getTotal() != null && other.getTotal().equals(this.getTotal()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHumanLabeled() == null) ? 0 : getHumanLabeled().hashCode());
hashCode = prime * hashCode + ((getPendingHuman() == null) ? 0 : getPendingHuman().hashCode());
hashCode = prime * hashCode + ((getTotal() == null) ? 0 : getTotal().hashCode());
return hashCode;
}
@Override
public LabelCountersForWorkteam clone() {
try {
return (LabelCountersForWorkteam) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.sagemaker.model.transform.LabelCountersForWorkteamMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
Java
|
public class PeripheralProvider implements IPeripheralProvider {
@Override
public IPeripheral getPeripheral(@Nonnull World world, @Nonnull BlockPos blockPos, @Nonnull EnumFacing enumFacing) {
TileEntity te = world.getTileEntity(blockPos);
if (te != null) {
try {
// Check for capability first
IPeripheral capability = te.getCapability(Constants.PERIPHERAL_CAPABILITY, enumFacing);
if (capability != null) return capability;
// Simple blacklisting
if (te instanceof IPeripheralTile) return null;
Class<?> klass = te.getClass();
if (isBlacklisted(klass)) return null;
MethodRegistry registry = MethodRegistry.instance;
ICostHandler handler = registry.getCostHandler(te, enumFacing);
BlockReference reference = new BlockReference(new WorldLocation(world, blockPos), world.getBlockState(blockPos), te);
IUnbakedContext<BlockReference> context = registry.makeContext(reference, handler, BasicModuleContainer.EMPTY_REF, new WorldLocation(world, blockPos));
IPartialContext<BlockReference> baked = new PartialContext<BlockReference>(reference, handler, new Object[]{new WorldLocation(world, blockPos)}, BasicModuleContainer.EMPTY);
Pair<List<IMethod<?>>, List<IUnbakedContext<?>>> paired = registry.getMethodsPaired(context, baked);
if (paired.getLeft().size() > 0) {
return new MethodWrapperPeripheral(Helpers.tryGetName(te).replace('.', '_'), te, paired, DefaultExecutor.INSTANCE);
}
} catch (RuntimeException e) {
DebugLogger.error("Error getting peripheral", e);
}
}
return null;
}
private static final Set<String> blacklist = new HashSet<String>();
public static void addToBlacklist(String klass) {
blacklist.add(klass);
}
public static boolean isBlacklisted(Class<?> klass) {
String name = klass.getName();
if (blacklist.contains(name)) return true;
if (Helpers.classBlacklisted(ConfigCore.Blacklist.blacklistTileEntities, name)) {
blacklist.add(name);
return true;
}
try {
klass.getField("PLETHORA_IGNORE");
blacklist.add(name);
return true;
} catch (NoSuchFieldException ignored) {
} catch (Throwable t) {
DebugLogger.warn("Cannot get ignored field from " + name, t);
}
return false;
}
}
|
Java
|
@XmlRootElement(name = "Polygon4")
@XmlType(name = "Polygon4")
public class Polygon4<T extends Number>
implements IPolygon4<T>, Serializable {
/**
* Serial Version UID.
*/
private static final long serialVersionUID = -6613114341290751004L;
@XmlElement(type = Point4.class)
private final List<IPoint4<T>> points;
@XmlAttribute
private final Class<? extends T> type;
@Override
public Class<? extends T> getType() {
return this.type;
}
@Override
public List<IPoint4<T>> getPoints() {
return Collections.unmodifiableList(this.points);
}
@Override
public boolean addPoint(final IPoint4<? extends Number> point) {
final Point4<T> pointToAdd = new Point4<>(point, this.type);
return this.points.add(pointToAdd);
}
@Override
public boolean removePoint(final IPoint4<? extends Number> point) {
final Point4<T> pointToRemove = new Point4<>(point, this.type);
return this.points.remove(pointToRemove);
}
@Override
public void clearPoints() {
this.points.clear();
}
/**
* Creates a new instance of the {@code Polygon4} class. (Serialization
* Constructor)
*/
public Polygon4() {
this(null, null, true);
}
/**
* Creates a new instance of the {@code Polygon4} class.
*
* @param type
* the type.
*/
public Polygon4(final Class<? extends T> type) {
this(null, type, false);
}
/**
* Creates a new instance of the {@link Polygon4} class with the provided
* type and parameters.
*
* @param <S>
* the {@link Number} type of the {@link IPoint4 Points}.
* @param points
* the {@link IPoint4 Points}.
* @param type
* the type.
*/
public <S extends Number> Polygon4(final List<IPoint4<S>> points,
final Class<? extends T> type) {
this(points, type, false);
}
/**
* Creates a new instance of the {@link Polygon4} class with the provided
* type and parameters.
*
* @param <S>
* the {@link Number} type of the {@link IPoint4 Points}.
* @param points
* the {@link IPoint4 Points}.
* @param type
* the type.
* @param serialization
* whether or not the constructor is invoked during serialization.
*/
public <S extends Number> Polygon4(final List<IPoint4<S>> points,
final Class<? extends T> type, final boolean serialization) {
if ((type == null) && !serialization) {
throw new IllegalArgumentException(
"Cannot create a polygon without a type!");
}
this.points = new LinkedList<>();
this.type = type;
if ((points != null) && (type != null)) {
points.stream().map(point -> new Point4<T>(point, type))
.forEach(this.getPoints()::add);
}
}
/**
* Copy Constructor.
*
* @param polygonToCopy
* the polygon to copy.
*/
public Polygon4(final IPolygon4<T> polygonToCopy) {
this(polygonToCopy, polygonToCopy.getType());
}
/**
* Copy Constructor.
*
* @param polygonToCopy
* the polygon to cop
* @param type
* the desired type of the rectangle to copy.
*/
public Polygon4(final IPolygon4<?> polygonToCopy,
final Class<? extends T> type) {
this(polygonToCopy.getPoints(), type);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Polygon4 [ ");
this.points.forEach(builder::append);
builder.append(" ]");
return builder.toString();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || !(obj instanceof IPolygon4<?>)) {
return false;
}
final IPolygon4<?> other = (IPolygon4<?>) obj;
return this.getPoints().size() == (other.getPoints().size())
&& this.getPoints().containsAll(other.getPoints());
}
@Override
public int hashCode() {
int hash = 7;
hash += this.getPoints().stream().map(Object::hashCode)
.map(hashCode -> 13 * hashCode).reduce(0, Integer::sum);
return hash;
}
}
|
Java
|
public class AssertionValidationProcessor {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(AssertionValidationProcessor.class);
private final Collection<PolicyAssertionValidator> validators = new LinkedList<PolicyAssertionValidator>();
/**
* This constructor instantiates the object with a set of dynamically
* discovered PolicyAssertionValidators.
*
* @throws PolicyException Thrown if the set of dynamically discovered
* PolicyAssertionValidators is empty.
*/
private AssertionValidationProcessor() throws PolicyException {
this(null);
}
/**
* This constructor adds the given set of policy validators to the dynamically
* discovered PolicyAssertionValidators.
*
* This constructor is intended to be used by the JAX-WS com.sun.xml.internal.ws.policy.api.ValidationProcessor.
*
* @param policyValidators A set of PolicyAssertionValidators. May be null
* @throws PolicyException Thrown if the set of given PolicyAssertionValidators
* and dynamically discovered PolicyAssertionValidators is empty.
*/
protected AssertionValidationProcessor(final Collection<PolicyAssertionValidator> policyValidators)
throws PolicyException {
for(PolicyAssertionValidator validator : PolicyUtils.ServiceProvider.load(PolicyAssertionValidator.class)) {
validators.add(validator);
}
if (policyValidators != null) {
for (PolicyAssertionValidator validator : policyValidators) {
validators.add(validator);
}
}
if (validators.size() == 0) {
throw LOGGER.logSevereException(new PolicyException(WSP_0076_NO_SERVICE_PROVIDERS_FOUND(PolicyAssertionValidator.class.getName())));
}
}
/**
* Factory method that returns singleton instance of the class.
*
* This method is only intended to be used by code that has no dependencies on
* JAX-WS. Otherwise use com.sun.xml.internal.ws.api.policy.ValidationProcessor.
*
* @return singleton An instance of the class.
* @throws PolicyException If instantiation failed.
*/
public static AssertionValidationProcessor getInstance() throws PolicyException {
return new AssertionValidationProcessor();
}
/**
* Validates fitness of the {@code assertion} on the client side.
*
* return client side {@code assertion} fitness
* @param assertion The assertion to be validated.
* @return The fitness of the assertion on the client side.
* @throws PolicyException If validation failed.
*/
public PolicyAssertionValidator.Fitness validateClientSide(final PolicyAssertion assertion) throws PolicyException {
PolicyAssertionValidator.Fitness assertionFitness = PolicyAssertionValidator.Fitness.UNKNOWN;
for ( PolicyAssertionValidator validator : validators ) {
assertionFitness = assertionFitness.combine(validator.validateClientSide(assertion));
if (assertionFitness == PolicyAssertionValidator.Fitness.SUPPORTED) {
break;
}
}
return assertionFitness;
}
/**
* Validates fitness of the {@code assertion} on the server side.
*
* return server side {@code assertion} fitness
* @param assertion The assertion to be validated.
* @return The fitness of the assertion on the server side.
* @throws PolicyException If validation failed.
*/
public PolicyAssertionValidator.Fitness validateServerSide(final PolicyAssertion assertion) throws PolicyException {
PolicyAssertionValidator.Fitness assertionFitness = PolicyAssertionValidator.Fitness.UNKNOWN;
for (PolicyAssertionValidator validator : validators) {
assertionFitness = assertionFitness.combine(validator.validateServerSide(assertion));
if (assertionFitness == PolicyAssertionValidator.Fitness.SUPPORTED) {
break;
}
}
return assertionFitness;
}
}
|
Java
|
@Path("/author")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
public class AuthorRest {
private final static Logger LOGGER = Logger.getLogger(AuthorRest.class.getName());
@GET
@Path("/all")
public List<AuthorEntity> getAllAuthors() throws AppException{
LOGGER.info("AuthorRest.getAllAuthors");
List<AuthorEntity> listAuthors = new ArrayList<AuthorEntity>();
listAuthors.add(new AuthorEntity(1L));
listAuthors.add(new AuthorEntity(2L));
listAuthors.add(new AuthorEntity(3L));
LOGGER.info("AuthorRest.getAllAuthors: "+listAuthors);
return listAuthors;
}
}
|
Java
|
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"vnfType",
"vnfId",
"vfModuleModelName",
"asdcServiceModelVersion",
"serviceInstanceId",
"backoutOnFailure",
"serviceType",
"serviceId",
"aicNodeClli",
"aicCloudRegion",
"tenantId",
"volumeGroupName",
"volumeGroupId"
})
@XmlRootElement(name = "volume-inputs")
public class VolumeInputs {
@XmlElement(name = "vnf-type", required = true)
protected String vnfType;
@XmlElement(name = "vnf-id")
protected String vnfId;
@XmlElement(name = "vf-module-model-name")
protected String vfModuleModelName;
@XmlElement(name = "asdc-service-model-version")
protected String asdcServiceModelVersion;
@XmlElement(name = "service-instance-id", required = true)
protected String serviceInstanceId;
@XmlElement(name = "backout-on-failure")
protected Boolean backoutOnFailure;
@XmlElement(name = "service-type")
protected String serviceType;
@XmlElement(name = "service-id")
protected String serviceId;
@XmlElement(name = "aic-node-clli", required = true)
protected String aicNodeClli;
@XmlElement(name = "aic-cloud-region")
protected String aicCloudRegion;
@XmlElement(name = "tenant-id", required = true)
protected String tenantId;
@XmlElement(name = "volume-group-name")
protected String volumeGroupName;
@XmlElement(name = "volume-group-id")
protected String volumeGroupId;
/**
* Gets the value of the volumeGroupId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVolumeGroupId() {
return volumeGroupId;
}
/**
* Sets the value of the volumeGroupId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVolumeGroupId(String value) {
this.volumeGroupId = value;
}
/**
* Gets the value of the volumeGroupName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVolumeGroupName() {
return volumeGroupName;
}
/**
* Sets the value of the volumeGroupName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVolumeGroupName(String value) {
this.volumeGroupName = value;
}
/**
* Gets the value of the vnfType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVnfType() {
return vnfType;
}
/**
* Sets the value of the vnfType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVnfType(String value) {
this.vnfType = value;
}
/**
* Gets the value of the vnfId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVnfId() {
return vnfId;
}
/**
* Sets the value of the vnfId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVnfId(String value) {
this.vnfId = value;
}
/**
* Gets the value of the serviceInstanceId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceInstanceId() {
return serviceInstanceId;
}
/**
* Sets the value of the serviceInstanceId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceInstanceId(String value) {
this.serviceInstanceId = value;
}
/**
* Gets the value of the serviceType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceType() {
return serviceType;
}
/**
* Sets the value of the serviceType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceType(String value) {
this.serviceType = value;
}
/**
* Gets the value of the serviceId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceId() {
return serviceId;
}
/**
* Sets the value of the serviceId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceId (String value) {
this.serviceId = value;
}
/**
* Gets the value of the aicNodeClli property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAicNodeClli() {
return aicNodeClli;
}
/**
* Sets the value of the aicNodeClli property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAicNodeClli(String value) {
this.aicNodeClli = value;
}
/**
* Gets the value of the aicCloudRegion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAicCloudRegion() {
return aicCloudRegion;
}
/**
* Sets the value of the aicCloudRegion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAicCloudRegion(String value) {
this.aicCloudRegion = value;
}
/**
* Gets the value of the tenantId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTenantId() {
return tenantId;
}
/**
* Sets the value of the tenantId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTenantId(String value) {
this.tenantId = value;
}
/**
* Gets the value of the vfModuleModelName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVfModuleModelName() {
return vfModuleModelName;
}
/**
* Sets the value of the vfModuleModelName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVfModuleModelName(String value) {
this.vfModuleModelName = value;
}
/**
* Gets the value of the asdcServiceModelVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAsdcServiceModelVersion() {
return asdcServiceModelVersion;
}
/**
* Sets the value of the asdcServiceModelVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAsdcServiceModelVersion(String value) {
this.asdcServiceModelVersion = value;
}
/**
* Gets the value of the backoutOnFailure property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean getBackoutOnFailure() {
return backoutOnFailure;
}
/**
* Sets the value of the backoutOnFailure property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setBackoutOnFailure(Boolean value) {
this.backoutOnFailure = value;
}
}
|
Java
|
public class CreateFunctionTest {
private static String runningDir = "fe/mocked/CreateFunctionTest/" + UUID.randomUUID().toString() + "/";
private static ConnectContext connectContext;
private static DorisAssert dorisAssert;
@BeforeClass
public static void setup() throws Exception {
UtFrameUtils.createDorisCluster(runningDir);
FeConstants.runningUnitTest = true;
// create connect context
connectContext = UtFrameUtils.createDefaultCtx();
}
@AfterClass
public static void teardown() {
File file = new File("fe/mocked/CreateFunctionTest/");
file.delete();
}
@Test
public void test() throws Exception {
ConnectContext ctx = UtFrameUtils.createDefaultCtx();
// create database db1
String createDbStmtStr = "create database db1;";
CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx);
Catalog.getCurrentCatalog().createDb(createDbStmt);
System.out.println(Catalog.getCurrentCatalog().getDbNames());
String createTblStmtStr = "create table db1.tbl1(k1 int, k2 bigint, k3 varchar(10), k4 char(5)) duplicate key(k1) "
+ "distributed by hash(k2) buckets 1 properties('replication_num' = '1');";
CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, connectContext);
Catalog.getCurrentCatalog().createTable(createTableStmt);
dorisAssert = new DorisAssert();
dorisAssert.useDatabase("db1");
Database db = Catalog.getCurrentCatalog().getDbNullable("default_cluster:db1");
Assert.assertNotNull(db);
String createFuncStr = "create function db1.my_add(VARCHAR(1024)) RETURNS BOOLEAN properties\n" +
"(\n" +
"\"symbol\" = \"_ZN9doris_udf6AddUdfEPNS_15FunctionContextERKNS_9StringValE\",\n" +
"\"prepare_fn\" = \"_ZN9doris_udf13AddUdfPrepareEPNS_15FunctionContextENS0_18FunctionStateScopeE\",\n" +
"\"close_fn\" = \"_ZN9doris_udf11AddUdfCloseEPNS_15FunctionContextENS0_18FunctionStateScopeE\",\n" +
"\"object_file\" = \"http://127.0.0.1:8008/libcmy_udf.so\"\n" +
");";
CreateFunctionStmt createFunctionStmt = (CreateFunctionStmt) UtFrameUtils.parseAndAnalyzeStmt(createFuncStr, ctx);
Catalog.getCurrentCatalog().createFunction(createFunctionStmt);
List<Function> functions = db.getFunctions();
Assert.assertEquals(1, functions.size());
Assert.assertTrue(functions.get(0).isUdf());
String queryStr = "select db1.my_add(null)";
ctx.getState().reset();
StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr);
stmtExecutor.execute();
Assert.assertNotEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType());
Planner planner = stmtExecutor.planner();
Assert.assertEquals(1, planner.getFragments().size());
PlanFragment fragment = planner.getFragments().get(0);
Assert.assertTrue(fragment.getPlanRoot() instanceof UnionNode);
UnionNode unionNode = (UnionNode)fragment.getPlanRoot();
List<List<Expr>> constExprLists = Deencapsulation.getField(unionNode, "constExprLists");
Assert.assertEquals(1, constExprLists.size());
Assert.assertEquals(1, constExprLists.get(0).size());
Assert.assertTrue(constExprLists.get(0).get(0) instanceof FunctionCallExpr);
// create alias function
createFuncStr = "create alias function db1.id_masking(bigint) with parameter(id) as concat(left(id,3),'****',right(id,4));";
createFunctionStmt = (CreateFunctionStmt) UtFrameUtils.parseAndAnalyzeStmt(createFuncStr, ctx);
Catalog.getCurrentCatalog().createFunction(createFunctionStmt);
functions = db.getFunctions();
Assert.assertEquals(2, functions.size());
queryStr = "select db1.id_masking(13888888888);";
ctx.getState().reset();
stmtExecutor = new StmtExecutor(ctx, queryStr);
stmtExecutor.execute();
Assert.assertNotEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType());
planner = stmtExecutor.planner();
Assert.assertEquals(1, planner.getFragments().size());
fragment = planner.getFragments().get(0);
Assert.assertTrue(fragment.getPlanRoot() instanceof UnionNode);
unionNode = (UnionNode)fragment.getPlanRoot();
constExprLists = Deencapsulation.getField(unionNode, "constExprLists");
Assert.assertEquals(1, constExprLists.size());
Assert.assertEquals(1, constExprLists.get(0).size());
Assert.assertTrue(constExprLists.get(0).get(0) instanceof FunctionCallExpr);
queryStr = "select db1.id_masking(k1) from db1.tbl1";
Assert.assertTrue(dorisAssert.query(queryStr).explainQuery().contains("concat(left(`k1`, 3), '****', right(`k1`, 4))"));
// create alias function with cast
// cast any type to decimal with specific precision and scale
createFuncStr = "create alias function db1.decimal(all, int, int) with parameter(col, precision, scale)" +
" as cast(col as decimal(precision, scale));";
createFunctionStmt = (CreateFunctionStmt) UtFrameUtils.parseAndAnalyzeStmt(createFuncStr, ctx);
Catalog.getCurrentCatalog().createFunction(createFunctionStmt);
functions = db.getFunctions();
Assert.assertEquals(3, functions.size());
queryStr = "select db1.decimal(333, 4, 1);";
ctx.getState().reset();
stmtExecutor = new StmtExecutor(ctx, queryStr);
stmtExecutor.execute();
Assert.assertNotEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType());
planner = stmtExecutor.planner();
Assert.assertEquals(1, planner.getFragments().size());
fragment = planner.getFragments().get(0);
Assert.assertTrue(fragment.getPlanRoot() instanceof UnionNode);
unionNode = (UnionNode)fragment.getPlanRoot();
constExprLists = Deencapsulation.getField(unionNode, "constExprLists");
System.out.println(constExprLists.get(0).get(0));
Assert.assertTrue(constExprLists.get(0).get(0) instanceof StringLiteral);
queryStr = "select db1.decimal(k3, 4, 1) from db1.tbl1;";
Assert.assertTrue(dorisAssert.query(queryStr).explainQuery().contains("CAST(`k3` AS DECIMAL(4,1))"));
// cast any type to varchar with fixed length
createFuncStr = "create alias function db1.varchar(all, int) with parameter(text, length) as " +
"cast(text as varchar(length));";
createFunctionStmt = (CreateFunctionStmt) UtFrameUtils.parseAndAnalyzeStmt(createFuncStr, ctx);
Catalog.getCurrentCatalog().createFunction(createFunctionStmt);
functions = db.getFunctions();
Assert.assertEquals(4, functions.size());
queryStr = "select db1.varchar(333, 4);";
ctx.getState().reset();
stmtExecutor = new StmtExecutor(ctx, queryStr);
stmtExecutor.execute();
Assert.assertNotEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType());
planner = stmtExecutor.planner();
Assert.assertEquals(1, planner.getFragments().size());
fragment = planner.getFragments().get(0);
Assert.assertTrue(fragment.getPlanRoot() instanceof UnionNode);
unionNode = (UnionNode)fragment.getPlanRoot();
constExprLists = Deencapsulation.getField(unionNode, "constExprLists");
Assert.assertEquals(1, constExprLists.size());
Assert.assertEquals(1, constExprLists.get(0).size());
Assert.assertTrue(constExprLists.get(0).get(0) instanceof StringLiteral);
queryStr = "select db1.varchar(k1, 4) from db1.tbl1;";
Assert.assertTrue(dorisAssert.query(queryStr).explainQuery().contains("CAST(`k1` AS CHARACTER)"));
// cast any type to char with fixed length
createFuncStr = "create alias function db1.char(all, int) with parameter(text, length) as " +
"cast(text as char(length));";
createFunctionStmt = (CreateFunctionStmt) UtFrameUtils.parseAndAnalyzeStmt(createFuncStr, ctx);
Catalog.getCurrentCatalog().createFunction(createFunctionStmt);
functions = db.getFunctions();
Assert.assertEquals(5, functions.size());
queryStr = "select db1.char(333, 4);";
ctx.getState().reset();
stmtExecutor = new StmtExecutor(ctx, queryStr);
stmtExecutor.execute();
Assert.assertNotEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType());
planner = stmtExecutor.planner();
Assert.assertEquals(1, planner.getFragments().size());
fragment = planner.getFragments().get(0);
Assert.assertTrue(fragment.getPlanRoot() instanceof UnionNode);
unionNode = (UnionNode)fragment.getPlanRoot();
constExprLists = Deencapsulation.getField(unionNode, "constExprLists");
Assert.assertEquals(1, constExprLists.size());
Assert.assertEquals(1, constExprLists.get(0).size());
Assert.assertTrue(constExprLists.get(0).get(0) instanceof StringLiteral);
queryStr = "select db1.char(k1, 4) from db1.tbl1;";
Assert.assertTrue(dorisAssert.query(queryStr).explainQuery().contains("CAST(`k1` AS CHARACTER)"));
}
}
|
Java
|
public class ComputeServer {
/**
* The DRIP compute Service Engine Port
*/
public static final int DRIP_COMPUTE_ENGINE_PORT = 9090;
private int _iListenerPort = -1;
private java.net.ServerSocket _socketListener = null;
/**
* Create a Standard Instance of the ComputeServer
*
* @return The Standard ComputeServer Instance
*/
public static final ComputeServer Standard()
{
try {
ComputeServer cs = new ComputeServer (DRIP_COMPUTE_ENGINE_PORT);
return cs.initialize() ? cs : null;
} catch (java.lang.Exception e) {
e.printStackTrace();
}
return null;
}
/**
* ComputServer Constructor
*
* @param iListenerPort The Listener Port
*
* @throws java.lang.Exception Thrown if the Inputs are Invalid
*/
public ComputeServer (
final int iListenerPort)
throws java.lang.Exception
{
if (0 >= (_iListenerPort = iListenerPort))
throw new java.lang.Exception ("ComputeServer Constructor => Invalid Inputs");
}
/**
* Initialize the Compute Server Engine Listener Setup
*
* @return TRUE - The Compute Server Engine Listener Setup
*/
public boolean initialize()
{
try {
_socketListener = new java.net.ServerSocket (_iListenerPort);
return true;
} catch (java.lang.Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Spin on the Listener Loop
*
* @return FALSE - Spinning Terminated
*/
public boolean spin()
{
while (true) {
try {
java.net.Socket s = _socketListener.accept();
if (null == s) return false;
java.lang.String strJSONRequest = new java.io.BufferedReader (new java.io.InputStreamReader
(s.getInputStream())).readLine();
System.out.println (strJSONRequest);
java.lang.Object objRequest = org.drip.json.simple.JSONValue.parse (strJSONRequest);
if (null == objRequest || !(objRequest instanceof org.drip.json.simple.JSONObject))
return false;
org.drip.json.simple.JSONObject jsonRequest = (org.drip.json.simple.JSONObject) objRequest;
java.lang.Object objResponse = org.drip.json.simple.JSONValue.parse
(org.drip.service.json.KeyHoleSkeleton.Thunker (strJSONRequest));
if (null == objResponse) return false;
org.drip.json.simple.JSONObject jsonResponse = (org.drip.json.simple.JSONObject) objResponse;
if (!org.drip.service.engine.RequestResponseDecorator.AffixResponseHeaders (jsonResponse,
jsonRequest))
return false;
System.out.println ("\n\n" + jsonResponse.toJSONString());
java.io.PrintWriter pw = new java.io.PrintWriter (s.getOutputStream(), true);
pw.write (jsonResponse.toJSONString() + "\n");
pw.flush();
} catch (java.lang.Exception e) {
e.printStackTrace();
return false;
}
}
}
public static final void main (
final java.lang.String[] astrArgs)
throws java.lang.Exception
{
org.drip.service.env.EnvManager.InitEnv ("");
ComputeServer cs = ComputeServer.Standard();
cs.spin();
}
}
|
Java
|
public class VoiceManager
{
private final long pointer;
private final Core core;
VoiceManager(long pointer, Core core)
{
this.pointer = pointer;
this.core = core;
}
/**
* Gets the current voice input mode of the user.
* <p>
* This method only returns a <i>copy</i> of the input mode.
* Modifying it will not affect the current voice input mode
* unless you use {@link #setInputMode(VoiceInputMode, Consumer)}.
* @return The current {@link VoiceInputMode}
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #setInputMode(VoiceInputMode, Consumer)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#getinputmode">
* https://discord.com/developers/docs/game-sdk/discord-voice#getinputmode</a>
*/
public VoiceInputMode getInputMode()
{
Object ret = core.execute(()->getInputMode(pointer));
if(ret instanceof Result)
{
throw new GameSDKException((Result) ret);
}
else
{
return (VoiceInputMode) ret;
}
}
/**
* Sets a new voice input mode for the current user.
* <p>
* Discord checks the validity of the {@link VoiceInputMode#getShortcut()} and
* e.g. removes illegal keys (no error is thrown).
* However, the plausibility is not checked, allowing shortcuts to
* contain the same key multiple times and to be composed of as many
* keys as you can fit into the string (max length is 255 bytes).
* @param inputMode The new voice input mode
* @param callback Callback to process the returned {@link Result}
* @see #setInputMode(VoiceInputMode)
* @see #getInputMode()
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#setinputmode">
* https://discord.com/developers/docs/game-sdk/discord-voice#setinputmode</a>
*/
public void setInputMode(VoiceInputMode inputMode, Consumer<Result> callback)
{
core.execute(()->setInputMode(pointer, inputMode, Objects.requireNonNull(callback)));
}
/**
* Sets a new voice input mode for the current user.
* <p>
* The {@link Core#DEFAULT_CALLBACK} is used to handle the returned {@link Result}.
* @param inputMode The new voice input mode
* @see #setInputMode(VoiceInputMode, Consumer)
* @see #getInputMode()
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#setinputmode">
* https://discord.com/developers/docs/game-sdk/discord-voice#setinputmode</a>
*/
public void setInputMode(VoiceInputMode inputMode)
{
setInputMode(inputMode, Core.DEFAULT_CALLBACK);
}
/**
* Gets whether the current user has muted themselves.
* @return {@code true} if the current user is currently muted
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #setSelfMute(boolean)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#isselfmute">
* https://discord.com/developers/docs/game-sdk/discord-voice#isselfmute</a>
*/
public boolean isSelfMute()
{
Object ret = core.execute(()->isSelfMute(pointer));
if(ret instanceof Result)
{
throw new GameSDKException((Result) ret);
}
else
{
return (Boolean) ret;
}
}
/**
* Mutes or unmutes the current user (self mute).
* @param selfMute {@code true} to mute, {@code false} to unmute
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #isSelfMute()
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#setselfmute">
* https://discord.com/developers/docs/game-sdk/discord-voice#setselfmute</a>
*/
public void setSelfMute(boolean selfMute)
{
Result result = core.execute(()->setSelfMute(pointer, selfMute));
if(result != Result.OK)
{
throw new GameSDKException(result);
}
}
/**
* Gets whether the current user has deafened themselves.
* @return {@code true} if the current user is currently deafened
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #setSelfDeaf(boolean)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#isselfdeaf">
* https://discord.com/developers/docs/game-sdk/discord-voice#isselfdeaf</a>
*/
public boolean isSelfDeaf()
{
Object ret = core.execute(()->isSelfDeaf(pointer));
if(ret instanceof Result)
{
throw new GameSDKException((Result) ret);
}
else
{
return (Boolean) ret;
}
}
/**
* Deafens or undeafens the current user (self deaf).
* @param selfDeaf {@code true} to deafen, {@code false} to undeafen
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #isSelfDeaf()
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#setselfdeaf">
* https://discord.com/developers/docs/game-sdk/discord-voice#setselfdeaf</a>
*/
public void setSelfDeaf(boolean selfDeaf)
{
Result result = core.execute(()->setSelfDeaf(pointer, selfDeaf));
if(result != Result.OK)
{
throw new GameSDKException(result);
}
}
/**
* Checks if a user with a given ID is locally muted by the current user.
* @param userId ID of the user to check
* @return {@code true} if the user is locally muted
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #setLocalMute(long, boolean)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#islocalmute">
* https://discord.com/developers/docs/game-sdk/discord-voice#islocalmute</a>
*/
public boolean isLocalMute(long userId)
{
Object ret = core.execute(()->isLocalMute(pointer, userId));
if(ret instanceof Result)
{
throw new GameSDKException((Result) ret);
}
else
{
return (Boolean) ret;
}
}
/**
* Locally mutes or unmutes the user with the given ID.
* @param userId ID of the user to (un)mute
* @param mute {@code true} to mute the user, {@code false} to unmute the user
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #isLocalMute(long)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#setlocalmute">
* https://discord.com/developers/docs/game-sdk/discord-voice#setlocalmute</a>
*/
public void setLocalMute(long userId, boolean mute)
{
Result result = core.execute(()->setLocalMute(pointer, userId, mute));
if(result != Result.OK)
{
throw new GameSDKException(result);
}
}
/**
* Gets the local volume adjustment for the user with the given ID.
* <p>
* A volume of {@code 100} is default.
* A volume lower than that means that the volume for the given user
* is reduced (a volume of {@code 0} means no sound at all).
* If the volume is higher than the default, it is boosted
* (up to {@code 200} which is the maximal boost).
* @param userId ID of the user to get the volume adjustment for
* @return The volume adjustment in percent, an integer in percent between 0 and 200
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #setLocalVolume(long, int)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#getlocalvolume">
* https://discord.com/developers/docs/game-sdk/discord-voice#getlocalvolume</a>
*/
public int getLocalVolume(long userId)
{
Object ret = core.execute(()->getLocalVolume(pointer, userId));
if(ret instanceof Result)
{
throw new GameSDKException((Result) ret);
}
else
{
return (Integer) ret;
}
}
/**
* Adjust the volume for a given user id locally.
* <p>
* A volume of {@code 100} is default.
* A volume lower than that means that the volume for the given user
* is reduced (a volume of {@code 0} means no sound at all).
* If the volume is higher than the default, it is boosted
* (up to {@code 200} which is the maximal boost).
* @param userId ID of the user to adjust the volume for
* @param volume New volume adjustment in percent, an integer from 0 to 200
* @throws GameSDKException for a {@link Result} that is not {@link Result#OK}
* @see #getLocalVolume(long)
* @see <a href="https://discord.com/developers/docs/game-sdk/discord-voice#setlocalvolume">
* https://discord.com/developers/docs/game-sdk/discord-voice#setlocalvolume</a>
*/
public void setLocalVolume(long userId, int volume)
{
if(volume < 0 || volume > 200)
throw new IllegalArgumentException("volume out of range: "+volume);
Result result = core.execute(()->setLocalVolume(pointer, userId, (byte)volume));
if(result != Result.OK)
{
throw new GameSDKException(result);
}
}
private native Object getInputMode(long pointer);
private native void setInputMode(long pointer, VoiceInputMode inputMode, Consumer<Result> callback);
private native Object isSelfMute(long pointer);
private native Result setSelfMute(long pointer, boolean mute);
private native Object isSelfDeaf(long pointer);
private native Result setSelfDeaf(long pointer, boolean deaf);
private native Object isLocalMute(long pointer, long userId);
private native Result setLocalMute(long pointer, long userId, boolean mute);
private native Object getLocalVolume(long pointer, long userId);
private native Result setLocalVolume(long pointer, long userId, byte volume);
}
|
Java
|
public class Solution_844 {
public boolean backspaceCompare( String S, String T ) {
return rm(S).equals(rm(T));
}
public String rm( String S ) {
int i = 0;
char[] stack = new char[S.length() + 1];
for (char ch : S.toCharArray()) {
if (ch == '#') {
i--;
continue;
} else {
if (i < 0) {
i = 0;
}
i++;
stack[i] = ch;
}
}
return new String(stack, 1, i);
}
public static void main( String[] args ) {
System.out.println(new Solution_844().backspaceCompare("a#c","ad#c"));
}
}
|
Java
|
public class WrappedStringPolicy implements MissingPolicy{
private final String start;
private final String end;
private final int length;
/**
* Creates a new instance with the provided strings.
*
* @param start The string to prepend the source String. Can be <code>null</code>.
* @param end The string to append to the source string. Can be <code>null</code>.
*/
public WrappedStringPolicy(@Nullable String start, @Nullable String end) {
this.start = start;
this.end = end;
int length = 0;
if (!TextUtils.isEmpty(start)) {
length += start.length();
}
if (!TextUtils.isEmpty(end)) {
length += end.length();
}
this.length = length;
}
/**
* Wraps the provided sourceString with the <code>start</code> and <code>end</code> strings.
* <p>
* If sourceString is {@link Spanned}, a {@link SpannedString} containing the same spans is
* returned.
*/
@NonNull CharSequence wrapString(@NonNull CharSequence sourceString) {
if (TextUtils.isEmpty(start) && TextUtils.isEmpty(end)) {
return sourceString;
}
boolean isSpanned = sourceString instanceof Spanned;
if (isSpanned) {
SpannableStringBuilder sb = new SpannableStringBuilder();
if (!TextUtils.isEmpty(start)) {
sb.append(start);
}
sb.append(sourceString);
if (!TextUtils.isEmpty(end)) {
sb.append(end);
}
return new SpannedString(sb);
}
else {
StringBuilder sb = new StringBuilder(sourceString.length() + length);
if (!TextUtils.isEmpty(start)) {
sb.append(start);
}
sb.append(sourceString);
if (!TextUtils.isEmpty(end)) {
sb.append(end);
}
return sb.toString();
}
}
/**
* Returns a wrapped string.
*/
@Override
@NonNull public CharSequence get(@NonNull CharSequence sourceString, @StringRes int id,
@NonNull String resourceName, @NonNull String locale) {
return wrapString(sourceString);
}
/**
* Returns a wrapped quantity string.
*/
@Override
@NonNull public CharSequence getQuantityString(
@NonNull CharSequence sourceQuantityString, @PluralsRes int id, int quantity,
@NonNull String resourceName, @NonNull String locale) {
return wrapString(sourceQuantityString);
}
}
|
Java
|
@SuppressWarnings("WeakerAccess")
public class LinearCreepCoefficientFactory implements Factory<Double> {
private ConcreteClassification concreteClassification;
private double rh;
private double t0;
private double t;
private Shape shape;
private int cementClassification;
/**
* Creates an instance of the factory
*
* @param concreteClassification concrete classification of the cross section
* @param rh relative humidity of environment
* @param t0 time of loading in days
* @param t age of concrete in days
* @param shape shape of cross section
* @param cementClassification cement classification of concrete
* @see CementClassification#CEMENT_S
* @see CementClassification#CEMENT_N
* @see CementClassification#CEMENT_R
*/
public LinearCreepCoefficientFactory(ConcreteClassification concreteClassification, double rh, double t0, double
t, Shape shape, int cementClassification) {
this.concreteClassification = concreteClassification;
this.rh = rh;
this.t0 = t0;
this.t = t;
this.shape = shape;
this.cementClassification = cementClassification;
}
/**
* Calculates and returns linear creep coefficient according to B.1
*
* @return linear creep coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
@Override
public Double build() throws ImproperDataException, LSException {
return calculatePhiln();
}
/**
* Calculates and returns linear creep coefficient according to B.1
*
* @return linear creep coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculatePhiln() throws ImproperDataException, LSException {
double phi0 = pos(calculatePhi0());
double betactt0 = pos(calculateBetactt0());
return pos(phi0 * betactt0);
}
/**
* Calculates and returns linear notional creep coefficient according to B.1
*
* @return linear notional creep coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculatePhi0() throws ImproperDataException, LSException {
double phirh = pos(calculatePhirh());
double betafcm = pos(calculateBetafcm());
double betat0 = pos(calculateBetat0());
return pos(phirh * betafcm * betat0);
}
/**
* Calculates and returns concrete strength factor according to B.1
*
* @return concrete strength factor
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateBetafcm() throws ImproperDataException, LSException {
double fcm = pos(notNull(concreteClassification).getFcm());
return pos(16800 / sqrt(fcm));
}
/**
* Calculates and returns concrete age factor according to B.1
*
* @return concrete age factor
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateBetat0() throws ImproperDataException, LSException {
double t0mod = pos(this::calculateT0mod);
return pos(1 / pos(0.1 + pow(t0mod, 0.2)));
}
/**
* Calculates and returns cement adjusted time of loading in days according to B.1
*
* @return cement adjusted time of loading in days
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateT0mod() throws ImproperDataException, LSException {
pos(t0);
double alfacem = real(calculateAlpha());
return pos(t0 * pow(1 + 9 / (2 + pos(pow(t0, 1.2))), alfacem));
}
/**
* Calculates and returns alpha coefficient returns according to B.1
*
* @return alpha coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateAlpha() throws ImproperDataException, LSException {
switch (cementClassification) {
case CEMENT_S:
return -1;
case CEMENT_N:
return 0;
case CEMENT_R:
return 1;
default:
throw new ImproperDataException();
}
}
/**
* Calculates and returns relative humidity factor according to B.1
*
* @return relative humidity factor
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculatePhirh() throws ImproperDataException, LSException {
double fcm = pos(notNull(concreteClassification).getFcm());
pos(rh);
double h0 = pos(calculateH0());
double alfa1 = pos(calculateAlpha1());
double alfa2 = pos(calculateAlpha2());
double factor = pos(pos(1 - rh) / pos(pow(h0, 1.0 / 3.0)));
return (fcm <= 35000000) ? pos(1 + factor) : pos((1 + factor * alfa1) * alfa2);
}
/**
* Calculates and returns alpha1 coefficient returns according to B.1
*
* @return alpha1 coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateAlpha1() throws ImproperDataException, LSException {
return calculateAlpha(0.7);
}
/**
* Calculates and returns alpha2 coefficient returns according to B.1
*
* @return alpha2 coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateAlpha2() throws ImproperDataException, LSException {
return calculateAlpha(0.2);
}
/**
* Calculates and returns notional size in meters according to B.1
*
* @return notional size in meters
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateH0() throws ImproperDataException, LSException {
notNull(shape);
double ac = pos(shape.getA());
double u = pos(shape.getU());
return pos(2 * ac / u);
}
/**
* Calculates and returns development factor according to B.1
*
* @return development factor
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateBetactt0() throws ImproperDataException, LSException {
if (t == Double.POSITIVE_INFINITY) return 1;
pos(t);
double t0mod = pos(this::calculateT0mod);
double betaH = pos(calculateBetaH());
pos(rh);
return pos(pow(pos(t - t0mod) / pos(betaH + t - t0mod), 0.3));
}
/**
* Calculates and returns relative humidity and notional size factor according to B.1
*
* @return relative humidity and notional size factor
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateBetaH() throws ImproperDataException, LSException {
double fcm = pos(notNull(concreteClassification).getFcm());
double h0 = pos(calculateH0());
double factor = pos(1.5 * ((1 + pow(1.2 * rh, 18)) * h0 * 1000));
double alfa3 = calculateAlfa3();
return pos((fcm <= 35000000) ? min(factor + 250, 1500) : min(factor + 250 * alfa3, 1500 * alfa3));
}
/**
* Calculates and returns alpha coefficient returns according to B.1
*
* @return alpha coefficient
* @throws ImproperDataException if data is improper
* @throws LSException if limit state is exceeded
*/
protected double calculateAlfa3() throws ImproperDataException, LSException {
return calculateAlpha(0.5);
}
private double calculateAlpha(double exponent) throws ImproperDataException, LSException {
double fcm = pos(notNull(concreteClassification).getFcm());
return pow((35000000 / fcm), pos(exponent));
}
}
|
Java
|
private class RefreshTreeAndOpenNodeSubscriber implements EventTopicSubscriber<String> {
public void onEvent(String topic, String data) {
refreshTreeAndOpenNode(data);
}
}
|
Java
|
@SuppressWarnings("javadoc")
public class X_EDI_cctop_901_991_v extends org.compiere.model.PO implements I_EDI_cctop_901_991_v, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -361433412L;
/** Standard Constructor */
public X_EDI_cctop_901_991_v (Properties ctx, int EDI_cctop_901_991_v_ID, String trxName)
{
super (ctx, EDI_cctop_901_991_v_ID, trxName);
}
/** Load Constructor */
public X_EDI_cctop_901_991_v (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_C_Invoice getC_Invoice()
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
@Override
public void setC_Invoice(org.compiere.model.I_C_Invoice C_Invoice)
{
set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice);
}
@Override
public void setC_Invoice_ID (int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
set_Value (COLUMNNAME_C_Invoice_ID, null);
else
set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID));
}
@Override
public int getC_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_ID);
}
@Override
public void setEDI_cctop_901_991_v_ID (int EDI_cctop_901_991_v_ID)
{
if (EDI_cctop_901_991_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_EDI_cctop_901_991_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EDI_cctop_901_991_v_ID, Integer.valueOf(EDI_cctop_901_991_v_ID));
}
@Override
public int getEDI_cctop_901_991_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_901_991_v_ID);
}
@Override
public de.metas.esb.edi.model.I_EDI_cctop_invoic_v getEDI_cctop_invoic_v()
{
return get_ValueAsPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class);
}
@Override
public void setEDI_cctop_invoic_v(de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v)
{
set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v);
}
@Override
public void setEDI_cctop_invoic_v_ID (int EDI_cctop_invoic_v_ID)
{
if (EDI_cctop_invoic_v_ID < 1)
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null);
else
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, Integer.valueOf(EDI_cctop_invoic_v_ID));
}
@Override
public int getEDI_cctop_invoic_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID);
}
@Override
public void setESRReferenceNumber (java.lang.String ESRReferenceNumber)
{
set_Value (COLUMNNAME_ESRReferenceNumber, ESRReferenceNumber);
}
@Override
public java.lang.String getESRReferenceNumber()
{
return (java.lang.String)get_Value(COLUMNNAME_ESRReferenceNumber);
}
@Override
public void setRate (java.math.BigDecimal Rate)
{
set_Value (COLUMNNAME_Rate, Rate);
}
@Override
public java.math.BigDecimal getRate()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmt (java.math.BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public java.math.BigDecimal getTaxAmt()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmt (java.math.BigDecimal TaxBaseAmt)
{
set_Value (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
@Override
public java.math.BigDecimal getTaxBaseAmt()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
@Override
public java.math.BigDecimal getTotalAmt()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
Java
|
public class Mob extends Character {
public int lvl;
private String m_name;
private int m_attack;
public int expGain;
private int m_hp;
@Override
public int GetHp() {
return m_hp;
}
public void SetHp(int value) {
m_hp = value;
}
@Override
public void Attack(Character whom, GameData gameData) {
Random rng = gameData.Rng;
int damage = m_attack + rng.nextInt(m_attack/2);
whom.ReceiveAttack(damage);
}
@Override
public String Description() {
return String.format(Textdata.Get("mobDesc"), GetName(), lvl);
}
public static Mob GenerateMob(MobConf conf, GameData gameData) {
Mob result = new Mob();
result.lvl = gameData.Player.level;
result.SetName(conf.name);
result.SetHp(conf.hp *gameData.Player.level);
result.m_attack = (conf.attack + gameData.Rng.nextInt(1))*result.lvl;
result.expGain = conf.expGain*result.lvl;
return result;
}
@Override
public void ReceiveAttack(int damage) {
SetHp(GetHp() - damage);
}
@Override
public boolean IsDead() {
return GetHp() <= 0;
}
@Override
public String GetName() {
return m_name;
}
public void SetName(String value) {
m_name = value;
}
@Override
public int GetExpGain() {
return expGain;
}
}
|
Java
|
public class GCInfo {
/**
* in milliSeconds
*/
private long timestamp;
/**
* in milliSeconds
*/
private long bootTime;
private GCType type;
/**
* Young Generation used size before gc, peak size, eden + one survivor
*/
private int youngUsedBefore;
/**
* Young Generation used size after gc, eden + one survivor
*/
private int youngUsedAfter;
/**
* Young Generation size, eden + one survivor
*/
private int youngSize;
/**
* Heap used size before gc, eden + one survivor + old
*/
private int heapUsedBefore;
/**
* Heap used size after gc, eden + one survivor + old
*/
private int heapUsedAfter;
/**
* Heap size, eden + one survivor + old
*/
private int heapSize;
/**
* gc Stop-The-World time, in milliSeconds
*/
private long gcPauseSum;
private long maxGcPause;
private long maxGcPauseTimestamp;
public void addPause(long pause, long timestamp) {
gcPauseSum += pause;
if (maxGcPause < pause) {
maxGcPause = pause;
maxGcPauseTimestamp = timestamp;
}
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public long getBootTime() {
return bootTime;
}
public void setBootTime(long bootTime) {
this.bootTime = bootTime;
}
public GCType getType() {
return type;
}
public void setType(GCType type) {
this.type = type;
}
public int getYoungUsedBefore() {
return youngUsedBefore;
}
public void setYoungUsedBefore(int youngUsedBefore) {
this.youngUsedBefore = youngUsedBefore;
}
public int getYoungUsedAfter() {
return youngUsedAfter;
}
public void setYoungUsedAfter(int youngUsedAfter) {
this.youngUsedAfter = youngUsedAfter;
}
public int getYoungSize() {
return youngSize;
}
public void setYoungSize(int youngSize) {
this.youngSize = youngSize;
}
public int getHeapUsedBefore() {
return heapUsedBefore;
}
public void setHeapUsedBefore(int heapUsedBefore) {
this.heapUsedBefore = heapUsedBefore;
}
public int getHeapUsedAfter() {
return heapUsedAfter;
}
public void setHeapUsedAfter(int heapUsedAfter) {
this.heapUsedAfter = heapUsedAfter;
}
public int getHeapSize() {
return heapSize;
}
public void setHeapSize(int heapSize) {
this.heapSize = heapSize;
}
public long getGcPauseSum() {
return gcPauseSum;
}
public void setGcPauseSum(long gcPauseSum) {
this.gcPauseSum = gcPauseSum;
}
public long getMaxGcPause() {
return maxGcPause;
}
public long getMaxGcPauseTimestamp() {
return maxGcPauseTimestamp;
}
@Override
public String toString() {
return "{" +
"timestamp=" + timestamp +
", bootTime=" + bootTime +
", type=" + type +
", youngUsedBefore=" + youngUsedBefore +
", youngUsedAfter=" + youngUsedAfter +
", youngSize=" + youngSize +
", heapUsedBefore=" + heapUsedBefore +
", heapUsedAfter=" + heapUsedAfter +
", heapSize=" + heapSize +
", gcPause=" + gcPauseSum +
'}';
}
public enum GCType {
YongGC, OldGC, MixedGC, FullGC
}
}
|
Java
|
public class FunctionTagTableModel extends ThreadedTableModel<FunctionTagRowObject, Program> {
private Program program;
private TagListPanel tagListPanel;
protected FunctionTagTableModel(String modelName, ServiceProvider serviceProvider,
TagListPanel tagLoader) {
super(modelName, serviceProvider);
this.tagListPanel = tagLoader;
}
public void setProgram(Program program) {
this.program = program;
}
@Override
protected void doLoad(Accumulator<FunctionTagRowObject> accumulator, TaskMonitor monitor)
throws CancelledException {
if (program == null) {
return;
}
FunctionManager functionManager = program.getFunctionManager();
FunctionTagManager tagManager = functionManager.getFunctionTagManager();
Set<FunctionTag> tags = tagListPanel.backgroundLoadTags();
monitor.initialize(tags.size());
for (FunctionTag tag : tags) {
monitor.checkCanceled();
accumulator.add(new FunctionTagRowObject(tag, tagManager.getUseCount(tag)));
monitor.incrementProgress(1);
}
}
@Override
protected TableColumnDescriptor<FunctionTagRowObject> createTableColumnDescriptor() {
TableColumnDescriptor<FunctionTagRowObject> descriptor = new TableColumnDescriptor<>();
descriptor.addVisibleColumn(new FunctionTagNameColumn());
descriptor.addVisibleColumn(new FunctionTagCountColumn());
return descriptor;
}
@Override
public Program getDataSource() {
return program;
}
/**
* Removes all function tags from the model
*/
public void clear() {
super.clearData();
}
/**
* Returns true if a function tag with a given name is in the model
*
* @param name the tag name
* @return true if the tag exists in the model
*/
public boolean containsTag(String name) {
return getRowObject(name) != null;
}
/**
* Returns the row object that matches the given tag name
* @param name the tag name
* @return the row object
*/
public FunctionTagRowObject getRowObject(String name) {
return getAllData().stream()
.filter(row -> row.getName().equals(name))
.findFirst()
.orElseGet(() -> null);
}
/**
* Table column that displays a count of the number of times a function tag has been
* applied to a function (in the selected program)
*/
private class FunctionTagCountColumn
extends AbstractDynamicTableColumnStub<FunctionTagRowObject, Integer> {
@Override
public String getColumnDisplayName(Settings settings) {
// don't display any name, but need it to be at least one space wide so the correct
// space is allocated to the header
return " ";
}
@Override
public String getColumnName() {
return "Count";
}
@Override
public int getColumnPreferredWidth() {
return 30;
}
@Override
public Integer getValue(FunctionTagRowObject rowObject, Settings settings,
ServiceProvider sp) throws IllegalArgumentException {
return rowObject.getCount();
}
}
/**
* Table column that displays the name of a function tag
*/
private class FunctionTagNameColumn
extends AbstractDynamicTableColumnStub<FunctionTagRowObject, String> {
@Override
public String getColumnName() {
return "Name";
}
@Override
public String getValue(FunctionTagRowObject rowObject, Settings settings,
ServiceProvider sp) throws IllegalArgumentException {
return rowObject.getName();
}
}
}
|
Java
|
private class FunctionTagCountColumn
extends AbstractDynamicTableColumnStub<FunctionTagRowObject, Integer> {
@Override
public String getColumnDisplayName(Settings settings) {
// don't display any name, but need it to be at least one space wide so the correct
// space is allocated to the header
return " ";
}
@Override
public String getColumnName() {
return "Count";
}
@Override
public int getColumnPreferredWidth() {
return 30;
}
@Override
public Integer getValue(FunctionTagRowObject rowObject, Settings settings,
ServiceProvider sp) throws IllegalArgumentException {
return rowObject.getCount();
}
}
|
Java
|
private class FunctionTagNameColumn
extends AbstractDynamicTableColumnStub<FunctionTagRowObject, String> {
@Override
public String getColumnName() {
return "Name";
}
@Override
public String getValue(FunctionTagRowObject rowObject, Settings settings,
ServiceProvider sp) throws IllegalArgumentException {
return rowObject.getName();
}
}
|
Java
|
public class LongestWordinDictionarythroughDeleting {
public String findLongestWord(String s, List<String> d) {
Collections.sort(d, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if(o2.length() != o1.length()) return o2.length() - o1.length();
return o1.compareTo(o2);
}
});
for(String word: d)
{
if(isSubSeq(s, word))
{
return word;
}
}
return "";
}
public String findLongestWord2(String s, List<String> d) {
String ans = "";
int maxLen = 0;
for(String word: d)
{
if(isSubSeq2(s,word))
{
if(word.length() > maxLen || (word.length() == maxLen && word.compareTo(ans) < 0))
{
ans = word;
maxLen = word.length();
}
}
}
return ans;
}
private boolean isSubSeq(String source, String target)
{
if(target.length() > source.length())return false;
int idx = 0;
char t = target.charAt(idx);
for (int i = 0; i < source.length(); i++) {
if(source.charAt(i) == t)
{
idx++;
t = target.charAt(idx); // 减少chatAt(i) 的执行次数可以提升性能
if(idx == target.length())return true;
}
}
return false;
}
public String findLongestWord3(String s, List<String> d) {
String ans = "";
int maxLen = 0;
for(String word: d)
{
if(word.length() > maxLen || (word.length() == maxLen && word.compareTo(ans) < 0))
{
if(isSubSeq2(s,word) )
{
ans = word;
maxLen = word.length();
}
}
}
return ans;
}
private boolean isSubSeq2(String source, String target)
{
if(target.length() > source.length())return false;
int idx = -1;
int i = 0;
while (i < target.length())
{
char t = target.charAt(i);
idx = source.indexOf(t, idx +1);
if(idx < 0)return false;
i++;
}
return true;
}
}
|
Java
|
@JsonIgnoreProperties(ignoreUnknown = true)
public class IceServer {
private final String credential;
private final String username;
private final URI url;
/**
* Initialize an IceServer.
*
* @param credential credentials for the server
* @param username user account name
* @param url url of server
*/
@JsonCreator
public IceServer(@JsonProperty("credential") final String credential,
@JsonProperty("username") final String username,
@JsonProperty("url") final URI url) {
this.credential = credential;
this.username = username;
this.url = url;
}
public URI getUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getCredential() {
return credential;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IceServer other = (IceServer) o;
return (Objects.equals(credential, other.credential) &&
Objects.equals(username, other.username) &&
Objects.equals(url, other.url));
}
@Override
public int hashCode() {
return Objects.hash(credential, username, url);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("credential", credential)
.add("username", username)
.add("url", url)
.toString();
}
}
|
Java
|
public class RetryOnFailureXSiteCommand<O> {
public static final RetryPolicy NO_RETRY = new MaxRetriesPolicy(0);
private static final Log log = LogFactory.getLog(RetryOnFailureXSiteCommand.class);
private static final boolean trace = log.isTraceEnabled();
private final XSiteBackup xSiteBackup;
private final XSiteReplicateCommand<O> command;
private final RetryPolicy retryPolicy;
private RetryOnFailureXSiteCommand(XSiteBackup backup, XSiteReplicateCommand<O> command, RetryPolicy retryPolicy) {
this.xSiteBackup = backup;
this.command = command;
this.retryPolicy = retryPolicy;
}
/**
* Invokes remotely the command using the {@code Transport} passed as parameter.
*
* @param rpcManager the {@link RpcManager} to use.
* @param waitTimeBetweenRetries the waiting time if the command fails before retrying it.
* @param unit the {@link java.util.concurrent.TimeUnit} of the waiting time.
* @throws Throwable if the maximum retries is reached (defined by the {@link org.infinispan.remoting.transport.RetryOnFailureXSiteCommand.RetryPolicy},
* the last exception occurred is thrown.
*/
public void execute(RpcManager rpcManager, long waitTimeBetweenRetries, TimeUnit unit) throws Throwable {
assertNotNull(rpcManager, "RpcManager");
assertNotNull(unit, "TimeUnit");
assertGreaterThanZero(waitTimeBetweenRetries, "WaitTimeBetweenRetries");
do {
try {
CompletionStage<O> response = rpcManager.invokeXSite(xSiteBackup, command);
response.toCompletableFuture().join();
if (trace) {
log.trace("Successful Response received.");
}
return;
} catch (Throwable throwable) {
throwable = CompletableFutures.extractException(throwable);
if (!retryPolicy.retry(throwable, rpcManager)) {
if (trace) {
log.tracef("Failing command with exception %s", throwable);
}
throw throwable;
} else {
if (trace) {
log.tracef("Will retry command after exception %s", throwable);
}
}
}
unit.sleep(waitTimeBetweenRetries);
} while (true);
}
/**
* It builds a new instance with the destination site, the command and the retry policy.
*
* @param backup the destination site.
* @param command the command to invoke remotely.
* @param retryPolicy the retry policy.
* @return the new instance.
* @throws java.lang.NullPointerException if any parameter is {@code null}
*/
public static <O> RetryOnFailureXSiteCommand<O> newInstance(XSiteBackup backup, XSiteReplicateCommand<O> command,
RetryPolicy retryPolicy) {
assertNotNull(backup, "XSiteBackup");
assertNotNull(command, "XSiteReplicateCommand");
assertNotNull(retryPolicy, "RetryPolicy");
return new RetryOnFailureXSiteCommand<>(backup, command, retryPolicy);
}
@Override
public String toString() {
return "RetryOnLinkFailureXSiteCommand{" +
"backup=" + xSiteBackup +
", command=" + command +
'}';
}
private static void assertNotNull(Object value, String field) {
if (value == null) {
throw new NullPointerException(field + " must be not null.");
}
}
private static void assertGreaterThanZero(long value, String field) {
if (value <= 0) {
throw new IllegalArgumentException(field + " must be greater that zero but instead it is " + value);
}
}
public interface RetryPolicy {
boolean retry(Throwable throwable, RpcManager transport);
}
public static class MaxRetriesPolicy implements RetryPolicy {
private int maxRetries;
public MaxRetriesPolicy(int maxRetries) {
this.maxRetries = maxRetries;
}
@Override
public boolean retry(Throwable throwable, RpcManager transport) {
return maxRetries-- > 0;
}
}
}
|
Java
|
public class AnchorCommand extends PaginatedCoreCommand<String> {
public AnchorCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Create, Delete and Manage Anchor Destinations.");
this.setCommandUsage("/mv anchor " + ChatColor.GREEN + "{name}" + ChatColor.GOLD + " [-d]");
this.setArgRange(0, 2);
this.addKey("mv anchor");
this.addKey("mv anchors");
this.addKey("mvanchor");
this.addKey("mvanchors");
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "awesomething");
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "otherthing");
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "awesomething " + ChatColor.RED + "-d");
this.addCommandExample("/mv anchors ");
this.setPermission("multiverse.core.anchor.list", "Allows a player to list all anchors.", PermissionDefault.OP);
this.addAdditonalPermission(new Permission("multiverse.core.anchor.create",
"Allows a player to create anchors.", PermissionDefault.OP));
this.addAdditonalPermission(new Permission("multiverse.core.anchor.delete",
"Allows a player to delete anchors.", PermissionDefault.OP));
this.setItemsPerPage(8); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
private List<String> getFancyAnchorList(Player p) {
List<String> anchorList = new ArrayList<String>();
ChatColor color = ChatColor.GREEN;
for (String anchor : this.plugin.getAnchorManager().getAnchors(p)) {
anchorList.add(color + anchor);
color = (color == ChatColor.GREEN) ? ChatColor.GOLD : ChatColor.GREEN;
}
return anchorList;
}
private void showList(CommandSender sender, List<String> args) {
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.list", true)) {
sender.sendMessage(ChatColor.RED + "You don't have the permission to list anchors!");
return;
}
sender.sendMessage(ChatColor.LIGHT_PURPLE + "====[ Multiverse Anchor List ]====");
Player p = null;
if (sender instanceof Player) {
p = (Player) sender;
}
FilterObject filterObject = this.getPageAndFilter(args);
List<String> availableAnchors = new ArrayList<String>(this.getFancyAnchorList(p));
if (filterObject.getFilter().length() > 0) {
availableAnchors = this.getFilteredItems(availableAnchors, filterObject.getFilter());
if (availableAnchors.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE
+ "No anchors matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
return;
}
} else {
if (availableAnchors.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE + "No anchors were defined.");
return;
}
}
if (!(sender instanceof Player)) {
for (String c : availableAnchors) {
sender.sendMessage(c);
}
return;
}
int totalPages = (int) Math.ceil(availableAnchors.size() / (this.itemsPerPage + 0.0));
if (filterObject.getPage() > totalPages) {
filterObject.setPage(totalPages);
} else if (filterObject.getPage() < 1) {
filterObject.setPage(1);
}
sender.sendMessage(ChatColor.AQUA + " Page " + filterObject.getPage() + " of " + totalPages);
this.showPage(filterObject.getPage(), sender, availableAnchors);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (args.size() == 0) {
this.showList(sender, args);
return;
}
if (args.size() == 1 && (this.getPageAndFilter(args).getPage() != 1 || args.get(0).equals("1"))) {
this.showList(sender, args);
return;
}
if (args.size() == 2 && args.get(1).equalsIgnoreCase("-d")) {
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.delete", true)) {
sender.sendMessage(ChatColor.RED + "You don't have the permission to delete anchors!");
} else {
if (this.plugin.getAnchorManager().deleteAnchor(args.get(0))) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.RED + "deleted!");
} else {
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "deleted!");
}
}
return;
}
if (!(sender instanceof Player)) {
sender.sendMessage("You must be a player to create Anchors.");
return;
}
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.create", true)) {
sender.sendMessage(ChatColor.RED + "You don't have the permission to create anchors!");
} else {
Player player = (Player) sender;
if (this.plugin.getAnchorManager().saveAnchorLocation(args.get(0), player.getLocation())) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.GREEN + "created!");
} else {
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "created!");
}
}
}
@Override
protected List<String> getFilteredItems(List<String> availableItems, String filter) {
List<String> filtered = new ArrayList<String>();
for (String s : availableItems) {
if (s.matches("(?i).*" + filter + ".*")) {
filtered.add(s);
}
}
return filtered;
}
@Override
protected String getItemText(String item) {
return item;
}
}
|
Java
|
class ReflectionResourceMethodIntrospector
implements ResourceMethodIntrospector {
private static final Logger logger = LoggerFactory.getLogger(
ReflectionResourceMethodIntrospector.class);
private final ResourceDescriptorFactory descriptorFactory;
/**
* Constructs a new instance using the default resource descriptor factory.
*/
ReflectionResourceMethodIntrospector() {
this(new SimpleResourceDescriptorFactory());
}
/**
* Constructs a new instance using the specified resource descriptor factory.
* @param descriptorFactory descriptor factory
*/
ReflectionResourceMethodIntrospector(
ResourceDescriptorFactory descriptorFactory) {
this.descriptorFactory = descriptorFactory;
}
@Override
public Collection<ResourceDescriptor> describe(Method method,
String resourcePath, ModelPath modelPath,
TemplateResolver templateResolver,
ReflectionService reflectionService,
ResourceTypeIntrospector typeIntrospector)
throws ResourceConfigurationException {
final Path path = reflectionService.getAnnotation(method, Path.class);
resourcePath = resourcePath(resourcePath, path);
final boolean resourceMethod = isResourceMethod(method, reflectionService);
if (path == null && !resourceMethod) {
return Collections.emptyList();
}
TemplateResolver methodTemplateResolver = reflectionService.getAnnotation(
method, TemplateResolver.class);
Class<?> returnType = reflectionService.getReturnType(method);
if (resourceMethod) {
return describeResourceMethod(method, resourcePath, modelPath,
templateResolver, reflectionService, methodTemplateResolver);
}
ModelPathSpec modelPathSpec = reflectionService.getAnnotation(method,
ModelPathSpec.class);
if (reflectionService.isAbstractType(returnType)) {
if (modelPathSpec == null) return Collections.emptyList();
returnType = findMatchingSubResourceType(modelPath.concat(modelPathSpec),
reflectionService, method);
}
else if (modelPathSpec != null && modelPathSpec.inherit()) {
modelPath = modelPath.concat(modelPathSpec);
}
if (methodTemplateResolver == null) {
TemplateResolver typeTemplateResolver = reflectionService.getAnnotation(
returnType, TemplateResolver.class);
if (typeTemplateResolver != null) {
templateResolver = typeTemplateResolver;
}
}
else {
templateResolver = methodTemplateResolver;
}
return typeIntrospector.describe(returnType, resourcePath, modelPath,
templateResolver, reflectionService);
}
private Collection<ResourceDescriptor> describeResourceMethod(Method method,
String resourcePath, ModelPath modelPath,
TemplateResolver templateResolver, ReflectionService reflectionService,
TemplateResolver methodTemplateResolver) {
if (methodTemplateResolver != null) {
templateResolver = methodTemplateResolver;
}
ModelPathSpec[] specs = getModelPathSpecs(method, reflectionService);
if (specs.length == 0) {
logger.trace("ignoring method {}", methodToString(method));
return Collections.emptyList();
}
if (templateResolver == null) {
throw new ResourceConfigurationException(
"no template resolver for method " + methodToString(method));
}
final PathTemplateResolver pathTemplateResolver = TemplateResolverUtils
.newResolver(templateResolver.value());
final List<ResourceDescriptor> descriptors = new ArrayList<>();
for (final ModelPathSpec spec : specs) {
final ModelPath path = spec.inherit() ? modelPath.concat(spec) : modelPath;
descriptors.add(descriptorFactory.newDescriptor(method,
resourcePath, path, pathTemplateResolver));
}
return descriptors;
}
private ModelPathSpec[] getModelPathSpecs(Method method,
ReflectionService reflectionService) {
final ModelPathSpecs specs =
reflectionService.getAnnotation(method, ModelPathSpecs.class);
final ModelPathSpec spec = reflectionService.getAnnotation(method,
ModelPathSpec.class);
if (specs != null && spec == null) {
return specs.value();
}
if (specs == null && spec != null) {
return new ModelPathSpec[] { spec };
}
if (specs == null) {
return new ModelPathSpec[0];
}
throw new ResourceConfigurationException("cannot use both @"
+ ModelPathSpecs.class.getSimpleName() + " and @"
+ ModelPathSpec.class.getSimpleName() + " on the same method");
}
/**
* Determines whether the given method is annotated with an HTTP method
* annotation.
* @param method the method to examine
* @param reflector reflection service
* @return {@code true} if {@code method} has at least one HTTP method
* annotation
*/
private boolean isResourceMethod(Method method,
ReflectionService reflector) {
return reflector.getAnnotation(method, GET.class) != null
|| reflector.getAnnotation(method, POST.class) != null
|| reflector.getAnnotation(method, PUT.class) != null
|| reflector.getAnnotation(method, DELETE.class) != null
|| reflector.getAnnotation(method, HEAD.class) != null
|| reflector.getAnnotation(method, OPTIONS.class) != null;
}
/**
* Finds the unique concrete subtype of the return type of the given method
* whose referenced-by annotation is equivalent to the referenced-by
* annotation of the method.
*
* @param modelPath model path to match
* @param reflectionService reflection service @return matching sub type
* @param method the subject method
* @throws ResourceConfigurationException if the number of concrete types
* that satisfy the above criterion is not equal to 1
*/
private Class<?> findMatchingSubResourceType(ModelPath modelPath,
ReflectionService reflectionService, Method method) {
final List<Class<?>> types = new ArrayList<>();
final Class<?> returnType = reflectionService.getReturnType(method);
final Class<?>[] methodReferences = modelPath.asArray();
for (Class<?> type : reflectionService.getSubTypesOf(returnType)) {
ModelPathSpec typeModelPathSpec = reflectionService.getAnnotation(type,
ModelPathSpec.class);
if (typeModelPathSpec == null) continue;
final Class<?>[] typeReferences = typeModelPathSpec.value();
if (!Arrays.equals(typeReferences, methodReferences)) continue;
types.add(type);
}
final int numTypes = types.size();
if (numTypes == 0) {
throw new ResourceConfigurationException("there is no subtype of "
+ returnType.getSimpleName() + " with a @"
+ ModelPathSpec.class.getSimpleName() + " that matches "
+ modelPath + " at " + methodToString(method));
}
else if (numTypes > 1) {
throw new ResourceConfigurationException(
"there is more than one subtype of "
+ returnType.getSimpleName() + " with a @"
+ ModelPathSpec.class.getSimpleName() + " that matches "
+ modelPath + " at " + method);
}
return types.get(0);
}
/**
* Creates a new resource path from a parent path and the path specified
* by a {@link Path} annotation.
* @param parent parent path
* @param path path annotation whose value is to be appended
* @return {@code parent} with the value of {@link Path} appended to it
*/
private String resourcePath(String parent, Path path) {
UriBuilder uriBuilder = UriBuilder.fromUri(parent);
if (path != null) {
uriBuilder.path(path.value());
}
return uriBuilder.toTemplate();
}
private String methodToString(Method method) {
return method.getDeclaringClass().getSimpleName() + "." + method.getName();
}
}
|
Java
|
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InputVenueMessageContent implements InputMessageContent {
private final float latitude;
private final float longitude;
private final String title;
private final String address;
private final String foursquareId;
private final String foursquareType;
/**
* @param latitude Latitude of the location in degrees
* @param longitude Longitude of the location in degrees
* @param title Name of the venue
* @param address Address of the venue
* @param foursquareId Optional. Foursquare identifier of the venue, if known
* @param foursquareType Optional. Foursquare type of the venue, if known. (For example,
* “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
*/
public InputVenueMessageContent(float latitude, float longitude, String title, String address, String foursquareId, final String foursquareType) {
this.latitude = latitude;
this.longitude = longitude;
this.title = title;
this.address = address;
this.foursquareId = foursquareId;
this.foursquareType = foursquareType;
}
@JsonProperty("latitude")
public float getLatitude() {
return latitude;
}
@JsonProperty("longitude")
public float getLongitude() {
return longitude;
}
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("address")
public String getAddress() {
return address;
}
@JsonProperty("foursquare_id")
public String getFoursquareId() {
return foursquareId;
}
@JsonProperty("foursquare_type")
public String getFoursquareType() {
return foursquareType;
}
public String toJson() {
return JsonUtil.toJson(this);
}
@Override public String toString() {
return this.toJson();
}
}
|
Java
|
public class RelevanceNode extends ExpressionNode {
public static final int classId = registerClass(0x4000 + 59, RelevanceNode.class);
private FloatResultNode relevance = new FloatResultNode();
public RelevanceNode() {
}
@Override
public void onPrepare() {
}
@Override
public boolean onExecute() {
return true;
}
@Override
protected int onGetClassId() {
return classId;
}
@Override
protected void onSerialize(Serializer buf) {
super.onSerialize(buf);
relevance.serialize(buf);
}
@Override
protected void onDeserialize(Deserializer buf) {
super.onDeserialize(buf);
relevance.deserialize(buf);
}
@Override
public RelevanceNode clone() {
RelevanceNode obj = (RelevanceNode)super.clone();
obj.relevance = (FloatResultNode)relevance.clone();
return obj;
}
@Override
public void visitMembers(ObjectVisitor visitor) {
super.visitMembers(visitor);
visitor.visit("relevance", relevance);
}
@Override
public ResultNode getResult() {
return relevance;
}
@Override
protected boolean equalsExpression(ExpressionNode obj) {
return relevance.equals(((RelevanceNode)obj).relevance);
}
}
|
Java
|
public final class Sapproductconfigb2baddonWebConstants
{
/**
* view name to trigger a re-direct to the chekcout page
*/
public static final String REDIRECT_TO_CHECKOUT = AbstractController.REDIRECT_PREFIX + "/checkout/multi/summary/view";
/**
* view name to trigger a re-direct to the cart page
*/
public static final String REDIRECT_TO_CART = AbstractController.REDIRECT_PREFIX + "/cart";
private Sapproductconfigb2baddonWebConstants()
{
//empty to avoid instantiating this constant class
}
}
|
Java
|
public class MultiListIterator implements Iterator {
private List lists[] = new List[6];
private int listCount;
private int currentList;
private Iterator currentIterator;
public MultiListIterator() {
}
public MultiListIterator(List ls1) {
addList(ls1);
}
public MultiListIterator(List ls1, List ls2) {
addList(ls1);
addList(ls2);
}
public MultiListIterator(List ls1, List ls2, List ls3) {
addList(ls1);
addList(ls2);
addList(ls3);
}
public MultiListIterator(List ls1, List ls2, List ls3, List ls4) {
addList(ls1);
addList(ls2);
addList(ls3);
addList(ls4);
}
/**
* Use this to add more lists after the constructor.
*/
public void addList(List ls) {
if (ls.size() != 0) {
if (listCount == lists.length) {
List[] newLists = new List[listCount * 2];
System.arraycopy(lists, 0, newLists, 0, listCount);
lists = newLists;
}
lists[listCount++] = ls;
}
}
public boolean hasNext() {
if (currentIterator == null) {
if (listCount != 0) {
currentIterator = lists[0].iterator();
} else {
return false;
}
}
boolean hasNext = currentIterator.hasNext();
if (!hasNext && currentList < listCount - 1) {
return true;
} else {
return hasNext;
}
}
public Object next() {
if (currentIterator == null) {
if (listCount != 0) {
currentIterator = lists[0].iterator();
} else {
throw new NoSuchElementException(
"No next element; the list is empty.");
}
}
if (currentIterator.hasNext() || currentList == listCount - 1) {
return currentIterator.next();
} else {
currentList++;
currentIterator = lists[currentList].iterator();
return currentIterator.next();
}
}
public void remove() {
currentIterator.remove();
}
}
|
Java
|
public class PeriodListTest extends TestCase {
private Logger log = LoggerFactory.getLogger(PeriodListTest.class);
private PeriodList periodList;
private PeriodList expectedPeriodList;
private int expectedSize;
private Period expectedPeriod;
/**
* @param periodList
* @param periodList2
*/
public PeriodListTest(PeriodList periodList, PeriodList expectedPeriodList) {
super("testEquals");
this.periodList = periodList;
this.expectedPeriodList = expectedPeriodList;
}
/**
* @param periodList
* @param expectedSize
*/
public PeriodListTest(PeriodList periodList, int expectedSize) {
super("testSize");
this.periodList = periodList;
this.expectedSize = expectedSize;
}
/**
* @param periodList
* @param expectedFirstPeriod
*/
public PeriodListTest(String testMethod, PeriodList periodList, Period expectedPeriod) {
super(testMethod);
this.periodList = periodList;
this.expectedPeriod = expectedPeriod;
}
/**
* @param testMethod
* @param periodList
*/
public PeriodListTest(String testMethod, PeriodList periodList) {
super(testMethod);
this.periodList = periodList;
}
/**
* @param testMethod
*/
public PeriodListTest(String testMethod) {
super(testMethod);
}
/**
*
*/
public void testEquals() {
assertEquals(expectedPeriodList, periodList);
}
/**
*
*/
public void testSize() {
assertEquals(expectedSize, periodList.size());
}
/**
*
*/
public void testIsEmpty() {
assertTrue(periodList.isEmpty());
}
/**
*
*/
public void testFirstPeriodEquals() {
assertEquals(expectedPeriod, periodList.toArray()[0]);
}
public void testContains() {
assertTrue(periodList.contains(expectedPeriod));
}
/**
* @return
*/
public static TestSuite suite() {
TestSuite suite = new TestSuite();
// create ranges that are intervals
java.util.Calendar cal = new GregorianCalendar(1994,
java.util.Calendar.JANUARY, 1);
DateTime begin1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.DECEMBER, 31);
DateTime end1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.JANUARY, 22);
DateTime jan1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.FEBRUARY, 15);
DateTime feb1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.MARCH, 4);
DateTime mar1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.APRIL, 12);
DateTime apr1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.MAY, 19);
DateTime may1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.JUNE, 21);
DateTime jun1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.JULY, 28);
DateTime jul1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.AUGUST, 20);
DateTime aug1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.SEPTEMBER, 17);
DateTime sep1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.OCTOBER, 29);
DateTime oct1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.NOVEMBER, 11);
DateTime nov1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.DECEMBER, 2);
DateTime dec1994 = new DateTime(cal.getTime().getTime());
Period monthJanuary = new Period(jan1994, feb1994);
Period monthFebruary = new Period(feb1994, mar1994);
Period monthMarch = new Period(mar1994, apr1994);
Period monthApril = new Period(apr1994, may1994);
Period monthMay = new Period(may1994, jun1994);
Period monthJune = new Period(jun1994, jul1994);
Period monthJuly = new Period(jul1994, aug1994);
Period monthAugust = new Period(aug1994, sep1994);
Period monthSeptember = new Period(sep1994, oct1994);
Period monthOctober = new Period(oct1994, nov1994);
Period monthNovember = new Period(nov1994, dec1994);
Period monthDecember = new Period(dec1994, end1994);
Period head1994 = new Period(begin1994, jan1994);
Period tail1994 = new Period(dec1994, end1994);
// create sets that contain the ranges
PeriodList oddMonths = new PeriodList();
oddMonths.add(monthJanuary);
oddMonths.add(monthMarch);
oddMonths.add(monthMay);
oddMonths.add(monthJuly);
oddMonths.add(monthSeptember);
oddMonths.add(monthNovember);
PeriodList tailSet = new PeriodList();
tailSet.add(tail1994);
/*
* assertNull("Removing null from a null set should return null", empty1.subtract(null)); assertNull("Removing
* from a null set should return null", normalizer.subtractDateRanges(null, headSet));
*/
PeriodList evenMonths = new PeriodList();
evenMonths.add(monthFebruary);
evenMonths.add(monthApril);
evenMonths.add(monthJune);
evenMonths.add(monthAugust);
evenMonths.add(monthOctober);
evenMonths.add(monthDecember);
PeriodList headSet = new PeriodList();
headSet.add(head1994);
PeriodList empty1 = new PeriodList();
PeriodList empty2 = new PeriodList();
suite.addTest(new PeriodListTest(evenMonths.subtract(null), evenMonths));
suite.addTest(new PeriodListTest(empty1.subtract(empty2), empty1));
suite.addTest(new PeriodListTest(headSet.subtract(empty1), headSet));
suite.addTest(new PeriodListTest(evenMonths.subtract(empty1), evenMonths));
// add disjoint ranges..
PeriodList periodList1 = new PeriodList();
periodList1.add(monthNovember);
periodList1.add(monthDecember);
PeriodList periodList2 = new PeriodList();
periodList2.add(monthJuly);
periodList2.add(monthNovember);
/*
* SortedSet normalizedSet = normalizer.addDateRanges(dateRangeSet1, dateRangeSet2);
*/
PeriodList sum = periodList1.add(periodList2);
suite.addTest(new PeriodListTest(sum, 2));
// Period lonePeriod = (Period) sum.toArray()[0];
// assertEquals(lonePeriod.getStart(), jul1994);
// assertEquals(lonePeriod.getEnd(), aug1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum, new Period(jul1994, aug1994)));
// add one range containing another..
periodList1 = new PeriodList();
periodList1.add(monthOctober);
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthNovember);
/*
* SortedSet normalizedSet = normalizer.addDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.add(periodList2);
suite.addTest(new PeriodListTest(sum, 1));
// Period lonePeriod = (Period) sum.toArray()[0];
// assertEquals(lonePeriod.getStart(), oct1994);
// assertEquals(lonePeriod.getEnd(), end1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum, new Period(oct1994, end1994)));
// Test Intersecting Periods
periodList1 = new PeriodList();
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthOctober);
periodList2.add(monthNovember);
/*
* SortedSet normalizedSet = normalizer.addDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.add(periodList2);
suite.addTest(new PeriodListTest(sum, 1));
// Period lonePeriod = (Period) sum.toArray()[0];
// assertEquals(lonePeriod.getStart(), oct1994);
// assertEquals(lonePeriod.getEnd(), end1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum, new Period(oct1994, end1994)));
// Test adding adjacent periods.
periodList1 = new PeriodList();
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthOctober);
/*
* SortedSet normalizedSet = normalizer.addDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.add(periodList2);
suite.addTest(new PeriodListTest(sum, 1));
// Period lonePeriod = (Period) sum.toArray()[0];
// assertEquals(lonePeriod.getStart(), oct1994);
// assertEquals(lonePeriod.getEnd(), end1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum, new Period(oct1994, end1994)));
// Test adding the same range twice
periodList1 = new PeriodList();
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthOctober);
periodList2.add(monthNovember);
/*
* SortedSet normalizedSet1 = normalizer.addDateRanges(dateRangeSet1, dateRangeSet2); SortedSet normalizedSet2 =
* normalizer.addDateRanges(dateRangeSet1, dateRangeSet2);
*/
PeriodList sum1 = periodList1.add(periodList2);
suite.addTest(new PeriodListTest(sum1, 1));
// Period lonePeriod1 = (Period) sum1.toArray()[0];
// assertEquals(lonePeriod1.getStart(), oct1994);
// assertEquals(lonePeriod1.getEnd(), end1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum1, new Period(oct1994, end1994)));
PeriodList sum2 = periodList1.add(periodList2);
suite.addTest(new PeriodListTest(sum2, 1));
// Period lonePeriod2 = (Period) sum2.toArray()[0];
// assertEquals(lonePeriod2.getStart(), oct1994);
// assertEquals(lonePeriod2.getEnd(), end1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum2, new Period(oct1994, end1994)));
// Test subtract a containing date range set..
periodList1 = new PeriodList();
periodList1.add(monthSeptember);
periodList1.add(monthOctober);
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthOctober);
periodList2.add(monthNovember);
/*
* SortedSet normalizedSet = normalizer.subtractDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.subtract(periodList2);
suite.addTest(new PeriodListTest(sum, 2));
// Period lonePeriod1 = (Period) sum.toArray()[0];
// assertEquals(lonePeriod1.getStart(), sep1994);
// assertEquals(lonePeriod1.getEnd(), oct1994);
suite.addTest(new PeriodListTest("testFirstPeriodEquals", sum, new Period(sep1994, oct1994)));
// FIXME: don't use asserts here..
Period lonePeriod2 = (Period) sum.toArray()[1];
assertEquals(lonePeriod2.getStart(), dec1994);
assertEquals(lonePeriod2.getEnd(), end1994);
// Test removing a Disjoint Set of Date Ranges..
periodList1 = new PeriodList();
periodList1.add(monthSeptember);
periodList1.add(monthOctober);
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthApril);
periodList2.add(monthMay);
/*
* SortedSet normalizedSet = normalizer.subtractDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.subtract(periodList2);
suite.addTest(new PeriodListTest(sum, periodList1));
// SubtractSameRangesTwice...
periodList1 = new PeriodList();
periodList1.add(monthSeptember);
periodList1.add(monthOctober);
periodList1.add(monthNovember);
periodList1.add(monthDecember);
periodList2 = new PeriodList();
periodList2.add(monthOctober);
periodList2.add(monthNovember);
PeriodList expectedResult = new PeriodList();
expectedResult.add(monthSeptember);
expectedResult.add(monthDecember);
/*
* SortedSet normalizedSet = normalizer.subtractDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.subtract(periodList2);
suite.addTest(new PeriodListTest(sum, expectedResult));
/*
* normalizedSet = normalizer.subtractDateRanges(dateRangeSet1, dateRangeSet2);
*/
sum = periodList1.subtract(periodList2);
suite.addTest(new PeriodListTest(sum, expectedResult));
// other tests..
suite.addTest(new PeriodListTest("testTimezone"));
suite.addTest(new PeriodListTest("testNormalise"));
return suite;
}
public final void testPeriodListSort() {
PeriodList periods = new PeriodList();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 25);
periods.add(new Period(new DateTime(), new DateTime(cal.getTime()
.getTime())));
periods.add(new Period(new DateTime(cal.getTime().getTime()), new Dur(
0, 2, 0, 0)));
periods.add(new Period(new DateTime(), new Dur(0, 2, 0, 0)));
periods.add(new Period(new DateTime(), new Dur(0, 1, 0, 0)));
// log.info("Unsorted list: " + periods);
// Collections.sort(periods);
log.info("Sorted list: " + periods);
}
/**
* test null init and add test null init test null add test empty init and add test empty init test empty add
* @throws Exception
*/
/*
* public void testEmptyAddPeriods() throws Exception { SortedSet empty1 = new TreeSet(); SortedSet empty2 = new
* TreeSet(); assertNull("Normalizing null sets should return null", normalizer.addDateRanges(null, null));
* assertEquals(headSet, normalizer.addDateRanges(null, headSet)); assertEquals(evenMonths,
* normalizer.addDateRanges(evenMonths, null)); assertEquals(empty1, normalizer.addDateRanges(empty1, empty2));
* assertEquals(headSet, normalizer.addDateRanges(empty1, headSet)); assertEquals(evenMonths,
* normalizer.addDateRanges(evenMonths, empty1)); }
*/
/**
* Test null dateList Test empty dateList Test Jan/Feb/Mar dateList
* @throws Exception
*/
/*
* public void testCreateDateRangeSet() throws Exception { // Test null dateList
* assertNull(normalizer.createDateRangeSet(null, 0)); // Test empty dateList DateList emptyDateList = new
* DateList(Value.DATE_TIME); assertEquals(normalizer.createDateRangeSet(emptyDateList, 0).size(), 0); // Test
* Jan/Feb/Mar dateList DateList dateList1 = new DateList(Value.DATE_TIME); final long EIGHT_HOURS = 1000 * 60 * 60 *
* 8; dateList1.add(jan1994); // Jan 22 dateList1.add(feb1994); // Feb 15 dateList1.add(mar1994); // Mar 4 SortedSet
* dateRangeSet = normalizer.createDateRangeSet(dateList1, EIGHT_HOURS); Object[] objArray = dateRangeSet.toArray();
* DateRange[] dateRangeArray = new DateRange[objArray.length]; for (int i = 0; i < objArray.length; i++) {
* dateRangeArray[i] = (DateRange) objArray[i]; } assertEquals(dateRangeArray[0].getStartDate(), jan1994);
* assertEquals(dateRangeArray[0].getEndDate(), new Date(jan1994.getTime() + EIGHT_HOURS));
* assertEquals(dateRangeArray[1].getStartDate(), feb1994); assertEquals(dateRangeArray[1].getEndDate(), new
* Date(feb1994.getTime() + EIGHT_HOURS)); assertEquals(dateRangeArray[2].getStartDate(), mar1994);
* assertEquals(dateRangeArray[2].getEndDate(), new Date(mar1994.getTime() + EIGHT_HOURS)); }
*/
/**
* Test null ranges
* @throws Exception
*/
/*
* public void testAddNullDateRanges() throws Exception { // Test null ranges.
* assertNull(normalizer.addDateRanges(null, null)); }
*/
/**
* Test subtract null range sets.
* @throws Exception
*/
/*
* public void testSubtractNullDateRanges() throws Exception { assertNull(normalizer.subtractDateRanges(null,
* null)); }
*/
/**
* Test timezone functionality.
*/
public void testTimezone() {
// TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance()
// .createRegistry();
// TimeZone timezone = registry.getTimeZone("Australia/Melbourne");
PeriodList list = new PeriodList(true);
java.util.Calendar cal = java.util.Calendar.getInstance();
for (int i = 0; i < 5; i++) {
DateTime start = new DateTime(cal.getTime());
cal.add(Calendar.DAY_OF_YEAR, 1);
DateTime end = new DateTime(cal.getTime());
list.add(new Period(start, end));
}
log.info("Timezone test - period list: [" + list + "]");
for (Iterator<Period> i = list.iterator(); i.hasNext();) {
Period p = i.next();
assertTrue(p.getStart().isUtc());
assertTrue(p.getEnd().isUtc());
}
}
/**
* Unit tests for {@link PeriodList#normalise()}.
*/
public void testNormalise() {
// test a list of periods consuming no time..
PeriodList periods = new PeriodList();
DateTime start = new DateTime();
periods.add(new Period(start, start));
DateTime start2 = new DateTime();
periods.add(new Period(start2, start2));
assertTrue(periods.normalise().isEmpty());
}
}
|
Java
|
public class TestSCMChillModeManager {
private static EventQueue queue;
private SCMChillModeManager scmChillModeManager;
private static Configuration config;
private List<ContainerInfo> containers;
@Rule
public Timeout timeout = new Timeout(1000 * 35);
@BeforeClass
public static void setUp() {
queue = new EventQueue();
config = new OzoneConfiguration();
}
@Test
public void testChillModeState() throws Exception {
// Test 1: test for 0 containers
testChillMode(0);
// Test 2: test for 20 containers
testChillMode(20);
}
@Test
public void testChillModeStateWithNullContainers() {
new SCMChillModeManager(config, null, null, queue);
}
private void testChillMode(int numContainers) throws Exception {
containers = new ArrayList<>();
containers.addAll(HddsTestUtils.getContainerInfo(numContainers));
// Assign open state to containers to be included in the chill mode
// container list
for (ContainerInfo container : containers) {
container.setState(HddsProtos.LifeCycleState.OPEN);
}
scmChillModeManager = new SCMChillModeManager(
config, containers, null, queue);
assertTrue(scmChillModeManager.getInChillMode());
queue.fireEvent(SCMEvents.NODE_REGISTRATION_CONT_REPORT,
HddsTestUtils.createNodeRegistrationContainerReport(containers));
GenericTestUtils.waitFor(() -> {
return !scmChillModeManager.getInChillMode();
}, 100, 1000 * 5);
}
@Test
public void testChillModeExitRule() throws Exception {
containers = new ArrayList<>();
containers.addAll(HddsTestUtils.getContainerInfo(25 * 4));
// Assign open state to containers to be included in the chill mode
// container list
for (ContainerInfo container : containers) {
container.setState(HddsProtos.LifeCycleState.CLOSED);
}
scmChillModeManager = new SCMChillModeManager(
config, containers, null, queue);
assertTrue(scmChillModeManager.getInChillMode());
testContainerThreshold(containers.subList(0, 25), 0.25);
assertTrue(scmChillModeManager.getInChillMode());
testContainerThreshold(containers.subList(25, 50), 0.50);
assertTrue(scmChillModeManager.getInChillMode());
testContainerThreshold(containers.subList(50, 75), 0.75);
assertTrue(scmChillModeManager.getInChillMode());
testContainerThreshold(containers.subList(75, 100), 1.0);
GenericTestUtils.waitFor(() -> {
return !scmChillModeManager.getInChillMode();
}, 100, 1000 * 5);
}
@Test
@Ignore("TODO:HDDS-1140")
public void testDisableChillMode() {
OzoneConfiguration conf = new OzoneConfiguration(config);
conf.setBoolean(HddsConfigKeys.HDDS_SCM_CHILLMODE_ENABLED, false);
scmChillModeManager = new SCMChillModeManager(
conf, containers, null, queue);
assertFalse(scmChillModeManager.getInChillMode());
}
@Test
public void testChillModeDataNodeExitRule() throws Exception {
containers = new ArrayList<>();
testChillModeDataNodes(0);
testChillModeDataNodes(3);
testChillModeDataNodes(5);
}
/**
* Check that containers in Allocated state are not considered while
* computing percentage of containers with at least 1 reported replica in
* chill mode exit rule.
*/
@Test
public void testContainerChillModeRule() throws Exception {
containers = new ArrayList<>();
// Add 100 containers to the list of containers in SCM
containers.addAll(HddsTestUtils.getContainerInfo(25 * 4));
// Assign CLOSED state to first 25 containers and OPEM state to rest
// of the containers
for (ContainerInfo container : containers.subList(0, 25)) {
container.setState(HddsProtos.LifeCycleState.CLOSED);
}
for (ContainerInfo container : containers.subList(25, 100)) {
container.setState(HddsProtos.LifeCycleState.OPEN);
}
scmChillModeManager = new SCMChillModeManager(
config, containers, null, queue);
assertTrue(scmChillModeManager.getInChillMode());
// When 10 CLOSED containers are reported by DNs, the computed container
// threshold should be 10/25 as there are only 25 CLOSED containers.
// Containers in OPEN state should not contribute towards list of
// containers while calculating container threshold in SCMChillNodeManager
testContainerThreshold(containers.subList(0, 10), 0.4);
assertTrue(scmChillModeManager.getInChillMode());
// When remaining 15 OPEN containers are reported by DNs, the container
// threshold should be (10+15)/25.
testContainerThreshold(containers.subList(10, 25), 1.0);
GenericTestUtils.waitFor(() -> {
return !scmChillModeManager.getInChillMode();
}, 100, 1000 * 5);
}
private void testChillModeDataNodes(int numOfDns) throws Exception {
OzoneConfiguration conf = new OzoneConfiguration(config);
conf.setInt(HddsConfigKeys.HDDS_SCM_CHILLMODE_MIN_DATANODE, numOfDns);
scmChillModeManager = new SCMChillModeManager(
conf, containers, null, queue);
// Assert SCM is in Chill mode.
assertTrue(scmChillModeManager.getInChillMode());
// Register all DataNodes except last one and assert SCM is in chill mode.
for (int i = 0; i < numOfDns-1; i++) {
queue.fireEvent(SCMEvents.NODE_REGISTRATION_CONT_REPORT,
HddsTestUtils.createNodeRegistrationContainerReport(containers));
assertTrue(scmChillModeManager.getInChillMode());
assertTrue(scmChillModeManager.getCurrentContainerThreshold() == 1);
}
if(numOfDns == 0){
GenericTestUtils.waitFor(() -> {
return scmChillModeManager.getInChillMode();
}, 10, 1000 * 10);
return;
}
// Register last DataNode and check that SCM is out of Chill mode.
queue.fireEvent(SCMEvents.NODE_REGISTRATION_CONT_REPORT,
HddsTestUtils.createNodeRegistrationContainerReport(containers));
GenericTestUtils.waitFor(() -> {
return !scmChillModeManager.getInChillMode();
}, 10, 1000 * 10);
}
private void testContainerThreshold(List<ContainerInfo> dnContainers,
double expectedThreshold)
throws Exception {
queue.fireEvent(SCMEvents.NODE_REGISTRATION_CONT_REPORT,
HddsTestUtils.createNodeRegistrationContainerReport(dnContainers));
GenericTestUtils.waitFor(() -> {
double threshold = scmChillModeManager.getCurrentContainerThreshold();
return threshold == expectedThreshold;
}, 100, 2000 * 9);
}
@Test
public void testChillModePipelineExitRule() throws Exception {
containers = new ArrayList<>();
containers.addAll(HddsTestUtils.getContainerInfo(25 * 4));
String storageDir = GenericTestUtils.getTempPath(
TestSCMChillModeManager.class.getName() + UUID.randomUUID());
try{
MockNodeManager nodeManager = new MockNodeManager(true, 3);
config.set(HddsConfigKeys.OZONE_METADATA_DIRS, storageDir);
// enable pipeline check
config.setBoolean(
HddsConfigKeys.HDDS_SCM_CHILLMODE_PIPELINE_AVAILABILITY_CHECK, true);
SCMPipelineManager pipelineManager = new SCMPipelineManager(config,
nodeManager, queue);
PipelineProvider mockRatisProvider =
new MockRatisPipelineProvider(nodeManager,
pipelineManager.getStateManager(), config);
pipelineManager.setPipelineProvider(HddsProtos.ReplicationType.RATIS,
mockRatisProvider);
Pipeline pipeline = pipelineManager.createPipeline(
HddsProtos.ReplicationType.RATIS,
HddsProtos.ReplicationFactor.THREE);
PipelineReportsProto.Builder reportBuilder = PipelineReportsProto
.newBuilder();
reportBuilder.addPipelineReport(PipelineReport.newBuilder()
.setPipelineID(pipeline.getId().getProtobuf()));
scmChillModeManager = new SCMChillModeManager(
config, containers, pipelineManager, queue);
queue.fireEvent(SCMEvents.NODE_REGISTRATION_CONT_REPORT,
HddsTestUtils.createNodeRegistrationContainerReport(containers));
assertTrue(scmChillModeManager.getInChillMode());
// Trigger the processed pipeline report event
queue.fireEvent(SCMEvents.PROCESSED_PIPELINE_REPORT,
new PipelineReportFromDatanode(pipeline.getNodes().get(0),
reportBuilder.build()));
GenericTestUtils.waitFor(() -> {
return !scmChillModeManager.getInChillMode();
}, 100, 1000 * 10);
pipelineManager.close();
} finally {
config.setBoolean(
HddsConfigKeys.HDDS_SCM_CHILLMODE_PIPELINE_AVAILABILITY_CHECK,
false);
FileUtil.fullyDelete(new File(storageDir));
}
}
}
|
Java
|
final class ModifiableBindingMethods {
private final Map<BindingRequest, ModifiableBindingMethod> methods = Maps.newLinkedHashMap();
/** Registers a new method encapsulating a modifiable binding. */
void addNewModifiableMethod(
ModifiableBindingType type,
BindingRequest request,
TypeMirror returnType,
MethodSpec method,
boolean finalized) {
checkArgument(type.isModifiable());
addMethod(ModifiableBindingMethod.create(type, request, returnType, method, finalized));
}
/** Registers a reimplemented modifiable method. */
void addReimplementedMethod(ModifiableBindingMethod method) {
addMethod(method);
}
private void addMethod(ModifiableBindingMethod method) {
ModifiableBindingMethod previousMethod = methods.put(method.request(), method);
verify(
previousMethod == null,
"registering %s but %s is already registered for the same binding request",
method,
previousMethod);
}
/** Returns all {@link ModifiableBindingMethod}s that have not been marked as finalized. */
ImmutableMap<BindingRequest, ModifiableBindingMethod> getNonFinalizedMethods() {
return ImmutableMap.copyOf(Maps.filterValues(methods, m -> !m.finalized()));
}
/** Returns the {@link ModifiableBindingMethod} for the given binding if present. */
Optional<ModifiableBindingMethod> getMethod(BindingRequest request) {
return Optional.ofNullable(methods.get(request));
}
/** Returns all of the {@link ModifiableBindingMethod}s. */
ImmutableList<ModifiableBindingMethod> allMethods() {
return ImmutableList.copyOf(methods.values());
}
/** Whether a given binding has been marked as finalized. */
// TODO(ronshapiro): possibly rename this to something that indicates that the BindingRequest for
// `method` has been finalized in *this* component implementation?
boolean finalized(ModifiableBindingMethod method) {
ModifiableBindingMethod storedMethod = methods.get(method.request());
return storedMethod != null && storedMethod.finalized();
}
@AutoValue
abstract static class ModifiableBindingMethod {
private static ModifiableBindingMethod create(
ModifiableBindingType type,
BindingRequest request,
TypeMirror returnType,
MethodSpec methodSpec,
boolean finalized) {
return new AutoValue_ModifiableBindingMethods_ModifiableBindingMethod(
type, request, MoreTypes.equivalence().wrap(returnType), methodSpec, finalized);
}
/** Creates a {@ModifiableBindingMethod} that reimplements the current method. */
ModifiableBindingMethod reimplement(
ModifiableBindingType newModifiableBindingType,
MethodSpec newImplementation,
boolean finalized) {
return new AutoValue_ModifiableBindingMethods_ModifiableBindingMethod(
newModifiableBindingType, request(), returnTypeWrapper(), newImplementation, finalized);
}
abstract ModifiableBindingType type();
abstract BindingRequest request();
final TypeMirror returnType() {
return returnTypeWrapper().get();
}
abstract Equivalence.Wrapper<TypeMirror> returnTypeWrapper();
abstract MethodSpec methodSpec();
abstract boolean finalized();
/** Whether a {@link ModifiableBindingMethod} is for the same binding request. */
boolean fulfillsSameRequestAs(ModifiableBindingMethod other) {
return request().equals(other.request());
}
}
}
|
Java
|
@Internal
public class HiveFunctionWrapper<UDFType> implements Serializable {
public static final long serialVersionUID = 393313529306818205L;
private final String className;
private transient UDFType instance = null;
public HiveFunctionWrapper(String className) {
this.className = className;
}
/**
* Instantiate a Hive function instance.
*
* @return a Hive function instance
*/
public UDFType createFunction() {
if (instance != null) {
return instance;
} else {
UDFType func = null;
try {
func = getUDFClass().newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new FlinkHiveUDFException(
String.format("Failed to create function from %s", className), e);
}
if (!(func instanceof UDF)) {
// We cache the function if it is not the Simple UDF,
// as we always have to create new instance for Simple UDF.
instance = func;
}
return func;
}
}
/**
* Get class name of the Hive function.
*
* @return class name of the Hive function
*/
public String getClassName() {
return className;
}
/**
* Get class of the Hive function.
*
* @return class of the Hive function
* @throws ClassNotFoundException thrown when the class is not found in classpath
*/
public Class<UDFType> getUDFClass() throws ClassNotFoundException {
return (Class<UDFType>) Thread.currentThread().getContextClassLoader().loadClass(className);
}
}
|
Java
|
public class InvalidLocationsArgumentProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
return Stream.of(
Arguments.of(new Desk().area(DATA_AND_TECHNOLOGY)), // location is null
Arguments.of(new Desk().area(DATA_AND_TECHNOLOGY).location(new DeskLocation().column(12))), // location.row is null
Arguments.of(new Desk().area(DATA_AND_TECHNOLOGY).location(new DeskLocation().row("D"))), // location.column is null
Arguments.of(new Desk().area(DATA_AND_TECHNOLOGY).location(new DeskLocation().row("").column(12))) // location.row is empty
);
}
}
|
Java
|
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Offering implements Serializable, Cloneable, StructuredPojo {
/** The type of currency that is used for billing. The currencyCode used for all reservations is US dollars. */
private String currencyCode;
/** The length of time that your reservation would be active. */
private Integer duration;
/** The unit of measurement for the duration of the offering. */
private String durationUnits;
/** The Amazon Resource Name (ARN) that MediaConnect assigns to the offering. */
private String offeringArn;
/** A description of the offering. */
private String offeringDescription;
/** The cost of a single unit. This value, in combination with priceUnits, makes up the rate. */
private String pricePerUnit;
/**
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the
* rate.
*/
private String priceUnits;
/** A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. */
private ResourceSpecification resourceSpecification;
/**
* The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
*
* @param currencyCode
* The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
*/
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
/**
* The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
*
* @return The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
*/
public String getCurrencyCode() {
return this.currencyCode;
}
/**
* The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
*
* @param currencyCode
* The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Offering withCurrencyCode(String currencyCode) {
setCurrencyCode(currencyCode);
return this;
}
/**
* The length of time that your reservation would be active.
*
* @param duration
* The length of time that your reservation would be active.
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
* The length of time that your reservation would be active.
*
* @return The length of time that your reservation would be active.
*/
public Integer getDuration() {
return this.duration;
}
/**
* The length of time that your reservation would be active.
*
* @param duration
* The length of time that your reservation would be active.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Offering withDuration(Integer duration) {
setDuration(duration);
return this;
}
/**
* The unit of measurement for the duration of the offering.
*
* @param durationUnits
* The unit of measurement for the duration of the offering.
* @see DurationUnits
*/
public void setDurationUnits(String durationUnits) {
this.durationUnits = durationUnits;
}
/**
* The unit of measurement for the duration of the offering.
*
* @return The unit of measurement for the duration of the offering.
* @see DurationUnits
*/
public String getDurationUnits() {
return this.durationUnits;
}
/**
* The unit of measurement for the duration of the offering.
*
* @param durationUnits
* The unit of measurement for the duration of the offering.
* @return Returns a reference to this object so that method calls can be chained together.
* @see DurationUnits
*/
public Offering withDurationUnits(String durationUnits) {
setDurationUnits(durationUnits);
return this;
}
/**
* The unit of measurement for the duration of the offering.
*
* @param durationUnits
* The unit of measurement for the duration of the offering.
* @return Returns a reference to this object so that method calls can be chained together.
* @see DurationUnits
*/
public Offering withDurationUnits(DurationUnits durationUnits) {
this.durationUnits = durationUnits.toString();
return this;
}
/**
* The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
*
* @param offeringArn
* The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
*/
public void setOfferingArn(String offeringArn) {
this.offeringArn = offeringArn;
}
/**
* The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
*
* @return The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
*/
public String getOfferingArn() {
return this.offeringArn;
}
/**
* The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
*
* @param offeringArn
* The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Offering withOfferingArn(String offeringArn) {
setOfferingArn(offeringArn);
return this;
}
/**
* A description of the offering.
*
* @param offeringDescription
* A description of the offering.
*/
public void setOfferingDescription(String offeringDescription) {
this.offeringDescription = offeringDescription;
}
/**
* A description of the offering.
*
* @return A description of the offering.
*/
public String getOfferingDescription() {
return this.offeringDescription;
}
/**
* A description of the offering.
*
* @param offeringDescription
* A description of the offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Offering withOfferingDescription(String offeringDescription) {
setOfferingDescription(offeringDescription);
return this;
}
/**
* The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
*
* @param pricePerUnit
* The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
*/
public void setPricePerUnit(String pricePerUnit) {
this.pricePerUnit = pricePerUnit;
}
/**
* The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
*
* @return The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
*/
public String getPricePerUnit() {
return this.pricePerUnit;
}
/**
* The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
*
* @param pricePerUnit
* The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Offering withPricePerUnit(String pricePerUnit) {
setPricePerUnit(pricePerUnit);
return this;
}
/**
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the
* rate.
*
* @param priceUnits
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up
* the rate.
* @see PriceUnits
*/
public void setPriceUnits(String priceUnits) {
this.priceUnits = priceUnits;
}
/**
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the
* rate.
*
* @return The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up
* the rate.
* @see PriceUnits
*/
public String getPriceUnits() {
return this.priceUnits;
}
/**
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the
* rate.
*
* @param priceUnits
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up
* the rate.
* @return Returns a reference to this object so that method calls can be chained together.
* @see PriceUnits
*/
public Offering withPriceUnits(String priceUnits) {
setPriceUnits(priceUnits);
return this;
}
/**
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the
* rate.
*
* @param priceUnits
* The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up
* the rate.
* @return Returns a reference to this object so that method calls can be chained together.
* @see PriceUnits
*/
public Offering withPriceUnits(PriceUnits priceUnits) {
this.priceUnits = priceUnits.toString();
return this;
}
/**
* A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering.
*
* @param resourceSpecification
* A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering.
*/
public void setResourceSpecification(ResourceSpecification resourceSpecification) {
this.resourceSpecification = resourceSpecification;
}
/**
* A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering.
*
* @return A definition of the amount of outbound bandwidth that you would be reserving if you purchase the
* offering.
*/
public ResourceSpecification getResourceSpecification() {
return this.resourceSpecification;
}
/**
* A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering.
*
* @param resourceSpecification
* A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Offering withResourceSpecification(ResourceSpecification resourceSpecification) {
setResourceSpecification(resourceSpecification);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCurrencyCode() != null)
sb.append("CurrencyCode: ").append(getCurrencyCode()).append(",");
if (getDuration() != null)
sb.append("Duration: ").append(getDuration()).append(",");
if (getDurationUnits() != null)
sb.append("DurationUnits: ").append(getDurationUnits()).append(",");
if (getOfferingArn() != null)
sb.append("OfferingArn: ").append(getOfferingArn()).append(",");
if (getOfferingDescription() != null)
sb.append("OfferingDescription: ").append(getOfferingDescription()).append(",");
if (getPricePerUnit() != null)
sb.append("PricePerUnit: ").append(getPricePerUnit()).append(",");
if (getPriceUnits() != null)
sb.append("PriceUnits: ").append(getPriceUnits()).append(",");
if (getResourceSpecification() != null)
sb.append("ResourceSpecification: ").append(getResourceSpecification());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Offering == false)
return false;
Offering other = (Offering) obj;
if (other.getCurrencyCode() == null ^ this.getCurrencyCode() == null)
return false;
if (other.getCurrencyCode() != null && other.getCurrencyCode().equals(this.getCurrencyCode()) == false)
return false;
if (other.getDuration() == null ^ this.getDuration() == null)
return false;
if (other.getDuration() != null && other.getDuration().equals(this.getDuration()) == false)
return false;
if (other.getDurationUnits() == null ^ this.getDurationUnits() == null)
return false;
if (other.getDurationUnits() != null && other.getDurationUnits().equals(this.getDurationUnits()) == false)
return false;
if (other.getOfferingArn() == null ^ this.getOfferingArn() == null)
return false;
if (other.getOfferingArn() != null && other.getOfferingArn().equals(this.getOfferingArn()) == false)
return false;
if (other.getOfferingDescription() == null ^ this.getOfferingDescription() == null)
return false;
if (other.getOfferingDescription() != null && other.getOfferingDescription().equals(this.getOfferingDescription()) == false)
return false;
if (other.getPricePerUnit() == null ^ this.getPricePerUnit() == null)
return false;
if (other.getPricePerUnit() != null && other.getPricePerUnit().equals(this.getPricePerUnit()) == false)
return false;
if (other.getPriceUnits() == null ^ this.getPriceUnits() == null)
return false;
if (other.getPriceUnits() != null && other.getPriceUnits().equals(this.getPriceUnits()) == false)
return false;
if (other.getResourceSpecification() == null ^ this.getResourceSpecification() == null)
return false;
if (other.getResourceSpecification() != null && other.getResourceSpecification().equals(this.getResourceSpecification()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCurrencyCode() == null) ? 0 : getCurrencyCode().hashCode());
hashCode = prime * hashCode + ((getDuration() == null) ? 0 : getDuration().hashCode());
hashCode = prime * hashCode + ((getDurationUnits() == null) ? 0 : getDurationUnits().hashCode());
hashCode = prime * hashCode + ((getOfferingArn() == null) ? 0 : getOfferingArn().hashCode());
hashCode = prime * hashCode + ((getOfferingDescription() == null) ? 0 : getOfferingDescription().hashCode());
hashCode = prime * hashCode + ((getPricePerUnit() == null) ? 0 : getPricePerUnit().hashCode());
hashCode = prime * hashCode + ((getPriceUnits() == null) ? 0 : getPriceUnits().hashCode());
hashCode = prime * hashCode + ((getResourceSpecification() == null) ? 0 : getResourceSpecification().hashCode());
return hashCode;
}
@Override
public Offering clone() {
try {
return (Offering) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.mediaconnect.model.transform.OfferingMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
Java
|
public class InnerJoinOnlyAbortableResultJoinNodeVisitor implements AbortableResultJoinNodeVisitor<Boolean> {
public static final InnerJoinOnlyAbortableResultJoinNodeVisitor INSTANCE = new InnerJoinOnlyAbortableResultJoinNodeVisitor();
private InnerJoinOnlyAbortableResultJoinNodeVisitor() {
}
@Override
public Boolean getStopValue() {
return Boolean.TRUE;
}
@Override
public Boolean visit(JoinNode node) {
return node.getJoinType() != null && node.getJoinType() != JoinType.INNER;
}
}
|
Java
|
public final class DCTMJaxbContext {
private final static JAXBContext context;
static {
JAXBContext c = null;
try {
c = JAXBContext.newInstance("com.emc.documentum.rest.client.sample.model.xml.jaxb");
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
context = c;
}
public static Object unmarshal(Node node) {
Object obj = null;
try {
obj = context.createUnmarshaller().unmarshal(node);
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
}
return obj;
}
public static Object unmarshal(String xml) {
Object obj = null;
try {
obj = context.createUnmarshaller().unmarshal(new ByteArrayInputStream(xml.getBytes()));
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
}
return obj;
}
public static void marshal(OutputStream os, Object object) {
try {
context.createMarshaller().marshal(object, os);
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
}
}
public static String marshal(Object object) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
context.createMarshaller().marshal(object, os);
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
}
return os.toString();
}
}
|
Java
|
public class Tuple {
public final Pair pair;
public final double f;
Tuple(Pair pair, double f) {
this.pair = pair;
this.f = f;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Tuple other = (Tuple) obj;
return this.pair.equals(other.pair) && Math.abs(other.f - this.f) <= 1e-8;
}
}
|
Java
|
@Service("helloWorldRecordService")
public class HelloWorldRecordServiceImpl implements HelloWorldRecordService {
@Autowired
private HelloWorldRecordsDataService helloWorldRecordsDataService;
@Override
public void create(String name, String message) {
helloWorldRecordsDataService.create(
new HelloWorldRecord(name, message)
);
}
@Override
public void add(HelloWorldRecord record) {
helloWorldRecordsDataService.create(record);
}
@Override
public HelloWorldRecord findRecordByName(String recordName) {
HelloWorldRecord record = helloWorldRecordsDataService.findRecordByName(recordName);
if (null == record) {
return null;
}
return record;
}
@Override
public List<HelloWorldRecord> getRecords() {
return helloWorldRecordsDataService.retrieveAll();
}
@Override
public void update(HelloWorldRecord record) {
helloWorldRecordsDataService.update(record);
}
@Override
public void delete(HelloWorldRecord record) {
helloWorldRecordsDataService.delete(record);
}
}
|
Java
|
public class Problem001 implements Problem {
@Override
public long solve() {
return LongStream.range(1, 1000).
filter(value -> value % 3 == 0 || value % 5 == 0).
sum();
}
}
|
Java
|
public class ClientHandshakePacket extends DefaultByteBufHolder implements ClientPacket {
private final long timestamp = System.currentTimeMillis();
private final Set<CapabilityFlags> capabilities = EnumSet.noneOf(CapabilityFlags.class);
private final int sequenceId;
private final int maxPacketSize;
private final MysqlCharacterSet characterSet;
private final String username;
private final String database;
private final String authPluginName;
private final Map<String, String> attributes = new LinkedHashMap<String, String>();
private ClientHandshakePacket(Builder builder) {
super(builder.authPluginData);
this.capabilities.addAll(builder.capabilities);
this.sequenceId = builder.sequenceId;
this.maxPacketSize = builder.maxPacketSize;
this.characterSet = builder.characterSet;
this.username = builder.username;
this.database = builder.database;
this.authPluginName = builder.authPluginName;
this.attributes.putAll(builder.attributes);
}
public static Builder create() {
return new Builder();
}
public static ClientHandshakePacket createSslResponse(Set<CapabilityFlags> capabilities, int maxPacketSize,
MysqlCharacterSet characterSet) {
return create()
.maxPacketSize(maxPacketSize)
.characterSet(characterSet)
.addCapabilities(capabilities)
.addCapabilities(CapabilityFlags.CLIENT_SSL)
.build();
}
public ByteBuf getAuthPluginData() {
return content();
}
public Set<CapabilityFlags> getCapabilities() {
return EnumSet.copyOf(capabilities);
}
public int getMaxPacketSize() {
return maxPacketSize;
}
public MysqlCharacterSet getCharacterSet() {
return characterSet;
}
public String getUsername() {
return username;
}
public String getDatabase() {
return database;
}
public String getAuthPluginName() {
return authPluginName;
}
public Map<String, String> getAttributes() {
return attributes;
}
@Override
public long getTimestamp() {
return timestamp;
}
@Override
public int getSequenceId() {
return sequenceId;
}
@Override
public String toString() {
return getClass().getSimpleName()+","+database+","+username+","+attributes;
}
public static class Builder extends AbstractAuthPluginDataBuilder<Builder> {
private int maxPacketSize = Constants.DEFAULT_MAX_PACKET_SIZE;
private int sequenceId;
private MysqlCharacterSet characterSet = MysqlCharacterSet.DEFAULT;
private String username;
private String database;
private String authPluginName;
private Map<String, String> attributes = new LinkedHashMap<>();
public Builder sequenceId(int sequenceId) {
this.sequenceId = sequenceId;
return this;
}
public Builder maxPacketSize(int maxPacketSize) {
this.maxPacketSize = maxPacketSize;
return this;
}
public Builder characterSet(MysqlCharacterSet characterSet) {
if(characterSet != null) {
this.characterSet = characterSet;
}
return this;
}
public Builder username(String username) {
this.username = username;
return this;
}
public Builder database(String database) {
addCapabilities(CapabilityFlags.CLIENT_CONNECT_WITH_DB);
this.database = database;
return this;
}
public Builder authPluginName(String authPluginName) {
addCapabilities(CapabilityFlags.CLIENT_PLUGIN_AUTH);
this.authPluginName = authPluginName;
return this;
}
public Builder addAttribute(String key, String value) {
attributes.put(key, value);
return this;
}
public ClientHandshakePacket build() {
return new ClientHandshakePacket(this);
}
}
}
|
Java
|
public class DataCompletenessScheduler {
private static final Logger LOG = LoggerFactory.getLogger(DataCompletenessScheduler.class);
private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
private DataCompletenessJobRunner dataCompletenessJobRunner;
private DataCompletenessJobContext dataCompletenessJobContext;
public void start() {
LOG.info("Starting data completeness checker service");
dataCompletenessJobContext = new DataCompletenessJobContext();
dataCompletenessJobRunner = new DataCompletenessJobRunner(dataCompletenessJobContext);
scheduledExecutorService.scheduleAtFixedRate(dataCompletenessJobRunner, 0, 15, TimeUnit.MINUTES);
}
public void shutdown() {
AnomalyUtils.safelyShutdownExecutionService(scheduledExecutorService, this.getClass());
}
}
|
Java
|
public class RunAsUserToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Class<? extends Authentication> originalAuthentication;
private final Object credentials;
private final Object principal;
private final int keyHash;
public RunAsUserToken(String key, Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities,
Class<? extends Authentication> originalAuthentication) {
super(authorities);
this.keyHash = key.hashCode();
this.principal = principal;
this.credentials = credentials;
this.originalAuthentication = originalAuthentication;
setAuthenticated(true);
}
@Override
public Object getCredentials() {
return this.credentials;
}
public int getKeyHash() {
return this.keyHash;
}
public Class<? extends Authentication> getOriginalAuthentication() {
return this.originalAuthentication;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(super.toString());
String className = (this.originalAuthentication != null) ? this.originalAuthentication.getName() : null;
sb.append("; Original Class: ").append(className);
return sb.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.