hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
7816cd6560cd685e6996a14f8ed7572affa0eb53
| 1,887
|
package de.metas.contracts.flatrate.process;
import de.metas.contracts.model.I_C_Flatrate_Term;
import de.metas.process.PInstanceId;
import de.metas.process.RunOutOfTrx;
import de.metas.util.Services;
import org.adempiere.ad.dao.IQueryBL;
import org.adempiere.ad.dao.IQueryBuilder;
import org.adempiere.ad.dao.IQueryFilter;
import org.adempiere.exceptions.AdempiereException;
import org.compiere.model.IQuery;
public class C_Flatrate_Term_Change extends C_Flatrate_Term_Change_Base
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@Override
@RunOutOfTrx
protected void prepare()
{
final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = createQueryBuilder();
final int selectionCount = createSelection(queryBuilder, getPinstanceId());
if (selectionCount <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
@Override
protected Iterable<I_C_Flatrate_Term> getFlatrateTermsToChange()
{
return retrieveSelection(getPinstanceId());
}
private IQueryBuilder<I_C_Flatrate_Term> createQueryBuilder()
{
final IQueryFilter<I_C_Flatrate_Term> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
.createQueryBuilder(I_C_Flatrate_Term.class)
.filter(userSelectionFilter)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient();
}
private final Iterable<I_C_Flatrate_Term> retrieveSelection(final PInstanceId adPInstanceId)
{
return () -> queryBL
.createQueryBuilder(I_C_Flatrate_Term.class)
.setOnlySelection(adPInstanceId)
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMN_C_Flatrate_Term_ID)
.endOrderBy()
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, false)
.setOption(IQuery.OPTION_IteratorBufferSize, 50)
.iterate(I_C_Flatrate_Term.class);
}
}
| 29.484375
| 106
| 0.785374
|
41a9b86d961cc6cc466cd13d921a67b1a86d5a8f
| 110
|
package com.topnotch.variables;
public interface AppConstants {
public static final String USER = "user";
}
| 18.333333
| 42
| 0.772727
|
b477ccd46fc6718d099e94d31b1cc7cd4507535e
| 1,039
|
package zer0n1.multiversion.mixin;
import net.minecraft.block.BlockBase;
import net.minecraft.block.Grass;
import net.minecraft.block.material.Material;
import net.minecraft.level.BlockView;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import zer0n1.multiversion.protocol.ProtocolManager;
@Mixin(Grass.class)
public abstract class MixinGrass extends BlockBase
{
protected MixinGrass(int id, Material material) {
super(id, material);
}
@Inject(method = "getColourMultiplier(Lnet/minecraft/level/BlockView;III)I", at = @At("HEAD"), cancellable = true)
public void injectGetColourMultiplier(BlockView tileView, int x, int y, int z, CallbackInfoReturnable<Integer> cir) {
if(ProtocolManager.version() == 2) {
cir.setReturnValue(super.getColourMultiplier(tileView, x, y, z));
}
}
}
| 38.481481
| 122
| 0.74206
|
eaa7ca910f065717e97ff98a4786b1e8225d126c
| 5,526
|
package de.gurkenlabs.litiengine.graphics.emitters.particles;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.GameTime;
import de.gurkenlabs.litiengine.physics.Collision;
import de.gurkenlabs.litiengine.physics.PhysicsEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.MockedStatic;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mockStatic;
public class ParticleTests {
private Particle particle;
@BeforeEach
public void setUp(){
// arrange
particle = new TextParticle("test");
}
@Test
public void testUpdate_hasCollision(){
// arrange
Particle testParticle = spy(particle);
Game.init(Game.COMMADLINE_ARG_NOGUI);
// act
testParticle.update(new Point2D.Double(1, 1), 1.2f);
// assert
verify(testParticle, atLeast(3)).applyUpdateRatioToMember(any(Supplier.class), any(Consumer.class), any(float.class), any(float.class));
}
@Test
public void testUpdate_ttlExpired(){
// arrange
Particle testParticle = spy(particle);
when(testParticle.getAliveTime()).thenReturn(100000l);
when(testParticle.getTimeToLive()).thenReturn(10);
Game.init(Game.COMMADLINE_ARG_NOGUI);
// act
testParticle.update(new Point2D.Double(1, 1), 1.2f);
// assert
verify(testParticle, never()).applyUpdateRatioToMember(any(Supplier.class), any(Consumer.class), any(float.class), any(float.class));
}
@Test
public void testUpdate_hasNoCollision(){
// arrange
Particle testParticle = spy(particle);
testParticle.setX(10);
testParticle.setY(42);
testParticle.setVelocityX(5);
testParticle.setVelocityY(10);
Game.init(Game.COMMADLINE_ARG_NOGUI);
// act
testParticle.update(new Point2D.Double(1, 1), 1.2f);
// assert
verify(testParticle, atLeast(5)).applyUpdateRatioToMember(any(Supplier.class), any(Consumer.class), any(float.class), any(float.class));
}
@Test
public void testUpdate_colliding(){
// arrange
Particle testParticle = spy(particle);
PhysicsEngine physicsEngine = mock(PhysicsEngine.class);
GameTime gameTime = mock(GameTime.class);
when(physicsEngine.collides(any(Line2D.class), any(Collision.class))).thenReturn(true);
when(gameTime.now()).thenReturn(100000l);
try(MockedStatic<Game> gameMockedStatic = mockStatic(Game.class)) {
gameMockedStatic.when(Game::physics).thenReturn(physicsEngine);
gameMockedStatic.when(Game::time).thenReturn(gameTime);
testParticle.setVelocityX(5);
testParticle.setVelocityY(5);
testParticle.setContinuousCollision(true);
testParticle.setCollisionType(Collision.ANY);
// act
testParticle.update(new Point2D.Double(1, 1), 1.2f);
testParticle.update(new Point2D.Double(1, 1), 1.2f);
// assert
verify(testParticle, atMost(5)).applyUpdateRatioToMember(any(Supplier.class), any(Consumer.class), any(float.class), any(float.class));
}
}
@Test
public void testApplyUpdateRatioToMember(){
// act
particle.applyUpdateRatioToMember(particle::getWidth, particle::setWidth, 1.2f, 1.0f);
// assert
assertEquals(2.2f, particle.getWidth());
}
@Test
public void testHasRayCastCollision_hasHit(){
// arrange
particle.setX(1);
particle.setY(1);
// act
boolean result = particle.hasRayCastCollision(new Point2D.Double(1, 1), 1.0f);
// assert
assertTrue(result);
}
@Test
public void testHasRayCastCollision_hasCollision(){
// arrange
PhysicsEngine physicsEngine = mock(PhysicsEngine.class);
when(physicsEngine.collides(any(Line2D.class), any(Collision.class))).thenReturn(true);
try(MockedStatic<Game> gameMockedStatic = mockStatic(Game.class)) {
gameMockedStatic.when(Game::physics).thenReturn(physicsEngine);
particle.setX(10);
particle.setY(42);
particle.setVelocityX(5);
particle.setVelocityY(5);
particle.setContinuousCollision(true);
particle.setCollisionType(Collision.ANY);
// act
boolean result = particle.hasRayCastCollision(new Point2D.Double(42, 42), 1f);
// assert
assertTrue(result);
}
}
@ParameterizedTest(name = "testHasRayCastCollision_hasNoCollision velocityX={0}, velocityY={1}")
@CsvSource({
"5, 5",
"0, 5",
"5, 0"
})
public void testHasRayCastCollision_hasNoCollision(float velocityX, float velocityY){
// arrange
particle.setX(10);
particle.setY(42);
particle.setVelocityX(velocityX);
particle.setVelocityY(velocityY);
// act
boolean result = particle.hasRayCastCollision(new Point2D.Double(42, 42), 1f);
// assert
assertFalse(result);
}
}
| 32.698225
| 147
| 0.655085
|
489f2b55c9b529b86964b322cc99e6f7ad788409
| 63
|
package com.github.t1.webresource;
public class PageFooter {}
| 15.75
| 34
| 0.793651
|
8434c049ca93ba7cb6e6f73206e2dfc07d3e6ded
| 2,143
|
package io.crnk.client.inheritance;
import io.crnk.client.AbstractClientTest;
import io.crnk.client.inheritance.repositories.cyclic.CyclicResourceARepository;
import io.crnk.client.inheritance.repositories.cyclic.CyclicResourceBRespository;
import io.crnk.client.inheritance.repositories.cyclic.CyclicResourceCRepository;
import io.crnk.client.inheritance.repositories.related.RelatedResourceARepository;
import io.crnk.client.inheritance.repositories.related.RelatedResourceBRepository;
import io.crnk.client.inheritance.resources.cyclic.CyclicResourceA;
import io.crnk.client.inheritance.resources.related.RelatedResourceA;
import io.crnk.client.inheritance.resources.related.RelatedResourceAsub1;
import io.crnk.core.module.SimpleModule;
import io.crnk.core.queryspec.QuerySpec;
import org.junit.Assert;
import org.junit.Test;
/**
* Examples makes use of Inheritance of resources that share a common resource path. Make sure it correctly handles
* multiple resources with same path and able to find fields on subtypes.
*
* @author syri.
*/
public class SamePathInheritanceClientTest extends AbstractClientTest {
@Override
protected TestApplication configure() {
TestApplication app = super.configure();
SimpleModule cyclicModule = new SimpleModule("crnk-test");
cyclicModule.addRepository(new CyclicResourceARepository());
cyclicModule.addRepository(new CyclicResourceBRespository());
cyclicModule.addRepository(new CyclicResourceCRepository());
cyclicModule.addRepository(new RelatedResourceARepository());
cyclicModule.addRepository(new RelatedResourceBRepository());
app.getFeature().addModule(cyclicModule);
return app;
}
@Test
public void testInheritedRelation() {
QuerySpec querySpec = new QuerySpec(RelatedResourceA.class);
RelatedResourceA resource = client.getRepositoryForType(RelatedResourceA.class).findOne(1L, querySpec);
RelatedResourceAsub1 subResource = (RelatedResourceAsub1) resource;
Assert.assertEquals(1, subResource.getRelatedResourceBS().size());
}
@Test
public void testCyclicRelationsRepository() {
// Crash
client.getRepositoryForType(CyclicResourceA.class);
}
}
| 39.685185
| 115
| 0.822212
|
33cd7c3545079d16a33a16304c2543ea4c0bfb5c
| 13,408
|
/*
* This file was automatically generated by EvoSuite
* Mon Jun 01 14:28:58 GMT 2020
*/
package com.capitalone.dashboard.model.score.settings;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.capitalone.dashboard.model.score.settings.BuildScoreSettings;
import com.capitalone.dashboard.model.score.settings.ScoreCriteria;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class BuildScoreSettings_ESTest extends BuildScoreSettings_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setNumberOfDays(1372);
buildScoreSettings0.toString();
assertEquals(1372, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test01() throws Throwable {
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
buildScoreSettings_BuildDurationScoreSettings0.setDisabled(true);
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setStatus(buildScoreSettings_BuildDurationScoreSettings0);
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings1 = (BuildScoreSettings.BuildDurationScoreSettings)buildScoreSettings0.getStatus();
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings1.getBuildDurationThresholdInMillis());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test02() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setStatus(buildScoreSettings0);
buildScoreSettings0.setWeight(14);
BuildScoreSettings buildScoreSettings1 = (BuildScoreSettings)buildScoreSettings0.getStatus();
assertEquals(14, buildScoreSettings1.getNumberOfDays());
}
@Test(timeout = 4000)
public void test03() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setWeight((-2889));
buildScoreSettings0.setStatus(buildScoreSettings0);
BuildScoreSettings buildScoreSettings1 = (BuildScoreSettings)buildScoreSettings0.getStatus();
assertEquals(14, buildScoreSettings1.getNumberOfDays());
}
@Test(timeout = 4000)
public void test04() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
buildScoreSettings0.setNumberOfDays(0);
int int0 = buildScoreSettings0.getNumberOfDays();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test05() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
buildScoreSettings0.setNumberOfDays((-1));
int int0 = buildScoreSettings0.getNumberOfDays();
assertEquals((-1), int0);
}
@Test(timeout = 4000)
public void test06() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
buildScoreSettings0.setDuration(buildScoreSettings_BuildDurationScoreSettings0);
buildScoreSettings_BuildDurationScoreSettings0.setDisabled(true);
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings1 = buildScoreSettings0.getDuration();
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings1.getBuildDurationThresholdInMillis());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test07() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
buildScoreSettings_BuildDurationScoreSettings0.setWeight(125);
buildScoreSettings0.setDuration(buildScoreSettings_BuildDurationScoreSettings0);
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings1 = buildScoreSettings0.getDuration();
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings1.getBuildDurationThresholdInMillis());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test08() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
buildScoreSettings0.setDuration(buildScoreSettings_BuildDurationScoreSettings0);
buildScoreSettings_BuildDurationScoreSettings0.setWeight((-544));
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings1 = buildScoreSettings0.getDuration();
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings1.getBuildDurationThresholdInMillis());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test09() throws Throwable {
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setDuration(buildScoreSettings_BuildDurationScoreSettings0);
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings0.getBuildDurationThresholdInMillis());
buildScoreSettings_BuildDurationScoreSettings0.setBuildDurationThresholdInMillis(0L);
buildScoreSettings0.getDuration();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test10() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
buildScoreSettings_BuildDurationScoreSettings0.setBuildDurationThresholdInMillis((-221));
buildScoreSettings0.setDuration(buildScoreSettings_BuildDurationScoreSettings0);
assertEquals((-221L), buildScoreSettings_BuildDurationScoreSettings0.getBuildDurationThresholdInMillis());
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings1 = buildScoreSettings0.getDuration();
assertEquals((-221L), buildScoreSettings_BuildDurationScoreSettings1.getBuildDurationThresholdInMillis());
}
@Test(timeout = 4000)
public void test11() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setDisabled(true);
BuildScoreSettings buildScoreSettings1 = BuildScoreSettings.cloneBuildScoreSettings(buildScoreSettings0);
assertTrue(buildScoreSettings1.isDisabled());
assertNotSame(buildScoreSettings1, buildScoreSettings0);
assertEquals(14, buildScoreSettings1.getNumberOfDays());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test12() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setWeight(1156);
BuildScoreSettings buildScoreSettings1 = BuildScoreSettings.cloneBuildScoreSettings(buildScoreSettings0);
assertEquals(1156, buildScoreSettings1.getWeight());
assertNotSame(buildScoreSettings1, buildScoreSettings0);
assertEquals(14, buildScoreSettings1.getNumberOfDays());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test13() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.setWeight((-2407));
BuildScoreSettings buildScoreSettings1 = BuildScoreSettings.cloneBuildScoreSettings(buildScoreSettings0);
assertNotSame(buildScoreSettings1, buildScoreSettings0);
assertEquals(14, buildScoreSettings1.getNumberOfDays());
assertEquals((-2407), buildScoreSettings1.getWeight());
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test14() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
buildScoreSettings0.setNumberOfDays(0);
BuildScoreSettings.cloneBuildScoreSettings(buildScoreSettings0);
assertEquals(0, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test15() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
buildScoreSettings0.setNumberOfDays((-1));
BuildScoreSettings.cloneBuildScoreSettings(buildScoreSettings0);
assertEquals((-1), buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test16() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
ScoreCriteria scoreCriteria0 = new ScoreCriteria();
buildScoreSettings0.setCriteria(scoreCriteria0);
// Undeclared exception!
try {
BuildScoreSettings.cloneBuildScoreSettings(buildScoreSettings0);
fail("Expecting exception: NoClassDefFoundError");
} catch(NoClassDefFoundError e) {
//
// org/apache/commons/collections/CollectionUtils
//
verifyException("com.capitalone.dashboard.model.score.settings.ScoreCriteria", e);
}
}
@Test(timeout = 4000)
public void test17() throws Throwable {
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = BuildScoreSettings.BuildDurationScoreSettings.cloneBuildDurationScoreSettings((BuildScoreSettings.BuildDurationScoreSettings) null);
assertNull(buildScoreSettings_BuildDurationScoreSettings0);
}
@Test(timeout = 4000)
public void test18() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.getStatus();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test19() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
buildScoreSettings0.getDuration();
assertEquals(14, buildScoreSettings0.getNumberOfDays());
}
@Test(timeout = 4000)
public void test20() throws Throwable {
BuildScoreSettings buildScoreSettings0 = new BuildScoreSettings();
int int0 = buildScoreSettings0.getNumberOfDays();
assertEquals(14, int0);
}
@Test(timeout = 4000)
public void test21() throws Throwable {
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
long long0 = buildScoreSettings_BuildDurationScoreSettings0.getBuildDurationThresholdInMillis();
assertEquals(300000L, long0);
}
@Test(timeout = 4000)
public void test22() throws Throwable {
BuildScoreSettings buildScoreSettings0 = BuildScoreSettings.cloneBuildScoreSettings((BuildScoreSettings) null);
assertNull(buildScoreSettings0);
}
@Test(timeout = 4000)
public void test23() throws Throwable {
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
String string0 = buildScoreSettings_BuildDurationScoreSettings0.toString();
assertEquals("BuildDurationScoreSettings{buildDurationThresholdInMillis=300000, disabled=false, weight=0, criteria=null}", string0);
}
@Test(timeout = 4000)
public void test24() throws Throwable {
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings0 = new BuildScoreSettings.BuildDurationScoreSettings();
BuildScoreSettings.BuildDurationScoreSettings buildScoreSettings_BuildDurationScoreSettings1 = BuildScoreSettings.BuildDurationScoreSettings.cloneBuildDurationScoreSettings(buildScoreSettings_BuildDurationScoreSettings0);
assertNotSame(buildScoreSettings_BuildDurationScoreSettings1, buildScoreSettings_BuildDurationScoreSettings0);
assertNotNull(buildScoreSettings_BuildDurationScoreSettings1);
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings1.getBuildDurationThresholdInMillis());
assertEquals(300000L, buildScoreSettings_BuildDurationScoreSettings0.getBuildDurationThresholdInMillis());
}
}
| 51.175573
| 233
| 0.791095
|
c7e9a47ccbc9c5bb9530181761326d63baa5cdda
| 2,485
|
package dev.flashlabs.flashlibs.inventory;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.item.inventory.ClickInventoryEvent;
import org.spongepowered.api.event.item.inventory.InteractInventoryEvent;
import org.spongepowered.api.item.inventory.transaction.SlotTransaction;
import java.util.function.Consumer;
/**
* Represents an active inventory event connected to a {@link View}, such as
* opening/closing the inventory or clicking a slot.
*/
public class Action<T extends InteractInventoryEvent> {
private final T event;
private final Player player;
private final View view;
Action(T event, Player player, View view) {
this.event = event;
this.player = player;
this.view = view;
}
/**
* Returns the inventory event, which is initially cancelled for
* {@link Click}s.
*/
public final T getEvent() {
return event;
}
/**
* Returns the player causing this event.
*/
public final Player getPlayer() {
return player;
}
/**
* Adds a callback which is executed after this event has completed. The
* callback is given access to the view linked to this event.
*
* Any actions which can cause an inventory event, such as modifying a slot
* or opening/closing an inventory, must be done through a callback.
*/
public final void callback(Consumer<View> callback) {
view.execute(callback);
}
/**
* An action for clicks that provides the slot transaction and index. The
* incoming event is always cancelled, but can be uncanceled to allow the
* event to proceed.
*/
public static final class Click extends Action<ClickInventoryEvent> {
private final SlotTransaction slot;
private final int index;
Click(ClickInventoryEvent event, Player player, View view, SlotTransaction slot, int index) {
super(event, player, view);
this.slot = slot;
this.index = index;
}
/**
* Returns the slot transaction corresponding to this click. The result
* can only be modified if the event is not cancelled.
*/
public SlotTransaction getSlot() {
return slot;
}
/**
* Returns the index of the slot corresponding to the linked view.
*/
public int getIndex() {
return index;
}
}
}
| 28.895349
| 101
| 0.647485
|
5d5ae71c5248ba9068785989d2b94406d961cfb4
| 3,878
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.zhengcaiyun.idata.develop.dto.job;
import cn.zhengcaiyun.idata.develop.constant.enums.JobTypeEnum;
import cn.zhengcaiyun.idata.develop.dto.job.di.DiJobDetailsDto;
import cn.zhengcaiyun.idata.develop.dto.job.kylin.KylinJobDto;
import cn.zhengcaiyun.idata.develop.dto.job.script.ScriptJobContentDto;
import cn.zhengcaiyun.idata.develop.dto.job.spark.SparkJobDetailsDto;
import cn.zhengcaiyun.idata.develop.dto.job.sql.SqlJobDetailsDto;
/**
* @author caizhedong
* @date 2021-11-29 上午9:16
*/
public class JobDetailsDto {
private JobTypeEnum jobType;
private String driverMemory;
private String executorMemory;
private int executorCores;
private String yarnQueue;
// JobTypeEnum.engine
private String engineType;
private DiJobDetailsDto diJobDetails;
private SqlJobDetailsDto sqlJobDetails;
private SparkJobDetailsDto sparkJobDetails;
private KylinJobDto kylinJobDetails;
private ScriptJobContentDto scriptJobDetails;
// GaS
public JobTypeEnum getJobType() {
return jobType;
}
public void setJobType(JobTypeEnum jobType) {
this.jobType = jobType;
}
public String getDriverMemory() {
return driverMemory;
}
public void setDriverMemory(String driverMemory) {
this.driverMemory = driverMemory;
}
public String getExecutorMemory() {
return executorMemory;
}
public void setExecutorMemory(String executorMemory) {
this.executorMemory = executorMemory;
}
public int getExecutorCores() {
return executorCores;
}
public void setExecutorCores(int executorCores) {
this.executorCores = executorCores;
}
public String getYarnQueue() {
return yarnQueue;
}
public void setYarnQueue(String yarnQueue) {
this.yarnQueue = yarnQueue;
}
public String getEngineType() {
return engineType;
}
public void setEngineType(String engineType) {
this.engineType = engineType;
}
public DiJobDetailsDto getDiJobDetails() {
return diJobDetails;
}
public void setDiJobDetails(DiJobDetailsDto diJobDetails) {
this.diJobDetails = diJobDetails;
}
public SqlJobDetailsDto getSqlJobDetails() {
return sqlJobDetails;
}
public void setSqlJobDetails(SqlJobDetailsDto sqlJobDetails) {
this.sqlJobDetails = sqlJobDetails;
}
public SparkJobDetailsDto getSparkJobDetails() {
return sparkJobDetails;
}
public void setSparkJobDetails(SparkJobDetailsDto sparkJobDetails) {
this.sparkJobDetails = sparkJobDetails;
}
public KylinJobDto getKylinJobDetails() {
return kylinJobDetails;
}
public void setKylinJobDetails(KylinJobDto kylinJobDetails) {
this.kylinJobDetails = kylinJobDetails;
}
public ScriptJobContentDto getScriptJobDetails() {
return scriptJobDetails;
}
public void setScriptJobDetails(ScriptJobContentDto scriptJobDetails) {
this.scriptJobDetails = scriptJobDetails;
}
}
| 28.725926
| 75
| 0.720474
|
7cede0d324b46aa57fd2b2eb668d88f9fac2c56c
| 1,100
|
public class Organism {
int x;
int y;
public enum Direction {
UP,
DOWN,
LEFT,
RIGHT,
NONE
}
Direction dir;
public Organism(int x, int y) {
this.x = x;
this.y = y;
this.dir = Direction.NONE;
}
// return true if there is a wall on the board at screen position (x, y)
public static boolean isWallAtPoint(PacmanGame.Things board[][], int x, int y)
{
int i = y / PacmanGame.SQUARE_SIZE;
int j = x / PacmanGame.SQUARE_SIZE;
if (board[i][j] == PacmanGame.Things.WALL)
return true;
else
return false;
}
public void move(PacmanGame.Things board[][], int speed) {
int newX = x, newY = y;
if(dir == Direction.RIGHT)
newX += speed;
if(dir == Direction.LEFT)
newX -= speed;
if(dir == Direction.UP)
newY -= speed;
if(dir == Direction.DOWN)
newY += speed;
if (isWallAtPoint(board, newX, newY) ||
isWallAtPoint(board, newX + PacmanGame.SQUARE_SIZE - 1, newY + PacmanGame.SQUARE_SIZE - 1))
{
// we will run into a wall if we keep moving, so stop moving
dir = Direction.NONE;
} else {
x = newX;
y = newY;
}
}
}
| 19.298246
| 94
| 0.622727
|
4b91ed50d8565a04db795a3afa3cca4e43afc78c
| 404
|
package bg.example.football.repository;
import bg.example.football.model.entities.NationalityEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface NationalityRepository extends JpaRepository<NationalityEntity, String> {
Optional<NationalityEntity> findByName(String name);
}
| 31.076923
| 89
| 0.844059
|
caccebbb292fcdf3f0f165e3ddeb1a83f5bf292b
| 943
|
package com.xiaowu5759.common.constant;
import cn.hutool.core.date.DateUtil;
import java.util.*;
/**
* 参考js中六大数据类型
* number
* string
* boolean
* undefined 使用var声明了变量,但未给变量初始化值
* null null类型被看做空对象指针,前文说到null类型也是空的对象引用
* object {}
* 时空属性
*
* @author xiaowu
* @date 2021/6/22 11:28 AM
*/
public final class DefaultFieldConstants {
private DefaultFieldConstants(){}
// 默认int是0
public static final Integer NumberVal = 0;
// 默认string是 ''
public static final String StringVal = "";
// 默认boolean
public static final Boolean BooleanVal = false;
// 默认时间是 '1970-01-01 00:00:00'
// 默认北京时间
public static final Date DateVal = DateUtil.parse("1970-01-01 08:00:00", "yyyy-MM-dd HH:mm:ss");
// 来自java开发手册,嵩山版
// 前后端数据列表相关的接口返回,如果为空,则返回空数组[]或空集合{}
public static final Map<String, Object> ObjectVal = new HashMap<>();
public static final List<Object> ArrayVal = new ArrayList<>();
}
| 21.431818
| 100
| 0.677625
|
7bf028ec5348cd989cf0cdcbd45827cd5fc43f76
| 844
|
package com.seedfinding.mcbiome.layer.water;
import com.seedfinding.mcbiome.biome.Biomes;
import com.seedfinding.mcbiome.layer.IntBiomeLayer;
import com.seedfinding.mccore.version.MCVersion;
public class OldRiverInBiomes extends IntBiomeLayer {
// before the introduction of noise based rivers, river were based on the rare biomes
public OldRiverInBiomes(MCVersion version, long worldSeed, long salt, IntBiomeLayer parent) {
super(version, worldSeed, salt, parent);
}
@Override
public int sample(int x, int y, int z) {
this.setSeed(x, z);
int center = this.getParent(IntBiomeLayer.class).get(x, y, z);
if((center != Biomes.SWAMP.getId() || this.nextInt(6) != 0)
&& (center != Biomes.JUNGLE.getId() && center != Biomes.JUNGLE_HILLS.getId() || this.nextInt(8) != 0)) {
return center;
}
return Biomes.RIVER.getId();
}
}
| 35.166667
| 107
| 0.731043
|
2cf89b957263f0d3dd5be06dfb7688661b39a404
| 2,257
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
/**
* Created by moham on 9/8/17.
*/
@Autonomous
public class TestAuto extends OpMode {
VuforiaLocalizer vuforia;
int cameraMonitorViewId;
VuforiaTrackables relicTrackables;
VuforiaTrackable relicTemplate;
RelicRecoveryVuMark vuMark;
@Override
public void init() {
cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
parameters.vuforiaLicenseKey = "AY1sGR7/////AAAAGUIEPxq1Q0OHlg+rWY6E5Kh4qSsw5c/A1GkGZpCg2zSlxfB97RdicKHfBIuhCnfS1Lx+HQL68oWdyLX5SGlgYVH1BW8TiWpRnNFQ4o0f1qwG5P67klb5EQilENwYt7EIBFTSjFOAWxX9vWyjhL+rW6u9k9dGnCut3ukqr+JML+UjSEXIAhXWEAVu86UH/Y70mx8cobzt3UqSv4PpNStZHPB6OakhBgIiCe2Leh04/kWJ+uAsIyO6bukEOilVcSC0A7LsbvNwOzbqPI1poFBqVXeEP5xqenaGIfgLAjj6g2b4sHXosmphZyAiL8v8XXrq/Uz3KTD1B8Lj9aLcs7c0mZ02yZnqCfOpIhYoUmKRVBgB";
parameters.cameraDirection = VuforiaLocalizer.CameraDirection.BACK;
this.vuforia = ClassFactory.createVuforiaLocalizer(parameters);
relicTrackables = this.vuforia.loadTrackablesFromAsset("RelicVuMark");
relicTemplate = relicTrackables.get(0);
relicTemplate.setName("relicVuMarkTemplate");
relicTrackables.activate();
}
@Override
public void loop() {
vuMark = RelicRecoveryVuMark.from(relicTemplate);
if (vuMark != RelicRecoveryVuMark.UNKNOWN) {
telemetry.addData("VuMark", "%s visible", vuMark);
}
}
}
| 44.254902
| 422
| 0.799291
|
215ae3f7c73f56fc174955ad0ec8c5fe7f5654c9
| 1,930
|
package be.etnic.qa.selenium.accessibility.samples;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import be.etnic.qa.tools.accessibility.AccessibilityCheckApi;
import be.etnic.qa.tools.accessibility.AxeImpactEnum;
public class TestAccessibilityOnCharteV3 {
private static AccessibilityCheckApi api;
private static final String BASE_URL = "C:/Dev/workspace-eclipse/charteV3/design-web/src/main/resources/";
@BeforeAll
public static void globalSetup() {
Map<String, String> headers = new HashMap<String, String>();
api = new AccessibilityCheckApi(headers, AxeImpactEnum.MODERATE);
}
@BeforeEach
public void setUp() {
api.startDriver();
}
@AfterEach
public void finalisation() {
api.stopDriver();
}
@AfterAll
private static void generateReport() {
api.generateGlobalReport();
}
@Test
@Disabled
public void analyseAccessibility() {
Stream.of(new File(BASE_URL)
.listFiles())
.filter(file -> !file.isDirectory())
.filter(file -> !file.getName().startsWith("ZZZ"))
.filter(file -> file.getName().startsWith("accueil"))
.map(File::getName)
.sorted()
.forEach(file -> analyseFile(file));
api.assertGlobalAnalysis();
}
private void analyseFile(String fileName) {
System.out.println(fileName);
api.openPage(BASE_URL + fileName);
api.analyseAccessibilityForCurrentPage();
}
}
| 27.183099
| 111
| 0.632124
|
ff7d3f6ee4ef45ad4dbae09cfa5b482e551715ac
| 846
|
package com.lieve.online.base.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.lieve.online.base.entity.UserGroup;
import com.lieve.online.base.service.UserGroupService;
import java.util.Properties;
import com.lieve.online.base.common.BaseAction;
import org.springframework.stereotype.Component;
@Component("UserGroupActionTarget")
public class UserGroupAction extends BaseAction<UserGroup, UserGroupService> {
private static final Logger log = LoggerFactory.getLogger(UserGroupAction.class);
@Autowired
public void setService(UserGroupService service) {
super.setService(service);
}
public UserGroupAction() {
Properties funcIdAttributes = new Properties();
this.setFuncIdAttributes(funcIdAttributes);
}
}
| 29.172414
| 82
| 0.783688
|
e247c10fd7f2c08db38733f4d965b95a796173b3
| 640
|
package me.academeg.blog.dal.utils.helperentities;
import lombok.Getter;
import lombok.Setter;
import static me.academeg.blog.dal.utils.Relations.setManyToOne;
/**
* @author Yuriy A. Samsonov <y.samsonov@erpscan.com>
* @date 23.02.2017
*/
@Setter
@Getter
public class Page {
private int number;
private Book book;
public Page(int number) {
this.number = number;
}
public Page setBook(Book book) {
return setManyToOne(
this,
book,
Page::getBook,
book1 -> this.book = book,
Book::addPage,
Book::removePage
);
}
}
| 18.823529
| 64
| 0.596875
|
e8d65aa14ee353294109d60eda79164f1e227dda
| 913
|
package org.lcsim.plugin;
import org.freehep.record.loop.RecordLoop;
import org.freehep.util.FreeHEPLookup;
import org.lcsim.event.EventHeader;
/**
* The methods in this class are made available to scripts via the <code>lcsim</code>
* variable.
* @author tonyj
*/
public class LCSim
{
private final FreeHEPLookup lookup;
/** Creates a new instance of LCSim */
LCSim(FreeHEPLookup lookup)
{
this.lookup = lookup;
}
/**
* Get the current event.
* @return The event, or <code>null</code> if event not available
*/
public EventHeader getCurrentEvent()
{
try
{
RecordLoop loop = (RecordLoop) lookup.lookup(RecordLoop.class);
Object event = loop.getRecordSource().getCurrentRecord();
return (event instanceof EventHeader) ? (EventHeader) event : null;
}
catch (Exception x)
{
return null;
}
}
}
| 24.026316
| 85
| 0.647317
|
0251f15613404557c644927487368d202192d878
| 3,056
|
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.oracle;
import com.google.common.collect.ImmutableMap;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.etl.api.batch.BatchSink;
import io.cdap.plugin.db.DBRecord;
import io.cdap.plugin.db.SchemaReader;
import io.cdap.plugin.db.batch.config.DBSpecificSinkConfig;
import io.cdap.plugin.db.batch.sink.AbstractDBSink;
import io.cdap.plugin.db.batch.sink.FieldsValidator;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Sink support for Oracle database.
*/
@Plugin(type = BatchSink.PLUGIN_TYPE)
@Name(OracleConstants.PLUGIN_NAME)
@Description("Writes records to Oracle table. Each record will be written in a row in the table")
public class OracleSink extends AbstractDBSink {
private final OracleSinkConfig oracleSinkConfig;
public OracleSink(OracleSinkConfig oracleSinkConfig) {
super(oracleSinkConfig);
this.oracleSinkConfig = oracleSinkConfig;
}
@Override
protected DBRecord getDBRecord(StructuredRecord output) {
return new OracleSinkDBRecord(output, columnTypes);
}
@Override
protected FieldsValidator getFieldsValidator() {
return new OracleFieldsValidator();
}
@Override
protected SchemaReader getSchemaReader() {
return new OracleSinkSchemaReader();
}
/**
* Oracle action configuration.
*/
public static class OracleSinkConfig extends DBSpecificSinkConfig {
@Name(OracleConstants.DEFAULT_BATCH_VALUE)
@Description("The default batch value that triggers an execution request.")
@Nullable
public Integer defaultBatchValue;
@Name(OracleConstants.CONNECTION_TYPE)
@Description("Whether to use an SID or Service Name when connecting to the database.")
public String connectionType;
@Override
public String getConnectionString() {
if (OracleConstants.SERVICE_CONNECTION_TYPE.equals(this.connectionType)) {
return String.format(OracleConstants.ORACLE_CONNECTION_STRING_SERVICE_NAME_FORMAT,
host, port, database);
}
return String.format(OracleConstants.ORACLE_CONNECTION_STRING_SID_FORMAT, host, port, database);
}
@Override
protected Map<String, String> getDBSpecificArguments() {
return ImmutableMap.of(OracleConstants.DEFAULT_BATCH_VALUE, String.valueOf(defaultBatchValue));
}
}
}
| 33.217391
| 102
| 0.758508
|
28093ebb1a1bb5598d4023bda91536133759140b
| 1,772
|
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
caminoMasCorto cmc = new caminoMasCorto();
Scanner entrada = new Scanner(System.in);
// Se realizan las acciones correspondientes mientras hayan casos (Ciudades) disponibles
while(entrada.hasNext()){
// Se registran la cantidad de vertices (Intersecciones) y aristas(Calles) del grafo
int intersecciones = entrada.nextInt();
int calles = entrada.nextInt();
ArrayList<int[]> callesList = new ArrayList<>();
// Se crea una lista con todas las aristas del grafo (Calles)
for (int i = 0; i < calles; i++) {
callesList.add(new int[]{entrada.nextInt(), entrada.nextInt()});
}
// Se crea una lista de nodos, que nos servirá como lista de adyacencia para representar el grafo
caminoMasCorto.Nodo[] grafo = cmc.crearListaAdyacencia(callesList, intersecciones);
int numCasos = entrada.nextInt();
for (int i = 0; i < numCasos; i++) {
// Se obtienen los vertices (Intersecciones) de inicio y fin
int inicio = entrada.nextInt()-1;
int fin = entrada.nextInt()-1;
// Mediante BFS, se encuentra la ruta mas corta entre 2 vertices (Intersecciones)
cmc.rutaMasCorta(grafo, inicio, fin);
// Se desmarcan todos los nodos visitados en el traversal anterior
for (caminoMasCorto.Nodo nodo: grafo) {
nodo.desmarcarNodo();
}
}
System.out.println("- - - -");
}
}
}
| 41.209302
| 110
| 0.566591
|
508e3defd6293a49e5a902b94c37a0022e779912
| 10,568
|
/*
* Copyright (c) 2019, Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.daml.product.bondissuance;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.daml.extensions.testing.junit4.Sandbox;
import com.daml.extensions.testing.ledger.DefaultLedgerAdapter;
import com.daml.extensions.testing.utils.ContractWithId;
import com.daml.ledger.javaapi.data.Party;
import da.finance.asset.AssetDeposit;
import da.refapps.bond.auction.Auction;
import da.refapps.bond.auction.AuctionBid;
import da.refapps.bond.auction.AuctionInvitation;
import da.refapps.bond.auction.AuctionParticipantSettleRequest;
import da.refapps.bond.auction.BidderParticipation;
import da.refapps.bond.fixedratebond.FixedRateBondFact;
import da.refapps.bond.lock.AuctionLockedCash;
import da.refapps.bond.redemption.RedemptionPayoutInfo;
import da.refapps.bond.redemption.RedemptionRequest;
import da.refapps.bond.roles.issuerrole.IssuanceRequest;
import da.refapps.bond.roles.issuerrole.IssuerRole;
import da.refapps.bond.settlement.AuctionSettleRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
public class BondIssuanceIT {
private static final Path RELATIVE_DAR_PATH = Paths.get("./target/bond-issuance.dar");
private static final Path RELATIVE_TRIGGER_DAR_PATH =
Paths.get("./target/bond-issuance-triggers.dar");
private static final Party ISSUER_PARTY = new Party("Issuer");
private static final Party CSD_PARTY = new Party("Csd");
private static final Party AGENT_PARTY = new Party("AuctionAgent");
private static final Party BANK1_PARTY = new Party("Bank1");
private static final Party BANK2_PARTY = new Party("Bank2");
private static final Party BANK3_PARTY = new Party("Bank3");
private static final Party CENTRALBANK_PARTY = new Party("CentralBank");
private static final Sandbox sandbox =
Sandbox.builder()
.dar(RELATIVE_DAR_PATH)
.parties(
BANK1_PARTY.getValue(),
BANK2_PARTY.getValue(),
BANK3_PARTY.getValue(),
AGENT_PARTY.getValue(),
CENTRALBANK_PARTY.getValue(),
ISSUER_PARTY.getValue(),
CSD_PARTY.getValue())
.useWallclockTime()
.observationTimeout(Duration.ofMinutes(1L))
.moduleAndScript("DA.RefApps.Bond.MarketSetup.MarketSetupScript", "setupMarket")
.build();
@ClassRule public static ExternalResource sandboxClassRule = sandbox.getClassRule();
@Rule
public TestRule sandboxWithTriggers =
RuleChain.outerRule(sandbox.getRule()).around(new Automation(sandbox::getSandboxPort));
@Test
public void testFullWorkflow() throws IOException, InterruptedException {
DefaultLedgerAdapter ledgerAdapter = sandbox.getLedgerAdapter();
// Issuance of a bond
LocalDate now = LocalDate.now().plusDays(1);
LocalDate maturityDate = now.plusDays(365);
BigDecimal couponRate = BigDecimal.valueOf(0.1);
BigDecimal denomination = BigDecimal.valueOf(40.1);
String currency = "USD";
List<LocalDate> couponDates = Collections.emptyList();
IssuerRole.ContractId issuerRoleCid =
ledgerAdapter.getCreatedContractId(
ISSUER_PARTY, IssuerRole.TEMPLATE_ID, IssuerRole.ContractId::new);
ledgerAdapter.exerciseChoice(
ISSUER_PARTY,
issuerRoleCid.exerciseIssuerRole_Issuance(
3000000L, now, currency, denomination, maturityDate, couponRate, couponDates));
String bondIsin = "BOND-007";
IssuanceRequest.ContractId issuanceRequest =
ledgerAdapter.getCreatedContractId(
CSD_PARTY, IssuanceRequest.TEMPLATE_ID, IssuanceRequest.ContractId::new);
ledgerAdapter.exerciseChoice(
CSD_PARTY, issuanceRequest.exerciseIssuanceRequest_Accept(bondIsin));
// Auction commission
AssetDeposit.ContractId assetDeposit = findBondAssetDeposit(bondIsin);
LocalDate auctionStartDate = now.plusDays(10);
LocalDate auctionEndDate = auctionStartDate.plusDays(10);
BigDecimal minPrize = BigDecimal.valueOf(40.0);
Long size = 1000000L;
ledgerAdapter.exerciseChoice(
ISSUER_PARTY,
issuerRoleCid.exerciseIssuerRole_CommissionAuction(
assetDeposit, auctionStartDate, auctionEndDate, minPrize, size));
// System.in.read();
// Commission, by bot.
// Acceptance of invitation
AuctionInvitation.ContractId auctionInvitation =
ledgerAdapter.getCreatedContractId(
AGENT_PARTY, AuctionInvitation.TEMPLATE_ID, AuctionInvitation.ContractId::new);
ledgerAdapter.exerciseChoice(
AGENT_PARTY, auctionInvitation.exerciseAuctionInvitation_Accept("testAuction"));
Auction.ContractId auction1 =
ledgerAdapter.getCreatedContractId(
AGENT_PARTY, Auction.TEMPLATE_ID, Auction.ContractId::new);
ledgerAdapter.exerciseChoice(
AGENT_PARTY,
auction1.exerciseAuction_InviteBidders(
Arrays.asList(BANK1_PARTY.getValue(), BANK2_PARTY.getValue(), BANK3_PARTY.getValue())));
// Bidding
BidderParticipation.ContractId bidderParticipationBank1 =
ledgerAdapter.getCreatedContractId(
BANK1_PARTY, BidderParticipation.TEMPLATE_ID, BidderParticipation.ContractId::new);
ledgerAdapter.exerciseChoice(
BANK1_PARTY,
bidderParticipationBank1.exerciseBidderParticipation_PlaceBid(
BigDecimal.valueOf(42.0), 200000L));
BidderParticipation.ContractId bidderParticipationBank2 =
ledgerAdapter.getCreatedContractId(
BANK2_PARTY, BidderParticipation.TEMPLATE_ID, BidderParticipation.ContractId::new);
ledgerAdapter.exerciseChoice(
BANK2_PARTY,
bidderParticipationBank2.exerciseBidderParticipation_PlaceBid(
BigDecimal.valueOf(25.0), 800000L));
BidderParticipation.ContractId bidderParticipationBank3 =
ledgerAdapter.getCreatedContractId(
BANK3_PARTY, BidderParticipation.TEMPLATE_ID, BidderParticipation.ContractId::new);
ledgerAdapter.exerciseChoice(
BANK3_PARTY,
bidderParticipationBank3.exerciseBidderParticipation_PlaceBid(
BigDecimal.valueOf(10.0), 800000L));
AuctionBid.ContractId bid =
ledgerAdapter.getCreatedContractId(
BANK3_PARTY, AuctionBid.TEMPLATE_ID, AuctionBid.ContractId::new);
AuctionLockedCash.ContractId lockedCash =
ledgerAdapter.getCreatedContractId(
BANK3_PARTY, AuctionLockedCash.TEMPLATE_ID, AuctionLockedCash.ContractId::new);
ledgerAdapter.exerciseChoice(
BANK3_PARTY,
bidderParticipationBank3.exerciseAuctionBidderParticipantion_RevokeLockedBid(
bid, lockedCash));
// Finalizing auction
Auction.ContractId auction2 =
ledgerAdapter.getCreatedContractId(
AGENT_PARTY, Auction.TEMPLATE_ID, Auction.ContractId::new);
ledgerAdapter.exerciseChoice(AGENT_PARTY, auction2.exerciseAuction_Finalize());
// Sanity checks
ContractWithId<AuctionSettleRequest.ContractId> settleReq1 =
ledgerAdapter.getMatchedContract(
BANK1_PARTY, AuctionSettleRequest.TEMPLATE_ID, AuctionSettleRequest.ContractId::new);
assertEquals(
42L * 200000L,
AuctionSettleRequest.fromValue(settleReq1.record)
.cashAmountToPay
.toBigInteger()
.longValue());
AuctionParticipantSettleRequest.ContractId apSettleReq1 =
ledgerAdapter.getCreatedContractId(
BANK1_PARTY,
AuctionParticipantSettleRequest.TEMPLATE_ID,
AuctionParticipantSettleRequest.ContractId::new);
ledgerAdapter.exerciseChoice(
BANK1_PARTY, apSettleReq1.exerciseAuctionParticipantSettleRequest_Settle());
ContractWithId<AuctionParticipantSettleRequest.ContractId> apSettleReq2 =
ledgerAdapter.getMatchedContract(
BANK2_PARTY,
AuctionParticipantSettleRequest.TEMPLATE_ID,
AuctionParticipantSettleRequest.ContractId::new);
assertTrue(
AuctionParticipantSettleRequest.fromValue(apSettleReq2.record).settleRequestCids.isEmpty());
ledgerAdapter.exerciseChoice(
BANK2_PARTY, apSettleReq2.contractId.exerciseAuctionParticipantSettleRequest_Settle());
ledgerAdapter.getCreatedContractId(
BANK1_PARTY, RedemptionPayoutInfo.TEMPLATE_ID, RedemptionPayoutInfo.ContractId::new);
// Requesting redemption at CSD
FixedRateBondFact.ContractId fixedRateBondFact =
ledgerAdapter.getCreatedContractId(
ISSUER_PARTY, FixedRateBondFact.TEMPLATE_ID, FixedRateBondFact.ContractId::new);
ledgerAdapter.exerciseChoice(
ISSUER_PARTY, issuerRoleCid.exerciseIssuerRole_Redeem(fixedRateBondFact));
RedemptionRequest.ContractId redemptionRequest =
ledgerAdapter.getCreatedContractId(
CSD_PARTY, RedemptionRequest.TEMPLATE_ID, RedemptionRequest.ContractId::new);
ledgerAdapter.exerciseChoice(CSD_PARTY, redemptionRequest.exerciseRedemptionRequest_Accept());
assertTrue(
ledgerAdapter.observeMatchingContracts(
BANK1_PARTY,
AssetDeposit.TEMPLATE_ID,
AssetDeposit::fromValue,
false,
assetDepositFinal -> // 50 000 000 - (42 * 200 000)
assetDepositFinal.asset.quantity.compareTo(BigDecimal.valueOf(41_600_000L)) == 0,
assetDepositFinal -> // Redemption value (with coupon): 40.1 * 200 000 * 1.1
assetDepositFinal.asset.quantity.compareTo(BigDecimal.valueOf(8_822_000L)) == 0));
}
private AssetDeposit.ContractId findBondAssetDeposit(String expectedLabel) {
while (true) {
// This will fail, after there are no more asset deposit contracts
ContractWithId<AssetDeposit.ContractId> assetDeposit =
sandbox
.getLedgerAdapter()
.getMatchedContract(
ISSUER_PARTY, AssetDeposit.TEMPLATE_ID, AssetDeposit.ContractId::new);
if (AssetDeposit.fromValue(assetDeposit.record).asset.id.label.equals(expectedLabel)) {
return assetDeposit.contractId;
}
}
}
}
| 42.95935
| 100
| 0.738456
|
1501e44e0f31faddd7deb702e38737b9830ea5b5
| 5,577
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2015-2021 the original author or authors.
*/
package org.assertj.db.util;
import org.assertj.db.common.AbstractTest;
import org.assertj.db.type.DateTimeValue;
import org.assertj.db.type.DateValue;
import org.assertj.db.type.TimeValue;
import org.junit.Test;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests on {@code getRepresentationFromValueInFrontOfExpected} method from utility class {@code Values}.
*
* @author Régis Pouiller
*
*/
public class Values_GetOutputFromValueInFrontOfExpected_Test extends AbstractTest {
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code Date}s.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_dates() throws Exception {
Date date = Date.valueOf("2007-12-23");
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, date), DateValue.of(2007, 12, 23))).isEqualTo(
DateValue.from(date));
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, date), DateTimeValue.of(DateValue.of(2007, 12, 23), TimeValue.of(9, 1)))).isEqualTo(
DateTimeValue.of(DateValue.from(date)));
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, date), "")).isEqualTo("2007-12-23");
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, date), "T")).isEqualTo(
"2007-12-23T00:00:00.000000000");
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, date), null)).isEqualTo(date);
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code Time}s.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_times() throws Exception {
Time time = Time.valueOf("09:01:06");
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, time), null)).isEqualTo(TimeValue.from(time));
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, time), "")).isEqualTo("09:01:06.000000000");
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code Timestamp}s.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_datetime() throws Exception {
Timestamp timestamp = Timestamp.valueOf("2007-12-23 09:01:06.000000003");
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, timestamp), null)).isEqualTo(
DateTimeValue.from(timestamp));
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, timestamp), "")).isEqualTo(
"2007-12-23T09:01:06.000000003");
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for array of {@code byte}.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_bytes() throws Exception {
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, new byte[] {1, 2}), null)).isEqualTo(
new byte[] { 1, 2 });
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code String}s.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_text() throws Exception {
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, "text"), null)).isEqualTo("text");
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code UUID}s.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_UUID() throws Exception {
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, UUID.fromString("30B443AE-C0C9-4790-9BEC-CE1380808435")), "30B443AE-C0C9-4790-9BEC-CE1380808435")).isEqualTo(
"30b443ae-c0c9-4790-9bec-ce1380808435");
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, UUID.fromString("30B443AE-C0C9-4790-9BEC-CE1380808435")), null)).isEqualTo(
UUID.fromString("30B443AE-C0C9-4790-9BEC-CE1380808435"));
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code Boolean}s.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_boolean() throws Exception {
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, true), null)).isEqualTo(true);
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, false), null)).isEqualTo(false);
}
/**
* This method tests the {@code getRepresentationFromValueInFrontOfExpected} method for {@code null}.
*/
@Test
public void test_getRepresentationFromValueInFrontOfExpected_for_null() throws Exception {
assertThat(Values.getRepresentationFromValueInFrontOfExpected(getValue(null, null), null)).isNull();
}
}
| 46.475
| 190
| 0.765107
|
8d9e1cf9f0adb65fadd90766e3551b6e477ed83f
| 888
|
package com.easy.easycan.home.stramer.adapter;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.easy.easycan.R;
import com.easy.easycan.goods.model.ExcellentGoodsListBean;
import com.easy.easycan.home.stramer.bean.StreamerInfoBean;
import java.util.List;
/**
* @author merlin720
* date 2019-09-21
* mail zy44638@gmail.com
* description 蒸罐信息
*/
public class StreamerInfoAdapter
extends BaseQuickAdapter<StreamerInfoBean, BaseViewHolder> {
public StreamerInfoAdapter() {
super(R.layout.streamer_info_item);
}
@Override protected void convert(@NonNull BaseViewHolder helper, StreamerInfoBean item) {
helper.setText(R.id.streamer_info_item_title, TextUtils.isEmpty(item.getTitle())?item.getAddress():item.getTitle());
}
}
| 30.62069
| 124
| 0.786036
|
52a883ab83db9c1fbb6a73acbd243096789fb8d6
| 5,878
|
package org.metafetish.buttplug.components.controls;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.metafetish.buttplug.core.ButtplugLogLevel;
import org.metafetish.buttplug.core.Messages.Log;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class LogAdapter extends RecyclerView.Adapter<LogAdapter.ViewHolder> {
private Handler handler;
private List<Pair<Date, Log>> dataSet;
private ButtplugLogLevel logLevel;
private List<Pair<Date, Log>> filteredDataSet;
private DateFormat dateFormat;
private View.OnLongClickListener onLongClickListener;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView lineMessage;
ViewHolder(View view) {
super(view);
this.lineMessage = view.findViewById(R.id.line_message);
}
}
public LogAdapter(Handler handler, ButtplugLogLevel logLevel, View.OnLongClickListener onLongClickListener) {
this(handler, new ArrayList<Pair<Date, Log>>(), logLevel, onLongClickListener);
}
@SuppressLint("SimpleDateFormat")
public LogAdapter(Handler handler, List<Pair<Date, Log>> dataSet, ButtplugLogLevel logLevel, View.OnLongClickListener onLongClickListener) {
this.handler = handler;
this.dataSet = new ArrayList<>(dataSet);
this.logLevel = ButtplugLogLevel.OFF;
this.filteredDataSet = new ArrayList<>();
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
this.onLongClickListener = onLongClickListener;
this.setLogLevel(logLevel);
}
public void setLogLevel(final ButtplugLogLevel logLevel) {
this.handler.post(new Runnable() {
@Override
public void run() {
if (logLevel.ordinal() != LogAdapter.this.logLevel.ordinal()) {
if (logLevel.ordinal() >= LogAdapter.this.logLevel.ordinal()) {
LogAdapter.this.filteredDataSet = new ArrayList<>();
for (Pair<Date, Log> dataItem : LogAdapter.this.dataSet) {
if (dataItem.second != null && dataItem.second.logLevel.ordinal() <= logLevel.ordinal()) {
LogAdapter.this.filteredDataSet.add(dataItem);
}
}
} else {
List<Pair<Date, Log>> replacementDataSet = new ArrayList<>();
for (Pair<Date, Log> dataItem : LogAdapter.this.filteredDataSet) {
if (dataItem.second != null && dataItem.second.logLevel.ordinal() <= logLevel.ordinal()) {
replacementDataSet.add(dataItem);
}
}
LogAdapter.this.filteredDataSet = replacementDataSet;
}
LogAdapter.this.logLevel = logLevel;
LogAdapter.this.notifyDataSetChanged();
}
}
});
}
public void add(Log msg) {
final Pair<Date, Log> dataItem = new Pair<>(new Date(), msg);
this.dataSet.add(dataItem);
if (msg.logLevel.ordinal() <= this.logLevel.ordinal()) {
this.handler.post(new Runnable() {
@Override
public void run() {
LogAdapter.this.filteredDataSet.add(dataItem);
LogAdapter.this.notifyItemInserted(LogAdapter.this.filteredDataSet.size() - 1);
}
});
}
}
public void clear() {
this.dataSet.clear();
this.handler.post(new Runnable() {
@Override
public void run() {
LogAdapter.this.filteredDataSet.clear();
LogAdapter.this.notifyDataSetChanged();
}
});
}
public String getLogMessage(Pair<Date, Log> dataItem) {
if (dataItem.second != null) {
return String.format("[%s][%s][%s] %s",
this.dateFormat.format(dataItem.first),
dataItem.second.logLevel.toString().toUpperCase(),
dataItem.second.tag,
dataItem.second.logMessage);
} else {
return null;
}
}
public List<String> getLogMessages() {
List<String> logMessages = new ArrayList<>();
for (Pair<Date, Log> dataItem : this.filteredDataSet) {
String logMessage = this.getLogMessage(dataItem);
if (logMessage != null) {
logMessages.add(logMessage);
}
}
return logMessages;
}
@NonNull
@Override
public LogAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Pair<Date, Log> dataItem = this.filteredDataSet.get(position);
String logMessage = this.getLogMessage(dataItem);
if (logMessage != null) {
holder.lineMessage.setText(logMessage);
holder.lineMessage.setOnLongClickListener(this.onLongClickListener);
}
}
@Override
public int getItemCount() {
return this.filteredDataSet.size();
}
}
| 38.418301
| 144
| 0.605138
|
36a8a50914cd639cbce9e3d8d20b7874a6e7b6da
| 1,583
|
package com.bono.util.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.function.BiFunction;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.bono.util.excel.model.ColumnLineInfo;
import com.bono.util.excel.model.SheetAnalysisModel;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ExcelLoader {
public static <T> List<T> load(File configFile, int pageIndex, Class<?> modelClass,
BiFunction<XSSFSheet, Class<?>, List<T>> analysisFunction) {
XSSFWorkbook workbook = null;
try {
FileInputStream inStream = new FileInputStream(configFile);
workbook = new XSSFWorkbook(inStream);
return analysisFunction.apply(workbook.getSheetAt(pageIndex), modelClass);
} catch (Exception e) {
log.error("{}", e);
} finally {
if (workbook != null)
try {
workbook.close();
} catch (IOException e) {
// do nothing.
}
}
return null;
}
public static <T> List<T> loadDataOnSheet(XSSFSheet sheet, Class<?> modelClass, ColumnLineInfo columnLineInfo)
throws InvalidFormatException, InstantiationException, IllegalAccessException {
SheetAnalysisModel analysisModel = ExcelSheet2Class.extractAnalysisModel(modelClass, columnLineInfo);
List<T> alarmConfigs = ExcelSheet2Class.parseSheet(analysisModel, sheet);
// for debugging.
// for (T alarmConfig : alarmConfigs) {
// System.out.println(alarmConfig);
// }
return alarmConfigs;
}
}
| 29.867925
| 112
| 0.71952
|
91a3e9b49a6ce52821da4cc8a33eb4d6a041c3e7
| 1,980
|
// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.ros2.rcljava.detail;
import org.ros2.rcljava.common.JNIUtils;
import org.ros2.rcljava.events.EventStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class serves as a bridge between rmw_qos_incompatible_event_status_t
* and RCLJava.
*/
public class QosIncompatibleStatus implements EventStatus {
public int totalCount;
public int totalCountChange;
public PolicyKind lastPolicyKind;
public enum PolicyKind {
INVALID,
DURABILITY,
DEADLINE,
LIVELINESS,
RELIABILITY,
HISTORY,
LIFESPAN;
}
public final long allocateRCLStatusEvent() {
return nativeAllocateRCLStatusEvent();
}
public final void deallocateRCLStatusEvent(long handle) {
nativeDeallocateRCLStatusEvent(handle);
}
public final void fromRCLEvent(long handle) {
nativeFromRCLEvent(handle);
}
private static final Logger logger = LoggerFactory.getLogger(QosIncompatibleStatus.class);
static {
try {
JNIUtils.loadImplementation(QosIncompatibleStatus.class);
} catch (UnsatisfiedLinkError ule) {
logger.error("Native code library failed to load.\n" + ule);
System.exit(1);
}
}
private static native long nativeAllocateRCLStatusEvent();
private static native void nativeDeallocateRCLStatusEvent(long handle);
private native void nativeFromRCLEvent(long handle);
}
| 30
| 92
| 0.75101
|
6bf4edb07e9c1afa798b059fd6dc6e84282c784b
| 1,088
|
package com.sherlocky.headfirst.pattern._02_observer.use_java_api;
import com.sherlocky.headfirst.pattern._02_observer.DisplayElement;
import java.util.Observable;
import java.util.Observer;
/**
* 实现 Java API 提供的 Observer 接口
* @author: zhangcx
* @date: 2018/12/23 16:36
*/
public class GeneralDisplay implements Observer, DisplayElement {
Observable obs;
private float temperature;
private float humidity;
private float pressure;
public GeneralDisplay(Observable obs) {
this.obs = obs;
obs.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof WeatherData) {
WeatherData wd = (WeatherData) o;
this.temperature = wd.getTemperature();
this.humidity = wd.getHumidity();
this.pressure = wd.getPressure();
display();
}
}
@Override
public void display() {
System.out.println("General(use Java API): " + temperature + "°(摄氏度) and " + humidity + "%(湿度) humidity and " + pressure + "hPa(百帕)");
}
}
| 27.2
| 142
| 0.643382
|
ec082a3adc71da9f842c781b72a5d66c17c7cf7b
| 1,346
|
package pl.mikbac.salary_app.spring.controller.api;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import pl.mikbac.salary_app.WebApplication;
import pl.mikbac.salary_app.constants.WebConstants.Mapping;
import javax.annotation.Resource;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by MikBac on 02.01.2022
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class)
@AutoConfigureMockMvc
public class SalaryControllerTest {
@Resource
private MockMvc mockMvc;
@Test
@DisplayName("Get salary.")
public void get_salary_when_data_is_correct() throws Exception {
this.mockMvc.perform(get(Mapping.API + Mapping.CALCULATOR + "/?countryCode=UK&salary=123")
.contentType(APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
}
| 35.421053
| 98
| 0.784547
|
3810faa84735924a365825c216e8c547e7eda310
| 3,486
|
package base.stopwatch.chronometer;
import android.content.Context;
import android.graphics.Typeface;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;
//import base.stopwatch.chronometer.ChronoList.GetChronoInformation;
import base.stopwatch.chronometer.ChronometerInterfaces.GetChronoInformation;
import base.stopwatch.chronometer.ChronometerInterfaces.UpdateChronosOnTickListener;
public class BaseChronometer extends Chronometer implements GetChronoInformation{
private boolean STOPED = false;
private boolean STARTED = false;
private UpdateChronosOnTickListener tickUpdater;
//set communication from ForCoachesChronometer to ChronoList
public void setUpdateChronosOnTickListener(UpdateChronosOnTickListener tickUpdater) {
this.tickUpdater = tickUpdater;
}
public BaseChronometer(Context context) {
super(context);
initialize(context);
}
public BaseChronometer(Context context, AttributeSet arg1) {
super(context, arg1);
initialize(context);
}
public BaseChronometer(Context context, AttributeSet arg1, int arg2) {
super(context, arg1, arg2);
initialize(context);
}
private void initialize(Context context){
Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/DS-DIGIB.TTF");
setTypeface(font);
setOnChronometerTickListener(new OnChronometerTickListener() {
public void onChronometerTick(Chronometer chronometer) {
tickUpdater.updateChronosOnTickListener(getChronoElapsedTime());
}
});
}
public long getChronoElapsedTime(){
if (started()){
return getElapsedTime();
}else{
return 0;
}
}
public long getElapsedTime(){
return SystemClock.elapsedRealtime() - getBase();
}
public void startChrono(){
setBase(SystemClock.elapsedRealtime());
start();
STARTED = true;
STOPED = false;
}
public void startChronoWithoutSettingBase(){
start();
STARTED = true;
}
public void restartChrono(){
start();
STARTED = true;
STOPED = false;
}
public void stopChrono(){
stop();
STARTED = false;
STOPED = true;
}
public void resetChrono(){
setText("00:00");
STARTED = false;
STOPED = false;
}
public boolean started(){
return STARTED;
}
public boolean stoped(){
return STOPED;
}
public static String getTimeString(long time){
long hours = (time/1000)/60/60;
long minutes = (time/1000)/60;
long seconds = ((time)/1000)%60;
long cent = (time%1000)/10;
String timeStr = "";
if (hours != 0){
if (hours < 10){
timeStr += "0" + hours;
}else{
timeStr += hours;
}
timeStr += ":";
}
if (minutes < 10){
timeStr += "0" + minutes;
}else{
timeStr += minutes;
}
timeStr += ":";
if (seconds < 10){
timeStr += "0" + seconds;
}else{
timeStr += seconds;
}
timeStr += ":";
if (cent < 10){
timeStr += "0" + cent;
}else{
timeStr += cent;
}
return timeStr;
}
public static String getSecTimeString(long time){
long hours = (time/1000)/60/60;
long minutes = (time/1000)/60;
long seconds = ((time)/1000)%60;
String timeStr = "";
if (hours != 0){
if (hours < 10){
timeStr += "0" + hours;
}else{
timeStr += hours;
}
timeStr += ":";
}
if (minutes < 10){
timeStr += "0" + minutes;
}else{
timeStr += minutes;
}
timeStr += ":";
if (seconds < 10){
timeStr += "0" + seconds;
}else{
timeStr += seconds;
}
return timeStr;
}
}
| 20.385965
| 87
| 0.668101
|
0a4f83d644de2f79f4b48a9e3901780fb5bcd836
| 2,114
|
package com.teamgannon.trips.report;
import com.teamgannon.trips.graphics.entities.StarDisplayRecord;
import com.teamgannon.trips.listener.ReportGenerator;
import com.teamgannon.trips.report.distance.DistanceReport;
import com.teamgannon.trips.report.distance.DistanceReportDialog;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Optional;
@Slf4j
public class ReportManager {
public void generateDistanceReport(Stage stage, StarDisplayRecord starDescriptor, List<StarDisplayRecord> currentStarsInView) {
DistanceReport distanceReport = new DistanceReport(starDescriptor);
distanceReport.findDistance(currentStarsInView);
distanceReport.generateReport();
DistanceReportDialog dialog = new DistanceReportDialog(distanceReport);
Optional<DistanceReport> distanceReportOptional = dialog.showAndWait();
if (distanceReportOptional.isPresent()) {
distanceReport = distanceReportOptional.get();
if (distanceReport.isSaveSelected()) {
// save the file
FileChooser fileChooser = new FileChooser();
//Set extension filter for text files
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(stage);
if (file != null) {
saveTextToFile(distanceReport.getGeneratedReport(), file);
}
}
}
}
private void saveTextToFile(String generatedReport, File file) {
try (PrintWriter out = new PrintWriter(file)) {
out.println(generatedReport);
} catch (FileNotFoundException e) {
log.error("Can't create file {} because of {}", file.getAbsolutePath(), e.getMessage());
}
}
}
| 38.436364
| 131
| 0.684957
|
3c1777c4dd707cfe1238a0fb597d7d060516183f
| 702
|
package ga.deluded_fruitcakes_anonymous.velocityangles;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
public class MainActivity extends AppCompatActivity {
GameView v;
static int width,height;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
v = new GameView(this);
setContentView(v);
}
}
| 29.25
| 75
| 0.712251
|
4d1605f45c6f8ffaec24f9e4a769b5732560bad9
| 811
|
package o.w.o.app;
import lombok.extern.slf4j.Slf4j;
import o.w.o.domain.core.storage.service.FileStorageService;
import o.w.o.infrastructure.definition.ApiRateLimiter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
/**
* API 入口
*
* @author symbols@dingtalk.com
* @date 2021/02/23
* @since 1.0.0
*/
@Slf4j
@Controller
public class App {
@Resource
private FileStorageService fileStorageService;
@ApiRateLimiter(limits = 20)
@RequestMapping(path = "/")
public String index() {
fileStorageService
.loadTemplateResource("public/index.html", "index.html")
.guard();
return "index";
}
@RequestMapping(path = "/test")
public String demo() {
return "test";
}
}
| 20.794872
| 64
| 0.713933
|
5e3d66157a1543495dcccc90cd5c828ff82ea991
| 476
|
package me.galaxy.lock.spring;
import me.galaxy.lock.spring.aspect.LockActionAspect;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class LockActionAspectCondition implements Condition {
@Override
public synchronized boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return false;
}
}
| 29.75
| 99
| 0.817227
|
c79f9b5a15314a8024cedc69f4e9c33aaf884fce
| 1,347
|
package com.innochi.audiorecorderbookmark;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;
import androidx.preference.PreferenceFragmentCompat;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBarHelper.enableBackButton(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
| 32.071429
| 84
| 0.688196
|
00b4f6316a696cf32b1faba2efb03e424b8ea4f6
| 446
|
package com.vduty.vbackstage.configs;
public class Constants {
public static final String ADMIN_PATH = "/vdutymanager";
public static final String USERCENTER_PATH = "/usercenter";
public static final String REFER_URL_KEY="referurl";
public static final String JWT_SECURITY_KEY="vbstSecretKey";
public static final String JWT_TOKEN_FLAG="bsmsecurity";
public static final String JWT_HEADER_NAME = "Authorization";
}
| 20.272727
| 63
| 0.762332
|
27355effa65556763bf82a21fe430e7bc1a929b7
| 784
|
package com.github.jeuxjeux20.loupsgarous.game.inventory;
import com.github.jeuxjeux20.loupsgarous.game.LGComponents;
import com.github.jeuxjeux20.loupsgarous.game.OrchestratorComponentsModule;
public final class LGInventoryModule extends InventoryItemsModule {
@Override
protected void configureBindings() {
bind(LGInventoryManager.class);
install(new OrchestratorComponentsModule() {
@Override
protected void configureOrchestratorComponents() {
addOrchestratorComponent(LGComponents.INVENTORY, LGInventoryManager.class);
}
});
}
@Override
protected void configureInventoryItems() {
addInventoryItem(QuitGameItem.class);
addInventoryItem(EditLobbyItem.class);
}
}
| 32.666667
| 91
| 0.719388
|
bf95c5b6417852ed6fba8bf1432dab1f5361483d
| 8,493
|
package com.darrenswhite.rs.ironquest.quest;
import com.darrenswhite.rs.ironquest.dto.QuestDTO;
import com.darrenswhite.rs.ironquest.player.Player;
import com.darrenswhite.rs.ironquest.quest.Quest.Serializer;
import com.darrenswhite.rs.ironquest.quest.requirement.CombatRequirement;
import com.darrenswhite.rs.ironquest.quest.requirement.QuestPointsRequirement;
import com.darrenswhite.rs.ironquest.quest.requirement.QuestRequirement;
import com.darrenswhite.rs.ironquest.quest.requirement.QuestRequirements;
import com.darrenswhite.rs.ironquest.quest.requirement.Requirement;
import com.darrenswhite.rs.ironquest.quest.requirement.SkillRequirement;
import com.darrenswhite.rs.ironquest.quest.reward.QuestRewards;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A class representing a quest.
*
* @author Darren S. White
*/
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonSerialize(using = Serializer.class)
public class Quest {
private final int id;
private final String title;
private final String displayName;
private final QuestAccess access;
private final QuestType type;
private final QuestRequirements requirements;
private final QuestRewards rewards;
public Quest(@JsonProperty("id") int id, @JsonProperty("title") String title,
@JsonProperty("displayName") String displayName, @JsonProperty("access") QuestAccess access,
@JsonProperty("type") QuestType type,
@JsonProperty("requirements") QuestRequirements requirements,
@JsonProperty("rewards") QuestRewards rewards) {
this.id = id;
this.title = title;
this.displayName = displayName;
this.access = access;
this.type = type;
this.requirements = requirements != null ? requirements : QuestRequirements.NONE;
this.rewards = rewards != null ? rewards : QuestRewards.NONE;
}
Quest(Builder builder) {
this.id = builder.id;
this.title = builder.title;
this.displayName = builder.displayName;
this.access = builder.access;
this.type = builder.type;
this.requirements = builder.requirements;
this.rewards = builder.rewards;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDisplayName() {
return displayName;
}
public QuestAccess getAccess() {
return access;
}
public QuestType getType() {
return type;
}
public QuestRequirements getRequirements() {
return requirements;
}
public QuestRewards getRewards() {
return rewards;
}
/**
* Test if the player meets the {@link CombatRequirement}s, if any.
*
* @param player the player
* @return <tt>true</tt> if the player meets the combat requirement; <tt>false</tt> otherwise
*/
public boolean meetsCombatRequirement(Player player) {
return requirements.getCombat() == null || requirements.getCombat().test(player);
}
/**
* Test if the player meets the {@link QuestPointsRequirement}s, if any.
*
* @param player the player
* @return <tt>true</tt> if the player meets the quest point requirement; <tt>false</tt> otherwise
*/
public boolean meetsQuestPointRequirement(Player player) {
return requirements.getQuestPoints() == null || requirements.getQuestPoints().test(player);
}
/**
* Test if the player meets all {@link QuestRequirement}s.
*
* @param player the player
* @return <tt>true</tt> if the player meets all quest requirements; <tt>false</tt> otherwise
*/
public boolean meetsQuestRequirements(Player player) {
return requirements.getQuests().stream().allMatch(r -> r.test(player));
}
/**
* Test if the player meets all {@link SkillRequirement}s.
*
* @param player the player
* @return <tt>true</tt> if the player meets all skill requirements; <tt>false</tt> otherwise
*/
public boolean meetsSkillRequirements(Player player) {
return requirements.getSkills().stream().allMatch(r -> r.test(player));
}
/**
* Test if the player meets all {@link Requirement}s.
*
* @param player the player
* @return <tt>true</tt> if the player meets all requirements; <tt>false</tt> otherwise
*/
public boolean meetsAllRequirements(Player player) {
return meetsCombatRequirement(player) && meetsQuestPointRequirement(player)
&& meetsQuestRequirements(player) && meetsSkillRequirements(player);
}
/**
* Test if this {@link Quest} is a placeholder.
*
* @return <tt>true</tt> if this quest is a placeholder; <tt>false</tt> otherwise
*/
public boolean isPlaceholder() {
return id < 0;
}
/**
* Get all {@link QuestRequirements}s to complete this {@link Quest}.
*
* @param recursive <tt>true</tt> to get requirements recursively; <tt>false</tt> otherwise
* @return quest requirements
*/
public Set<QuestRequirement> getQuestRequirements(boolean recursive) {
Set<QuestRequirement> questRequirements = new HashSet<>(requirements.getQuests());
if (recursive) {
questRequirements.addAll(requirements.getQuests().stream()
.flatMap(qr -> qr.getQuest().getQuestRequirements(true).stream())
.collect(Collectors.toSet()));
}
return questRequirements;
}
/**
* {@inheritDoc}
*/
@Override
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Quest)) {
return false;
}
Quest quest = (Quest) o;
return id == quest.id;
}
/**
* {@inheritDoc}
*/
@Override
public final int hashCode() {
return Objects.hash(id);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Quest{" + "id=" + id + ", displayName='" + displayName + '\'' + '}';
}
/**
* Returns a DTO for this {@link Quest}.
*
* @return the DTO
*/
public QuestDTO createDTO() {
return new QuestDTO.Builder().withDisplayName(getDisplayName()).build();
}
public static class Builder {
private int id;
private String title;
private String displayName;
private QuestAccess access;
private QuestType type;
private QuestRequirements requirements = QuestRequirements.NONE;
private QuestRewards rewards = QuestRewards.NONE;
public Builder() {
}
public Builder(int id) {
this.id = id;
}
public Builder withId(int id) {
this.id = id;
return this;
}
public Builder withTitle(String title) {
this.title = title;
return this;
}
public Builder withDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
public Builder withAccess(QuestAccess access) {
this.access = access;
return this;
}
public Builder withType(QuestType type) {
this.type = type;
return this;
}
public Builder withRequirements(QuestRequirements requirements) {
this.requirements = requirements;
return this;
}
public Builder withRewards(QuestRewards rewards) {
this.rewards = rewards;
return this;
}
public Quest build() {
return new Quest(this);
}
}
public static class Serializer extends JsonSerializer<Quest> {
@Override
public void serialize(Quest quest, JsonGenerator gen, SerializerProvider provider)
throws IOException {
gen.writeStartObject();
provider.defaultSerializeField("access", quest.access, gen);
provider.defaultSerializeField("displayName", quest.displayName, gen);
provider.defaultSerializeField("id", quest.id, gen);
if (quest.requirements != QuestRequirements.NONE) {
provider.defaultSerializeField("requirements", quest.requirements, gen);
}
if (quest.rewards != QuestRewards.NONE) {
provider.defaultSerializeField("rewards", quest.rewards, gen);
}
provider.defaultSerializeField("title", quest.title, gen);
provider.defaultSerializeField("type", quest.type, gen);
gen.writeEndObject();
}
}
}
| 29.185567
| 100
| 0.694925
|
9fd4dcc8b87dcdc25c607dd15e05004f524a8b88
| 308
|
package com.api.delivery.domain.service;
import java.util.List;
import com.api.delivery.domain.filter.VendaDiariaFilter;
import com.api.delivery.domain.model.dto.VendaDiaria;
public interface VendaQueryService {
List<VendaDiaria> consultarVendasDiarias(VendaDiariaFilter filtro, String timeOffset);
}
| 23.692308
| 87
| 0.824675
|
b5779fb54a412e2991e659b1bec18d5a345f7540
| 1,850
|
package com.zhuanghl.jfinal.api;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.zhuanghl.jfinal.common.bean.BaseResponse;
import com.zhuanghl.jfinal.common.bean.Code;
import com.zhuanghl.jfinal.common.utils.DateUtils;
import com.zhuanghl.jfinal.common.utils.RandomUtils;
import com.zhuanghl.jfinal.model.PublishDaoyou;
public class APIPublishDaoyouController extends BaseAPIController {
public void upload() {
if (!methodType("post")) {
render404();
return;
}
String contentId = RandomUtils.randomCustomUUID();
new PublishDaoyou()
.set(PublishDaoyou.USER_ID, getPara("userId"))
.set(PublishDaoyou.CONTENT_ID, contentId)
.set(PublishDaoyou.TAGS, getPara("tags"))
.set(PublishDaoyou.TYPE, "BOZHU")
.set(PublishDaoyou.CONTENT_DETAILS, getPara("contentDetails"))
.set(PublishDaoyou.CREATION_DATE, DateUtils.getNowTimeStamp())
.save();
String sql = "SELECT * FROM t_publish_daoyou WHERE contentId=?";
PublishDaoyou publishDaoyou = PublishDaoyou.publishDaoyou.findFirst(sql, contentId);
renderJson(new BaseResponse(Code.SUCCESS, "", publishDaoyou.getAttrs()));
}
public void getAllDaoyou() {
if (!methodType("post")) {
render404();
return;
}
Page<Record> publishDaoyouPage =
Db.paginate(Integer.parseInt(getPara("pageNumber")),
Integer.parseInt(getPara("pageSize")),
"select *",
"from t_publish_daoyou order by creationDate desc");
renderJson(new BaseResponse(Code.SUCCESS, "", publishDaoyouPage));
}
}
| 39.361702
| 92
| 0.64
|
b0f2f10e0b6336b6e6633f4e13599740f13f4a35
| 6,227
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.applib.util;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.Base64;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.apache.isis.applib.value.Blob;
import org.apache.isis.applib.value.Markup;
import org.apache.isis.commons.internal.base._Bytes;
import org.apache.isis.commons.internal.base._Strings;
/**
* Provides JAXB XmlAdapters for Java built-in temporal types.
* Others types might be added, if convenient.
* <p>
*
* Example:<pre>
* @XmlElement @XmlJavaTypeAdapter(JaxbAdapters.LocalDateAdapter.class)
* @Getter @Setter private LocalDate javaLocalDate;
* </pre>
*
*
* @since 2.0
*/
public final class JaxbAdapters {
// -- MARKUP
public static final class MarkupAdapter extends XmlAdapter<String, Markup> {
private final static Base64.Encoder encoder = Base64.getEncoder();
private final static Base64.Decoder decoder = Base64.getDecoder();
@Override
public Markup unmarshal(String v) throws Exception {
if(v==null) {
return null;
}
final String html = _Strings.ofBytes(decoder.decode(v), StandardCharsets.UTF_8);
return new Markup(html);
}
@Override
public String marshal(Markup v) throws Exception {
if(v==null) {
return null;
}
final String html = v.asString();
return encoder.encodeToString(_Strings.toBytes(html, StandardCharsets.UTF_8));
}
}
// -- BLOB
public static final class BlobAdapter extends XmlAdapter<String, Blob> {
// copy pasted code from BlobValueSemanticsProvider
@Override
public Blob unmarshal(String data) throws Exception {
if(data==null) {
return null;
}
final int colonIdx = data.indexOf(':');
final String name = data.substring(0, colonIdx);
final int colon2Idx = data.indexOf(":", colonIdx+1);
final String mimeTypeBase = data.substring(colonIdx+1, colon2Idx);
final String payload = data.substring(colon2Idx+1);
final byte[] bytes = _Bytes.decodeBase64(Base64.getDecoder(), payload.getBytes(StandardCharsets.UTF_8));
try {
return new Blob(name, new MimeType(mimeTypeBase), bytes);
} catch (MimeTypeParseException e) {
throw new RuntimeException(e);
}
}
@Override
public String marshal(Blob blob) throws Exception {
if(blob==null) {
return null;
}
return blob.getName() + ":" +
blob.getMimeType().getBaseType() + ":" +
_Strings.ofBytes(_Bytes.encodeToBase64(Base64.getEncoder(), blob.getBytes()),
StandardCharsets.UTF_8);
}
}
// -- TEMPORAL VALUE TYPES
public static final class DateAdapter extends XmlAdapter<String, java.util.Date> {
@Override
public java.util.Date unmarshal(String v) throws Exception {
return new java.util.Date(Long.parseLong(v));
}
@Override
public String marshal(java.util.Date v) throws Exception {
return Long.toString(v.getTime());
}
}
public static final class SqlDateAdapter extends XmlAdapter<String, java.sql.Date> {
@Override
public java.sql.Date unmarshal(String v) throws Exception {
return java.sql.Date.valueOf(v);
}
@Override
public String marshal(java.sql.Date v) throws Exception {
return v.toString();
}
}
public static final class SqlTimestampAdapter extends XmlAdapter<String, java.sql.Timestamp> {
@Override
public java.sql.Timestamp unmarshal(String v) throws Exception {
return new java.sql.Timestamp(Long.parseLong(v));
}
@Override
public String marshal(java.sql.Timestamp v) throws Exception {
return Long.toString(v.getTime());
}
}
public static final class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
@Override
public LocalDate unmarshal(String v) throws Exception {
return LocalDate.parse(v);
}
@Override
public String marshal(LocalDate v) throws Exception {
return v.toString();
}
}
public static final class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
@Override
public LocalDateTime unmarshal(String v) throws Exception {
return LocalDateTime.parse(v);
}
@Override
public String marshal(LocalDateTime v) throws Exception {
return v.toString();
}
}
public static final class OffsetDateTimeAdapter extends XmlAdapter<String, OffsetDateTime> {
@Override
public OffsetDateTime unmarshal(String v) throws Exception {
return OffsetDateTime.parse(v);
}
@Override
public String marshal(OffsetDateTime v) throws Exception {
return v.toString();
}
}
}
| 30.826733
| 116
| 0.636422
|
e961c3ec1a24c9ae08407a76b0e29e32172a25c9
| 1,849
|
package karstenroethig.imagetags.webapp.bean;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import karstenroethig.imagetags.webapp.dto.ImagePageDto;
import karstenroethig.imagetags.webapp.dto.ImageSearchDto;
import karstenroethig.imagetags.webapp.util.MessageKeyEnum;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Component
@Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.TARGET_CLASS)
public class ImagesSearchBean
{
private ImageSearchDto searchParams;
private List<Long> searchResultImageIds;
private int currentPage;
private String errorMessageKey;
public ImagesSearchBean()
{
clear();
}
public void clear()
{
searchParams = null;
searchResultImageIds = new ArrayList<>();
currentPage = 0;
errorMessageKey = null;
}
public ImagePageDto getCurrentImagePage()
{
ImagePageDto imagePageDto = new ImagePageDto();
imagePageDto.setCurrentPageNumber(currentPage);
imagePageDto.setMaxPageNumber(searchResultImageIds.size());
imagePageDto.setErrorMessageKey(errorMessageKey);
return imagePageDto;
}
public Long getImageIdForCurrentPage()
{
if (searchResultImageIds == null || searchResultImageIds.isEmpty() || currentPage < 1)
{
errorMessageKey = MessageKeyEnum.IMAGES_SEARCH_EMPTY_RESULT.getKey();
return null;
}
return searchResultImageIds.get(currentPage - 1);
}
public void switchToCurrentPage(int page)
{
if (page < 1)
{
page = 1;
}
currentPage = Math.min(page, searchResultImageIds.size());
}
public void removeImageFormSearchResult(Long imageId)
{
searchResultImageIds.remove(imageId);
}
}
| 23.705128
| 89
| 0.788534
|
4bd922682bcbcd57b0779ad8001374b70d9034ba
| 1,235
|
package io.github.fxboy.io;
/**
* @author: Fanxing
* @time: 2022/3/5 16:08
* @description: This is a class object !!!
* At first, only God and I knew what it meant. [2022/3/5 16:08]
* Now, only God knows what it means. Oh, no, God doesn't know what it means. [Later]
*/
public class MonitorTick implements Runnable{
private long interval;
private FileExecutorAdaptor fileExecutorAdaptor;
private volatile boolean enable;
public MonitorTick(FileExecutorAdaptor fileExecutorAdaptor){
this.interval = 1000L;
this.fileExecutorAdaptor = fileExecutorAdaptor;
}
public MonitorTick(FileExecutorAdaptor fileExecutorAdaptor,long interval){
this.interval = interval;
this.fileExecutorAdaptor = fileExecutorAdaptor;
}
public void setEnable(boolean enable){
this.enable = enable;
}
@Override
public void run() {
fileExecutorAdaptor.onStart();
while (enable){
fileExecutorAdaptor.run();
// 执行完后间隔
try {
Thread.sleep(this.interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fileExecutorAdaptor.onStop();
}
}
| 28.068182
| 85
| 0.633198
|
55daaad25c01e007a6ef3abb2c7358aac8b9776b
| 3,973
|
package com.anysoftkeyboard.ime;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import com.anysoftkeyboard.api.KeyCodes;
import com.anysoftkeyboard.keyboards.Keyboard;
import com.anysoftkeyboard.keyboards.views.AnyKeyboardView;
import com.anysoftkeyboard.quicktextkeys.QuickTextKey;
import com.anysoftkeyboard.quicktextkeys.ui.QuickTextPagerView;
import com.anysoftkeyboard.quicktextkeys.ui.QuickTextViewFactory;
import com.menny.android.anysoftkeyboard.AnyApplication;
import com.menny.android.anysoftkeyboard.R;
public abstract class AnySoftKeyboardWithQuickText extends AnySoftKeyboardHardware {
private boolean mDoNotFlipQuickTextKeyAndPopupFunctionality;
private String mOverrideQuickTextText = "";
@Override
public void onCreate() {
super.onCreate();
addDisposable(prefs().getBoolean(R.string.settings_key_do_not_flip_quick_key_codes_functionality, R.bool.settings_default_do_not_flip_quick_keys_functionality)
.asObservable().subscribe(value -> mDoNotFlipQuickTextKeyAndPopupFunctionality = value));
addDisposable(prefs().getString(R.string.settings_key_emoticon_default_text, R.string.settings_default_empty)
.asObservable().subscribe(value -> mOverrideQuickTextText = value));
}
protected void onQuickTextRequested(Keyboard.Key key) {
if (mDoNotFlipQuickTextKeyAndPopupFunctionality) {
outputCurrentQuickTextKey(key);
} else {
switchToQuickTextKeyboard();
}
}
protected void onQuickTextKeyboardRequested(Keyboard.Key key) {
if (mDoNotFlipQuickTextKeyAndPopupFunctionality) {
switchToQuickTextKeyboard();
} else {
outputCurrentQuickTextKey(key);
}
}
private void outputCurrentQuickTextKey(Keyboard.Key key) {
QuickTextKey quickTextKey = AnyApplication.getQuickTextKeyFactory(this).getEnabledAddOn();
if (TextUtils.isEmpty(mOverrideQuickTextText))
onText(key, quickTextKey.getKeyOutputText());
else
onText(key, mOverrideQuickTextText);
}
private void switchToQuickTextKeyboard() {
abortCorrectionAndResetPredictionState(false);
setCandidatesViewShown(false);
cleanUpQuickTextKeyboard(false);
final AnyKeyboardView actualInputView = (AnyKeyboardView) getInputView();
final int height = actualInputView.getHeight();
actualInputView.setVisibility(View.GONE);
QuickTextPagerView quickTextsLayout = QuickTextViewFactory.createQuickTextView(getApplicationContext(), getInputViewContainer(), height, getQuickKeyHistoryRecords());
actualInputView.resetInputView();
quickTextsLayout.setThemeValues(actualInputView.getLabelTextSize(), actualInputView.getKeyTextColor(),
actualInputView.getDrawableForKeyCode(KeyCodes.CANCEL), actualInputView.getDrawableForKeyCode(KeyCodes.DELETE), actualInputView.getDrawableForKeyCode(KeyCodes.SETTINGS),
actualInputView.getBackground());
getInputViewContainer().addView(quickTextsLayout);
}
private boolean cleanUpQuickTextKeyboard(boolean reshowStandardKeyboard) {
final ViewGroup inputViewContainer = getInputViewContainer();
if (inputViewContainer == null) return false;
QuickTextPagerView quickTextsLayout = inputViewContainer.findViewById(R.id.quick_text_pager_root);
if (quickTextsLayout != null) {
inputViewContainer.removeView(quickTextsLayout);
if (reshowStandardKeyboard) {
View standardKeyboardView = (View) getInputView();
standardKeyboardView.setVisibility(View.VISIBLE);
}
return true;
} else {
return false;
}
}
@Override
protected boolean handleCloseRequest() {
return super.handleCloseRequest() || cleanUpQuickTextKeyboard(true);
}
}
| 41.821053
| 185
| 0.732444
|
9a39028a802a3077ff0911e8fa41dc2e0d2f7333
| 2,341
|
package sswl.caipai.ui.activity.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.shizhefei.view.indicator.FixedIndicatorView;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.shizhefei.view.viewpager.SViewPager;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import sswl.caipai.R;
import sswl.caipai.ui.activity.MainActivity;
import sswl.caipai.ui.activity.base.BaseFragment;
import sswl.caipai.ui.activity.search.SearchActivity;
import sswl.caipai.ui.adapter.fragment.LiveFragmentAdapter;
/**
* Created by Administrator on 2016/5/12 0012.
*/
@ContentView(R.layout.fragment_live)
public class LiveFragment extends BaseFragment {
@ViewInject(R.id.fiv_live_tab)
private FixedIndicatorView fiv_live_tab;
@ViewInject(R.id.svp_live)
private SViewPager svp_live;
@ViewInject(R.id.iv_search)
private ImageView iv_search;
private IndicatorViewPager indicatorvp;
private String[] tab_name={"关注","热门","最新"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void initData() {
indicatorvp = new IndicatorViewPager(fiv_live_tab,svp_live);
indicatorvp.setAdapter(new LiveFragmentAdapter(getFragmentManager(),getActivity(),tab_name));
indicatorvp.setIndicatorOnTransitionListener(new OnTransitionTextListener());
indicatorvp.setCurrentItem(1,false);
iv_search.setOnClickListener(this);
}
@Override
public void initViews() {
super.initViews();
}
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()){
case R.id.iv_search:
Intent intent = new Intent(MainActivity.mainActivity, SearchActivity.class);
startActivity(intent);
}
}
}
| 30.402597
| 103
| 0.739855
|
ff74e1fc0461b9d5ab7665acef8c54e4ccca13a6
| 480
|
package cn.generation.service;
import cn.generation.pojo.book_list;
import org.apache.ibatis.annotations.Param;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
public interface book_listservice {
List<book_list> select_book(int op, int ed);
String save(MultipartFile file, book_list book, ModelMap map) throws IOException;
Integer select_allbook();
}
| 30
| 86
| 0.775
|
f025365977902a07f39edc6b8c0052383dcc640a
| 239
|
import testpackage.*;
import testpackage.World;
public class Hoi extends Hello {
public Y m(X x) {
Z z = new Aap();
a = b;
if (a==b) {
if (a==b) { b = a; }
{ a = b; }
;
}
}
public Hoep() {
}
}
| 12.578947
| 32
| 0.447699
|
d61de04970d8a496343317f77627020956a2a65d
| 1,626
|
/**
*
*/
package net.beaconcontroller.packet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
/**
* @author David Erickson (daviderickson@cs.stanford.edu)
*
*/
public class IPv4Test {
@Test
public void testToIPv4Address() {
int expected = 0xc0a80001;
assertEquals(expected, IPv4.toIPv4Address("192.168.0.1"));
}
@Test
public void testToIPv4AddressBytes() {
byte[] expected = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
Assert.assertArrayEquals(expected, IPv4.toIPv4AddressBytes("255.255.255.255"));
expected = new byte[] {(byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80};
Assert.assertArrayEquals(expected, IPv4.toIPv4AddressBytes("128.128.128.128"));
expected = new byte[] {0x7f,0x7f,0x7f,0x7f};
Assert.assertArrayEquals(expected, IPv4.toIPv4AddressBytes("127.127.127.127"));
}
@Test
public void testSerialize() {
byte[] expected = new byte[] { 0x45, 0x00, 0x00, 0x14, 0x5e, 0x4e,
0x00, 0x00, 0x3f, 0x06, 0x31, 0x2e, (byte) 0xac, 0x18,
0x4a, (byte) 0xdf, (byte) 0xab, 0x40, 0x4a, 0x30 };
IPv4 packet = new IPv4()
.setIdentification((short) 24142)
.setTtl((byte) 63)
.setProtocol((byte) 0x06)
.setSourceAddress("172.24.74.223")
.setDestinationAddress("171.64.74.48");
byte[] actual = packet.serialize();
assertTrue(Arrays.equals(expected, actual));
}
}
| 32.52
| 90
| 0.624231
|
c7f24ed3b39ee8639bcdd9bd9965ed195af38143
| 2,912
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.requestcontroller;
import java.util.Collections;
import java.util.List;
/**
*
* Class that can be used to report of the current system state.
*
* @author Stuart Douglas
*/
public class RequestControllerState {
private final boolean paused;
private final int outstandingRequests;
private final int maxRequests;
private final List<EntryPointState> entryPoints;
public RequestControllerState(boolean paused, int outstandingRequests, int maxRequests, List<EntryPointState> entryPoints) {
this.paused = paused;
this.outstandingRequests = outstandingRequests;
this.maxRequests = maxRequests;
this.entryPoints = entryPoints;
}
public boolean isPaused() {
return paused;
}
public int getOutstandingRequests() {
return outstandingRequests;
}
public int getMaxRequests() {
return maxRequests;
}
public List<EntryPointState> getEntryPoints() {
return Collections.unmodifiableList(entryPoints);
}
public static class EntryPointState {
private final String deployment;
private final String endpoint;
private final boolean paused;
private final int outstandingRequests;
public EntryPointState(String deployment, String endpoint, boolean paused, int outstandingRequests) {
this.deployment = deployment;
this.endpoint = endpoint;
this.paused = paused;
this.outstandingRequests = outstandingRequests;
}
public String getDeployment() {
return deployment;
}
public String getEndpoint() {
return endpoint;
}
public boolean isPaused() {
return paused;
}
public int isOutstandingRequests() {
return outstandingRequests;
}
}
}
| 31.311828
| 128
| 0.689217
|
13be62ec74ca33ae3d36181eee7ab6b39e839808
| 145
|
package video.api.uploader.api.upload;
public interface UploadPartProgressListener {
void onProgress(Long bytesWritten, Long totalBytes);
}
| 24.166667
| 56
| 0.806897
|
85a5858e97b39c306e2c51484f2f8cf8fc2594ea
| 802
|
/* $Id: ParseException.java 150536 2014-04-15 20:54:59Z nwinant $
*
* Copyright (c) 2010 Cycorp, Inc. All rights reserved.
* This software is the proprietary information of Cycorp, Inc.
* Use is subject to license terms.
*/
package com.cyc.baseclient.util;
/**
* <P>ParseException is designed to...
*
* <P>Copyright (c) 2010 Cycorp, Inc. All rights reserved.
* <BR>This software is the proprietary information of Cycorp, Inc.
* <P>Use is subject to license terms.
*
* Created on : May 24, 2010, 10:37:18 AM
* Author : nwinant
* @version $Id: ParseException.java 150536 2014-04-15 20:54:59Z nwinant $
*/
public class ParseException extends Exception {
/** Creates a new instance of ParseException. */
public ParseException(final String message) {
super(message);
}
}
| 27.655172
| 74
| 0.695761
|
09e707e3fd78a377a1c2c379b13cd44d21cc6735
| 4,062
|
/**
* Copyright 2016 Yurii Rashkovskii
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*/
package graphql.annotations.processor.typeFunctions;
import graphql.annotations.annotationTypes.GraphQLID;
import org.testng.annotations.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import static graphql.Scalars.GraphQLID;
import static graphql.annotations.processor.typeFunctions.DefaultTypeFunctionTestHelper.testedDefaultTypeFunction;
import static org.testng.Assert.assertEquals;
public class IDFunctionTests {
public @graphql.annotations.annotationTypes.GraphQLID String idStringMethod() {
return "asd";
}
public @GraphQLID Integer idIntegerMethod() {
return 5;
}
public @GraphQLID int idIntMethod() {
return 5;
}
public @GraphQLID String idStringField;
public @GraphQLID Integer idIntegerField;
public @GraphQLID int idIntField;
@Test
public void buildType_stringMethodAnnotatedWithGraphQLID_returnsGraphQLID() throws NoSuchMethodException, NoSuchFieldException {
// Arrange
DefaultTypeFunction instance = testedDefaultTypeFunction();
Method idStringMethod = IDFunctionTests.class.getMethod("idStringMethod");
// Act+Assert
assertEquals(instance.buildType(idStringMethod.getReturnType(), idStringMethod.getAnnotatedReturnType(), null), GraphQLID);
}
@Test
public void buildType_integerMethodAnnotatedWithGraphQLID_returnsGraphQLID() throws NoSuchMethodException {
// Arrange
DefaultTypeFunction instance = testedDefaultTypeFunction();
Method idIntegerMethod = IDFunctionTests.class.getMethod("idIntegerMethod");
// Act+Assert
assertEquals(instance.buildType(idIntegerMethod.getReturnType(), idIntegerMethod.getAnnotatedReturnType(), null), GraphQLID);
}
@Test
public void buildType_intMethodAnnotatedWithGraphQLID_returnsGraphQLID() throws NoSuchMethodException {
// Arrange
DefaultTypeFunction instance = testedDefaultTypeFunction();
Method idIntMethod = IDFunctionTests.class.getMethod("idIntMethod");
// Act+Assert
assertEquals(instance.buildType(idIntMethod.getReturnType(), idIntMethod.getAnnotatedReturnType(), null), GraphQLID);
}
@Test
public void buildType_stringFieldAnnotatedWithGraphQLID_returnsGraphQLID() throws NoSuchFieldException {
// Arrange
DefaultTypeFunction instance = testedDefaultTypeFunction();
Field idStringField = IDFunctionTests.class.getField("idStringField");
// Act+Assert
assertEquals(instance.buildType(idStringField.getType(), idStringField.getAnnotatedType(), null), GraphQLID);
}
@Test
public void buildType_integerFieldAnnotatedWithGraphQLID_returnsGraphQLID() throws NoSuchFieldException {
// Arrange
DefaultTypeFunction instance = testedDefaultTypeFunction();
Field idIntegerField = IDFunctionTests.class.getField("idIntegerField");
// Act+Assert
assertEquals(instance.buildType(idIntegerField.getType(), idIntegerField.getAnnotatedType(), null), GraphQLID);
}
@Test
public void buildType_intFieldAnnotatedWithGraphQLID_returnsGraphQLID() throws NoSuchFieldException {
// Arrange
DefaultTypeFunction instance = testedDefaultTypeFunction();
Field idIntField = IDFunctionTests.class.getField("idIntField");
// Act+Assert
assertEquals(instance.buildType(idIntField.getType(), idIntField.getAnnotatedType(), null), GraphQLID);
}
}
| 37.611111
| 133
| 0.744953
|
9b9e449cde6d8f76a35e521cb47c4fd2f5cca9b9
| 1,354
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.can.TalonFX;
import com.ctre.phoenix.motorcontrol.can.VictorSPX;
import edu.wpi.first.wpilibj.PneumaticsModuleType;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.RobotContainer;
public class ClimbSub extends SubsystemBase {
private Solenoid climbSol;
public TalonFX climbMaster;
public VictorSPX climbSlave;
/** Creates a new ClimbSub. */
public ClimbSub() {
climbSol = new Solenoid(PneumaticsModuleType.CTREPCM, 1);
climbMaster = new TalonFX(4);
climbSlave = new VictorSPX(2);
climbSlave.follow(climbMaster);
}
@Override
public void periodic() {
// This method will be called once per scheduler run
}
public void skyHookToggle() {
if (climbSol.get() == true) {
climbSol.set(false);
} else {
climbSol.set(true);
}
}
public void skyHookExtend() {
climbMaster.set(ControlMode.PercentOutput, RobotContainer.operatorJoy.getRawAxis(Constants.operatorRightAxisY));
}
}
| 27.632653
| 116
| 0.742984
|
8fd75f3ca8bdd209869b937d637960e45a58964b
| 2,019
|
package com.liuscoding.acl.controller;
import com.liuscoding.acl.entity.Permission;
import com.liuscoding.acl.service.PermissionService;
import com.liuscoding.commonutils.vo.ResultVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 权限 菜单管理
* </p>
*
* @author testjava
* @since 2020-01-12
*/
@RestController
@RequestMapping("/admin/acl/permission")
/*@CrossOrigin*/
public class PermissionController {
@Autowired
private PermissionService permissionService;
//获取全部菜单
@ApiOperation(value = "查询所有菜单")
@GetMapping
public ResultVo indexAllPermission() {
List<Permission> list = permissionService.queryAllMenuGuli();
return ResultVo.ok().data("children",list);
}
@ApiOperation(value = "递归删除菜单")
@DeleteMapping("remove/{id}")
public ResultVo remove(@PathVariable String id) {
permissionService.removeChildByIdGuli(id);
return ResultVo.ok();
}
@ApiOperation(value = "给角色分配权限")
@PostMapping("/doAssign")
public ResultVo doAssign(String roleId,String[] permissionId) {
permissionService.saveRolePermissionRealtionShipGuli(roleId,permissionId);
return ResultVo.ok();
}
@ApiOperation(value = "根据角色获取菜单")
@GetMapping("toAssign/{roleId}")
public ResultVo toAssign(@PathVariable String roleId) {
List<Permission> list = permissionService.selectAllMenu(roleId);
return ResultVo.ok().data("children", list);
}
@ApiOperation(value = "新增菜单")
@PostMapping("save")
public ResultVo save(@RequestBody Permission permission) {
permissionService.save(permission);
return ResultVo.ok();
}
@ApiOperation(value = "修改菜单")
@PutMapping("update")
public ResultVo updateById(@RequestBody Permission permission) {
permissionService.updateById(permission);
return ResultVo.ok();
}
}
| 26.565789
| 82
| 0.699356
|
441236a91194fd8e2abe462ed635a0fa57839a92
| 724
|
package com.github.gof.behavioral.iterator.demo2;
import java.util.ArrayList;
import java.util.List;
/**
* 书架为图书的数组
*
* @author db1995
*/
public class BookShelf implements Aggregate {
private List<Book> books;
private int last = 0;
public BookShelf(int maxSize) {
this.books = new ArrayList<>();
}
public Book getBookAt(int index) {
return books.get(index);
}
public void appendBook(Book book) {
books.add(book);
last++;
}
public int getLength() {
return last; //这里也许还可以写成return books.length;
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
| 19.567568
| 56
| 0.589779
|
76ba3d613733c2ce379d743cae08115152047977
| 764
|
/**
* NameModelMapperConverter.java 21 mar. 2021
*
*/
package org.sylrsykssoft.springboot.common.api.mapper.converter.model.embeddable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.modelmapper.Converters.Converter;
import org.sylrsykssoft.springboot.common.api.dto.embeddable.NameModelDTO;
import org.sylrsykssoft.springboot.common.api.model.embeddable.NameModel;
/**
* NameModelMapperConverter
*
* @author juan.gonzalez.fernandez.jgf
*
*/
public class NameModelMapperConverter implements Converter<NameModelDTO, NameModel> {
/**
* {@inheritDoc}
*/
@Override
@Valid
public NameModel convert(@NotNull @Valid final NameModelDTO source) {
return NameModel.builder().name(source.getName()).build();
}
}
| 25.466667
| 85
| 0.777487
|
e024f8ccd600c3663760959e8e3f750c89bb40bb
| 6,945
|
package com.houarizegai.learnsql.java.controllers.form;
import com.houarizegai.learnsql.java.controllers.ManageAccountController;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXSnackbar;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXToggleButton;
import com.houarizegai.learnsql.java.dao.UserDao;
import com.houarizegai.learnsql.java.models.User;
import java.net.URL;
import java.sql.Date;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import static javafx.scene.input.KeyCode.ENTER;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import org.controlsfx.control.Notifications;
public class AddUserFormController implements Initializable {
/* Start Add Account Pane */
@FXML
private VBox root;
@FXML
private JFXTextField userNameField;
@FXML
private JFXPasswordField passwordField;
@FXML
private JFXTextField firstNameField;
@FXML
private JFXTextField lastNameField;
@FXML
private JFXDatePicker datePicker;
@FXML
private JFXTextField emailField;
@FXML
private JFXToggleButton isTeacherToggleButton;
@FXML
private JFXComboBox<String> comboSection, comboGroup;
private JFXSnackbar toastErrorMsg; // Error Message
/* End Add Account Pane */
@Override
public void initialize(URL url, ResourceBundle rb) {
// This ComboBox for Add Account
comboSection.getItems().addAll(new String[]{"1", "2", "3", "4"});
comboGroup.getItems().addAll(new String[]{"1", "2", "3"});
/* End ComboBox */
root.setOnKeyPressed(event -> { // Add Key Listener, if i click to the Enter Button Call btnLogin() method
if (event.getCode().equals(ENTER)) {
btnAdd();
}
});
toastErrorMsg = new JFXSnackbar(root);
userNameField.setOnKeyReleased(event -> { // this event for check max length of the answer area
if (userNameField.getText().length() > 25) {
userNameField.setText(userNameField.getText().substring(0, 25));
userNameField.positionCaret(userNameField.getText().length());
}
});
passwordField.setOnKeyReleased(event -> { // this event for check max length of the answer area
if (passwordField.getText().length() > 50) {
passwordField.setText(passwordField.getText().substring(0, 50));
passwordField.positionCaret(passwordField.getText().length());
}
});
}
/* Start Add Account Action Part */
@FXML
public void btnClear() {
userNameField.setText("");
passwordField.setText("");
firstNameField.setText("");
lastNameField.setText("");
datePicker.setValue(null);
emailField.setText("");
isTeacherToggleButton.setSelected(false);
comboSection.setVisible(true);
comboGroup.setVisible(true);
comboSection.getSelectionModel().select(null);
comboGroup.getSelectionModel().select(null);
}
@FXML
public void btnAdd() { // Add New Student
if (!userNameField.getText().trim().toLowerCase().matches("[a-z0-9_]{4,}")) {
toastErrorMsg.show("Username error !", 1500);
return;
}
if (passwordField.getText().length() < 8) {
toastErrorMsg.show("Password error !", 1500);
return;
}
if (!firstNameField.getText().trim().toLowerCase().matches("[a-z]{3,}")) {
toastErrorMsg.show("First name error !", 1500);
return;
}
if (!lastNameField.getText().trim().toLowerCase().matches("[a-z]{3,}")) {
toastErrorMsg.show("Last name error !", 1500);
return;
}
if (datePicker.getValue() == null) {
toastErrorMsg.show("Please fill Date of Birth !", 1500);
return;
}
if (!emailField.getText().trim().matches("[a-zA-Z_][\\w]*[-]{0,4}[\\w]+@[a-zA-Z0-9]+.[a-zA-Z]{2,6}")) {
toastErrorMsg.show("Email error !", 1500);
return;
}
if (!isTeacherToggleButton.isSelected()) {
if (comboSection.getSelectionModel().getSelectedItem() == null) {
toastErrorMsg.show("Please fill section !", 1500);
return;
}
if (comboGroup.getSelectionModel().getSelectedItem() == null) {
toastErrorMsg.show("Please fill group !", 1500);
return;
}
}
User user = new User();
user.setUsername(userNameField.getText().trim().toLowerCase());
user.setPassword(passwordField.getText());
user.setFirstName(firstNameField.getText().trim().toLowerCase());
user.setLastName(lastNameField.getText().trim().toLowerCase());
System.out.println("Date : " + datePicker.getValue().toString());
user.setDateOfBirth(Date.valueOf(datePicker.getValue()));
user.setEmail(emailField.getText().trim().toLowerCase());
user.setIsTeacher(isTeacherToggleButton.isSelected());
if (!isTeacherToggleButton.isSelected()) {
user.setSection(Integer.parseInt(comboSection.getSelectionModel().getSelectedItem()));
user.setGroup(Integer.parseInt(comboGroup.getSelectionModel().getSelectedItem()));
}
int status = new UserDao().addUser(user);
switch (status) {
case -1:
toastErrorMsg.show("Connection failed :", 1500);
break;
case 0:
toastErrorMsg.show("User not added :", 1500);
break;
case 2:
toastErrorMsg.show("Username aleady exists !", 1500);
break;
case 1: {
Notifications.create()
.title("You Successfuly added new user !")
.graphic(new ImageView(new Image("/com/houarizegai/learnsql/resources/images/icons/valid.png")))
.hideAfter(Duration.millis(2000))
.position(Pos.BOTTOM_RIGHT)
.darkStyle()
.show();
ManageAccountController.addUserDialog.close();
}
}
}
@FXML
public void actionToggleButton() {
if (isTeacherToggleButton.isSelected()) {
comboSection.setVisible(false);
comboGroup.setVisible(false);
} else {
comboSection.setVisible(true);
comboGroup.setVisible(true);
}
}
@FXML
private void btnClose() {
ManageAccountController.addUserDialog.close();
}
}
| 37.33871
| 120
| 0.607343
|
7519e040e2e71f19a6c2beb2a0ea3fe524fa1708
| 3,452
|
package com.vaadin.database.data.entity;
import javax.persistence.*;
import javax.validation.constraints.Min;
import java.io.Serializable;
import java.time.LocalDate;
@Entity
public class Balances{
@Id
@SequenceGenerator(name = "balances_generator", sequenceName = "balances_seq", initialValue = 10)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "balances_generator")
private int balance_id;
@OneToOne()
@JoinColumn(name = "caller_ID", referencedColumnName = "caller_id")
private Callers caller_ID;
@Column(nullable = false)
@Min(0)
private int long_distance_calls_debt;
@Column(nullable = false)
@Min(0)
private int penalty_interest;
@Column(nullable = false)
@Min(0)
private int subscription_debt;
private LocalDate subscription_debt_date;
private LocalDate long_dist_debt_date;
public Balances(){}
public int getSubscription_debt() {
return subscription_debt;
}
public void setSubscription_debt(int subscription_debt) {
this.subscription_debt = subscription_debt;
}
public Balances(int balance_id, Callers caller_ID, @Min(0) int long_distance_calls_debt, @Min(0) int penalty_interest, @Min(0) int subscription_debt, LocalDate subscription_debt_date, LocalDate long_dist_debt_date) {
this.balance_id = balance_id;
this.caller_ID = caller_ID;
this.long_distance_calls_debt = long_distance_calls_debt;
this.penalty_interest = penalty_interest;
this.subscription_debt = subscription_debt;
this.subscription_debt_date = subscription_debt_date;
this.long_dist_debt_date = long_dist_debt_date;
}
public int getBalance_id() {
return balance_id;
}
public void setBalance_id(int balance_id) {
this.balance_id = balance_id;
}
public Callers getCaller_ID() {
return caller_ID;
}
public void setCaller_ID(Callers caller_ID) {
this.caller_ID = caller_ID;
}
public int getLong_distance_calls_debt() {
return long_distance_calls_debt;
}
public void setLong_distance_calls_debt(int long_distance_calls_debt) {
this.long_distance_calls_debt = long_distance_calls_debt;
}
public int getPenalty_interest() {
return penalty_interest;
}
public void setPenalty_interest(int penalty_interest) {
this.penalty_interest = penalty_interest;
}
public LocalDate getSubscription_debt_date() {
return subscription_debt_date;
}
public void setSubscription_debt_date(LocalDate subscription_debt_date) {
this.subscription_debt_date = subscription_debt_date;
}
public LocalDate getLong_dist_debt_date() {
return long_dist_debt_date;
}
public void setLong_dist_debt_date(LocalDate long_dist_debt_date) {
this.long_dist_debt_date = long_dist_debt_date;
}
@Override
public String toString() {
return "Balances{" +
"balance_id=" + balance_id +
", caller_ID=" + caller_ID +
", long_distance_calls_debt=" + long_distance_calls_debt +
", penalty_interest=" + penalty_interest +
", subscription_debt=" + subscription_debt +
", subscription_debt_date=" + subscription_debt_date +
", long_dist_debt_date=" + long_dist_debt_date +
'}';
}
}
| 29.504274
| 220
| 0.688586
|
09573ab23c98e13c32aea4217742dc8fda8e0bc1
| 2,327
|
/**
* Copyright 2019 The JoyQueue Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.chubao.joyqueue.network.transport.command.handler.filter;
import io.chubao.joyqueue.network.transport.command.Command;
import io.chubao.joyqueue.network.transport.command.handler.CommandHandler;
import io.chubao.joyqueue.network.transport.Transport;
import io.chubao.joyqueue.network.transport.exception.TransportException;
import org.apache.commons.collections.CollectionUtils;
import java.util.Iterator;
import java.util.List;
/**
* CommandHandlerInvocation
*
* author: gaohaoxiang
* date: 2018/8/16
*/
public class CommandHandlerInvocation {
private Transport transport;
private Command request;
private CommandHandler commandHandler;
private Iterator<CommandHandlerFilter> filterIterator;
private CommandHandlerContext context;
public CommandHandlerInvocation(Transport transport, Command request, CommandHandler commandHandler, List<CommandHandlerFilter> filterList) {
this.transport = transport;
this.request = request;
this.commandHandler = commandHandler;
this.filterIterator = (CollectionUtils.isEmpty(filterList) ? null : filterList.iterator());
}
public Command invoke() throws TransportException {
if (filterIterator == null || !filterIterator.hasNext()) {
return commandHandler.handle(transport, request);
} else {
return filterIterator.next().invoke(this);
}
}
public Transport getTransport() {
return transport;
}
public Command getRequest() {
return request;
}
public CommandHandlerContext getContext() {
if (context == null) {
context = new CommandHandlerContext();
}
return context;
}
}
| 33.242857
| 145
| 0.72196
|
9aac13ffc53dd804d7f4dc10ee7c25d8a56cb31b
| 379
|
package com.leetcode.algorithm.easy.twocityscheduling;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SolutionTest {
@Test
public void testCase1() {
Solution solution = new Solution();
assertEquals(
110, solution.twoCitySchedCost(new int[][] {{10, 20}, {30, 200}, {400, 50}, {30, 20}}));
}
}
| 25.266667
| 96
| 0.69657
|
072614ec2df6d9bba7dd4edf1efd165b598ce94c
| 3,772
|
package question5;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TheaterRevenue extends JFrame
{
private JPanel panel;
private JRadioButton calculateButton;
private JRadioButton exitButton;
private ButtonGroup bg;
private JLabel adultTicketPriceMessage;
private JLabel adultTicketSoldMessage;
private JLabel childTicketPriceMessage;
private JLabel childTicketSoldMessage;
private JTextField adultTicketPriceInput;
private JTextField adultTicketSoldInput;
private JTextField childTicketPriceInput;
private JTextField childTicketSoldInput;
private final int WINDOW_WIDTH = 400;
private final int WINDOW_HEIGHT = 200;
public TheaterRevenue()
{
setTitle("Travel Expenses");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
pack();
setVisible(true);
}
private void buildPanel()
{
calculateButton = new JRadioButton("Calculate");
exitButton = new JRadioButton("Exit");
bg = new ButtonGroup();
bg.add(calculateButton);
bg.add(exitButton);
adultTicketPriceMessage = new JLabel("Enter the price per adult ticket: $");
adultTicketSoldMessage = new JLabel("Number of adult tickets sold: ");
childTicketPriceMessage = new JLabel("Enter the price per child ticket: $");
childTicketSoldMessage = new JLabel("Number of child tickets sold: ");
adultTicketPriceInput = new JTextField(6);
adultTicketSoldInput = new JTextField(6);
childTicketPriceInput = new JTextField(6);
childTicketSoldInput = new JTextField(6);
panel = new JPanel();
panel.setLayout(new GridLayout(8,1));
panel.add(adultTicketPriceMessage);
panel.add(adultTicketPriceInput);
panel.add(adultTicketSoldMessage);
panel.add(adultTicketSoldInput);
panel.add(childTicketPriceMessage);
panel.add(childTicketPriceInput);
panel.add(childTicketSoldMessage);
panel.add(childTicketSoldInput);
panel.add(calculateButton);
panel.add(exitButton);
calculateButton.addActionListener(new ActionListeners());
exitButton.addActionListener(new ActionListeners());
bg = new ButtonGroup();
bg.add(calculateButton);
bg.add(exitButton);
}
public class ActionListeners implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(calculateButton.isSelected())
{
double grossRevenueAdult, netRevenueAdult, grossRevenueChild, netRevenueChild,
totalGrossRevenue, totlaNetRevenue;
grossRevenueAdult = Double.parseDouble(adultTicketPriceInput.getText()) *
Double.parseDouble(adultTicketSoldInput.getText());
netRevenueAdult = grossRevenueAdult * 0.80;
grossRevenueChild = Double.parseDouble(childTicketPriceInput.getText()) *
Double.parseDouble(childTicketSoldInput.getText());
netRevenueChild = grossRevenueChild * 0.80;
totalGrossRevenue = grossRevenueAdult + grossRevenueChild;
totlaNetRevenue = netRevenueAdult + netRevenueChild;
JOptionPane.showMessageDialog(null, String.format("The gross revenue adult amount: $%,.2f"
+ "\nThe net revenue adult amount: $%,.2f"+
"\nThe gross revenue child amount: $%,.2f"
+ "\nThe net revenue child amount: $%,.2f"+
"\nThe total gross revenue amount: $%,.2f"
+ "\nThe net revenue child amount: $%,.2f",
grossRevenueAdult, netRevenueAdult,grossRevenueChild, netRevenueChild,
totalGrossRevenue, totlaNetRevenue));
}
else if(exitButton.isSelected())
System.exit(0);
}
}
public static void main(String[] args)
{
new TheaterRevenue();
}
}
| 30.419355
| 96
| 0.720042
|
829c203cf3486916176707687be7e14989dcff9b
| 857
|
package com.company.onlinestore;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
public class Basket {
public final static List<String> COMPATIBLE_PRODUCTS =
Arrays.asList("SPORTS", "NEWS", "MOVIES_1", "MOVIES_2");
private List<String> products;
public Basket(List<String> products) {
this.products = products;
}
//implement basket contents
public List<String> getThreeDeeCompatibleProducts() {
return products.stream()
.filter(e -> COMPATIBLE_PRODUCTS.contains(e))
.collect(Collectors.toList());
}
//implement notifications
public String generateNotification(List<String> addOns) {
return CollectionUtils.isEmpty(addOns) ? "No 3D add-ons" : "All relevant addOns: " + addOns;
}
}
| 25.969697
| 96
| 0.704784
|
2add4759b313f1ae6d58686b7609f801f3e84fc7
| 509
|
package com.pubnub.api.callbacks;
import com.pubnub.api.PubNub;
import com.pubnub.api.models.consumer.pubsub.PNMessageResult;
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult;
import com.pubnub.api.models.consumer.PNStatus;
public abstract class SubscribeCallback {
public abstract void status(PubNub pubnub, PNStatus status);
public abstract void message(PubNub pubnub, PNMessageResult message);
public abstract void presence(PubNub pubnub, PNPresenceEventResult presence);
}
| 39.153846
| 81
| 0.817289
|
eeae7a2c6bb90f8a978d723214ec5362037234e8
| 1,239
|
package com.lin.utils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 享元模式工具类(全局运行环境中,相同的类共享同一个实例对象)
* @author lkmc2
* @since 1.0.0
*/
public class FlyweightUtils {
/** 存储类和对应的实例对象 **/
private static final ConcurrentMap<Class, Object> MAP = new ConcurrentHashMap<Class, Object>();
/**
* 获取指定类型的实例对象
* @param type 类的Class类型
* @param <T> 类的泛型
* @return 指定类型的实例对象
*/
@SuppressWarnings("unchecked")
public static <T> T getInstance(Class<T> type) {
// 从MAP中获取类型对应的实例对象
Object obj = MAP.get(type);
try {
// 对象为空
if (obj == null) {
synchronized (MAP) {
// 使用该类的无参构造器生成实例对象
obj = type.newInstance();
// 将实例对象放入MAP中
MAP.put(type, obj);
}
}
} catch (Exception e) {
throw new RuntimeException(String.format("实例化[ %s ]对象失败", type.getName()));
}
return (T) obj;
}
/**
* 移除指定类型的单例对象
* @param type 类的Class类型
* @param <T> 类的泛型
*/
public static <T> void remove(Class<T> type) {
MAP.remove(type);
}
}
| 23.826923
| 99
| 0.530266
|
7655150a54a818527b605f72989dc9c7f6435e27
| 1,343
|
package com.ibm.maersk.rest;
import org.glassfish.jersey.message.GZipEncoder;
import org.glassfish.jersey.message.filtering.EntityFilteringFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.EncodingFilter;
/**
* Registers the components to be used by the JAX-RS application
*
* @author ama
*
*/
public class RestDemoJaxRsApplication extends ResourceConfig {
/**
* Register JAX-RS application components.
*/
public RestDemoJaxRsApplication() {
packages("com.ibm.maersk.rest");
// // register application resources
// register(PodcastsResource.class);
// register(PodcastLegacyResource.class);
//
// // register filters
// register(RequestContextFilter.class);
// register(LoggingResponseFilter.class);
// register(CORSResponseFilter.class);
//
// // register exception mappers
// register(GenericExceptionMapper.class);
// register(AppExceptionMapper.class);
// register(CustomReasonPhraseExceptionMapper.class);
// register(NotFoundExceptionMapper.class);
//
// // register features
// register(JacksonFeature.class);
register(EntityFilteringFeature.class);
EncodingFilter.enableFor(this, GZipEncoder.class);
// property(EntityFilteringFeature.ENTITY_FILTERING_SCOPE, new Annotation[] {PodcastDetailedView.Factory.get()});
}
}
| 29.195652
| 114
| 0.756515
|
79603f42763588b4703aeb5df900ffce7812914f
| 614
|
package net.blueberrymc.common.event.block;
import net.blueberrymc.common.Blueberry;
import net.blueberrymc.common.bml.event.Event;
import net.blueberrymc.world.level.block.Block;
import org.jetbrains.annotations.NotNull;
public abstract class BlockEvent extends Event {
protected final Block block;
public BlockEvent(@NotNull Block block) {
this(block, !Blueberry.getUtil().isOnGameThread());
}
protected BlockEvent(@NotNull Block block, boolean async) {
super(async);
this.block = block;
}
@NotNull
public Block getBlock() {
return block;
}
}
| 24.56
| 63
| 0.705212
|
eca5281edcafce0ca207fce7b74ae76395275cb8
| 287
|
package com.hmtmcse.j2swagger.data;
public class Schema extends PropertyList<Schema> {
public Schema(){
super(Schema.class);
}
public Schema(String type, String format) {
super(Schema.class);
this.type = type;
this.format = format;
}
}
| 19.133333
| 50
| 0.620209
|
1401a13f0d4877b5480210374d9657b8349cf093
| 63,697
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.host.controller.parsing;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DIRECTORY_GROUPING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DISCOVERY_OPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DISCOVERY_OPTIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DOMAIN_CONTROLLER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HTTP_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HTTP_UPGRADE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IGNORED_RESOURCES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IGNORED_RESOURCE_TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IS_DOMAIN_CONTROLLER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LOOPBACK;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NATIVE_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ORGANIZATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROPERTIES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOTE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SSL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATIC_DISCOVERY;
import static org.jboss.as.controller.parsing.ParseUtils.isNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.nextElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNamespace;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.Attribute;
import org.jboss.as.controller.parsing.Element;
import org.jboss.as.controller.parsing.ExtensionXml;
import org.jboss.as.controller.parsing.Namespace;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.as.controller.parsing.ProfileParsingCompletionHandler;
import org.jboss.as.domain.management.parsing.AuditLogXml;
import org.jboss.as.domain.management.parsing.ManagementXml;
import org.jboss.as.domain.management.parsing.ManagementXmlDelegate;
import org.jboss.as.host.controller.discovery.DiscoveryOptionResourceDefinition;
import org.jboss.as.host.controller.discovery.StaticDiscoveryResourceDefinition;
import org.jboss.as.host.controller.ignored.IgnoredDomainTypeResourceDefinition;
import org.jboss.as.host.controller.logging.HostControllerLogger;
import org.jboss.as.host.controller.model.host.AdminOnlyDomainConfigPolicy;
import org.jboss.as.host.controller.model.host.HostResourceDefinition;
import org.jboss.as.host.controller.operations.DomainControllerWriteAttributeHandler;
import org.jboss.as.host.controller.operations.HostAddHandler;
import org.jboss.as.host.controller.resources.HttpManagementResourceDefinition;
import org.jboss.as.host.controller.resources.NativeManagementResourceDefinition;
import org.jboss.as.host.controller.resources.ServerConfigResourceDefinition;
import org.jboss.as.host.controller.resources.SslLoopbackResourceDefinition;
import org.jboss.as.process.CommandLineConstants;
import org.jboss.as.server.parsing.CommonXml;
import org.jboss.as.server.parsing.SocketBindingsXml;
import org.jboss.as.server.services.net.SocketBindingGroupResourceDefinition;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Parser for host controller configuration xml documents (e.g. host.xml) that use the urn:jboss:domain:5.0 schema.
*
* @author Brian Stansberry
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
* @author <a href="mailto:jperkins@jboss.com">James R. Perkins</a>
*/
final class HostXml_5 extends CommonXml implements ManagementXmlDelegate {
private final AuditLogXml auditLogDelegate;
private final String defaultHostControllerName;
private final RunningMode runningMode;
private final boolean isCachedDc;
private final ExtensionRegistry extensionRegistry;
private final ExtensionXml extensionXml;
private final Namespace namespace;
HostXml_5(String defaultHostControllerName, RunningMode runningMode, boolean isCachedDC,
final ExtensionRegistry extensionRegistry, final ExtensionXml extensionXml, final Namespace namespace) {
super(new SocketBindingsXml.HostSocketBindingsXml());
this.auditLogDelegate = AuditLogXml.newInstance(namespace, true);
this.defaultHostControllerName = defaultHostControllerName;
this.runningMode = runningMode;
this.isCachedDc = isCachedDC;
this.extensionRegistry = extensionRegistry;
this.extensionXml = extensionXml;
this.namespace = namespace;
}
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operationList)
throws XMLStreamException {
final ModelNode address = new ModelNode().setEmptyList();
if (Element.forName(reader.getLocalName()) != Element.HOST) {
throw unexpectedElement(reader);
}
// Instead of having to list the remaining versions we just check it is actually a valid version.
for (Namespace current : Namespace.domainValues()) {
if (namespace.equals(current)) {
readHostElement(reader, address, operationList);
return;
}
}
throw unexpectedElement(reader);
}
private void readHostElement(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
String hostName = null;
String organization = null;
// Deffer adding the namespaces and schema locations until after the host has been created.
List<ModelNode> namespaceOperations = new LinkedList<ModelNode>();
parseNamespaces(reader, address, namespaceOperations);
// attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
switch (Namespace.forUri(reader.getAttributeNamespace(i))) {
case NONE: {
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
hostName = value;
break;
}
case ORGANIZATION : {
organization = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
break;
}
case XML_SCHEMA_INSTANCE: {
switch (Attribute.forName(reader.getAttributeLocalName(i))) {
case SCHEMA_LOCATION: {
parseSchemaLocations(reader, address, namespaceOperations, i);
break;
}
case NO_NAMESPACE_SCHEMA_LOCATION: {
// todo, jeez
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
// The following also updates the address parameter so this address can be used for future operations
// in the context of this host.
final ModelNode hostAddOp = addLocalHost(address, list, hostName);
setOrganization(address, list, organization);
// The namespace operations were created before the host name was known, the address can now be updated
// to the local host specific address.
for (ModelNode operation : namespaceOperations) {
operation.get(OP_ADDR).set(address);
list.add(operation);
}
// Content
// Handle elements: sequence
Element element = nextElement(reader, namespace);
if (element == Element.EXTENSIONS) {
extensionXml.parseExtensions(reader, address, namespace, list);
element = nextElement(reader, namespace);
}
if (element == Element.SYSTEM_PROPERTIES) {
parseSystemProperties(reader, address, namespace, list, false);
element = nextElement(reader, namespace);
}
if (element == Element.PATHS) {
parsePaths(reader, address, namespace, list, true);
element = nextElement(reader, namespace);
}
if (element == Element.VAULT) {
parseVault(reader, address, namespace, list);
element = nextElement(reader, namespace);
}
if (element == Element.MANAGEMENT) {
ManagementXml managementXml = ManagementXml.newInstance(namespace, this, false);
managementXml.parseManagement(reader, address, list, true);
element = nextElement(reader, namespace);
} else {
throw missingRequiredElement(reader, EnumSet.of(Element.MANAGEMENT));
}
if (element == Element.DOMAIN_CONTROLLER) {
parseDomainController(reader, address, list, hostAddOp);
element = nextElement(reader, namespace);
}
final Set<String> interfaceNames = new HashSet<String>();
if (element == Element.INTERFACES) {
parseInterfaces(reader, interfaceNames, address, namespace, list, true);
element = nextElement(reader, namespace);
}
if (element == Element.JVMS) {
parseJvms(reader, address, list);
element = nextElement(reader, namespace);
}
if (element == Element.SERVERS) {
parseServers(reader, address, list);
element = nextElement(reader, namespace);
}
if (element == Element.PROFILE) {
parseHostProfile(reader, address, list);
element = nextElement(reader, namespace);
}
// Single socket binding group
if (element == Element.SOCKET_BINDING_GROUP) {
parseSocketBindingGroup(reader, interfaceNames, address, list);
element = nextElement(reader, namespace);
}
if (element != null) {
throw unexpectedElement(reader);
}
}
private void parseHttpManagementInterfaceAttributes(XMLExtendedStreamReader reader, ModelNode addOp) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case HTTP_AUTHENTICATION_FACTORY: {
HttpManagementResourceDefinition.HTTP_AUTHENTICATION_FACTORY.parseAndSetParameter(value, addOp, reader);
break;
}
case SASL_PROTOCOL: {
HttpManagementResourceDefinition.SASL_PROTOCOL.parseAndSetParameter(value, addOp, reader);
break;
}
case SECURITY_REALM: {
HttpManagementResourceDefinition.SECURITY_REALM.parseAndSetParameter(value, addOp, reader);
break;
}
case SERVER_NAME: {
HttpManagementResourceDefinition.SERVER_NAME.parseAndSetParameter(value, addOp, reader);
break;
}
case SSL_CONTEXT: {
HttpManagementResourceDefinition.SSL_CONTEXT.parseAndSetParameter(value, addOp, reader);
break;
}
case CONSOLE_ENABLED: {
HttpManagementResourceDefinition.CONSOLE_ENABLED.parseAndSetParameter(value, addOp, reader);
break;
}
case HTTP_UPGRADE_ENABLED: {
ModelNode httpUpgrade = addOp.get(HTTP_UPGRADE);
HttpManagementResourceDefinition.ENABLED.parseAndSetParameter(value, httpUpgrade, reader);
break;
}
case ALLOWED_ORIGINS: {
HttpManagementResourceDefinition.ALLOWED_ORIGINS.getParser().parseAndSetParameter(HttpManagementResourceDefinition.ALLOWED_ORIGINS, value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
}
private void parseNativeManagementInterfaceAttributes(XMLExtendedStreamReader reader, ModelNode addOp) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case SASL_AUTHENTICATION_FACTORY: {
NativeManagementResourceDefinition.SASL_AUTHENTICATION_FACTORY.parseAndSetParameter(value, addOp, reader);
break;
}
case SASL_PROTOCOL: {
NativeManagementResourceDefinition.SASL_PROTOCOL.parseAndSetParameter(value, addOp, reader);
break;
}
case SECURITY_REALM: {
NativeManagementResourceDefinition.SECURITY_REALM.parseAndSetParameter(value, addOp, reader);
break;
}
case SERVER_NAME: {
NativeManagementResourceDefinition.SERVER_NAME.parseAndSetParameter(value, addOp, reader);
break;
}
case SSL_CONTEXT: {
NativeManagementResourceDefinition.SSL_CONTEXT.parseAndSetParameter(value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
}
private void parseNativeManagementInterface(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> list) throws XMLStreamException {
final ModelNode operationAddress = address.clone();
operationAddress.add(MANAGEMENT_INTERFACE, NATIVE_INTERFACE);
final ModelNode addOp = Util.getEmptyOperation(ADD, operationAddress);
// Handle attributes
parseNativeManagementInterfaceAttributes(reader, addOp);
// Handle elements
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SOCKET:
parseNativeManagementSocket(reader, addOp);
break;
default:
throw unexpectedElement(reader);
}
}
list.add(addOp);
}
private void parseHttpManagementInterface(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> list) throws XMLStreamException {
final ModelNode operationAddress = address.clone();
operationAddress.add(MANAGEMENT_INTERFACE, HTTP_INTERFACE);
final ModelNode addOp = Util.getEmptyOperation(ADD, operationAddress);
// Handle attributes
parseHttpManagementInterfaceAttributes(reader, addOp);
// Handle elements
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SOCKET:
parseHttpManagementSocket(reader, addOp);
break;
case HTTP_UPGRADE:
parseHttpUpgrade(reader, addOp);
break;
default:
throw unexpectedElement(reader);
}
}
list.add(addOp);
}
private void parseNativeManagementSocket(XMLExtendedStreamReader reader, ModelNode addOp) throws XMLStreamException {
// Handle attributes
boolean hasInterface = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case INTERFACE: {
NativeManagementResourceDefinition.INTERFACE.parseAndSetParameter(value, addOp, reader);
hasInterface = true;
break;
}
case PORT: {
NativeManagementResourceDefinition.NATIVE_PORT.parseAndSetParameter(value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
if (!hasInterface) {
throw missingRequired(reader, Collections.singleton(Attribute.INTERFACE.getLocalName()));
}
}
private void parseHttpManagementSocket(XMLExtendedStreamReader reader, ModelNode addOp) throws XMLStreamException {
// Handle attributes
boolean hasInterface = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case INTERFACE: {
HttpManagementResourceDefinition.INTERFACE.parseAndSetParameter(value, addOp, reader);
hasInterface = true;
break;
}
case PORT: {
HttpManagementResourceDefinition.HTTP_PORT.parseAndSetParameter(value, addOp, reader);
break;
}
case SECURE_PORT: {
HttpManagementResourceDefinition.HTTPS_PORT.parseAndSetParameter(value, addOp, reader);
break;
}
case SECURE_INTERFACE: {
HttpManagementResourceDefinition.SECURE_INTERFACE.parseAndSetParameter(value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
if (!hasInterface) {
throw missingRequired(reader, Collections.singleton(Attribute.INTERFACE.getLocalName()));
}
}
private void parseHttpUpgrade(XMLExtendedStreamReader reader, ModelNode addOp) throws XMLStreamException {
// Handle attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLED: {
ModelNode httpUpgrade = addOp.get(HTTP_UPGRADE);
HttpManagementResourceDefinition.ENABLED.parseAndSetParameter(value, httpUpgrade, reader);
break;
}
case SASL_AUTHENTICATION_FACTORY: {
ModelNode httpUpgrade = addOp.get(HTTP_UPGRADE);
HttpManagementResourceDefinition.SASL_AUTHENTICATION_FACTORY.parseAndSetParameter(value, httpUpgrade, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
}
private void setOrganization(final ModelNode address, final List<ModelNode> operationList, final String value) {
if (value != null && !value.isEmpty()) {
final ModelNode update = Util.getWriteAttributeOperation(address, ORGANIZATION, value);
operationList.add(update);
}
}
/**
* Add the operation to add the local host definition.
*/
private ModelNode addLocalHost(final ModelNode address, final List<ModelNode> operationList, final String hostName) {
String resolvedHost = hostName != null ? hostName : defaultHostControllerName;
// All further operations should modify the newly added host so the address passed in is updated.
address.add(HOST, resolvedHost);
// Add a step to setup the ManagementResourceRegistrations for the root host resource
final ModelNode hostAddOp = new ModelNode();
hostAddOp.get(OP).set(HostAddHandler.OPERATION_NAME);
hostAddOp.get(OP_ADDR).set(address);
operationList.add(hostAddOp);
// Add a step to store the HC name
ModelNode nameValue = hostName == null ? new ModelNode() : new ModelNode(hostName);
final ModelNode writeName = Util.getWriteAttributeOperation(address, NAME, nameValue);
operationList.add(writeName);
return hostAddOp;
}
private void parseDomainController(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final ModelNode hostAddOp)
throws XMLStreamException {
requireNoAttributes(reader);
boolean hasLocal = false;
boolean hasRemote = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case LOCAL: {
if (hasLocal) {
throw ControllerLogger.ROOT_LOGGER.childAlreadyDeclared(element.getLocalName(), Element.DOMAIN_CONTROLLER.getLocalName(), reader.getLocation());
} else if (hasRemote) {
throw ControllerLogger.ROOT_LOGGER.childAlreadyDeclared(Element.REMOTE.getLocalName(), Element.DOMAIN_CONTROLLER.getLocalName(), reader.getLocation());
}
hostAddOp.get(IS_DOMAIN_CONTROLLER).set(true);
parseLocalDomainController(reader, address, list);
hasLocal = true;
break;
}
case REMOTE: {
if (hasRemote) {
throw ControllerLogger.ROOT_LOGGER.childAlreadyDeclared(element.getLocalName(), Element.DOMAIN_CONTROLLER.getLocalName(), reader.getLocation());
} else if (hasLocal) {
throw ControllerLogger.ROOT_LOGGER.childAlreadyDeclared(Element.LOCAL.getLocalName(), Element.DOMAIN_CONTROLLER.getLocalName(), reader.getLocation());
}
hostAddOp.get(IS_DOMAIN_CONTROLLER).set(false);
parseRemoteDomainController(reader, address, list);
hasRemote = true;
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!hasLocal && !hasRemote) {
throw ControllerLogger.ROOT_LOGGER.domainControllerMustBeDeclared(Element.REMOTE.getLocalName(), Element.LOCAL.getLocalName(), reader.getLocation());
}
}
private void parseLocalDomainController(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list) throws XMLStreamException {
requireNoAttributes(reader);
boolean hasDiscoveryOptions = false;
Set<String> staticDiscoveryOptionNames = new HashSet<String>();
Set<String> discoveryOptionNames = new HashSet<String>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case DISCOVERY_OPTIONS: {
if (hasDiscoveryOptions) {
throw ControllerLogger.ROOT_LOGGER.alreadyDefined(element.getLocalName(), reader.getLocation());
}
parseDiscoveryOptions(reader, address, list, staticDiscoveryOptionNames, discoveryOptionNames);
hasDiscoveryOptions = true;
break;
}
default:
throw unexpectedElement(reader);
}
}
}
private void parseRemoteDomainController(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list) throws XMLStreamException {
boolean requireDiscoveryOptions;
boolean hasDiscoveryOptions = false;
requireDiscoveryOptions = parseRemoteDomainControllerAttributes(reader, address, list);
Set<String> types = new HashSet<String>();
Set<String> staticDiscoveryOptionNames = new HashSet<String>();
Set<String> discoveryOptionNames = new HashSet<String>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case IGNORED_RESOURCE: {
parseIgnoredResource(reader, address, list, types);
break;
}
case DISCOVERY_OPTIONS: { // Different from parseRemoteDomainController1_1
if (hasDiscoveryOptions) {
throw ControllerLogger.ROOT_LOGGER.alreadyDefined(element.getLocalName(), reader.getLocation());
}
parseDiscoveryOptions(reader, address, list, staticDiscoveryOptionNames, discoveryOptionNames);
hasDiscoveryOptions = true;
break;
}
default:
throw unexpectedElement(reader);
}
}
if (requireDiscoveryOptions && !hasDiscoveryOptions) {
throw ControllerLogger.ROOT_LOGGER.discoveryOptionsMustBeDeclared(CommandLineConstants.ADMIN_ONLY,
Attribute.ADMIN_ONLY_POLICY.getLocalName(), AdminOnlyDomainConfigPolicy.FETCH_FROM_MASTER.toString(),
Element.DISCOVERY_OPTIONS.getLocalName(), Attribute.HOST.getLocalName(), Attribute.PORT.getLocalName(),
reader.getLocation());
}
}
private boolean parseRemoteDomainControllerAttributes(final XMLExtendedStreamReader reader, final ModelNode address,
final List<ModelNode> list) throws XMLStreamException {
final ModelNode remoteDc = new ModelNode();
final ModelNode updateDc = remoteDc.get(REMOTE).setEmptyObject() ;
// Handle attributes
AdminOnlyDomainConfigPolicy adminOnlyPolicy = AdminOnlyDomainConfigPolicy.DEFAULT;
boolean requireDiscoveryOptions = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case HOST: {
DomainControllerWriteAttributeHandler.HOST.parseAndSetParameter(value, updateDc, reader);
break;
}
case PORT: {
DomainControllerWriteAttributeHandler.PORT.parseAndSetParameter(value, updateDc, reader);
break;
}
case PROTOCOL: {
DomainControllerWriteAttributeHandler.PROTOCOL.parseAndSetParameter(value, updateDc, reader);
break;
}
case AUTHENTICATION_CONTEXT: {
DomainControllerWriteAttributeHandler.AUTHENTICATION_CONTEXT.parseAndSetParameter(value, updateDc, reader);
break;
}
case SECURITY_REALM: {
DomainControllerWriteAttributeHandler.SECURITY_REALM.parseAndSetParameter(value, updateDc, reader);
break;
}
case USERNAME: {
DomainControllerWriteAttributeHandler.USERNAME.parseAndSetParameter(value, updateDc, reader);
break;
}
case IGNORE_UNUSED_CONFIG: {
DomainControllerWriteAttributeHandler.IGNORE_UNUSED_CONFIG.parseAndSetParameter(value, updateDc, reader);
break;
}
case ADMIN_ONLY_POLICY: {
DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.parseAndSetParameter(value, updateDc, reader);
ModelNode nodeValue = updateDc.get(DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.getName());
if (nodeValue.getType() != ModelType.EXPRESSION) {
adminOnlyPolicy = AdminOnlyDomainConfigPolicy.getPolicy(nodeValue.asString());
}
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
if (!updateDc.hasDefined(DomainControllerWriteAttributeHandler.HOST.getName())) {
requireDiscoveryOptions = isRequireDiscoveryOptions(adminOnlyPolicy);
}
if (!updateDc.hasDefined(DomainControllerWriteAttributeHandler.PORT.getName())) {
requireDiscoveryOptions = requireDiscoveryOptions || isRequireDiscoveryOptions(adminOnlyPolicy);
}
final ModelNode update = Util.getWriteAttributeOperation(address, DOMAIN_CONTROLLER, remoteDc);
list.add(update);
return requireDiscoveryOptions;
}
private boolean isRequireDiscoveryOptions(AdminOnlyDomainConfigPolicy adminOnlyPolicy) {
return !isCachedDc &&
(runningMode != RunningMode.ADMIN_ONLY || adminOnlyPolicy == AdminOnlyDomainConfigPolicy.FETCH_FROM_MASTER);
}
private void parseIgnoredResource(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final Set<String> foundTypes) throws XMLStreamException {
ModelNode op = new ModelNode();
op.get(OP).set(ADD);
String type = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
}
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case TYPE: {
if (!foundTypes.add(value)) {
throw HostControllerLogger.ROOT_LOGGER.duplicateIgnoredResourceType(Element.IGNORED_RESOURCE.getLocalName(), value, reader.getLocation());
}
type = value;
break;
}
case WILDCARD: {
IgnoredDomainTypeResourceDefinition.WILDCARD.parseAndSetParameter(value, op, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (type == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.TYPE.getLocalName()));
}
ModelNode addr = op.get(OP_ADDR).set(address);
addr.add(CORE_SERVICE, IGNORED_RESOURCES);
addr.add(IGNORED_RESOURCE_TYPE, type);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case INSTANCE: {
String name = ParseUtils.readStringAttributeElement(reader, NAME);
IgnoredDomainTypeResourceDefinition.NAMES.parseAndAddParameterElement(name, op, reader);
break;
}
default:
throw unexpectedElement(reader);
}
}
list.add(op);
}
private void parseDiscoveryOptions(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final Set<String> staticDiscoveryOptionNames,
final Set<String> discoveryOptionNames) throws XMLStreamException {
requireNoAttributes(reader);
// Handle elements
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case DISCOVERY_OPTION:
parseDiscoveryOption(reader, address, list, discoveryOptionNames);
break;
case STATIC_DISCOVERY:
parseStaticDiscoveryOption(reader, address, list, staticDiscoveryOptionNames);
break;
default:
throw unexpectedElement(reader);
}
}
}
private void parseStaticDiscoveryOption(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final Set<String> staticDiscoveryOptionNames) throws XMLStreamException {
// OP_ADDR will be set after parsing the NAME attribute
final ModelNode staticDiscoveryOptionAddress = address.clone();
staticDiscoveryOptionAddress.add(CORE_SERVICE, DISCOVERY_OPTIONS);
final ModelNode addOp = Util.getEmptyOperation(ADD, new ModelNode());
list.add(addOp);
// Handle attributes
final Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.HOST, Attribute.PORT);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (!staticDiscoveryOptionNames.add(value)) {
throw ParseUtils.duplicateNamedElement(reader, value);
}
addOp.get(OP_ADDR).set(staticDiscoveryOptionAddress).add(STATIC_DISCOVERY, value);
break;
}
case HOST: {
StaticDiscoveryResourceDefinition.HOST.parseAndSetParameter(value, addOp, reader);
break;
}
case PROTOCOL: {
StaticDiscoveryResourceDefinition.PROTOCOL.parseAndSetParameter(value, addOp, reader);
break;
}
case PORT: {
StaticDiscoveryResourceDefinition.PORT.parseAndSetParameter(value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
}
private void parseDiscoveryOption(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final Set<String> discoveryOptionNames) throws XMLStreamException {
// Handle attributes
final ModelNode addOp = parseDiscoveryOptionAttributes(reader, address, list, discoveryOptionNames);
// Handle elements
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTY: {
parseDiscoveryOptionProperty(reader, addOp.get(PROPERTIES));
break;
}
default:
throw unexpectedElement(reader);
}
}
}
private ModelNode parseDiscoveryOptionAttributes(final XMLExtendedStreamReader reader, final ModelNode address,
final List<ModelNode> list, final Set<String> discoveryOptionNames) throws XMLStreamException {
// OP_ADDR will be set after parsing the NAME attribute
final ModelNode discoveryOptionAddress = address.clone();
discoveryOptionAddress.add(CORE_SERVICE, DISCOVERY_OPTIONS);
final ModelNode addOp = Util.getEmptyOperation(ADD, new ModelNode());
list.add(addOp);
final Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.CODE);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (!discoveryOptionNames.add(value)) {
throw ParseUtils.duplicateNamedElement(reader, value);
}
addOp.get(OP_ADDR).set(discoveryOptionAddress).add(DISCOVERY_OPTION, value);
break;
}
case CODE: {
DiscoveryOptionResourceDefinition.CODE.parseAndSetParameter(value, addOp, reader);
break;
}
case MODULE: {
DiscoveryOptionResourceDefinition.MODULE.parseAndSetParameter(value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
return addOp;
}
private void parseDiscoveryOptionProperty(XMLExtendedStreamReader reader, ModelNode discoveryOptionProperties) throws XMLStreamException {
String propertyName = null;
String propertyValue = null;
EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.VALUE);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
propertyName = value;
break;
}
case VALUE: {
propertyValue = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
discoveryOptionProperties.add(propertyName, propertyValue);
requireNoContent(reader);
}
private void parseJvms(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
requireNoAttributes(reader);
final Set<String> names = new HashSet<String>();
// Handle elements
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case JVM:
JvmXml.parseJvm(reader, address, namespace, list, names, false);
break;
default:
throw unexpectedElement(reader);
}
}
}
private void parseServersAttributes(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException {
// Handle attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DIRECTORY_GROUPING: {
final ModelNode address = parentAddress.clone();
list.add(Util.getWriteAttributeOperation(address, DIRECTORY_GROUPING, HostResourceDefinition.DIRECTORY_GROUPING.parse(value,reader)));
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
}
private void parseServers(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list) throws XMLStreamException {
parseServersAttributes(reader, address, list);
// Handle elements
final Set<String> names = new HashSet<String>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SERVER:
parseServer(reader, address, list, names);
break;
default:
throw unexpectedElement(reader);
}
}
}
private void parseServer(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list,
final Set<String> serverNames) throws XMLStreamException {
// Handle attributes
final ModelNode addUpdate = parseServerAttributes(reader, parentAddress, serverNames);
final ModelNode address = addUpdate.require(OP_ADDR);
list.add(addUpdate);
// Handle elements
parseServerContent(reader, addUpdate, address, list);
}
private void parseServerContent(final XMLExtendedStreamReader reader, final ModelNode serverAddOperation,
final ModelNode serverAddress, final List<ModelNode> list) throws XMLStreamException {
boolean sawJvm = false;
boolean sawSystemProperties = false;
boolean sawSocketBinding = false;
boolean sawSSL = false;
final Set<String> interfaceNames = new HashSet<String>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case INTERFACES: { // THIS IS DIFFERENT FROM 1.0
parseInterfaces(reader, interfaceNames, serverAddress, namespace, list, true);
break;
}
case JVM: {
if (sawJvm) {
throw ControllerLogger.ROOT_LOGGER.alreadyDefined(element.getLocalName(), reader.getLocation());
}
JvmXml.parseJvm(reader, serverAddress, namespace, list, new HashSet<String>(), true);
sawJvm = true;
break;
}
case PATHS: {
parsePaths(reader, serverAddress, namespace, list, true);
break;
}
case SOCKET_BINDINGS: {
if (sawSocketBinding) {
throw ControllerLogger.ROOT_LOGGER.alreadyDefined(element.getLocalName(), reader.getLocation());
}
parseServerSocketBindings(reader, serverAddOperation);
sawSocketBinding = true;
break;
}
case SSL: {
if (sawSSL) {
throw ControllerLogger.ROOT_LOGGER.alreadyDefined(element.getLocalName(), reader.getLocation());
}
parseServerSsl(serverAddress, reader, list);
sawSSL = true;
break;
}
case SYSTEM_PROPERTIES: {
if (sawSystemProperties) {
throw ControllerLogger.ROOT_LOGGER.alreadyDefined(element.getLocalName(), reader.getLocation());
}
parseSystemProperties(reader, serverAddress, namespace, list, false);
sawSystemProperties = true;
break;
}
default:
throw unexpectedElement(reader);
}
}
}
private ModelNode parseServerAttributes(final XMLExtendedStreamReader reader, final ModelNode parentAddress,
final Set<String> serverNames) throws XMLStreamException {
final ModelNode addUpdate = new ModelNode();
addUpdate.get(OP).set(ADD);
final Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.GROUP);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (!serverNames.add(value)) {
throw ControllerLogger.ROOT_LOGGER.duplicateDeclaration("server", value, reader.getLocation());
}
final ModelNode address = parentAddress.clone().add(SERVER_CONFIG, value);
addUpdate.get(OP_ADDR).set(address);
break;
}
case GROUP: {
ServerConfigResourceDefinition.GROUP.parseAndSetParameter(value, addUpdate, reader);
break;
}
case AUTO_START: {
ServerConfigResourceDefinition.AUTO_START.parseAndSetParameter(value, addUpdate, reader);
break;
}
case UPDATE_AUTO_START_WITH_SERVER_STATUS: {
ServerConfigResourceDefinition.UPDATE_AUTO_START_WITH_SERVER_STATUS.parseAndSetParameter(value, addUpdate, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
return addUpdate;
}
private void parseServerSocketBindings(final XMLExtendedStreamReader reader, final ModelNode serverAddOperation) throws XMLStreamException {
// Handle attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw ParseUtils.unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case SOCKET_BINDING_GROUP: {
ServerConfigResourceDefinition.SOCKET_BINDING_GROUP.parseAndSetParameter(value, serverAddOperation, reader);
break;
}
case DEFAULT_INTERFACE: {
ServerConfigResourceDefinition.SOCKET_BINDING_DEFAULT_INTERFACE.parseAndSetParameter(value, serverAddOperation, reader);
break;
}
case PORT_OFFSET: {
ServerConfigResourceDefinition.SOCKET_BINDING_PORT_OFFSET.parseAndSetParameter(value, serverAddOperation, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
// Handle elements
requireNoContent(reader);
}
private void parseServerSsl(final ModelNode parentAddress, final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
ModelNode addOp = new ModelNode();
addOp.get(OP).set(ADD);
final ModelNode address = parentAddress.clone();
address.add(SSL, LOOPBACK);
addOp.get(OP_ADDR).set(address);
operations.add(addOp);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw ParseUtils.unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case SSL_PROTOCOL: {
SslLoopbackResourceDefinition.SSL_PROTOCOCOL.parseAndSetParameter(value, addOp, reader);
break;
}
case TRUST_MANAGER_ALGORITHM: {
SslLoopbackResourceDefinition.TRUST_MANAGER_ALGORITHM.parseAndSetParameter(value, addOp, reader);
break;
}
case TRUSTSTORE_TYPE: {
SslLoopbackResourceDefinition.TRUSTSTORE_TYPE.parseAndSetParameter(value, addOp, reader);
break;
}
case TRUSTSTORE_PATH: {
SslLoopbackResourceDefinition.TRUSTSTORE_PATH.parseAndSetParameter(value, addOp, reader);
break;
}
case TRUSTSTORE_PASSWORD: {
SslLoopbackResourceDefinition.TRUSTSTORE_PASSWORD.parseAndSetParameter(value, addOp, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
}
private void parseHostProfile(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> list) throws XMLStreamException {
// Attributes
requireNoAttributes(reader);
// Content
final Map<String, List<ModelNode>> profileOps = new LinkedHashMap<String, List<ModelNode>>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (Element.forName(reader.getLocalName()) != Element.SUBSYSTEM) {
throw unexpectedElement(reader);
}
String namespace = reader.getNamespaceURI();
if (profileOps.containsKey(namespace)) {
throw ControllerLogger.ROOT_LOGGER.duplicateDeclaration("subsystem", reader.getLocation());
}
// parse subsystem
final List<ModelNode> subsystems = new ArrayList<ModelNode>();
reader.handleAny(subsystems);
profileOps.put(namespace, subsystems);
}
// Let extensions modify the profile
Set<ProfileParsingCompletionHandler> completionHandlers = extensionRegistry.getProfileParsingCompletionHandlers();
for (ProfileParsingCompletionHandler completionHandler : completionHandlers) {
completionHandler.handleProfileParsingCompletion(profileOps, list);
}
for (List<ModelNode> subsystems : profileOps.values()) {
for (final ModelNode update : subsystems) {
// Process relative subsystem path address
final ModelNode subsystemAddress = address.clone();
for (final Property path : update.get(OP_ADDR).asPropertyList()) {
subsystemAddress.add(path.getName(), path.getValue().asString());
}
update.get(OP_ADDR).set(subsystemAddress);
list.add(update);
}
}
}
private void parseSocketBindingGroup(final XMLExtendedStreamReader reader, final Set<String> interfaces,
final ModelNode address, final List<ModelNode> updates) throws XMLStreamException {
// unique names for both socket-binding and outbound-socket-binding(s)
final Set<String> uniqueBindingNames = new HashSet<String>();
ModelNode op = Util.getEmptyOperation(ADD, null);
// Handle attributes
String socketBindingGroupName = null;
final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.DEFAULT_INTERFACE);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
socketBindingGroupName = value;
required.remove(attribute);
break;
}
case DEFAULT_INTERFACE: {
SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.parseAndSetParameter(value, op, reader);
required.remove(attribute);
if (op.get(SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.getName()).getType() != ModelType.EXPRESSION
&& !interfaces.contains(value)) {
throw ControllerLogger.ROOT_LOGGER.unknownInterface(value, Attribute.DEFAULT_INTERFACE.getLocalName(), Element.INTERFACES.getLocalName(), reader.getLocation());
}
break;
}
case PORT_OFFSET: {
SocketBindingGroupResourceDefinition.PORT_OFFSET.parseAndSetParameter(value, op, reader);
break;
}
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
ModelNode groupAddress = address.clone().add(SOCKET_BINDING_GROUP, socketBindingGroupName);
op.get(OP_ADDR).set(groupAddress);
updates.add(op);
// Handle elements
while (reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SOCKET_BINDING: {
final String bindingName = parseSocketBinding(reader, interfaces, groupAddress, updates);
if (!uniqueBindingNames.add(bindingName)) {
throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), Element.OUTBOUND_SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation());
}
break;
}
case OUTBOUND_SOCKET_BINDING: {
final String bindingName = parseOutboundSocketBinding(reader, interfaces, groupAddress, updates);
if (!uniqueBindingNames.add(bindingName)) {
throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), Element.OUTBOUND_SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation());
}
break;
}
default:
throw unexpectedElement(reader);
}
}
}
/*
* ManagamentXmlDelegate Methods
*/
@Override
public boolean parseManagementInterfaces(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> operationsList)
throws XMLStreamException {
requireNoAttributes(reader);
boolean interfaceDefined = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case NATIVE_INTERFACE: {
interfaceDefined = true;
parseNativeManagementInterface(reader, address, operationsList);
break;
}
case HTTP_INTERFACE: {
interfaceDefined = true;
parseHttpManagementInterface(reader, address, operationsList);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!interfaceDefined) {
throw missingOneOf(reader, EnumSet.of(Element.NATIVE_INTERFACE, Element.HTTP_INTERFACE));
}
return true;
}
@Override
public boolean parseAuditLog(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> list)
throws XMLStreamException {
auditLogDelegate.parseAuditLog(reader, address, namespace, list);
return true;
}
}
| 46.325091
| 266
| 0.604016
|
7e551933606f7f96ff65a615fff43a6700724d93
| 5,462
|
package dev.iakunin.codexiabot.codexia.cron;
import com.github.javafaker.Faker;
import dev.iakunin.codexiabot.codexia.entity.CodexiaProject;
import dev.iakunin.codexiabot.codexia.repository.CodexiaProjectRepository;
import dev.iakunin.codexiabot.codexia.sdk.CodexiaClient;
import dev.iakunin.codexiabot.github.GithubModule;
import java.util.Optional;
import org.cactoos.list.ListOf;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RunWith(MockitoJUnitRunner.class)
public class ProjectsHealthCheckUnitTest {
private final Faker faker = new Faker();
@Mock
private CodexiaProjectRepository repository;
@Mock
private CodexiaClient codexiaClient;
@Mock
private GithubModule githubModule;
@InjectMocks
private ProjectsHealthCheck projectsHealthCheck;
@Test
public void noActiveProjectsInRepo() {
Mockito.when(repository.findAllActive()).thenReturn(new ListOf<>());
projectsHealthCheck.run();
Mockito.verify(codexiaClient, Mockito.never()).getProject(Mockito.any());
Mockito.verify(githubModule, Mockito.never()).removeAllRepoSources(Mockito.any());
Mockito.verify(repository, Mockito.never()).findByExternalId(Mockito.any());
Mockito.verify(repository, Mockito.never()).save(Mockito.any());
}
@Test
public void projectIsNotDeletedInCodexia() {
final int externalId = faker.random().nextInt(Integer.MAX_VALUE);
Mockito.when(repository.findAllActive()).thenReturn(
new ListOf<>(
new CodexiaProject().setExternalId(externalId)
)
);
Mockito.when(codexiaClient.getProject(externalId)).thenReturn(
new ResponseEntity<>(
new CodexiaClient.Project().setDeleted(null),
HttpStatus.OK
)
);
projectsHealthCheck.run();
Mockito.verify(codexiaClient).getProject(externalId);
Mockito.verify(githubModule, Mockito.never()).removeAllRepoSources(Mockito.any());
Mockito.verify(repository, Mockito.never()).findByExternalId(Mockito.any());
Mockito.verify(repository, Mockito.never()).save(Mockito.any());
}
@Test
public void projectIsDeletedInCodexia() {
final int externalId = faker.random().nextInt(Integer.MAX_VALUE);
final String deleted = faker.regexify("[a-z]{2,10}");
final CodexiaProject codexiaProject = new CodexiaProject().setExternalId(externalId);
Mockito.when(repository.findAllActive()).thenReturn(
new ListOf<>(codexiaProject)
);
Mockito.when(codexiaClient.getProject(externalId)).thenReturn(
new ResponseEntity<>(
new CodexiaClient.Project()
.setId(externalId)
.setDeleted(deleted),
HttpStatus.OK
)
);
Mockito.when(repository.findByExternalId(externalId)).thenReturn(
Optional.of(codexiaProject)
);
Mockito.when(repository.save(codexiaProject)).thenReturn(
codexiaProject.setDeleted(deleted)
);
projectsHealthCheck.run();
Mockito.verify(codexiaClient).getProject(externalId);
Mockito.verify(githubModule).removeAllRepoSources(
new GithubModule.DeleteArguments()
.setSource(GithubModule.Source.CODEXIA)
.setExternalId(String.valueOf(externalId))
);
Mockito.verify(repository).findByExternalId(externalId);
Mockito.verify(repository).save(codexiaProject.setDeleted(deleted));
}
@Test
public void projectIsDeletedInCodexiaButNotFoundInRepository() {
final int externalId = faker.random().nextInt(Integer.MAX_VALUE);
final String deleted = faker.regexify("[a-z]{2,10}");
Mockito.when(repository.findAllActive()).thenReturn(
new ListOf<>(
new CodexiaProject().setExternalId(externalId)
)
);
Mockito.when(codexiaClient.getProject(externalId)).thenReturn(
new ResponseEntity<>(
new CodexiaClient.Project()
.setId(externalId)
.setDeleted(deleted),
HttpStatus.OK
)
);
Mockito.when(repository.findByExternalId(externalId)).thenReturn(Optional.empty());
final RuntimeException exception = assertThrows(
RuntimeException.class,
() -> projectsHealthCheck.run()
);
assertEquals(
exception.getMessage(),
String.format("Unable to find CodexiaProject by externalId='%s'", externalId)
);
Mockito.verify(codexiaClient).getProject(externalId);
Mockito.verify(githubModule).removeAllRepoSources(
new GithubModule.DeleteArguments()
.setSource(GithubModule.Source.CODEXIA)
.setExternalId(String.valueOf(externalId))
);
Mockito.verify(repository).findByExternalId(externalId);
Mockito.verify(repository, Mockito.never()).save(Mockito.any());
}
}
| 37.410959
| 93
| 0.666056
|
fef9288c29edce9d5bc2c5da0ecde16ccbf6dbd4
| 11,656
|
/*
* MIT License
*
* Copyright (c) 2020 Ben Davies
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package uk.co.bjdavies.plugins;
import lombok.extern.log4j.Log4j2;
import uk.co.bjdavies.api.IApplication;
import uk.co.bjdavies.api.command.*;
import uk.co.bjdavies.api.plugins.IPluginSettings;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author ben.davies99@outlook.com (Ben Davies)
* @since 1.0.0
*/
@Log4j2
public final class PluginCommandParser {
private final IPluginSettings pluginSettings;
private final Object pluginObj;
private final IApplication application;
public PluginCommandParser(IApplication application, IPluginSettings pluginSettings, Object pluginObj) {
this.pluginSettings = pluginSettings;
this.pluginObj = pluginObj;
this.application = application;
}
public List<ICommand> parseCommands() {
List<ICommand> commands = new ArrayList<>();
for (final Method method : pluginObj.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(Command.class)) {
if (Arrays.asList(method.getParameterTypes()).contains(ICommandContext.class) && method.getParameterTypes().length == 1) {
Command command = method.getAnnotation(Command.class);
List<String> newAliases = new ArrayList<>(Arrays.asList(command.aliases()));
if (command.aliases().length == 0) {
newAliases.add(method.getName());
}
commands.add(new ICommand() {
@Override
public String[] getAliases() {
return newAliases.toArray(new String[0]);
}
@Override
public String[] getExamples() {
return generateExamples(method);
}
@Override
public String getDescription() {
return command.description();
}
@Override
public String getUsage() {
return command.usage().equals("") ? generateUsage(method) : command.usage();
}
@Override
public String getType() {
return command.type();
}
@Override
public String run(IApplication application, ICommandContext commandContext) {
return "";
}
@Override
public void exec(IApplication application, ICommandContext commandContext) {
PluginCommandDefinition cd = new PluginCommandExecutionBuilder(method.getName(),
pluginObj.getClass()).setParameterTypes(ICommandContext.class)
.setArgs(commandContext).build();
if (method.getReturnType().equals(Void.class)) {
executePluginCommand(cd);
} else {
if (!commandContext.getCommandResponse().send(method.getGenericReturnType(), executePluginCommand(cd))) {
log.error("Plugin command: " + pluginSettings.getName() + "#" + method.getName() +
" is not supported, command will not run please return a valid response type or use void and use commandContext.getCommandResponse()" +
".send(Data)");
}
}
}
@Override
public boolean validateUsage(ICommandContext commandContext) {
boolean[] isValid = new boolean[]{true};
//TODO: Remove this as is deprecated.
Arrays.stream(command.requiredParams()).forEach(e -> {
if (!commandContext.hasParameter(e) && !e.isEmpty()) {
if (isValid[0]) {
isValid[0] = false;
}
}
});
return isValid[0] && (!command.requiresValue() || !commandContext.getValue().equals("")) &&
hasRequiredParams(commandContext, method);
}
});
}
}
}
return commands;
}
private boolean hasRequiredParams(ICommandContext commandContext, Method method) {
AtomicBoolean isValid = new AtomicBoolean(true);
Arrays.stream(method.getAnnotationsByType(CommandParam.class))
.filter(cp -> !cp.optional())
.forEach(cp -> {
if (isValid.get()) {
if (cp.canBeEmpty()) {
isValid.set(commandContext.hasParameter(cp.value()));
} else {
isValid.set(commandContext.hasNonEmptyParameter(cp.value()));
}
}
});
return isValid.get();
}
private String generateUsage(Method method) {
StringBuilder stringBuilder = new StringBuilder(application.getConfig().getDiscordConfig().getCommandPrefix());
Command command = method.getAnnotation(Command.class);
if (command.aliases().length == 0) {
stringBuilder.append(method.getName()).append(" ");
} else {
stringBuilder.append("(");
for (int i = 0; i < command.aliases().length; i++) {
if (i != command.aliases().length - 1) {
stringBuilder.append(command.aliases()[i]).append("|");
} else {
stringBuilder.append(command.aliases()[i]);
}
}
stringBuilder.append(") ");
}
Arrays.stream(method.getAnnotationsByType(CommandParam.class)).forEach(cp -> {
stringBuilder.append("-(").append(cp.value());
if (cp.optional()) {
stringBuilder.append("?)");
} else {
stringBuilder.append("*)");
}
if (!cp.canBeEmpty()) {
stringBuilder.append("=*");
}
stringBuilder.append(" ");
});
stringBuilder.append("(value");
if (command.requiresValue()) {
stringBuilder.append("*)");
} else {
stringBuilder.append("?)");
}
return stringBuilder.toString();
}
private String[] generateExamples(Method method) {
List<String> examples = new ArrayList<>();
List<String> requiredParams = new ArrayList<>();
List<String> optionalParams = new ArrayList<>();
Arrays.stream(method.getAnnotationsByType(CommandParam.class))
.forEach(cp -> {
if (!cp.optional()) {
addToExamplesParamList(requiredParams, cp);
} else {
addToExamplesParamList(optionalParams, cp);
}
});
Command command = method.getAnnotation(Command.class);
StringBuilder sb = new StringBuilder(application.getConfig().getDiscordConfig().getCommandPrefix());
String defaultCommand = "";
if (command.aliases().length == 0) {
sb.append(method.getName()).append(" ");
} else {
sb.append(command.aliases()[0]).append(" ");
}
requiredParams.forEach(sb::append);
defaultCommand = sb.toString();
String finalDefaultCommand = defaultCommand;
String exampleValue = !command.exampleValue().equals("") ? command.exampleValue() : "example-value";
exampleValue = command.requiresValue() ? exampleValue : "";
String finalExampleValue = exampleValue;
optionalParams.forEach(op -> examples.add(finalDefaultCommand + op + " " + finalExampleValue));
examples.add(finalDefaultCommand + exampleValue);
Arrays.stream(method.getAnnotationsByType(CommandExample.class))
.map(CommandExample::value)
.forEach(examples::add);
return examples.toArray(new String[0]);
}
private void addToExamplesParamList(List<String> params, CommandParam cp) {
if (cp.canBeEmpty()) {
params.add("-" + cp.value() + " ");
} else {
if (!cp.exampleValue().equals("")) {
String exampleValue = cp.exampleValue().split(" ").length == 0
? cp.exampleValue()
: "\"" + cp.exampleValue() + "\"";
params.add("-" + cp.value() + "=" + exampleValue + " ");
} else {
params.add("-" + cp.value() + "=value ");
}
}
}
/**
* This will execute a plugin command that are placed in the plugin the command has to be
* annotated with {@link Command}
* <p>
* e.g. play()
*
* @param pluginCommandDefinition - This is the set of data that will be used to run the command.
* @return Object
*/
public Object executePluginCommand(PluginCommandDefinition pluginCommandDefinition) {
Class<?> pluginClass = pluginCommandDefinition.getPluginClass();
try {
Method method = pluginClass.getDeclaredMethod(pluginCommandDefinition.getName(),
pluginCommandDefinition.getParameterTypes());
method.setAccessible(true);
if (method.isAnnotationPresent(Command.class)) {
return method.invoke(pluginObj, pluginCommandDefinition.getArgs());
}
} catch (NoSuchMethodException e) {
log.error("The module command entered does not exist inside this module.", e);
} catch (InvocationTargetException | IllegalAccessException e) {
log.error("The module command did not execute correctly.", e);
}
return null;
}
}
| 40.61324
| 179
| 0.541953
|
e89f7cb01795da8f1dc7a04e3d566106a95b3c16
| 19,303
|
package com.github.jenya705.mcapi.server.module.link;
import com.github.jenya705.mcapi.LinkRequest;
import com.github.jenya705.mcapi.entity.event.EntityLinkEvent;
import com.github.jenya705.mcapi.entity.event.EntityUnlinkEvent;
import com.github.jenya705.mcapi.error.*;
import com.github.jenya705.mcapi.event.QuitEvent;
import com.github.jenya705.mcapi.player.Player;
import com.github.jenya705.mcapi.rest.event.RestLinkEvent;
import com.github.jenya705.mcapi.rest.event.RestUnlinkEvent;
import com.github.jenya705.mcapi.server.application.AbstractApplicationModule;
import com.github.jenya705.mcapi.server.application.OnStartup;
import com.github.jenya705.mcapi.server.application.ServerApplication;
import com.github.jenya705.mcapi.server.command.CommandsUtils;
import com.github.jenya705.mcapi.server.entity.AbstractBot;
import com.github.jenya705.mcapi.server.entity.BotLinkEntity;
import com.github.jenya705.mcapi.server.entity.BotPermissionEntity;
import com.github.jenya705.mcapi.server.form.FormComponent;
import com.github.jenya705.mcapi.server.form.FormPlatformProvider;
import com.github.jenya705.mcapi.server.form.component.*;
import com.github.jenya705.mcapi.server.module.command.CommandModule;
import com.github.jenya705.mcapi.server.module.config.ConfigModule;
import com.github.jenya705.mcapi.server.module.database.DatabaseModule;
import com.github.jenya705.mcapi.server.module.localization.LocalizationModule;
import com.github.jenya705.mcapi.server.module.storage.StorageModule;
import com.github.jenya705.mcapi.server.util.ListUtils;
import com.github.jenya705.mcapi.server.util.MultivaluedMap;
import com.github.jenya705.mcapi.server.util.OnlinePlayerImitation;
import com.github.jenya705.mcapi.server.util.ReactiveUtils;
import com.google.inject.Inject;
import java.util.*;
import java.util.stream.Stream;
/**
* @author Jenya705
*/
public class LinkingModuleImpl extends AbstractApplicationModule implements LinkingModule {
private final LinkingModuleConfig config;
private final LinkIgnores linkIgnores;
private final FormPlatformProvider formProvider;
private final DatabaseModule databaseModule;
private final StorageModule storageModule;
private final LocalizationModule localizationModule;
private final CommandModule commandModule;
private final MultivaluedMap<UUID, LinkObject> links = MultivaluedMap.create();
@Inject
public LinkingModuleImpl(ServerApplication application, FormPlatformProvider formProvider,
DatabaseModule databaseModule, StorageModule storageModule,
LocalizationModule localizationModule, CommandModule commandModule,
ConfigModule configModule) {
super(application);
config = new LinkingModuleConfig(
configModule
.getConfig()
.required("linking")
);
this.formProvider = formProvider;
this.databaseModule = databaseModule;
this.storageModule = storageModule;
this.localizationModule = localizationModule;
this.commandModule = commandModule;
eventLoop()
.handler(QuitEvent.class, event -> {
Player player = new OnlinePlayerImitation(event.getPlayer());
if (links.containsKey(player.getUuid())) {
links
.get(player.getUuid())
.forEach(it -> end(player, it, false));
links.remove(player.getUuid());
}
});
linkIgnores = new LinkIgnores(app());
linkIgnores.init();
}
@Override
public void requestLink(AbstractBot bot, Player player, LinkRequest request) {
validateLinkRequest(bot, player, request);
LinkObject obj = new LinkObject(
request, bot,
bot.getEntity().getId()
);
links.add(player.getUuid(), obj);
sendMessage(player, obj);
}
public void sendMessage(Player player, LinkObject request) {
formProvider.sendMessage(player,
formProvider
.newBuilder()
.components(
config.getLinkMessageComponents().toArray(String[]::new),
Map.of(
"newline", NewLineComponent.get(),
"title", TitleComponent.of(
CommandsUtils.placeholderMessage(
config.getTitle(),
"%bot_name%", request.getBot().getEntity().getName()
)
),
"content", ListComponent.joining(
new FormComponent[]{
ContentComponent.of(CommandsUtils.listMessage(
config.getContentLayout(),
config.getContentRequiredElement(),
config.getContentDelimiter(),
Arrays.asList(request.getRequest().getRequireRequestPermissions()),
it -> new String[]{
"%permission%", localizationModule.getLinkPermissionLocalization(it)
},
"%bot_name%", request.getBot().getEntity().getName()
))
},
request
.getOptionalPermissions()
.entrySet()
.stream()
.map(permissionEntry ->
ListComponent.of(
ContentComponent.of(
CommandsUtils.placeholderMessage(
config.getContentDelimiter()
)
),
ContentComponent.of(
CommandsUtils
.placeholderMessage(
config.getContentOptionalElement(),
"%permission%", localizationModule
.getLinkPermissionLocalization(
permissionEntry.getKey()
)
)
),
ButtonComponent.of(
CommandsUtils
.placeholderMessage(
permissionEntry.getValue() ?
config.getContentOptionalToggleFalse() :
config.getContentOptionalToggleTrue()
),
getCommand(
"toggle %d %s",
request.getId(),
permissionEntry.getKey()
)
)
)
)
.toArray(FormComponent[]::new),
new FormComponent[]{
ContentComponent.of(CommandsUtils.listMessage(
config.getContentMinecraftCommandLayout(),
config.getContentMinecraftCommandElement(),
config.getContentDelimiter(),
Arrays.asList(request.getRequest().getMinecraftRequestCommands()),
it -> new String[]{
"%command%",
String.format(
"%s %s", request.getBot().getEntity().getName(), it
)
}
))
}
),
"accept", ButtonComponent.of(
CommandsUtils.placeholderMessage(
config.getAcceptButton()
),
getCommand(
"end %d true",
request.getId()
)
),
"decline", ButtonComponent.of(
CommandsUtils.placeholderMessage(
config.getDeclineButton()
),
getCommand(
"end %d false",
request.getId()
)
)
)
)
.build()
);
}
@Override
public void unlink(int id, Player player) {
worker().invoke(() -> {
BotLinkEntity link = databaseModule
.storage()
.findLink(id, player.getUuid());
if (link == null) return;
databaseModule
.storage()
.delete(link);
eventTunnel()
.getClients()
.stream()
.filter(it -> it.getOwner().getEntity().getId() == id)
.filter(it -> it.isSubscribed(RestUnlinkEvent.type))
.forEach(it -> it.send(new EntityUnlinkEvent(player)));
});
}
@Override
public boolean isExists(Player player, int index, String permission) {
return getPlayerLinks(player)
.stream()
.anyMatch(linkObject -> linkObject.getId() == index);
}
@Override
public void toggle(Player player, int index, String permission) {
getPlayerLinksById(player, index)
.forEach(linkObject -> linkObject.toggleOptionalPermission(permission));
}
@Override
public void update(Player player, int index) {
getPlayerLinksById(player, index)
.forEach(linkObject -> sendMessage(player, linkObject));
}
@Override
public void end(Player player, int index, boolean enabled) {
List<LinkObject> playerLinks = getPlayerLinks(player);
for (int i = 0; i < playerLinks.size(); ++i) {
LinkObject currentPlayerLink = playerLinks.get(i);
if (currentPlayerLink.getId() == index) {
end(player, currentPlayerLink, enabled);
playerLinks.remove(i);
break;
}
}
}
private void end(Player player, LinkObject linkObject, boolean enabled) {
worker().invoke(() -> {
eventTunnel()
.getClients()
.stream()
.filter(client -> client.getOwner().getEntity().getId() == linkObject.getId())
.filter(client -> client.isSubscribed(RestLinkEvent.type))
.forEach(client -> client.send(
new EntityLinkEvent(
!enabled,
player,
linkObject
.getOptionalPermissions()
.entrySet()
.stream()
.filter(it -> !it.getValue())
.map(Map.Entry::getKey)
.toArray(String[]::new)
)
));
linkObject
.getOptionalPermissions()
.entrySet()
.stream()
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.forEach(it -> savePermission(linkObject, it, player));
for (String requirePermission: linkObject.getRequest().getRequireRequestPermissions()) {
savePermission(linkObject, requirePermission, player);
}
databaseModule
.storage()
.save(new BotLinkEntity(
linkObject.getId(),
player.getUuid()
));
});
player.sendMessage(
CommandsUtils.placeholderMessage(
enabled ?
config.getEnabledEnd() :
config.getDisabledEnd()
)
);
core()
.givePermission(
player,
true,
Arrays
.stream(linkObject.getRequest().getMinecraftRequestCommands())
.map(it -> String.format(
CommandModule.permissionFormat,
linkObject.getBot().getEntity().getId()
) + "." + it.replace(' ', '.')
)
.toArray(String[]::new)
);
}
private void validateLinkRequest(AbstractBot bot, Player player, LinkRequest request) {
ReactiveUtils.ifTrueThrow(
databaseModule
.storage()
.findLink(bot.getEntity().getId(), player.getUuid()) != null,
LinkExistException::create
);
ReactiveUtils.ifTrueThrow(
getPlayerLinks(player)
.stream()
.anyMatch(it -> it.getId() == bot.getEntity().getId()),
LinkRequestExistException::create
);
List<String> joinedList = ListUtils.join(
request.getRequireRequestPermissions(),
request.getOptionalRequestPermissions()
);
joinedList
.stream()
.filter(it -> storageModule.getPermission(it) == null || linkIgnores.isIgnored(it))
.findAny()
.ifPresent(it -> {
throw LinkRequestPermissionNotFoundException.create(it);
});
joinedList
.stream()
.filter(it -> storageModule.getPermission(it).isGlobal())
.findAny()
.ifPresent(it -> {
throw LinkRequestPermissionIsGlobalException.create(it);
});
Arrays
.stream(request.getMinecraftRequestCommands())
.filter(it -> commandModule.getBotCommandExecutor(bot, it) == null)
.findAny()
.ifPresent(it -> {
throw BotCommandNotExistException.create(it);
});
}
private List<LinkObject> getPlayerLinks(Player player) {
return links
.getOrDefault(player.getUuid(), Collections.emptyList());
}
private Stream<LinkObject> getPlayerLinksById(Player player, int index) {
return getPlayerLinks(player)
.stream()
.filter(it -> it.getId() == index);
}
private static String getCommand(String command, Object... formats) {
return linkCommand + " " + String.format(command, formats);
}
private void savePermission(LinkObject linkObject, String permission, Player player) {
databaseModule
.storage()
.upsert(new BotPermissionEntity(
linkObject.getId(),
BotPermissionEntity.toRegex(permission),
player.getUuid(),
false,
true
));
}
}
| 51.889785
| 144
| 0.403512
|
28b880b87ff23cffb1bc007c372a61ce45efb0c2
| 6,847
|
package org.wg3.storage;
import java.util.ArrayList;
import java.util.List;
/**
* An extension of RedBlackTree that stores generic values using Intervals as
* keys. The augmented nodes allow us to query in O(log(n)) time for overlaps.
*
* Algorithms furnished by CLRS
*
* Asymptotic Characteristics: Get Overlapping -- O(min(n,k*log(n))) where n is
* size of the tree and k is the number of overlapping intervals in the tree
*
* Credits:
*
* Taken from the rabinfingerprint project, licensed under
* http://www.apache.org/licences/LICENSE-2.0
*
* https://github.com/themadcreator/rabinfingerprint
*
* @author Bill Dwyer
*
*/
public class IntervalTree<Value> extends RedBlackTree< Interval, Value> {
/**
* An augmented node that holds extra information about its children.
*
* This allows us to make interval queries in O(log(n)). The trick is to
* update the ancestor tree on insertion and deletion (which is O(log(n)))
* and to update the two rotated nodes upon rotation (which is (O(1)))
*
* @see CLRS 14.3
*/
protected static class AugmentedNode< Value> extends RedBlackNode< Interval, Value> {
protected Integer maxEnd;
protected Integer minStart;
protected AugmentedNode(Interval key, Value value) {
super(key, value);
maxEnd = key.getEnd();
minStart = key.getStart();
}
protected Integer getMaxEnd() {
return maxEnd;
}
protected Integer getMinStart() {
return minStart;
}
/**
* maxEnd = max( this.maxEnd, left.maxEnd, right.maxEnd ); minStart =
* max( this.minStart, left.minStart, right.minStart );
*
* @see CLRS 14.3
*/
@Override
public void updateDataFromChildren() {
super.updateDataFromChildren();
maxEnd = key.getEnd();
if (getLeft() != null && getLeft().getMaxEnd() > maxEnd) {
maxEnd = getLeft().getMaxEnd();
}
if (getRight() != null && getRight().getMaxEnd() > maxEnd) {
maxEnd = getRight().getMaxEnd();
}
minStart = key.getStart();
if (getLeft() != null && getLeft().getMinStart() < minStart) {
minStart = getLeft().getMinStart();
}
if (getRight() != null && getRight().getMinStart() < minStart) {
minStart = getRight().getMinStart();
}
}
/**
* Convenience cast
*/
@Override
public AugmentedNode< Value> getLeft() {
return (AugmentedNode< Value>) super.getLeft();
}
/**
* Convenience cast
*/
@Override
public AugmentedNode< Value> getRight() {
return (AugmentedNode< Value>) super.getRight();
}
/**
* Convenience cast
*/
@Override
public AugmentedNode< Value> getParent() {
return (AugmentedNode< Value>) super.getParent();
}
}
/**
* Custom node factory
*/
@Override
protected AugmentedNode< Value> createNode(Interval key, Value value) {
return new AugmentedNode< Value>(key, value);
}
/**
* Convenience cast
*/
@Override
public AugmentedNode< Value> getRoot() {
return (AugmentedNode< Value>) super.getRoot();
}
/**
* Finds one interval that overlaps the input, if one exists.
*
* O(log(n))
*
* @see CLRS 14.3 - Interval-Search
*/
public Interval getOverlappingInterval(Interval interval) {
AugmentedNode< Value> node = getRoot();
while (node != null && node.getKey().isOverlap(interval) == false) {
if (node.getLeft() != null && node.getLeft().getMaxEnd() >= interval.getStart()) {
node = node.getLeft();
} else {
node = node.getRight();
}
}
return (node == null) ? null : node.getKey();
}
/**
* Finds all intervals that overlap the input. However, with the augmented
* node, we get major saving in pruning during the query.
*
* O(min(n,k*log(n))) where n is size of the tree and k is the number of
* overlapping intervals in the tree
*
* @see CLRS 14.3-4
*/
public List< Interval> getOverlappingIntervals(Interval interval) {
KeyVisitor< Value> visitor = new KeyVisitor< Value>();
getOverlappingIntervalsBelow(interval, getRoot(), visitor);
return visitor.getList();
}
public List< Value> getOverlappingValues(Interval interval) {
ValueVisitor< Value> visitor = new ValueVisitor< Value>();
getOverlappingIntervalsBelow(interval, getRoot(), visitor);
return visitor.getList();
}
/**
* Adds overlapping intervals to the list while traversing tree.
*/
protected void getOverlappingIntervalsBelow(Interval interval, AugmentedNode< Value> node, OverlappingVisitor<Value, ?> visitor) {
if (node == null) {
return;
}
if (node.getKey().isOverlap(interval)) {
visitor.visitOverlappingNode(node);
}
// if anything on the left side could overlap, descend
if (node.getLeft() != null && node.getLeft().getMaxEnd() >= interval.getStart()) {
getOverlappingIntervalsBelow(interval, node.getLeft(), visitor);
}
// if anything on the right side could overlap, descend
if (node.getRight() != null && node.getRight().getMinStart() < interval.getEnd()) {
getOverlappingIntervalsBelow(interval, node.getRight(), visitor);
}
}
protected abstract static class OverlappingVisitor< Value, ListType> {
protected final List< ListType> list;
public OverlappingVisitor() {
this.list = new ArrayList< ListType>();
}
public List< ListType> getList() {
return list;
}
public abstract void visitOverlappingNode(AugmentedNode< Value> node);
}
protected static class KeyVisitor< Value> extends OverlappingVisitor< Value, Interval> {
@Override
public void visitOverlappingNode(AugmentedNode< Value> node) {
list.add(node.getKey());
}
}
protected static class ValueVisitor< Value> extends OverlappingVisitor< Value, Value> {
@Override
public void visitOverlappingNode(AugmentedNode< Value> node) {
list.add(node.getValue());
}
}
}
| 31.699074
| 135
| 0.567402
|
88b70ef92be75a5589eb907b33ef20243f02cb3c
| 2,575
|
package org.deletethis.hardcode;
import org.deletethis.hardcode.objects.NodeFactory;
import org.deletethis.hardcode.objects.ParameterName;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* The configuration.
*
* Any implementation of this interface will do. Most people should be happy with {@link DefaultConfiguration}.
*/
public interface HardcodeConfiguration {
/**
* <p>Implements {@link java.util.function.Supplier}.
*
* <p>Setting this to true makes code require Java 1.8 to run.
*
* @return {@code true} if {@link java.util.function.Supplier} should be implemented, {@code false} otherwise
*/
boolean generateSupplier();
/**
* <p>Additional {@link NodeFactory} objects. This is commonly used to provide serializers for custom types.
*
* @return A collection of {@link NodeFactory} objects. Order is not important as they will be sorted anyways.
*/
Collection<NodeFactory> getAdditionalNodeFactories();
/**
* <p>An alternative to {@link HardcodeRoot} annotation on class.
*
* @return {@code true}, if the class should be considered to be the root
*/
boolean isRootClass(Class<?> clz);
/**
* <p>An alternative to {@link HardcodeRoot} annotation on a member.
*
* @param parent the parent class
* @param name the member name
*
* @return {@code true}, if member should be considered to be the root
*/
boolean isRootMembers(Class<?> parent, ParameterName name);
/**
* <p>An alternative to {@link HardcodeSplit} annotation on a member.
* @param parent the parent class
* @param name the member name
*
* @return null if member should not be split, or split value
*/
Integer getSplitMember(Class<?> parent, ParameterName name);
/**
* <p>Additional configuration for extensions.
*
* <p>They could require user to extend {@link HardcodeConfiguration}, however this approach doesn't really scale
* well - two extensions whould have to provide to incompatible sublcasses of {@link DefaultConfiguration}.
*
* <p>Therefore we have a mechanism to query objects by their type - somewhat similar to dependency injection - in order
* to provide additional configuration.
*
* @param clz type of additional configuration object
* @return additional config, or null if no such object exists
*/
<T> T getAdditionalConfiguration(Class<T> clz);
int getMethodLineCountHint();
}
| 33.881579
| 124
| 0.683883
|
b141bd774ad8e3922f4be526fb22d5d8342db537
| 2,291
|
package org.kalum.core.controllers;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.kalum.core.db.Conexion;
import org.kalum.core.db.ConexionPU;
import org.kalum.core.models.Usuario;
import org.kalum.core.sistema.Main;
import javax.persistence.ParameterMode;
import javax.swing.*;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
public class LoginController implements Initializable {
private Main escenarioPrincipal;
@FXML private TextField txtUsuario;
@FXML private PasswordField txtPassword;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void autenticar (){
try {
List<Usuario> usuario = ConexionPU.getInstacia().getEntityManager()
.createStoredProcedureQuery("sp_Autenticar",Usuario.class)
.registerStoredProcedureParameter(1,String.class, ParameterMode.IN)
.registerStoredProcedureParameter(2,String.class,ParameterMode.IN)
.setParameter(1,txtUsuario.getText())
.setParameter(2,txtPassword.getText())
.getResultList();
if(usuario.isEmpty()){
Alert aviso = new Alert(Alert.AlertType.ERROR);
aviso.setTitle("Kalum v1.0.0");
aviso.setHeaderText("Login");
aviso.setContentText("No existe el usuario, revise sus credenciales");
aviso.show();
}else{
Alert aviso = new Alert(Alert.AlertType.CONFIRMATION);
aviso.setTitle("Kalum v1.0.0");
aviso.setHeaderText("Login");
aviso.setContentText("Bienvenido: " + usuario.get(0).getNombres()+" "+usuario.get(0).getApellidos());
aviso.show();
this.escenarioPrincipal.mostrarEscenaPrincipal();
}
}catch (Exception e){
e.printStackTrace();
}
}
public void setEscenarioPrincipal(Main escenarioPrincipal) {
this.escenarioPrincipal = escenarioPrincipal;
}
}
| 35.796875
| 117
| 0.649935
|
df59f43dfaa384bb9a113e6a82eef59f1b11527d
| 1,622
|
package org.openfact.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotBlank;
@Entity
@Table(name = "NUMERACION_COMPROBANTE_PAGO")
public class NumeracionComprobantePagoEntity {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "ID")
private String id;
@NotNull
@NotBlank
@Column(name = "SERIE")
private String serie;
@NotNull
@NotBlank
@Column(name = "NUMERO")
private String numero;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSerie() {
return serie;
}
public void setSerie(String serie) {
this.serie = serie;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NumeracionComprobantePagoEntity other = (NumeracionComprobantePagoEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| 19.542169
| 80
| 0.704069
|
299099a4ac3561e61c0d1a19fb76d1e4389ef11b
| 364
|
package psaw.websocket.service.codec;
import psaw.websocket.domain.BasePdu;
import psaw.websocket.service.WSFtpException;
import java.nio.ByteBuffer;
/**
* <p>
* <code>PduEncoder</code> -
* Interface for encoding PDUs.
* </p>
*
* @author prabath.
*/
public interface PduEncoder<R extends BasePdu> {
ByteBuffer encode(R pdu) throws WSFtpException;
}
| 18.2
| 51
| 0.725275
|
98967de40d6d4e6a6e5bdbeb5b921747fbe01629
| 992
|
import java.util.*;
class TriangleAreaChecker{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double s, s1, s2, s3, ar, c=0.0; double ans[] = new double[40];
System.out.println("Input the value of side 1 of the triangle");
s1=(double)sc.nextDouble();
System.out.println("Input the value of side 2 of the triangle");
s2=(double)sc.nextDouble();
System.out.println("Input the value of side 3 of the triangle");
s3=(double)sc.nextDouble();
s=(s1+s2+s3)/2.0;
ar=Math.sqrt(s*(s-s1)*(s-s2)*(s-s3));
for(int i=0; i<40; i++){
System.out.println("Enter the answer obtained by the student");
ans[i]=(double)sc.nextDouble();
}
for(int j=0; j<40; j++){
if(ans[j]==ar) c=c+1.0;
}
System.out.println("Correct answer is "+ar);
System.out.println("Number of students who gave correct answer: "+c);
}
}
| 39.68
| 77
| 0.56754
|
ab6e1d6e3d6a739256ec80f95ac8007c092c8bf7
| 1,350
|
package edu.escuelaing.arep.client;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
/**
* Propiedades de la clase RoundRobbin
*/
public class RoundRobbin {
private String[] puertos;
private int numeroServidor;
private String url;
/**
* Constructor de la clase
*/
public RoundRobbin(){
puertos = new String[]{"4570", "4571", "4572"};
numeroServidor = 0;
}
/**
* Método encargado de manejar la petición de consulta
* @return variable de tipo String
* @throws UnirestException
*/
public String find() throws UnirestException {
HttpResponse<String> apiResponse = Unirest.get(url+":"+puertos[numeroServidor]+"/find").asString();
return apiResponse.getBody();
}
/**
* Método encargado de manejar la petición de inserción
* @param dato de tipo String
* @return variable de tipo String
* @throws UnirestException
*/
public String save(String dato) throws UnirestException{
HttpResponse<String> apiResponse = Unirest.post(url+":"+puertos[numeroServidor]+"/save")
.body(dato)
.asString();
return apiResponse.getBody();
}
}
| 28.723404
| 108
| 0.628148
|
0f8e538fcbd75b94bb2db08f58907c1b7dc67ef7
| 4,317
|
package com.jared.base.utils;
import android.app.Activity;
import java.util.Iterator;
import java.util.Stack;
/**
* @ClassName AppManager
* @Author Jared
* @Date 2022/3/2 16:12
* @Version 1.0
* @Description
*/
public class AppManager {
private Stack<Activity> mActivityStack;
private AppManager() {
}
/**
* 单一实例
*/
public static AppManager getInstance() {
return SingleApp.INSTANCE;
}
public static class SingleApp {
public static AppManager INSTANCE = new AppManager();
}
/**
* 添加Activity到堆栈
*/
public void addActivity(Activity activity) {
if (mActivityStack == null) {
mActivityStack = new Stack<Activity>();
}
mActivityStack.add(activity);
}
/**
* 移除Activity
*/
public void removeActivity(Activity activity) {
if (mActivityStack != null && !mActivityStack.isEmpty()) {
Iterator<Activity> iterator = mActivityStack.iterator();
while (iterator.hasNext()) {
Activity tmps = iterator.next();
if (tmps.equals(activity)) {
iterator.remove();
break;
}
}
// mActivityStack.remove(activity);
}
}
/**
* 获取指定的Activity
*/
public Activity getActivity(Class<?> cls) {
if (mActivityStack != null) {
for (Activity activity : mActivityStack) {
if (activity.getClass().equals(cls)) {
return activity;
}
}
}
return null;
}
/**
* 获取当前显示Activity(堆栈中最后一个传入的activity)
*/
public Activity getLastActivity() {
if (mActivityStack != null && !mActivityStack.isEmpty()) {
return mActivityStack.lastElement();
}
return null;
}
/**
* 将Stack中的Activity强转为Class<?>的实例
*
* @param cls 继承自Activity的Class
* @return 能转换的情况下,转换为Class<?>
*/
public <T extends Activity> T getLastActivity(Class<T> cls) {
Activity activity = getLastActivity();
if (cls.isInstance(activity)) {
return cls.cast(activity);
}
return null;
}
/**
* 获取所有Activity
*/
public Stack<Activity> getAllActivityStacks() {
return mActivityStack;
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
if (!activity.isFinishing()) {
activity.finish();
mActivityStack.remove(activity);
}
}
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
if (mActivityStack == null || mActivityStack.isEmpty()) {
return;
}
Iterator<Activity> iterator = mActivityStack.iterator();
while (iterator.hasNext()) {
Activity tmps = iterator.next();
if (cls.equals(tmps.getClass())) {
iterator.remove();
tmps.finish();
break;
}
}
}
/**
* 结束除当前传入以外所有Activity
*/
public void finishOthersActivity(Class<?> cls) {
if (mActivityStack != null) {
Iterator<Activity> iterator = mActivityStack.iterator();
while (iterator.hasNext()) {
Activity tmps = iterator.next();
if (!cls.equals(tmps.getClass())) {
iterator.remove();
tmps.finish();
}
}
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
if (mActivityStack == null || mActivityStack.isEmpty()) {
return;
}
Iterator<Activity> iterator = mActivityStack.iterator();
while (iterator.hasNext()) {
Activity tmps = iterator.next();
iterator.remove();
tmps.finish();
}
}
/**
* 退出应用程序
*/
public void appExit() {
try {
finishAllActivity();
android.os.Process.killProcess(android.os.Process.myPid());// 杀死该应用进程
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 22.962766
| 81
| 0.513319
|
a1362639baf920251308f6c8372609bb4a90f358
| 4,911
|
package javaGroceryGame;
import java.util.*;
public abstract class GameTools {
//Initializing random generator
private static Random rand = new Random();
//Initializing variables and arrays
public static ArrayList<String> usedList = new ArrayList<String>();
public static String[] startStringArr = {"Asparagus"
,"Broccoli"
,"Carrots"
,"Cauliflower"
,"Celery"
,"Corn"
,"Cucumbers"
,"Lettuce"
,"Mushrooms"
,"Onions"
,"Peppers"
,"Potatoes"
,"Spinach"
,"Squash"
,"Zucchini"
,"Tomatoes"
,"Apples"
,"Avocados"
,"Bananas"
,"Berries"
,"Cherries"
,"Grapefruit"
,"Grapes"
,"Kiwis"
,"Lemons"
,"Melon"
,"Oranges"
,"Peaches"
,"Nectarines"
,"Pears"
,"Plums"
,"Bagels"
,"Chip dip"
,"English muffins"
,"Eggs"
,"Fruit juice"
,"Hummus"
,"Tortillas"
,"Burritos"
,"Fish sticks"
,"Ice cream"
,"Juice concentrate"
,"Pizza"
,"Popsicles"
,"Fries"
,"TV dinners"
,"Vegetables"
,"Veggie burgers"
,"BBQ sauce"
,"Gravy"
,"Honey"
,"Hot sauce"
,"Pasta sauce"
,"Relish"
,"Salad dressing"
,"Salsa"
,"Soy sauce"
,"Steak sauce"
,"Syrup"
,"Cereal"
,"Coffee beans"
,"Lemon juice"
,"Mac & cheese"
,"Olive oil"
,"Pancake mix"
,"Pasta"
,"Peanut butter"
,"Pickles"
,"Rice"
,"Tea"
,"Vegetable oil"
,"Vinegar"
,"Applesauce"
,"Baked beans"
,"Chili"
,"Fruit"
,"Olives"
,"Tinned meats"
,"Tuna"
,"Soups"
,"Tomatoes"
,"Veggies"
,"Basil"
,"Black pepper"
,"Cilantro"
,"Cinnamon"
,"Garlic"
,"Ginger"
,"Mint"
,"Oregano"
,"Paprika"
,"Parsley"
,"Red pepper"
,"Salt"
,"Spice mix"
,"Vanilla extract"
,"Butter"
,"Cottage cheese"
,"Milk"
,"Sour cream"
,"Whipped cream"
,"Yogurt"
,"Blue cheese"
,"Cheddar cheese"
,"Cottage cheese"
,"Cream cheese"
,"Feta cheese"
,"Goat cheese cheese"
,"Mozzarella cheese"
,"Parmesan cheese"
,"Provolone cheese"
,"Ricotta cheese"
,"Sandwich slices"
,"Swiss"
,"Bacon"
,"Beef"
,"Chicken"
,"Ground beef"
,"Ham"
,"Hot dogs"
,"Turkey"
,"Catfish"
,"Crab"
,"Lobster"
,"Mussels"
,"Oysters"
,"Salmon"
,"Shrimp"
,"Tuna"
,"Beer"
,"Club soda"
,"Champagne"
,"Gin"
,"Juice"
,"Mixers"
,"Wine"
,"Rum"
,"Soda pop"
,"Sports drink"
,"Bagels"
,"Croissants"
,"Buns"
,"Rolls"
,"Cake"
,"Cookies"
,"Donuts"
,"Bread"
,"Pie"
,"Pita bread"
,"Baking powder"
,"Bread crumbs"
,"Brownie mix"
,"Cake icing"
,"Chocolate chips"
,"Flour"
,"Sugar"
,"Sugar substitute"
,"Yeast"
,"Candy"
,"Cookies"
,"Crackers"
,"Dried fruit"
,"Granola bars"
,"Nuts"
,"Oatmeal"
,"Popcorn"
,"Potato chips"
,"Pretzels"
,"Lotion"
,"Wipes"
,"Cat food"
,"Cat litter"
,"Dog food"
,"Flea treatment"
,"Pet shampoo"
,"Soap"
,"Cosmetics"
,"Cotton swabs"
,"Facial cleanser"
,"Facial tissue"
,"Floss"
,"Hair gel"
,"Lip balm"
,"Moisturizing lotion"
,"Mouthwash"
,"Razors"
,"Shampoo"
,"Sunblock"
,"Toilet paper"
,"Toothpaste"
,"Aluminum foil"
,"Napkins"
,"Non-stick spray"
,"Paper towels"
,"Plastic wrap"
,"Sandwich"
,"Wax paper"
,"Air freshener"
,"Bleach"
,"Dishwasher soap"
,"Garbage bags"
,"Glass cleaner"
,"Notepad"
,"Glue"
,"Printer paper"
,"Pens"
,"Postage stamps"
,"Batteries"
,"Charcoal"
,"Propane"
,"Flowers"
,"Bug spray"
,"Light bulbs"
,"Newspaper"};
//Generate random int
public static int getRandInt(int max) {
return rand.nextInt(max - 1);
}
public static int getRandInt(int min, int max) {
while(true) {
//Generating random integer
int r = rand.nextInt(max - 1);
//Testing if less than minimum, if so reseting random, else return random
if(r < min) {
r = rand.nextInt(max - 1);
} else {
return r;
}
}
}
//Method for adding words to used arraylist
public static void addWord(String s) {
usedList.add(s);
}
//Get random unused word and add to used arraylist
public static String getRandWord() {
int r;
boolean rep = true, used = false;
String tempWord = "Error!, Please Terminate Program";
while(rep) {
r = getRandInt(217);
tempWord = startStringArr[r];
for(int i = 0; i < usedList.size(); i++) {
if(tempWord.equalsIgnoreCase(usedList.get(i))) {
i = usedList.size();
} else {
used = false;
}
}
if(!used) {
rep = false;
}
}
usedList.add(tempWord);
return tempWord;
}
}
| 18.121771
| 77
| 0.529831
|
e948413e627c52c7d7aacce2d8fd06356488822e
| 2,534
|
package com.binggr.glmall.ware.service.impl;
import com.alibaba.fastjson.TypeReference;
import com.binggr.common.utils.R;
import com.binggr.glmall.ware.feign.MemberFeignService;
import com.binggr.glmall.ware.vo.FareResponseVo;
import com.binggr.glmall.ware.vo.MemberAddressVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.binggr.common.utils.PageUtils;
import com.binggr.common.utils.Query;
import com.binggr.glmall.ware.dao.WareInfoDao;
import com.binggr.glmall.ware.entity.WareInfoEntity;
import com.binggr.glmall.ware.service.WareInfoService;
@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
@Autowired
MemberFeignService memberFeignService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
String key = (String) params.get("key");
if(!StringUtils.isEmpty(key)){
queryWrapper.eq("id",key)
.or().like("name",key)
.or().like("address",key)
.or().like("areacode",key);
}
IPage<WareInfoEntity> page = this.page(
new Query<WareInfoEntity>().getPage(params),
queryWrapper
);
return new PageUtils(page);
}
/**
* 根据用户的收货地址计算运费
* @param addrId
* @return
*/
@Override
public FareResponseVo getFare(Long addrId) {
//远程查询运费
R info = memberFeignService.addrInfo(addrId);
MemberAddressVo data = info.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {
});
if(data!=null){
// TODO 可以结合第三方物流接口计算
FareResponseVo fareResponseVo = new FareResponseVo();
String phone = data.getPhone();
String substring = phone.substring(phone.length() - 1, phone.length());
BigDecimal decimal = new BigDecimal(substring);
fareResponseVo.setAddressVo(data);
fareResponseVo.setFare(decimal);
return fareResponseVo;
}
return null;
}
}
| 32.075949
| 110
| 0.680742
|
889cbda6f4571e5de835c2f7138ca8958243f6eb
| 1,793
|
package com.fred.inventory.presentation.supplieslist.viewmodels;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.support.v7.widget.RecyclerView;
import android.text.TextWatcher;
import android.view.View;
import com.fred.inventory.presentation.widgets.clicktoedittext.ClickToEditTextView;
import com.fred.inventory.utils.binding.Observer;
/**
* View model for the product list
* <p/>
* Created by fred on 09.07.16.
*/
public interface SuppliesListViewModel {
interface OnScanBarCodeButtonClickListener {
void onScanBarCodeButtonClicked();
}
void setOnScanBarCodeButtonClickListener(OnScanBarCodeButtonClickListener listener);
/***
* Prepare this view model to show details for this product list
*
* @param uuid The id of the product list
*/
void forProductList(String uuid);
void onActivityCreated();
void onDestroyView();
ObservableField<String> productListName();
TextWatcher productListTextWatcher();
void onDoneButtonClick(View view);
void onAddButtonClick(View view);
void onScanBarCodeButtonClick(View view);
ObservableInt emptyListVisibility();
ObservableInt itemListVisibility();
ObservableInt progressBarVisibility();
ObservableInt recyclerViewScrollPosition();
void unbindProductListIdObserver(Observer<String> observer);
void bindProductListIdObserver(Observer<String> observer);
RecyclerView.Adapter<?> productListRecyclerViewAdapter();
void onCodeScanned(String barcode);
void onSearchButtonClicked(View actionView);
ObservableInt toolBarDisplayedChild();
ObservableField<String> searchQuery();
ObservableField<ClickToEditTextView.Mode> productListNameMode();
TextWatcher searchQueryTextWatcher();
boolean onHomeButtonPressed();
}
| 24.902778
| 86
| 0.793084
|
1a600b383240c42a7776b87c74ad1984568f4078
| 2,922
|
/*
* @(#)ClippingFigure.java
* Copyright © 2021 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.draw.figure;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.transform.Transform;
import org.jhotdraw8.annotation.NonNull;
import org.jhotdraw8.css.CssSize;
import org.jhotdraw8.draw.handle.Handle;
import org.jhotdraw8.draw.handle.HandleType;
import org.jhotdraw8.draw.render.RenderContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* ClippingFigure.
*
* @author Werner Randelshofer
*/
public class ClippingFigure extends AbstractCompositeFigure
implements Clipping, StyleableFigure, LockedFigure, NonTransformableFigure {
public ClippingFigure() {
}
public ClippingFigure(@NonNull Collection<Figure> children) {
getChildren().addAll(children);
}
@Override
public void reshapeInLocal(@NonNull Transform transform) {
for (Figure child : getChildren()) {
child.reshapeInLocal(transform);
}
}
@Override
public void reshapeInLocal(@NonNull CssSize x, @NonNull CssSize y, @NonNull CssSize width, @NonNull CssSize height) {
// empty
}
@Override
public void updateNode(@NonNull RenderContext ctx, @NonNull Node n) {
applyStyleableFigureProperties(ctx, n);
List<Node> nodes = new ArrayList<>(getChildren().size());
for (Figure child : getChildren()) {
nodes.add(ctx.getNode(child));
}
ObservableList<Node> group = ((Group) n).getChildren();
if (!group.equals(nodes)) {
group.setAll(nodes);
}
}
@Override
public @NonNull Node createNode(@NonNull RenderContext ctx) {
Group n = new Group();
n.setManaged(false);
n.setAutoSizeChildren(false);
return n;
}
/**
* Layer figures always return false for isSelectable.
*
* @return false
*/
@Override
public boolean isSelectable() {
return false;
}
/**
* This method returns false for all new parents.
*
* @param newParent The new parent figure.
* @return false
*/
@Override
public boolean isSuitableParent(@NonNull Figure newParent) {
return false;
}
/**
* This method returns true for all children.
*
* @param newChild The new child figure.
* @return true
*/
@Override
public boolean isSuitableChild(@NonNull Figure newChild) {
return true;
}
/**
* Layers never create handles.
*/
@Override
public void createHandles(@NonNull HandleType handleType, @NonNull List<Handle> list) {
// empty
}
@Override
public @NonNull Bounds getBoundsInLocal() {
return getLayoutBounds();
}
}
| 25.189655
| 121
| 0.650924
|
6ccb375397c8c36e19329c97f189214ce25afedc
| 1,513
|
/*******************************************************************************
* Copyright (c) 2014 Tasktop Technologies.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.greensopinion.swagger.jaxrsgen.mock.noswagger.model;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import com.google.common.collect.ImmutableList;
public class PetListing {
private final int start;
private final int count;
private final int total;
private final List<PetHandle> pets;
public PetListing(int start, int count, int total, List<PetHandle> pets) {
this.start = start;
this.count = count;
this.total = total;
this.pets = ImmutableList.copyOf(checkNotNull(pets));
}
public int getStart() {
return start;
}
public int getCount() {
return count;
}
public int getTotal() {
return total;
}
public List<PetHandle> getPets() {
return pets;
}
}
| 26.086207
| 81
| 0.655651
|
648810eb6f7978652660d04004b84dfe6c45664a
| 538
|
package com.fs.voldemort.business.paramfinder;
import java.lang.annotation.Annotation;
import java.util.Collection;
/**
* The result of parameter finder{@link ParamFinder}
*/
public interface ParamFindResult {
/**
* Parameter name
* @return Parameter name
*/
String getParamName();
/**
* Parameter class
* @return Parameter class
*/
Class<?> getParamClazz();
/**
* Parameter annotation
* @return Parameter annotation
*/
Collection<Annotation> getAnnotation();
}
| 18.551724
| 52
| 0.64684
|
53f8034497958de6f0049ef8549e24f990f270b9
| 4,182
|
package ru.job4j.exam;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import ru.job4j.exam.store.ExamBaseHelper;
public class ExamListFragment extends Fragment {
private RecyclerView recycler;
private ExamBaseHelper store;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.exams_list_fragment, container, false);
this.recycler = view.findViewById(R.id.exams_list_fragment);
this.recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
this.store = ExamBaseHelper.getInstance(this.getContext());
updateUI();
return view;
}
private void updateUI() {
this.recycler.setAdapter(new ExamAdapter(store.getExams()));
}
public class ExamHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private View view;
private TextView text;
private TextView result;
private TextView date;
private Exam exam;
public ExamHolder(@NonNull View itemView) {
super(itemView);
this.view = itemView;
text = view.findViewById(R.id.q_text);
result = view.findViewById(R.id.result);
date = view.findViewById(R.id.date);
}
public void bind(Exam exam) {
this.exam = exam;
view.setOnClickListener(this);
text.setText(this.exam.getName());
if (exam.getResult() != null) {
result.setText(this.exam.getResult() + "%");
}
date.setText(this.exam.getTime());
}
@Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_image_click));
Intent intent = new Intent(getActivity(), ExamDescriptionActivity.class);
intent.putExtra(ExamBaseHelper.EXAM_ID, this.exam.getId());
startActivity(intent);
}
}
public class ExamAdapter extends RecyclerView.Adapter<ExamHolder> {
private final List<Exam> exams;
public ExamAdapter(List<Exam> exams) {
this.exams = exams;
}
@NonNull
@Override
public ExamHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
ExamHolder eh;
View itemLayoutView;
switch (i) {
case 0:
itemLayoutView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.info_exam_first_position, parent, false);
eh = new ExamHolder(itemLayoutView);
break;
case 1:
itemLayoutView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.info_exam, parent, false);
eh = new ExamHolder(itemLayoutView);
break;
default:
throw new IllegalStateException("Unexpected value: " + i);
}
return eh;
}
@Override
public void onBindViewHolder(@NonNull ExamHolder holder, int i) {
if (i != 0) {
holder.bind(this.exams.get(i - 1));
}
}
@Override
public int getItemViewType(int position) {
return position == 0 ? 0 : 1;
}
@Override
public int getItemCount() {
return this.exams.size() + 1;
}
}
}
| 33.190476
| 132
| 0.61143
|
d8c83625efe77d1ac7d033f26912192b3b457b64
| 1,043
|
package com.java110.api.bmo.returnPayFee;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.IApiBaseBMO;
import com.java110.core.context.DataFlowContext;
public interface IReturnPayFeeBMO extends IApiBaseBMO {
/**
* 添加退费表
*
* @param paramInJson
* @param dataFlowContext
* @return
*/
void addReturnPayFee(JSONObject paramInJson, DataFlowContext dataFlowContext);
/**
* 添加退费表信息
*
* @param paramInJson 接口调用放传入入参
* @param dataFlowContext 数据上下文
* @return 订单服务能够接受的报文
*/
void updateReturnPayFee(JSONObject paramInJson, DataFlowContext dataFlowContext);
void updateFeeDetail(JSONObject paramInJson, DataFlowContext dataFlowContext);
void addFeeDetail(JSONObject paramInJson, DataFlowContext dataFlowContext);
/**
* 删除退费表
*
* @param paramInJson 接口调用放传入入参
* @param dataFlowContext 数据上下文
* @return 订单服务能够接受的报文
*/
void deleteReturnPayFee(JSONObject paramInJson, DataFlowContext dataFlowContext);
}
| 24.833333
| 85
| 0.708533
|
33287d654b14c50cc45ab76dab5499a918515c23
| 3,168
|
package com.springboot.learning.learnspringsecurity.service;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Multimap;
import com.springboot.learning.learnspringsecurity.entity.Permission;
import com.springboot.learning.learnspringsecurity.vo.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
public class CustomerAuthorityService {
@Autowired
UrlLoader urlLoader;
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
checkRequest(request);
Object userInfo = authentication.getPrincipal();
boolean hasPermission = false;
if (userInfo instanceof UserDetails) {
UserPrincipal principal = (UserPrincipal) userInfo;
List<Permission> permissions = principal.getPermissions();
//获取资源,前后端分离,所以过滤页面权限,只保留按钮权限
List<Permission> btnPerms = permissions.stream()
// 过滤页面权限
.filter(permission -> Objects.equals(permission.getType(), 1))
// 过滤 URL 为空
.filter(permission -> StrUtil.isNotBlank(permission.getUrl()))
// 过滤 METHOD 为空
.filter(permission -> StrUtil.isNotBlank(permission.getMethod())).collect(Collectors.toList());
for (Permission btnPerm : btnPerms) {
AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(btnPerm.getUrl(), btnPerm.getMethod());
if (antPathMatcher.matches(request)) {
hasPermission = true;
break;
}
}
return hasPermission;
} else {
return false;
}
}
/**
* 校验请求是否存在
*
* @param request 请求
*/
private void checkRequest(HttpServletRequest request) {
// 获取当前 request 的方法
String currentMethod = request.getMethod();
Multimap<String, String> urlMapping = urlLoader.getUrlMapping();
for (String uri : urlMapping.keySet()) {
// 通过 AntPathRequestMatcher 匹配 url
// 可以通过 2 种方式创建 AntPathRequestMatcher
// 1:new AntPathRequestMatcher(uri,method) 这种方式可以直接判断方法是否匹配,因为这里我们把 方法不匹配 自定义抛出,所以,我们使用第2种方式创建
// 2:new AntPathRequestMatcher(uri) 这种方式不校验请求方法,只校验请求路径
AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(uri);
if (antPathMatcher.matches(request)) {
if (!urlMapping.get(uri).contains(currentMethod)) {
throw new SecurityException("Status.HTTP_BAD_METHOD");
} else {
return;
}
}
}
throw new SecurityException("Status.REQUEST_NOT_FOUND");
}
}
| 38.634146
| 120
| 0.648359
|
41d278a9a5780a9c998493377480e31f392af821
| 1,597
|
package com.bookstore;
import com.bookstore.service.BookstoreService;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
// For MySQL5Dialect (MyISAM) stoare engine): row-level locking not supported
// For MySQL5InnoDBDialect (InnoDB storage engine): row-level locking is aquired via FOR UPDATE
// For MySQL8Dialect (InnoDB storage engine): row-level locking is aquired via FOR UPDATE NOWAIT
// running the below method will throw: org.hibernate.QueryTimeoutException
// Caused by: com.mysql.cj.jdbc.exceptions.MySQLTimeoutException
// bookstoreService.editChapterTestLocking();
// For all dialects (MySQL5Dialect, MySQL5InnoDBDialect, MySQL8Dialect)
// running the below method will throw: javax.persistence.OptimisticLockException
// Caused by: org.hibernate.StaleObjectStateException:
bookstoreService.editChapterTestVersion();
};
}
}
| 39.925
| 108
| 0.708829
|
487e83bd9a344e7128bf04361102acaf054e69e1
| 5,258
|
package bayern.steinbrecher.sourceIncludeVisualizer.generators;
import bayern.steinbrecher.javaUtility.SupplyingMap;
import bayern.steinbrecher.sourceIncludeVisualizer.ColorPalette;
import java.awt.Color;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* @author Stefan Huber
* @since 0.1
*/
public final class GraphMLGenerator {
private static final Logger LOGGER = Logger.getLogger(GraphMLGenerator.class.getName());
private static final Collection<Color> GROUP_COLOR_NAMES = ColorPalette.COLOR_BLIND_FRIENDLY.getColors();
// FIXME Assure it's not a regular group color already
private static final Color DEFAULT_GROUP_COLOR = Color.WHITE;
private static final Color DEFAULT_EDGE_COLOR = Color.BLACK;
private static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n"
+ " http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n"
+ " <key id=\"groupColorRed\" for=\"node\" attr.name=\"r\" attr.type=\"int\"/>\n"
+ " <key id=\"groupColorGreen\" for=\"node\" attr.name=\"g\" attr.type=\"int\"/>\n"
+ " <key id=\"groupColorBlue\" for=\"node\" attr.name=\"b\" attr.type=\"int\"/>\n"
+ " <key id=\"edgeColorRed\" for=\"edge\" attr.name=\"r\" attr.type=\"int\"/>\n"
+ " <key id=\"edgeColorGreen\" for=\"edge\" attr.name=\"g\" attr.type=\"int\"/>\n"
+ " <key id=\"edgeColorBlue\" for=\"edge\" attr.name=\"b\" attr.type=\"int\"/>\n"
+ " <graph edgedefault=\"directed\">\n";
private static final String FOOTER = " </graph>\n"
+ "</graphml>\n";
private GraphMLGenerator() {
throw new UnsupportedOperationException("Construction of objects prohibited");
}
private static String generateNodeElement(String id, Color color) {
return String.format("<node id=\"%s\">\n"
+ " <data key=\"groupColorRed\">%d</data>\n"
+ " <data key=\"groupColorGreen\">%d</data>\n"
+ " <data key=\"groupColorBlue\">%d</data>\n"
+ "</node>\n",
id, color.getRed(), color.getGreen(), color.getBlue());
}
private static String generateEdgeElement(String source, String target, Color color) {
return String.format("<edge source=\"%s\" target=\"%s\">\n"
+ " <data key=\"edgeColorRed\">%d</data>\n"
+ " <data key=\"edgeColorGreen\">%d</data>\n"
+ " <data key=\"edgeColorBlue\">%d</data>\n"
+ "</edge>\n",
source, target, color.getRed(), color.getGreen(), color.getBlue());
}
public static String convert(Map<String, Collection<String>> includeDependencies) {
Queue<Color> remainingGroupColors = new ArrayDeque<>(GROUP_COLOR_NAMES);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
SupplyingMap<String, Color> associatedGroupColors = new SupplyingMap<>(groupName -> {
// NOTE Do not separate polling and checking for emptiness to prevent race conditions
Color groupColor = remainingGroupColors.poll();
if (groupColor == null) {
groupColor = DEFAULT_GROUP_COLOR;
}
return groupColor;
});
LibraryDetector libraryDetector = new LibraryDetector(includeDependencies.keySet());
StringBuilder graphMLBuilder = new StringBuilder(HEADER);
includeDependencies.forEach((file, includes) -> {
String sourceGroupName = libraryDetector.detect(file);
// Insert node for internal file
graphMLBuilder.append(generateNodeElement(file, associatedGroupColors.get(sourceGroupName)));
// Insert include dependency edges
includes.forEach(include -> {
String targetGroupName = libraryDetector.detect(include);
graphMLBuilder.append(generateNodeElement(include, associatedGroupColors.get(targetGroupName)));
graphMLBuilder.append(generateEdgeElement(file, include, DEFAULT_EDGE_COLOR));
});
});
Set<String> notFoundLibraries = libraryDetector.getNotFoundLibraries();
if (!notFoundLibraries.isEmpty()) {
String notFoundLibrariesList = notFoundLibraries.stream()
.sorted(String::compareToIgnoreCase)
.collect(Collectors.joining(", "));
String notFoundLibrariesStatistic = String.format(
"#NotFoundLibraries: %d\nNot Found: %s", notFoundLibraries.size(), notFoundLibrariesList);
LOGGER.log(Level.INFO, notFoundLibrariesStatistic);
}
graphMLBuilder.append(FOOTER);
return graphMLBuilder.toString();
}
}
| 51.54902
| 112
| 0.615824
|
03f23f0e9d2d7b5a4544fd9b72e4bbd87db7b6bd
| 1,193
|
package _09TrafficLights;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<TrafficLight> trafficLights = new ArrayList<>();
String[] input = reader.readLine().split("\\s+");
for (String s : input) {
TrafficLight trafficLight = new TrafficLight(s);
trafficLights.add(trafficLight);
}
int numberOfChanges = Integer.parseInt(reader.readLine());
for (int i = 0; i < numberOfChanges; i++) {
changeLights(trafficLights);
System.out.println(String.join(" ", trafficLights.stream()
.map(tl -> tl.getState().name())
.collect(Collectors.toList())));
}
}
private static void changeLights(List<TrafficLight> trafficLights) {
for (TrafficLight trafficLight : trafficLights) {
trafficLight.changeState();
}
}
}
| 32.243243
| 85
| 0.636211
|
8f24fc3463b66dd7671822f85f99914f3cb531c7
| 2,245
|
package us.codecraft.xsoup.w3c;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.UserDataHandler;
/**
* @author code4crafer@gmail.com
*/
public abstract class NodeAdaptor implements Node {
@Override
public void setNodeValue(String nodeValue) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public Node removeChild(Node oldChild) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public Node appendChild(Node newChild) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public void normalize() {
}
@Override
public boolean isSupported(String feature, String version) {
return false;
}
@Override
public String getNamespaceURI() {
return null;
}
@Override
public String getPrefix() {
return null;
}
@Override
public void setPrefix(String prefix) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public String getLocalName() {
return null;
}
@Override
public String getBaseURI() {
return null;
}
@Override
public void setTextContent(String textContent) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public String lookupPrefix(String namespaceURI) {
return null;
}
@Override
public boolean isDefaultNamespace(String namespaceURI) {
return false;
}
@Override
public String lookupNamespaceURI(String prefix) {
return null;
}
@Override
public Object getFeature(String feature, String version) {
return null;
}
@Override
public Object setUserData(String key, Object data, UserDataHandler handler) {
throw new UnsupportedOperationException();
}
}
| 22.009804
| 81
| 0.669933
|
83d91dd18c9b6c4ecf655d90325ae14fbcf7b202
| 3,793
|
/*
* Copyright 2021 Bonitasoft S.A.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.process.analytics.tools.bpmn.generator.converter.waypoint;
import io.process.analytics.tools.bpmn.generator.model.Edge;
import io.process.analytics.tools.bpmn.generator.model.Grid;
import io.process.analytics.tools.bpmn.generator.model.Position;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
@RequiredArgsConstructor
@Log4j2
public class GridSearcher {
private final Grid grid;
public Position getPositionFrom(Edge edge) {
return getPosition(edge, true);
}
public Position getPositionTo(Edge edge) {
return getPosition(edge, false);
}
private Position getPosition(Edge edge, boolean isFrom) {
String shapeId = isFrom && !edge.isReverted() || (!isFrom && edge.isReverted()) ? edge.getFrom() : edge.getTo();
return getPositionOfShape(shapeId);
}
private Position getPositionOfShape(String shapeId) {
return grid.getPositions()
.stream()
.filter(p -> shapeId.equals(p.getShape()))
.findFirst()
.get(); // always exist, otherwise error occur on flow node generation
}
public boolean isShapeExistAtLeft(Position position) {
return grid.getPositions()
.stream()
.filter(p -> p.getY() == position.getY())
.anyMatch(p -> p.getX() == position.getX() - 1);
}
public boolean isShapeExistAtRight(final Position position) {
return grid.getPositions()
.stream()
.filter(p -> p.getY() == position.getY())
.anyMatch(p -> p.getX() == position.getX() + 1);
}
public boolean isShapeExistAbove(final Position positionFrom) {
return grid.getPositions()
.stream()
.filter(p -> p.getX() == positionFrom.getX())
.anyMatch(p -> p.getY() == positionFrom.getY() - 1);
}
public BendConfiguration computeConfigurationToPassByEmptyRow(Position positionFrom, Position positionTo,
BendDirection searchDirection) {
int positionFromY = positionFrom.getY();
int offset = -1;
boolean isElementBetween = true;
log.debug("Search empty rows in direction {}", searchDirection);
while (isElementBetween) {
offset++;
isElementBetween = this.hasElementsBetweenPositionsHorizontally(
positionFromY + searchDirection.numericFactor() * offset,
positionFrom.getX(), positionTo.getX());
}
log.debug("Found empty row at offset {}", offset);
return BendConfiguration.builder().direction(searchDirection).offset(offset).build();
}
private boolean hasElementsBetweenPositionsHorizontally(final int y, final int x1, final int x2) {
log.debug("Searching for elements horizontally between positions. y={} x1={} x2={}", y, x1, x2);
return grid.getPositions()
.stream()
.filter(p -> p.getY() == y)
.filter(p -> p.getX() > Math.min(x1, x2))
.anyMatch(p -> p.getX() < Math.max(x1, x2));
}
}
| 39.510417
| 120
| 0.627999
|
2177fd20d685c9f8e4bebb1288f1060dcb33695e
| 371
|
package com.alipay.api.response;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.ebpp.invoice.title.sync response.
*
* @author auto create
* @since 1.0, 2019-06-21 16:58:07
*/
public class AlipayEbppInvoiceTitleSyncResponse extends AlipayResponse {
private static final long serialVersionUID = 3436277122951675989L;
}
| 17.666667
| 73
| 0.708895
|
5eb3c890723c0a77ae01551c72ee3ecfd9b6dbca
| 1,497
|
package br.com.knowledgeBase.api.knowledgebaseapi.services.impl;
import br.com.knowledgeBase.api.knowledgebaseapi.data.entities.Category;
import br.com.knowledgeBase.api.knowledgebaseapi.repositories.CategoryRepository;
import br.com.knowledgeBase.api.knowledgebaseapi.services.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class CategoryServiceImpl implements CategoryService {
private static final Logger LOG = LoggerFactory.getLogger(TagServiceImpl.class);
@Autowired
CategoryRepository categoryRepository;
@Override
public Page<Category> findAll(PageRequest pageRequest) {
LOG.info("Searching categories");
return this.categoryRepository.findAll(pageRequest);
}
@Override
public Category persist(Category category) {
LOG.info("Persisting category: {}", category);
return this.categoryRepository.save(category);
}
@Override
public Optional<Category> findById(Long id) {
LOG.info("searching category ID {}", id);
return this.categoryRepository.findById(id);
}
@Override
public void delete(Long id) {
LOG.info("Removing category ID {}", id);
this.categoryRepository.deleteById(id);
}
}
| 32.543478
| 84
| 0.752839
|
0f066fbc70c1586a7422e19c07dbf9090e327175
| 196
|
package enums;
public enum ListenerKey2D {
// definition of the Enums
FIELDLISTENER,
;// Enum implementation
public String getKey(int y, int x) {
return this.toString() + y + "" + x;
}
}
| 16.333333
| 38
| 0.673469
|
20b369e75aefafa7938d90d5c3cead6f7093c442
| 580
|
package com.board.ws;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml",
"/test-mariadb-context.xml",
"/test-servlet-context.xml"
})
public class TestConfig {
@Autowired
public ApplicationContext ctx;
}
| 29
| 71
| 0.815517
|
45a20a61efd63b432a5b64047e381e695fd166a3
| 4,396
|
package com.kadia.kblogserber.controller;
import com.alibaba.fastjson.JSONObject;
import com.kadia.kblogserber.common.Checker;
import com.kadia.kblogserber.common.ResponseData;
import com.kadia.kblogserber.common.ServicEexception;
import com.kadia.kblogserber.entity.Subscribe;
import com.kadia.kblogserber.entity.Verify;
import com.kadia.kblogserber.service.InfoService;
import com.kadia.kblogserber.service.SubscribeService;
import com.kadia.kblogserber.service.VerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.sql.rowset.serial.SerialException;
import java.util.List;
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {
@Autowired
private SubscribeService subscribeService;
@Autowired
private VerifyService verifyService;
@Autowired
private InfoService infoService;
@PostMapping("/sendVerify")
public ResponseData sendVerify(@RequestBody JSONObject body){
try {
if(Checker.existNullOrEmpty(new Object[]{body.get("email")})){
throw new ServicEexception("还没完善好信息哩!");
}
if(!Checker.isEmail((String) body.get("email"))){
throw new ServicEexception("请填写正确的邮箱哦!");
}
verifyService.sendVerifyAndRecord((String) body.get("email"));
return ResponseData.success();
}catch (ServicEexception e){
return ResponseData.error(e.getMessage());
}catch (Exception e){
return ResponseData.error("出错啦!请稍后再试");
}
}
@PostMapping("/doSubscribe")
public ResponseData doSubscribe(@RequestBody JSONObject body){
try {
if(Checker.existNullOrEmpty(new Object[]{body.get("code"),body.get("type")})){
throw new ServicEexception("还没完善好信息哩!");
}
Verify verify = verifyService.verifyAbleAndDelete((String) body.get("code"));
if(verify == null){
throw new ServicEexception("验证码不正确哦!");
}
if((Integer)body.get("type") == 0){
if(subscribeService.existSubscribe(verify.getEmail())){
throw new ServicEexception("已经订阅过啦!请勿重复订阅");
}
subscribeService.saveSubscribe(verify.getEmail());
return ResponseData.success("订阅成功");
}else if((Integer)body.get("type") == 1){
if(!subscribeService.existSubscribe(verify.getEmail())){
throw new ServicEexception("还没有订阅过哩");
}
subscribeService.deleteSubscribe(verify.getEmail());
return ResponseData.success("取消订阅成功");
}else{
throw new ServicEexception("遇到了点问题,请稍后再试!");
}
}catch (ServicEexception e){
return ResponseData.error(e.getMessage());
}catch (Exception e){
return ResponseData.error("出错啦!请稍后再试");
}
}
@RequestMapping("/getList")
public ResponseData getList(@RequestParam(value = "page",required = false,defaultValue = "0") Integer page,
@RequestParam(value = "token") String token){
try {
if(!infoService.isUser(token)){
throw new ServicEexception("身份验证失败!");
}
List<Subscribe> data = subscribeService.getList(page);
return ResponseData.success(data);
}catch (ServicEexception e){
return ResponseData.error(e.getMessage());
}catch (Exception e){
return ResponseData.error("出错啦!请稍后再试");
}
}
@PostMapping("/deleteSubscribe")
public ResponseData deleteSubscribe(@RequestBody JSONObject body){
try {
if(!infoService.isUser((String) body.get("token"))){
throw new ServicEexception("身份验证失败!");
}
if(Checker.existNullOrEmpty(new Object[]{body.get("email")})){
throw new ServicEexception("还没完善好信息哩!");
}
subscribeService.deleteSubscribe((String) body.get("email"));
return ResponseData.success("操作成功");
}catch (ServicEexception e){
return ResponseData.error(e.getMessage());
}catch (Exception e){
return ResponseData.error("出错啦!请稍后再试");
}
}
}
| 38.561404
| 111
| 0.61556
|
b9b6d67776eec4e2100da676978aa8cf005c88e7
| 605
|
package mvanish.mvanish.AllEvent;
import mvanish.mvanish.Main;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPickupItemEvent;
public class onPickupItem implements Listener {
public static Main plugin;
public onPickupItem(Main plugin){
this.plugin = plugin;
}
@EventHandler
public void onPickItem(PlayerPickupItemEvent e){
if (plugin.invisible.contains(e.getPlayer().getName()) && plugin.getConfig().getBoolean("player-can-pickup-items") == false){
e.setCancelled(true);
}
}
}
| 25.208333
| 133
| 0.710744
|
ab4bd6fa9922906c9938a05339ef72720d3dfca6
| 2,434
|
package fr.adbonnin.xtra.webclient.scraper;
import fr.adbonnin.xtra.collect.AbstractIterator;
import java.util.Iterator;
import static java.util.Collections.emptyIterator;
public abstract class BaseSearchScraper<E, T> implements Iterator<T> {
private final ItemIterator itemIterator = new ItemIterator();
private final PageIterator pageIterator = new PageIterator();
abstract Iterator<E> retrieveNextPage();
abstract T parseItem(E element, int index);
protected Iterator<E> noMorePage() {
return pageIterator.noMorePage();
}
/**
* Called at the end of a page.
* Note: Can be overridden
*/
protected void onEndOfPage(int pageNumber, boolean lastPage, int pageSize) {
}
@Override
public boolean hasNext() {
return itemIterator.hasNext();
}
@Override
public T next() {
return itemIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private class ItemIterator extends AbstractIterator<T> {
private Iterator<E> elementIterator = emptyIterator();
private int pageSize = 0;
private int pageNumber = 0;
@Override
protected T computeNext() {
for (; ; ) {
if (!elementIterator.hasNext()) {
final boolean hasMorePage = pageIterator.hasNext();
if (hasMorePage) {
elementIterator = pageIterator.next();
}
if (pageNumber > 0) {
onEndOfPage(pageNumber, !hasMorePage, pageSize);
}
++pageNumber;
pageSize = 0;
if (!hasMorePage) {
return endOfData();
}
}
if (elementIterator.hasNext()) {
final E element = elementIterator.next();
final T item = parseItem(element, pageSize);
++pageSize;
return item;
}
}
}
}
private class PageIterator extends AbstractIterator<Iterator<E>> {
@Override
protected Iterator<E> computeNext() {
return retrieveNextPage();
}
private Iterator<E> noMorePage() {
return endOfData();
}
}
}
| 24.836735
| 80
| 0.543961
|
b6500fd6bfc0c9c30a67df3baece0ce3e49bf565
| 4,278
|
/////////////////////////////////////////////////////////////
// FeaturedService.java
// gooru-api
// Created by Gooru on 2014
// Copyright (c) 2014 Gooru. All rights reserved.
// http://www.goorulearning.org/
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////////////////////////////////////////////////////////////
package org.ednovo.gooru.domain.service.featured;
import java.util.List;
import java.util.Map;
import org.ednovo.gooru.core.api.model.FeaturedSet;
import org.ednovo.gooru.core.api.model.FeaturedSetItems;
import org.ednovo.gooru.domain.service.search.SearchResults;
public interface FeaturedService {
FeaturedSet saveOrUpdateFeaturedSet(Integer featuredSetId, String name, Boolean activeFlag, Integer sequence, String themeCode) throws Exception;
FeaturedSetItems saveOrUpdateFeaturedSetItems(FeaturedSet featuredSet, String gooruContentId, Integer featuredSetItemId, String parentGooruContentId, Integer sequence) throws Exception;
List<FeaturedSet> getFeaturedTheme(int limit) throws Exception;
FeaturedSetItems updateFeaturedContent(String type, Integer featuredSetItemId, FeaturedSetItems featuredSetItems);
Map<Object, Object> getLibrary(String type, String libraryName);
List<Map<Object, Object>> getLibraryContributor(String libraryName);
List<Map<String, Object>> getLibraryTopic(String topicId, Integer limit, Integer offset, String type, String libraryName, String rootNode);
List<Map<String, Object>> getLibraryUnit(String unitId, String type, Integer offset, Integer limit, String libraryName, String rootNode);
List<Map<String, Object>> getLibraryCollection(Integer id, String type,Integer offset, Integer limit, String libraryName);
List<Map<String, Object>> getAllLibraryCollections(Integer limit, Integer offset, String themeCode, String themeType, String subjectId, String courseId, String unitId, String lessonId, String topicId, String gooruOid, String codeId);
SearchResults<Map<String, Object>> getLibraryCollections(Integer limit, Integer offset, String themeCode, String themeType, String subjectId, String courseId, String unitId, String lessonId, String topicId, String gooruOid, String codeId);
List<Map<String, Object>> getPopularLibrary(String courseId, Integer offset, Integer limit, String libraryName);
List<Map<String, Object>> getLibrarySubject(String code,String childCode, String libraryName, String rootNode);
List<Map<String,Object>> getCommunityLibraryResource(String type, Integer offset, Integer limit, String libraryName);
SearchResults<Map<String, Object>> getLibraryResource(String type, Integer offset, Integer limit, String libraryName);
Map<String, Object> assocaiateCollectionLibrary(String featuredId, String codeId, String gooruOid);
List<Map<String, Object>> getLibrary(String libraryName);
void deleteLibraryCollectionAssoc(String featuredSetId, String codeId, String gooruOid);
List<Map<String, Object>> getLibraryItem(String type, String libraryName);
List<Map<String, Object>> getLibraryItems(String itemType, String type,String codeId, String libraryName, String rootNodeId, Integer limit, Integer offset);
List<Map<String, Object>> getLibraryCourse(String code,String childCode, String libraryName, String rootNode);
}
| 55.558442
| 240
| 0.776064
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.