repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step7; import static com.xoppa.blog.libgdx.Main.data; import java.nio.IntBuffer; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectSet; import com.badlogic.gdx.utils.Pool; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; public final float[] vertices; public final short[] indices; public final Matrix4 transform = new Matrix4(); public Card(Suit suit, Pip pip, Sprite back, Sprite front) { assert(front.getTexture() == back.getTexture()); this.suit = suit; this.pip = pip; front.setSize(CARD_WIDTH, CARD_HEIGHT); back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setPosition(-front.getWidth() * 0.5f, -front.getHeight() * 0.5f); back.setPosition(-back.getWidth() * 0.5f, -back.getHeight() * 0.5f); vertices = convert(front.getVertices(), back.getVertices()); indices = new short[] {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4 }; } private static float[] convert(float[] front, float[] back) { return new float[] { front[Batch.X2], front[Batch.Y2], 0, 0, 0, 1, front[Batch.U2], front[Batch.V2], front[Batch.X1], front[Batch.Y1], 0, 0, 0, 1, front[Batch.U1], front[Batch.V1], front[Batch.X4], front[Batch.Y4], 0, 0, 0, 1, front[Batch.U4], front[Batch.V4], front[Batch.X3], front[Batch.Y3], 0, 0, 0, 1, front[Batch.U3], front[Batch.V3], back[Batch.X1], back[Batch.Y1], 0, 0, 0, -1, back[Batch.U1], back[Batch.V1], back[Batch.X2], back[Batch.Y2], 0, 0, 0, -1, back[Batch.U2], back[Batch.V2], back[Batch.X3], back[Batch.Y3], 0, 0, 0, -1, back[Batch.U3], back[Batch.V3], back[Batch.X4], back[Batch.Y4], 0, 0, 0, -1, back[Batch.U4], back[Batch.V4] }; } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable { Renderable renderable; Mesh mesh; MeshBuilder meshBuilder; public CardBatch(Material material) { final int maxNumberOfCards = 52; final int maxNumberOfVertices = maxNumberOfCards * 8; final int maxNumberOfIndices = maxNumberOfCards * 12; mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices, VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0)); meshBuilder = new MeshBuilder(); renderable = new Renderable(); renderable.material = material; } @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { meshBuilder.begin(mesh.getVertexAttributes()); meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart); for (Card card : this) { meshBuilder.setVertexTransform(card.transform); meshBuilder.addMesh(card.vertices, card.indices); } meshBuilder.end(mesh); renderables.add(renderable); } @Override public void dispose() { mesh.dispose(); } } TextureAtlas atlas; Sprite front; Sprite back; PerspectiveCamera cam; CardDeck deck; CardBatch cards; CameraInputController camController; ModelBatch modelBatch; @Override public void create() { modelBatch = new ModelBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); Material material = new Material( TextureAttribute.createDiffuse(atlas.getTextures().first()), new BlendingAttribute(false, 1f), FloatAttribute.createAlphaTest(0.5f)); cards = new CardBatch(material); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.transform.translate(-1, 0, 0); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Seven); card2.transform.translate(0, 0, 0); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.transform.translate(1, 0, 0); cards.add(card3); cam = new PerspectiveCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); } @Override public void resize(int width, int height) { float halfHeight = MINIMUM_VIEWPORT_SIZE * 0.5f; if (height > width) halfHeight *= (float)height / (float)width; float halfFovRadians = MathUtils.degreesToRadians * cam.fieldOfView * 0.5f; float distance = halfHeight / (float)Math.tan(halfFovRadians); cam.viewportWidth = width; cam.viewportHeight = height; cam.position.set(0, 0, distance); cam.lookAt(0, 0, 0); cam.update(); } @Override public void render() { final float delta = Math.min(1/30f, Gdx.graphics.getDeltaTime()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); cards.first().transform.rotate(Vector3.Y, 90 * delta); modelBatch.begin(cam); modelBatch.render(cards); modelBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { modelBatch.dispose(); atlas.dispose(); cards.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step1/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step1/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; public class CardGame extends ApplicationAdapter { SpriteBatch spriteBatch; TextureAtlas atlas; Sprite front; Sprite back; @Override public void create() { spriteBatch = new SpriteBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); front = atlas.createSprite("clubs", 2); front.setPosition(100, 100); back = atlas.createSprite("back", 3); back.setPosition(300, 100); } @Override public void dispose() { spriteBatch.dispose(); atlas.dispose(); } @Override public void render() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); spriteBatch.begin(); front.draw(spriteBatch); back.draw(spriteBatch); spriteBatch.end(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step6/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step6/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step6; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectSet; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card extends Renderable { public final Suit suit; public final Pip pip; public Card(Suit suit, Pip pip, Sprite back, Sprite front) { assert(front.getTexture() == back.getTexture()); this.suit = suit; this.pip = pip; material = new Material( TextureAttribute.createDiffuse(front.getTexture()), new BlendingAttribute(false, 1f), FloatAttribute.createAlphaTest(0.5f) ); front.setSize(CARD_WIDTH, CARD_HEIGHT); back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setPosition(-front.getWidth() * 0.5f, -front.getHeight() * 0.5f); back.setPosition(-back.getWidth() * 0.5f, -back.getHeight() * 0.5f); float[] vertices = convert(front.getVertices(), back.getVertices()); short[] indices = new short[] {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4 }; // FIXME: this Mesh needs to be disposed meshPart.mesh = new Mesh(true, 8, 12, VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0)); meshPart.mesh.setVertices(vertices); meshPart.mesh.setIndices(indices); meshPart.offset = 0; meshPart.size = meshPart.mesh.getNumIndices(); meshPart.primitiveType = GL20.GL_TRIANGLES; meshPart.update(); } private static float[] convert(float[] front, float[] back) { return new float[] { front[Batch.X2], front[Batch.Y2], 0, 0, 0, 1, front[Batch.U2], front[Batch.V2], front[Batch.X1], front[Batch.Y1], 0, 0, 0, 1, front[Batch.U1], front[Batch.V1], front[Batch.X4], front[Batch.Y4], 0, 0, 0, 1, front[Batch.U4], front[Batch.V4], front[Batch.X3], front[Batch.Y3], 0, 0, 0, 1, front[Batch.U3], front[Batch.V3], back[Batch.X1], back[Batch.Y1], 0, 0, 0, -1, back[Batch.U1], back[Batch.V1], back[Batch.X2], back[Batch.Y2], 0, 0, 0, -1, back[Batch.U2], back[Batch.V2], back[Batch.X3], back[Batch.Y3], 0, 0, 0, -1, back[Batch.U3], back[Batch.V3], back[Batch.X4], back[Batch.Y4], 0, 0, 0, -1, back[Batch.U4], back[Batch.V4] }; } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } TextureAtlas atlas; PerspectiveCamera cam; CardDeck deck; ObjectSet<Card> cards; CameraInputController camController; ModelBatch modelBatch; @Override public void create() { modelBatch = new ModelBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); cards = new ObjectSet<Card>(); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.worldTransform.translate(-1, 0, 0); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Four); card2.worldTransform.translate(0, 0, 0); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.worldTransform.translate(1, 0, 0); cards.add(card3); cam = new PerspectiveCamera(); cam.position.set(0, 0, 10); cam.lookAt(0, 0, 0); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); } @Override public void resize(int width, int height) { float halfHeight = MINIMUM_VIEWPORT_SIZE * 0.5f; if (height > width) halfHeight *= (float)height / (float)width; float halfFovRadians = MathUtils.degreesToRadians * cam.fieldOfView * 0.5f; float distance = halfHeight / (float)Math.tan(halfFovRadians); cam.viewportWidth = width; cam.viewportHeight = height; cam.position.set(0, 0, distance); cam.lookAt(0, 0, 0); cam.update(); } @Override public void render() { final float delta = Math.min(1/30f, Gdx.graphics.getDeltaTime()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camController.update(); cards.first().worldTransform.rotate(Vector3.Y, 90 * delta); modelBatch.begin(cam); for (Card card : cards) modelBatch.render(card); modelBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { modelBatch.dispose(); atlas.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step3/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step3/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectSet; public class CardGame implements ApplicationListener { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; public enum Suit { Clubs("clubs", 0), Diamonds("diamonds", 1), Hearts("hearts", 2), Spades("spades", 3); public final String name; public final int index; private Suit(String name, int index) { this.name = name; this.index = index; } } public enum Pip { Ace(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13); public final int value; public final int index; private Pip(int value) { this.value = value; this.index = value - 1; } } public static class Card { public final Suit suit; public final Pip pip; private final Sprite front; private final Sprite back; private boolean turned; public Card(Suit suit, Pip pip, Sprite back, Sprite front) { back.setSize(CARD_WIDTH, CARD_HEIGHT); front.setSize(CARD_WIDTH, CARD_HEIGHT); this.suit = suit; this.pip = pip; this.back = back; this.front = front; } public void setPosition(float x, float y) { front.setPosition(x - 0.5f * front.getWidth(), y - 0.5f * front.getHeight()); back.setPosition(x - 0.5f * back.getWidth(), y - 0.5f * back.getHeight()); } public void turn() { turned = !turned; } public void draw(Batch batch) { if (turned) back.draw(batch); else front.draw(batch); } } public static class CardDeck { private final Card[][] cards; public CardDeck(TextureAtlas atlas, int backIndex) { cards = new Card[Suit.values().length][]; for (Suit suit : Suit.values()) { cards[suit.index] = new Card[Pip.values().length]; for (Pip pip : Pip.values()) { Sprite front = atlas.createSprite(suit.name, pip.value); Sprite back = atlas.createSprite("back", backIndex); cards[suit.index][pip.index] = new Card(suit, pip, back, front); } } } public Card getCard(Suit suit, Pip pip) { return cards[suit.index][pip.index]; } } SpriteBatch spriteBatch; TextureAtlas atlas; Sprite front; Sprite back; OrthographicCamera cam; CardDeck deck; ObjectSet<Card> cards; @Override public void create() { spriteBatch = new SpriteBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); cards = new ObjectSet<Card>(); deck = new CardDeck(atlas, 3); Card card1 = deck.getCard(Suit.Diamonds, Pip.Queen); card1.setPosition(-1, 0); cards.add(card1); Card card2 = deck.getCard(Suit.Hearts, Pip.Four); card2.setPosition(0, 0); cards.add(card2); Card card3 = deck.getCard(Suit.Spades, Pip.Ace); card3.setPosition(1, 0); card3.turn(); cards.add(card3); cam = new OrthographicCamera(); } @Override public void resize(int width, int height) { if (width > height) { cam.viewportHeight = MINIMUM_VIEWPORT_SIZE; cam.viewportWidth = cam.viewportHeight * (float)width / (float)height; } else { cam.viewportWidth = MINIMUM_VIEWPORT_SIZE; cam.viewportHeight = cam.viewportWidth * (float)height / (float)width; } cam.update(); } @Override public void render() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); spriteBatch.setProjectionMatrix(cam.combined); spriteBatch.begin(); for (Card card : cards) card.draw(spriteBatch); spriteBatch.end(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { spriteBatch.dispose(); atlas.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step2/CardGame.java
tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step2/CardGame.java
package com.xoppa.blog.libgdx.g3d.cardgame.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.OrthographicCamera; public class CardGame extends ApplicationAdapter { public final static float CARD_WIDTH = 1f; public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f; public final static float MINIMUM_VIEWPORT_SIZE = 5f; SpriteBatch spriteBatch; TextureAtlas atlas; Sprite front; Sprite back; OrthographicCamera cam; @Override public void create() { spriteBatch = new SpriteBatch(); atlas = new TextureAtlas(data + "/carddeck.atlas"); front = atlas.createSprite("back", 2); front.setSize(CARD_WIDTH, CARD_HEIGHT); front.setPosition(-1, 1); back = atlas.createSprite("clubs", 3); back.setSize(CARD_WIDTH, CARD_HEIGHT); back.setPosition(1, 1); cam = new OrthographicCamera(); } @Override public void resize(int width, int height) { if (width > height) { cam.viewportHeight = MINIMUM_VIEWPORT_SIZE; cam.viewportWidth = cam.viewportHeight * (float)width / (float)height; } else { cam.viewportWidth = MINIMUM_VIEWPORT_SIZE; cam.viewportHeight = cam.viewportWidth * (float)height / (float)width; } cam.update(); } @Override public void render() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); spriteBatch.setProjectionMatrix(cam.combined); spriteBatch.begin(); front.draw(spriteBatch); back.draw(spriteBatch); spriteBatch.end(); } @Override public void dispose() { spriteBatch.dispose(); atlas.dispose(); } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step4/ShapeTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step4/ShapeTest.java
package com.xoppa.blog.libgdx.g3d.shapes.step4; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/using-collision-shapes/">Using collision shapes</a> * @author Xoppa */ public class ShapeTest extends InputAdapter implements ApplicationListener { public interface Shape { public abstract boolean isVisible(Matrix4 transform, Camera cam); /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public abstract float intersects(Matrix4 transform, Ray ray); } public static abstract class BaseShape implements Shape { protected final static Vector3 position = new Vector3(); public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public BaseShape(BoundingBox bounds) { bounds.getCenter(center); bounds.getDimensions(dimensions); } } public static class Sphere extends BaseShape { public float radius; public Sphere(BoundingBox bounds) { super(bounds); radius = dimensions.len() / 2f; } @Override public boolean isVisible(Matrix4 transform, Camera cam) { return cam.frustum.sphereInFrustum(transform.getTranslation(position).add(center), radius); } @Override public float intersects(Matrix4 transform, Ray ray) { transform.getTranslation(position).add(center); final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); if (len < 0f) return -1f; float dist2 = position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); return (dist2 <= radius * radius) ? dist2 : -1f; } } public static class Box extends BaseShape { public Box(BoundingBox bounds) { super(bounds); } @Override public boolean isVisible(Matrix4 transform, Camera cam) { return cam.frustum.boundsInFrustum(transform.getTranslation(position).add(center), dimensions); } @Override public float intersects(Matrix4 transform, Ray ray) { transform.getTranslation(position).add(center); if (Intersector.intersectRayBoundsFast(ray, position, dimensions)) { final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); return position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); } return -1f; } } public static class Disc extends BaseShape { public float radius; public Disc(BoundingBox bounds) { super(bounds); radius = 0.5f * (dimensions.x > dimensions.z ? dimensions.x : dimensions.z); } @Override public boolean isVisible (Matrix4 transform, Camera cam) { return cam.frustum.sphereInFrustum(transform.getTranslation(position).add(center), radius); } @Override public float intersects (Matrix4 transform, Ray ray) { transform.getTranslation(position).add(center); final float len = (position.y - ray.origin.y) / ray.direction.y; final float dist2 = position.dst2(ray.origin.x + len * ray.direction.x, ray.origin.y + len * ray.direction.y, ray.origin.z + len * ray.direction.z); return (dist2 < radius * radius) ? dist2 : -1f; } } public static class GameObject extends ModelInstance { public Shape shape; public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); } public boolean isVisible(Camera cam) { return shape == null ? false : shape.isVisible(transform, cam); } /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public float intersects(Ray ray) { return shape == null ? -1f : shape.intersects(transform, ray); } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Shape blockShape; protected Shape invaderShape; protected Shape shipShape; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private BoundingBox bounds = new BoundingBox(); private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) { instance.calculateBoundingBox(bounds); shipShape = new Sphere(bounds); instance.shape = shipShape; ship = instance; } else if (id.startsWith("block")) { if (blockShape == null) { instance.calculateBoundingBox(bounds); blockShape = new Box(bounds); } instance.shape = blockShape; blocks.add(instance); } else if (id.startsWith("invader")) { if (invaderShape == null) { instance.calculateBoundingBox(bounds); invaderShape = new Disc(bounds); } instance.shape = invaderShape; invaders.add(instance); } } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (instance.isVisible(cam)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (selecting < 0) return false; if (selected == selecting) { Ray ray = cam.getPickRay(screenX, screenY); final float distance = -ray.origin.y / ray.direction.y; position.set(ray.direction).scl(distance).add(ray.origin); instances.get(selected).transform.setTranslation(position); } return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final GameObject instance = instances.get(i); float dist2 = instance.intersects(ray); if (dist2 >= 0 && (distance < 0f || dist2 < distance)) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step1/ShapeTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step1/ShapeTest.java
package com.xoppa.blog.libgdx.g3d.shapes.step1; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/using-collision-shapes/">Using collision shapes</a> * @author Xoppa */ public class ShapeTest extends InputAdapter implements ApplicationListener { public static class GameObject extends ModelInstance { public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public final float radius; private final static BoundingBox bounds = new BoundingBox(); private final static Vector3 position = new Vector3(); public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); calculateBoundingBox(bounds); bounds.getCenter(center); bounds.getDimensions(dimensions); radius = dimensions.len() / 2f; } public boolean isVisible(Camera cam) { return cam.frustum.sphereInFrustum(transform.getTranslation(position).add(center), radius); } /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public float intersects(Ray ray) { transform.getTranslation(position).add(center); final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); if (len < 0f) return -1f; float dist2 = position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); return (dist2 <= radius * radius) ? dist2 : -1f; } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) ship = instance; else if (id.startsWith("block")) blocks.add(instance); else if (id.startsWith("invader")) invaders.add(instance); } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (instance.isVisible(cam)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (selecting < 0) return false; if (selected == selecting) { Ray ray = cam.getPickRay(screenX, screenY); final float distance = -ray.origin.y / ray.direction.y; position.set(ray.direction).scl(distance).add(ray.origin); instances.get(selected).transform.setTranslation(position); } return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final float dist2 = instances.get(i).intersects(ray); if (dist2 >= 0f && (distance < 0f || dist2 <= distance)) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step3/ShapeTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step3/ShapeTest.java
package com.xoppa.blog.libgdx.g3d.shapes.step3; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/using-collision-shapes/">Using collision shapes</a> * @author Xoppa */ public class ShapeTest extends InputAdapter implements ApplicationListener { public interface Shape { public abstract boolean isVisible(Matrix4 transform, Camera cam); /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public abstract float intersects(Matrix4 transform, Ray ray); } public static abstract class BaseShape implements Shape { protected final static Vector3 position = new Vector3(); public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public BaseShape(BoundingBox bounds) { bounds.getCenter(center); bounds.getDimensions(dimensions); } } public static class Sphere extends BaseShape { public float radius; public Sphere(BoundingBox bounds) { super(bounds); radius = dimensions.len() / 2f; } @Override public boolean isVisible(Matrix4 transform, Camera cam) { return cam.frustum.sphereInFrustum(transform.getTranslation(position).add(center), radius); } @Override public float intersects(Matrix4 transform, Ray ray) { transform.getTranslation(position).add(center); final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); if (len < 0f) return -1f; float dist2 = position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); return (dist2 <= radius * radius) ? dist2 : -1f; } } public static class Box extends BaseShape { public Box(BoundingBox bounds) { super(bounds); } @Override public boolean isVisible(Matrix4 transform, Camera cam) { return cam.frustum.boundsInFrustum(transform.getTranslation(position).add(center), dimensions); } @Override public float intersects(Matrix4 transform, Ray ray) { transform.getTranslation(position).add(center); if (Intersector.intersectRayBoundsFast(ray, position, dimensions)) { final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); return position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); } return -1f; } } public static class GameObject extends ModelInstance { public Shape shape; public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); } public boolean isVisible(Camera cam) { return shape == null ? false : shape.isVisible(transform, cam); } /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public float intersects(Ray ray) { return shape == null ? -1f : shape.intersects(transform, ray); } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Shape blockShape; protected Shape invaderShape; protected Shape shipShape; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private BoundingBox bounds = new BoundingBox(); private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) { instance.calculateBoundingBox(bounds); shipShape = new Sphere(bounds); instance.shape = shipShape; ship = instance; } else if (id.startsWith("block")) { if (blockShape == null) { instance.calculateBoundingBox(bounds); blockShape = new Box(bounds); } instance.shape = blockShape; blocks.add(instance); } else if (id.startsWith("invader")) { if (invaderShape == null) { instance.calculateBoundingBox(bounds); invaderShape = new Sphere(bounds); } instance.shape = invaderShape; invaders.add(instance); } } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (instance.isVisible(cam)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (selecting < 0) return false; if (selected == selecting) { Ray ray = cam.getPickRay(screenX, screenY); final float distance = -ray.origin.y / ray.direction.y; position.set(ray.direction).scl(distance).add(ray.origin); instances.get(selected).transform.setTranslation(position); } return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final GameObject instance = instances.get(i); float dist2 = instance.intersects(ray); if (dist2 >= 0 && (distance < 0f || dist2 < distance)) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step2/ShapeTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step2/ShapeTest.java
package com.xoppa.blog.libgdx.g3d.shapes.step2; import static com.xoppa.blog.libgdx.Main.data; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Array; /** @see <a href="http://blog.xoppa.com/using-collision-shapes/">Using collision shapes</a> * @author Xoppa */ public class ShapeTest extends InputAdapter implements ApplicationListener { public interface Shape { public abstract boolean isVisible(Matrix4 transform, Camera cam); /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public abstract float intersects(Matrix4 transform, Ray ray); } public static abstract class BaseShape implements Shape { protected final static Vector3 position = new Vector3(); public final Vector3 center = new Vector3(); public final Vector3 dimensions = new Vector3(); public BaseShape(BoundingBox bounds) { bounds.getCenter(center); bounds.getDimensions(dimensions); } } public static class Sphere extends BaseShape { public float radius; public Sphere(BoundingBox bounds) { super(bounds); radius = dimensions.len() / 2f; } @Override public boolean isVisible(Matrix4 transform, Camera cam) { return cam.frustum.sphereInFrustum(transform.getTranslation(position).add(center), radius); } @Override public float intersects(Matrix4 transform, Ray ray) { transform.getTranslation(position).add(center); final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z); if (len < 0f) return -1f; float dist2 = position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len); return (dist2 <= radius * radius) ? dist2 : -1f; } } public static class GameObject extends ModelInstance { public Shape shape; public GameObject (Model model, String rootNode, boolean mergeTransform) { super(model, rootNode, mergeTransform); } public boolean isVisible(Camera cam) { return shape == null ? false : shape.isVisible(transform, cam); } /** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this * object and the point on the ray closest to this object when there is intersection. */ public float intersects(Ray ray) { return shape == null ? -1f : shape.intersects(transform, ray); } } protected PerspectiveCamera cam; protected CameraInputController camController; protected ModelBatch modelBatch; protected AssetManager assets; protected Array<GameObject> instances = new Array<GameObject>(); protected Environment environment; protected boolean loading; protected Array<GameObject> blocks = new Array<GameObject>(); protected Array<GameObject> invaders = new Array<GameObject>(); protected ModelInstance ship; protected ModelInstance space; protected Shape blockShape; protected Shape invaderShape; protected Shape shipShape; protected Stage stage; protected Label label; protected BitmapFont font; protected StringBuilder stringBuilder; private int visibleCount; private Vector3 position = new Vector3(); private int selected = -1, selecting = -1; private Material selectionMaterial; private Material originalMaterial; @Override public void create () { stage = new Stage(); font = new BitmapFont(); label = new Label(" ", new Label.LabelStyle(font, Color.WHITE)); stage.addActor(label); stringBuilder = new StringBuilder(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0f, 7f, 10f); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer(this, camController)); assets = new AssetManager(); assets.load(data + "/invaderscene.g3db", Model.class); loading = true; selectionMaterial = new Material(); selectionMaterial.set(ColorAttribute.createDiffuse(Color.ORANGE)); originalMaterial = new Material(); } private BoundingBox bounds = new BoundingBox(); private void doneLoading () { Model model = assets.get(data + "/invaderscene.g3db", Model.class); for (int i = 0; i < model.nodes.size; i++) { String id = model.nodes.get(i).id; GameObject instance = new GameObject(model, id, true); if (id.equals("space")) { space = instance; continue; } instances.add(instance); if (id.equals("ship")) { if (shipShape == null) { instance.calculateBoundingBox(bounds); shipShape = new Sphere(bounds); } instance.shape = shipShape; ship = instance; } else if (id.startsWith("block")) { if (blockShape == null) { instance.calculateBoundingBox(bounds); blockShape = new Sphere(bounds); } instance.shape = blockShape; blocks.add(instance); } else if (id.startsWith("invader")) { if (invaderShape == null) { instance.calculateBoundingBox(bounds); invaderShape = new Sphere(bounds); } instance.shape = invaderShape; invaders.add(instance); } } loading = false; } @Override public void render () { if (loading && assets.update()) doneLoading(); camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); visibleCount = 0; for (final GameObject instance : instances) { if (instance.isVisible(cam)) { modelBatch.render(instance, environment); visibleCount++; } } if (space != null) modelBatch.render(space); modelBatch.end(); stringBuilder.setLength(0); stringBuilder.append(" FPS: ").append(Gdx.graphics.getFramesPerSecond()); stringBuilder.append(" Visible: ").append(visibleCount); stringBuilder.append(" Selected: ").append(selected); label.setText(stringBuilder); stage.draw(); } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { selecting = getObject(screenX, screenY); return selecting >= 0; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (selecting < 0) return false; if (selected == selecting) { Ray ray = cam.getPickRay(screenX, screenY); final float distance = -ray.origin.y / ray.direction.y; position.set(ray.direction).scl(distance).add(ray.origin); instances.get(selected).transform.setTranslation(position); } return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (selecting >= 0) { if (selecting == getObject(screenX, screenY)) setSelected(selecting); selecting = -1; return true; } return false; } public void setSelected (int value) { if (selected == value) return; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); mat.clear(); mat.set(originalMaterial); } selected = value; if (selected >= 0) { Material mat = instances.get(selected).materials.get(0); originalMaterial.clear(); originalMaterial.set(mat); mat.clear(); mat.set(selectionMaterial); } } public int getObject (int screenX, int screenY) { Ray ray = cam.getPickRay(screenX, screenY); int result = -1; float distance = -1; for (int i = 0; i < instances.size; ++i) { final GameObject instance = instances.get(i); float dist2 = instance.intersects(ray); if (dist2 >= 0 && (distance < 0f || dist2 < distance)) { result = i; distance = dist2; } } return result; } @Override public void dispose () { modelBatch.dispose(); instances.clear(); assets.dispose(); } @Override public void resize (int width, int height) { stage.getViewport().update(width, height, true); } @Override public void pause () { } @Override public void resume () { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/basic3d/step1/Basic3DTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/basic3d/step1/Basic3DTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.xoppa.blog.libgdx.g3d.basic3d.step1; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; /** * See: http://blog.xoppa.com/basic-3d-using-libgdx-2/ * @author Xoppa */ public class Basic3DTest implements ApplicationListener { public PerspectiveCamera cam; public ModelBatch modelBatch; public Model model; public ModelInstance instance; @Override public void create() { modelBatch = new ModelBatch(); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(10f, 10f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Usage.Position | Usage.Normal); instance = new ModelInstance(model); } @Override public void render() { Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instance); modelBatch.end(); } @Override public void dispose() { modelBatch.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/basic3d/step3/Basic3DTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/basic3d/step3/Basic3DTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.xoppa.blog.libgdx.g3d.basic3d.step3; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; /** * See: http://blog.xoppa.com/basic-3d-using-libgdx-2/ * @author Xoppa */ public class Basic3DTest implements ApplicationListener { public Environment environment; public PerspectiveCamera cam; public CameraInputController camController; public ModelBatch modelBatch; public Model model; public ModelInstance instance; @Override public void create() { environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); modelBatch = new ModelBatch(); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(10f, 10f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Usage.Position | Usage.Normal); instance = new ModelInstance(model); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); } @Override public void render() { camController.update(); Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instance, environment); modelBatch.end(); } @Override public void dispose() { modelBatch.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/basic3d/step2/Basic3DTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/basic3d/step2/Basic3DTest.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.xoppa.blog.libgdx.g3d.basic3d.step2; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; /** * See: http://blog.xoppa.com/basic-3d-using-libgdx-2/ * @author Xoppa */ public class Basic3DTest implements ApplicationListener { public Environment lights; public PerspectiveCamera cam; public ModelBatch modelBatch; public Model model; public ModelInstance instance; @Override public void create() { lights = new Environment(); lights.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); lights.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); modelBatch = new ModelBatch(); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(10f, 10f, 10f); cam.lookAt(0,0,0); cam.near = 1f; cam.far = 300f; cam.update(); ModelBuilder modelBuilder = new ModelBuilder(); model = modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Usage.Position | Usage.Normal); instance = new ModelInstance(model); } @Override public void render() { Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instance, lights); modelBatch.end(); } @Override public void dispose() { modelBatch.dispose(); model.dispose(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step8/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step8/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step8; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionWorld; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { instances.get(userValue0).moving = false; instances.get(userValue1).moving = false; return true; } } static class GameObject extends ModelInstance implements Disposable { public final btCollisionObject body; public boolean moving; public GameObject (Model model, String node, btCollisionShape shape) { super(model, node); body = new btCollisionObject(); body.setCollisionShape(shape); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public Constructor (Model model, String node, btCollisionShape shape) { this.model = model; this.node = node; this.shape = shape; } public GameObject construct () { return new GameObject(model, node, shape); } @Override public void dispose () { shape.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btCollisionWorld collisionWorld; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)))); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f))); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)))); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f))); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f))); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)))); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); collisionWorld = new btCollisionWorld(dispatcher, broadphase, collisionConfig); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); collisionWorld.addCollisionObject(object.body, GROUND_FLAG, ALL_FLAG); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); collisionWorld.addCollisionObject(obj.body, OBJECT_FLAG, GROUND_FLAG); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); for (GameObject obj : instances) { if (obj.moving) { obj.transform.trn(0f, -delta, 0f); obj.body.setWorldTransform(obj.transform); } } collisionWorld.performDiscreteCollisionDetection(); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); collisionWorld.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step4/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step4/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step4; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo; import com.badlogic.gdx.physics.bullet.collision.btManifoldResult; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { static class GameObject extends ModelInstance implements Disposable { public final btCollisionObject body; public boolean moving; public GameObject (Model model, String node, btCollisionShape shape) { super(model, node); body = new btCollisionObject(); body.setCollisionShape(shape); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public Constructor (Model model, String node, btCollisionShape shape) { this.model = model; this.node = node; this.shape = shape; } public GameObject construct () { return new GameObject(model, node, shape); } @Override public void dispose () { shape.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)))); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f))); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)))); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f))); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f))); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)))); instances = new Array<GameObject>(); instances.add(constructors.get("ground").construct()); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); instances.add(obj); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); for (GameObject obj : instances) { if (obj.moving) { obj.transform.trn(0f, -delta, 0f); obj.body.setWorldTransform(obj.transform); if (checkCollision(obj.body, instances.get(0).body)) obj.moving = false; } } if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } boolean checkCollision (btCollisionObject obj0, btCollisionObject obj1) { CollisionObjectWrapper co0 = new CollisionObjectWrapper(obj0); CollisionObjectWrapper co1 = new CollisionObjectWrapper(obj1); btCollisionAlgorithm algorithm = dispatcher.findAlgorithm(co0.wrapper, co1.wrapper); btDispatcherInfo info = new btDispatcherInfo(); btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper); algorithm.processCollision(co0.wrapper, co1.wrapper, info, result); boolean r = result.getPersistentManifold().getNumContacts() > 0; dispatcher.freeCollisionAlgorithm(algorithm.getCPointer()); result.dispose(); info.dispose(); co1.dispose(); co0.dispose(); return r; } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dispatcher.dispose(); collisionConfig.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step5/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step5/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step5; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionObjectWrapper; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo; import com.badlogic.gdx.physics.bullet.collision.btManifoldPoint; import com.badlogic.gdx.physics.bullet.collision.btManifoldResult; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { class MyContactListener extends ContactListener { @Override public boolean onContactAdded (btManifoldPoint cp, btCollisionObjectWrapper colObj0Wrap, int partId0, int index0, btCollisionObjectWrapper colObj1Wrap, int partId1, int index1) { instances.get(colObj0Wrap.getCollisionObject().getUserValue()).moving = false; instances.get(colObj1Wrap.getCollisionObject().getUserValue()).moving = false; return true; } } static class GameObject extends ModelInstance implements Disposable { public final btCollisionObject body; public boolean moving; public GameObject (Model model, String node, btCollisionShape shape) { super(model, node); body = new btCollisionObject(); body.setCollisionShape(shape); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public Constructor (Model model, String node, btCollisionShape shape) { this.model = model; this.node = node; this.shape = shape; } public GameObject construct () { return new GameObject(model, node, shape); } @Override public void dispose () { shape.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)))); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f))); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)))); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f))); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f))); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)))); instances = new Array<GameObject>(); instances.add(constructors.get("ground").construct()); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); contactListener = new MyContactListener(); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); for (GameObject obj : instances) { if (obj.moving) { obj.transform.trn(0f, -delta, 0f); obj.body.setWorldTransform(obj.transform); checkCollision(obj.body, instances.get(0).body); } } if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } boolean checkCollision (btCollisionObject obj0, btCollisionObject obj1) { CollisionObjectWrapper co0 = new CollisionObjectWrapper(obj0); CollisionObjectWrapper co1 = new CollisionObjectWrapper(obj1); btCollisionAlgorithm algorithm = dispatcher.findAlgorithm(co0.wrapper, co1.wrapper); btDispatcherInfo info = new btDispatcherInfo(); btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper); algorithm.processCollision(co0.wrapper, co1.wrapper, info, result); boolean r = result.getPersistentManifold().getNumContacts() > 0; dispatcher.freeCollisionAlgorithm(algorithm.getCPointer()); result.dispose(); info.dispose(); co1.dispose(); co0.dispose(); return r; } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step7/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step7/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step7; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionWorld; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { instances.get(userValue0).moving = false; instances.get(userValue1).moving = false; return true; } } static class GameObject extends ModelInstance implements Disposable { public final btCollisionObject body; public boolean moving; public GameObject (Model model, String node, btCollisionShape shape) { super(model, node); body = new btCollisionObject(); body.setCollisionShape(shape); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public Constructor (Model model, String node, btCollisionShape shape) { this.model = model; this.node = node; this.shape = shape; } public GameObject construct () { return new GameObject(model, node, shape); } @Override public void dispose () { shape.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btCollisionWorld collisionWorld; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)))); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f))); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)))); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f))); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f))); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)))); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); collisionWorld = new btCollisionWorld(dispatcher, broadphase, collisionConfig); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); collisionWorld.addCollisionObject(object.body); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); collisionWorld.addCollisionObject(obj.body); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); for (GameObject obj : instances) { if (obj.moving) { obj.transform.trn(0f, -delta, 0f); obj.body.setWorldTransform(obj.transform); } } collisionWorld.performDiscreteCollisionDetection(); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); collisionWorld.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step1/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step1/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step1; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Array<ModelInstance> instances; Environment environment; Model model; ModelInstance ground; ModelInstance ball; boolean collision; @Override public void create () { modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "ball"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); model = mb.end(); ground = new ModelInstance(model, "ground"); ball = new ModelInstance(model, "ball"); ball.transform.setToTranslation(0, 9f, 0); instances = new Array<ModelInstance>(); instances.add(ground); instances.add(ball); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); if (!collision) { ball.transform.translate(0f, -delta, 0f); collision = checkCollision(); } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } boolean checkCollision () { return false; } @Override public void dispose () { modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step6/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step6/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step6; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo; import com.badlogic.gdx.physics.bullet.collision.btManifoldResult; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { instances.get(userValue0).moving = false; instances.get(userValue1).moving = false; return true; } } static class GameObject extends ModelInstance implements Disposable { public final btCollisionObject body; public boolean moving; public GameObject (Model model, String node, btCollisionShape shape) { super(model, node); body = new btCollisionObject(); body.setCollisionShape(shape); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public Constructor (Model model, String node, btCollisionShape shape) { this.model = model; this.node = node; this.shape = shape; } public GameObject construct () { return new GameObject(model, node, shape); } @Override public void dispose () { shape.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)))); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f))); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)))); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f))); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f))); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)))); instances = new Array<GameObject>(); instances.add(constructors.get("ground").construct()); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); contactListener = new MyContactListener(); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); for (GameObject obj : instances) { if (obj.moving) { obj.transform.trn(0f, -delta, 0f); obj.body.setWorldTransform(obj.transform); checkCollision(obj.body, instances.get(0).body); } } if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } boolean checkCollision (btCollisionObject obj0, btCollisionObject obj1) { CollisionObjectWrapper co0 = new CollisionObjectWrapper(obj0); CollisionObjectWrapper co1 = new CollisionObjectWrapper(obj1); btCollisionAlgorithm algorithm = dispatcher.findAlgorithm(co0.wrapper, co1.wrapper); btDispatcherInfo info = new btDispatcherInfo(); btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper); algorithm.processCollision(co0.wrapper, co1.wrapper, info, result); boolean r = result.getPersistentManifold().getNumContacts() > 0; dispatcher.freeCollisionAlgorithm(algorithm.getCPointer()); result.dispose(); info.dispose(); co1.dispose(); co0.dispose(); return r; } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step3/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step3/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step3; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo; import com.badlogic.gdx.physics.bullet.collision.btManifoldResult; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Array<ModelInstance> instances; Environment environment; Model model; ModelInstance ground; ModelInstance ball; boolean collision; btCollisionShape groundShape; btCollisionShape ballShape; btCollisionObject groundObject; btCollisionObject ballObject; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "ball"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); model = mb.end(); ground = new ModelInstance(model, "ground"); ball = new ModelInstance(model, "ball"); ball.transform.setToTranslation(0, 5f, 0); instances = new Array<ModelInstance>(); instances.add(ground); instances.add(ball); groundShape = new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)); ballShape = new btSphereShape(0.5f); groundObject = new btCollisionObject(); groundObject.setCollisionShape(groundShape); groundObject.setCollisionFlags(groundObject.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); groundObject.setWorldTransform(ground.transform); ballObject = new btCollisionObject(); ballObject.setCollisionShape(ballShape); ballObject.setCollisionFlags(ballObject.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); ballObject.setWorldTransform(ball.transform); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); if (!collision) { ball.transform.translate(0f, -delta, 0f); ballObject.setWorldTransform(ball.transform); collision = checkCollision(ballObject, groundObject); } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } boolean checkCollision (btCollisionObject obj0, btCollisionObject obj1) { CollisionObjectWrapper co0 = new CollisionObjectWrapper(obj0); CollisionObjectWrapper co1 = new CollisionObjectWrapper(obj1); btCollisionAlgorithm algorithm = dispatcher.findAlgorithm(co0.wrapper, co1.wrapper); btDispatcherInfo info = new btDispatcherInfo(); btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper); algorithm.processCollision(co0.wrapper, co1.wrapper, info, result); boolean r = result.getPersistentManifold().getNumContacts() > 0; dispatcher.freeCollisionAlgorithm(algorithm.getCPointer()); result.dispose(); info.dispose(); co1.dispose(); co0.dispose(); return r; } @Override public void dispose () { groundObject.dispose(); groundShape.dispose(); ballObject.dispose(); ballShape.dispose(); dispatcher.dispose(); collisionConfig.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step2/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/collision/step2/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.collision.step2; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm; import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithmConstructionInfo; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo; import com.badlogic.gdx.physics.bullet.collision.btManifoldResult; import com.badlogic.gdx.physics.bullet.collision.btSphereBoxCollisionAlgorithm; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Array; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/ * @author Xoppa */ public class BulletTest implements ApplicationListener { PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Array<ModelInstance> instances; Environment environment; Model model; ModelInstance ground; ModelInstance ball; boolean collision; btCollisionShape groundShape; btCollisionShape ballShape; btCollisionObject groundObject; btCollisionObject ballObject; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "ball"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); model = mb.end(); ground = new ModelInstance(model, "ground"); ball = new ModelInstance(model, "ball"); ball.transform.setToTranslation(0, 9f, 0); instances = new Array<ModelInstance>(); instances.add(ground); instances.add(ball); ballShape = new btSphereShape(0.5f); groundShape = new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)); groundObject = new btCollisionObject(); groundObject.setCollisionShape(groundShape); groundObject.setWorldTransform(ground.transform); ballObject = new btCollisionObject(); ballObject.setCollisionShape(ballShape); ballObject.setWorldTransform(ball.transform); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); if (!collision) { ball.transform.translate(0f, -delta, 0f); ballObject.setWorldTransform(ball.transform); collision = checkCollision(); } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } boolean checkCollision () { CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject); CollisionObjectWrapper co1 = new CollisionObjectWrapper(groundObject); btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo(); ci.setDispatcher1(dispatcher); btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false); btDispatcherInfo info = new btDispatcherInfo(); btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper); algorithm.processCollision(co0.wrapper, co1.wrapper, info, result); boolean r = result.getPersistentManifold().getNumContacts() > 0; result.dispose(); info.dispose(); algorithm.dispose(); ci.dispose(); co1.dispose(); co0.dispose(); return r; } @Override public void dispose () { groundObject.dispose(); groundShape.dispose(); ballObject.dispose(); ballShape.dispose(); dispatcher.dispose(); collisionConfig.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step4/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step4/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.dynamics.step4; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.physics.bullet.dynamics.btConstraintSolver; import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver; import com.badlogic.gdx.physics.bullet.linearmath.btMotionState; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part2/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { if (userValue0 != 0) ((ColorAttribute)instances.get(userValue0).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); if (userValue1 != 0) ((ColorAttribute)instances.get(userValue1).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); return true; } } static class MyMotionState extends btMotionState { Matrix4 transform; @Override public void getWorldTransform (Matrix4 worldTrans) { worldTrans.set(transform); } @Override public void setWorldTransform (Matrix4 worldTrans) { transform.set(worldTrans); } } static class GameObject extends ModelInstance implements Disposable { public final btRigidBody body; public final MyMotionState motionState; public GameObject (Model model, String node, btRigidBody.btRigidBodyConstructionInfo constructionInfo) { super(model, node); motionState = new MyMotionState(); motionState.transform = transform; body = new btRigidBody(constructionInfo); body.setMotionState(motionState); } @Override public void dispose () { body.dispose(); motionState.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public final btRigidBody.btRigidBodyConstructionInfo constructionInfo; private static Vector3 localInertia = new Vector3(); public Constructor (Model model, String node, btCollisionShape shape, float mass) { this.model = model; this.node = node; this.shape = shape; if (mass > 0f) shape.calculateLocalInertia(mass, localInertia); else localInertia.set(0, 0, 0); this.constructionInfo = new btRigidBody.btRigidBodyConstructionInfo(mass, null, shape, localInertia); } public GameObject construct () { return new GameObject(model, node, constructionInfo); } @Override public void dispose () { shape.dispose(); constructionInfo.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btDynamicsWorld dynamicsWorld; btConstraintSolver constraintSolver; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)), 0f)); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f), 1f)); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)), 1f)); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f), 1f)); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f), 1f)); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)), 1f)); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); constraintSolver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig); dynamicsWorld.setGravity(new Vector3(0, -10f, 0)); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); dynamicsWorld.addRigidBody(object.body, GROUND_FLAG, ALL_FLAG); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.proceedToTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); dynamicsWorld.addRigidBody(obj.body, OBJECT_FLAG, GROUND_FLAG); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); dynamicsWorld.stepSimulation(delta, 5, 1f / 60f); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dynamicsWorld.dispose(); constraintSolver.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step5/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step5/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.dynamics.step5; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.physics.bullet.dynamics.btConstraintSolver; import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver; import com.badlogic.gdx.physics.bullet.linearmath.btMotionState; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part2/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, boolean match0, int userValue1, int partId1, int index1, boolean match1) { if (match0) ((ColorAttribute)instances.get(userValue0).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); if (match1) ((ColorAttribute)instances.get(userValue1).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); return true; } } static class MyMotionState extends btMotionState { Matrix4 transform; @Override public void getWorldTransform (Matrix4 worldTrans) { worldTrans.set(transform); } @Override public void setWorldTransform (Matrix4 worldTrans) { transform.set(worldTrans); } } static class GameObject extends ModelInstance implements Disposable { public final btRigidBody body; public final MyMotionState motionState; public GameObject (Model model, String node, btRigidBody.btRigidBodyConstructionInfo constructionInfo) { super(model, node); motionState = new MyMotionState(); motionState.transform = transform; body = new btRigidBody(constructionInfo); body.setMotionState(motionState); } @Override public void dispose () { body.dispose(); motionState.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public final btRigidBody.btRigidBodyConstructionInfo constructionInfo; private static Vector3 localInertia = new Vector3(); public Constructor (Model model, String node, btCollisionShape shape, float mass) { this.model = model; this.node = node; this.shape = shape; if (mass > 0f) shape.calculateLocalInertia(mass, localInertia); else localInertia.set(0, 0, 0); this.constructionInfo = new btRigidBody.btRigidBodyConstructionInfo(mass, null, shape, localInertia); } public GameObject construct () { return new GameObject(model, node, constructionInfo); } @Override public void dispose () { shape.dispose(); constructionInfo.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btDynamicsWorld dynamicsWorld; btConstraintSolver constraintSolver; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)), 0f)); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f), 1f)); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)), 1f)); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f), 1f)); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f), 1f)); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)), 1f)); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); constraintSolver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig); dynamicsWorld.setGravity(new Vector3(0, -10f, 0)); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); dynamicsWorld.addRigidBody(object.body); object.body.setContactCallbackFlag(GROUND_FLAG); object.body.setContactCallbackFilter(0); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.proceedToTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); dynamicsWorld.addRigidBody(obj.body); obj.body.setContactCallbackFlag(OBJECT_FLAG); obj.body.setContactCallbackFilter(GROUND_FLAG); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); dynamicsWorld.stepSimulation(delta, 5, 1f / 60f); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dynamicsWorld.dispose(); constraintSolver.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step1/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step1/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.dynamics.step1; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionWorld; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part2/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { instances.get(userValue0).moving = false; instances.get(userValue1).moving = false; return true; } } static class GameObject extends ModelInstance implements Disposable { public final btRigidBody body; public boolean moving; public GameObject (Model model, String node, btRigidBody.btRigidBodyConstructionInfo constructionInfo) { super(model, node); body = new btRigidBody(constructionInfo); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public final btRigidBody.btRigidBodyConstructionInfo constructionInfo; private static Vector3 localInertia = new Vector3(); public Constructor (Model model, String node, btCollisionShape shape, float mass) { this.model = model; this.node = node; this.shape = shape; if (mass > 0f) shape.calculateLocalInertia(mass, localInertia); else localInertia.set(0, 0, 0); this.constructionInfo = new btRigidBody.btRigidBodyConstructionInfo(mass, null, shape, localInertia); } public GameObject construct () { return new GameObject(model, node, constructionInfo); } @Override public void dispose () { shape.dispose(); constructionInfo.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btCollisionWorld collisionWorld; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)), 0f)); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f), 1f)); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)), 1f)); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f), 1f)); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f), 1f)); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)), 1f)); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); collisionWorld = new btCollisionWorld(dispatcher, broadphase, collisionConfig); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); collisionWorld.addCollisionObject(object.body, GROUND_FLAG, ALL_FLAG); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); collisionWorld.addCollisionObject(obj.body, OBJECT_FLAG, GROUND_FLAG); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); for (GameObject obj : instances) { if (obj.moving) { obj.transform.trn(0f, -delta, 0f); obj.body.setWorldTransform(obj.transform); } } collisionWorld.performDiscreteCollisionDetection(); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); collisionWorld.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step6/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step6/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.dynamics.step6; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.Collision; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.physics.bullet.dynamics.btConstraintSolver; import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver; import com.badlogic.gdx.physics.bullet.linearmath.btMotionState; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part2/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, boolean match0, int userValue1, int partId1, int index1, boolean match1) { if (match0) ((ColorAttribute)instances.get(userValue0).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); if (match1) ((ColorAttribute)instances.get(userValue1).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); return true; } } static class MyMotionState extends btMotionState { Matrix4 transform; @Override public void getWorldTransform (Matrix4 worldTrans) { worldTrans.set(transform); } @Override public void setWorldTransform (Matrix4 worldTrans) { transform.set(worldTrans); } } static class GameObject extends ModelInstance implements Disposable { public final btRigidBody body; public final MyMotionState motionState; public GameObject (Model model, String node, btRigidBody.btRigidBodyConstructionInfo constructionInfo) { super(model, node); motionState = new MyMotionState(); motionState.transform = transform; body = new btRigidBody(constructionInfo); body.setMotionState(motionState); } @Override public void dispose () { body.dispose(); motionState.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public final btRigidBody.btRigidBodyConstructionInfo constructionInfo; private static Vector3 localInertia = new Vector3(); public Constructor (Model model, String node, btCollisionShape shape, float mass) { this.model = model; this.node = node; this.shape = shape; if (mass > 0f) shape.calculateLocalInertia(mass, localInertia); else localInertia.set(0, 0, 0); this.constructionInfo = new btRigidBody.btRigidBodyConstructionInfo(mass, null, shape, localInertia); } public GameObject construct () { return new GameObject(model, node, constructionInfo); } @Override public void dispose () { shape.dispose(); constructionInfo.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btDynamicsWorld dynamicsWorld; btConstraintSolver constraintSolver; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)), 0f)); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f), 1f)); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)), 1f)); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f), 1f)); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f), 1f)); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)), 1f)); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); constraintSolver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig); dynamicsWorld.setGravity(new Vector3(0, -10f, 0)); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); object.body.setCollisionFlags(object.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_KINEMATIC_OBJECT); instances.add(object); dynamicsWorld.addRigidBody(object.body); object.body.setContactCallbackFlag(GROUND_FLAG); object.body.setContactCallbackFilter(0); object.body.setActivationState(Collision.DISABLE_DEACTIVATION); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.proceedToTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); dynamicsWorld.addRigidBody(obj.body); obj.body.setContactCallbackFlag(OBJECT_FLAG); obj.body.setContactCallbackFilter(GROUND_FLAG); } float angle, speed = 90f; @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); angle = (angle + delta * speed) % 360f; instances.get(0).transform.setTranslation(0, MathUtils.sinDeg(angle) * 2.5f, 0f); dynamicsWorld.stepSimulation(delta, 5, 1f / 60f); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dynamicsWorld.dispose(); constraintSolver.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step3/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step3/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.dynamics.step3; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.physics.bullet.dynamics.btConstraintSolver; import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part2/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { if (userValue0 != 0) ((ColorAttribute)instances.get(userValue0).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); if (userValue1 != 0) ((ColorAttribute)instances.get(userValue1).materials.get(0).get(ColorAttribute.Diffuse)).color.set(Color.WHITE); return true; } } static class GameObject extends ModelInstance implements Disposable { public final btRigidBody body; public GameObject (Model model, String node, btRigidBody.btRigidBodyConstructionInfo constructionInfo) { super(model, node); body = new btRigidBody(constructionInfo); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public final btRigidBody.btRigidBodyConstructionInfo constructionInfo; private static Vector3 localInertia = new Vector3(); public Constructor (Model model, String node, btCollisionShape shape, float mass) { this.model = model; this.node = node; this.shape = shape; if (mass > 0f) shape.calculateLocalInertia(mass, localInertia); else localInertia.set(0, 0, 0); this.constructionInfo = new btRigidBody.btRigidBodyConstructionInfo(mass, null, shape, localInertia); } public GameObject construct () { return new GameObject(model, node, constructionInfo); } @Override public void dispose () { shape.dispose(); constructionInfo.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btDynamicsWorld dynamicsWorld; btConstraintSolver constraintSolver; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)), 0f)); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f), 1f)); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)), 1f)); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f), 1f)); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f), 1f)); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)), 1f)); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); constraintSolver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig); dynamicsWorld.setGravity(new Vector3(0, -10f, 0)); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); dynamicsWorld.addRigidBody(object.body, GROUND_FLAG, ALL_FLAG); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); dynamicsWorld.addRigidBody(obj.body, OBJECT_FLAG, GROUND_FLAG); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); dynamicsWorld.stepSimulation(delta, 5, 1f / 60f); for (GameObject obj : instances) obj.body.getWorldTransform(obj.transform); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dynamicsWorld.dispose(); constraintSolver.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
xoppa/blog
https://github.com/xoppa/blog/blob/aa6611044582f2023709364a6af025c95a4f09ac/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step2/BulletTest.java
tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step2/BulletTest.java
package com.xoppa.blog.libgdx.g3d.bullet.dynamics.step2; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.ContactListener; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCapsuleShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.badlogic.gdx.physics.bullet.collision.btConeShape; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.physics.bullet.dynamics.btConstraintSolver; import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btDynamicsWorld; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; /** @see https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part2/ * @author Xoppa */ public class BulletTest implements ApplicationListener { final static short GROUND_FLAG = 1 << 8; final static short OBJECT_FLAG = 1 << 9; final static short ALL_FLAG = -1; class MyContactListener extends ContactListener { @Override public boolean onContactAdded (int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) { instances.get(userValue0).moving = false; instances.get(userValue1).moving = false; return true; } } static class GameObject extends ModelInstance implements Disposable { public final btRigidBody body; public boolean moving; public GameObject (Model model, String node, btRigidBody.btRigidBodyConstructionInfo constructionInfo) { super(model, node); body = new btRigidBody(constructionInfo); } @Override public void dispose () { body.dispose(); } static class Constructor implements Disposable { public final Model model; public final String node; public final btCollisionShape shape; public final btRigidBody.btRigidBodyConstructionInfo constructionInfo; private static Vector3 localInertia = new Vector3(); public Constructor (Model model, String node, btCollisionShape shape, float mass) { this.model = model; this.node = node; this.shape = shape; if (mass > 0f) shape.calculateLocalInertia(mass, localInertia); else localInertia.set(0, 0, 0); this.constructionInfo = new btRigidBody.btRigidBodyConstructionInfo(mass, null, shape, localInertia); } public GameObject construct () { return new GameObject(model, node, constructionInfo); } @Override public void dispose () { shape.dispose(); constructionInfo.dispose(); } } } PerspectiveCamera cam; CameraInputController camController; ModelBatch modelBatch; Environment environment; Model model; Array<GameObject> instances; ArrayMap<String, GameObject.Constructor> constructors; float spawnTimer; btCollisionConfiguration collisionConfig; btDispatcher dispatcher; MyContactListener contactListener; btBroadphaseInterface broadphase; btDynamicsWorld dynamicsWorld; btConstraintSolver constraintSolver; @Override public void create () { Bullet.init(); modelBatch = new ModelBatch(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(3f, 7f, 10f); cam.lookAt(0, 4f, 0); cam.near = 1f; cam.far = 300f; cam.update(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(camController); ModelBuilder mb = new ModelBuilder(); mb.begin(); mb.node().id = "ground"; mb.part("ground", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.RED))) .box(5f, 1f, 5f); mb.node().id = "sphere"; mb.part("sphere", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.GREEN))) .sphere(1f, 1f, 1f, 10, 10); mb.node().id = "box"; mb.part("box", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.BLUE))) .box(1f, 1f, 1f); mb.node().id = "cone"; mb.part("cone", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.YELLOW))) .cone(1f, 2f, 1f, 10); mb.node().id = "capsule"; mb.part("capsule", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.CYAN))) .capsule(0.5f, 2f, 10); mb.node().id = "cylinder"; mb.part("cylinder", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.MAGENTA))).cylinder(1f, 2f, 1f, 10); model = mb.end(); constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class); constructors.put("ground", new GameObject.Constructor(model, "ground", new btBoxShape(new Vector3(2.5f, 0.5f, 2.5f)), 0f)); constructors.put("sphere", new GameObject.Constructor(model, "sphere", new btSphereShape(0.5f), 1f)); constructors.put("box", new GameObject.Constructor(model, "box", new btBoxShape(new Vector3(0.5f, 0.5f, 0.5f)), 1f)); constructors.put("cone", new GameObject.Constructor(model, "cone", new btConeShape(0.5f, 2f), 1f)); constructors.put("capsule", new GameObject.Constructor(model, "capsule", new btCapsuleShape(.5f, 1f), 1f)); constructors.put("cylinder", new GameObject.Constructor(model, "cylinder", new btCylinderShape(new Vector3(.5f, 1f, .5f)), 1f)); collisionConfig = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfig); broadphase = new btDbvtBroadphase(); constraintSolver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig); dynamicsWorld.setGravity(new Vector3(0, -10f, 0)); contactListener = new MyContactListener(); instances = new Array<GameObject>(); GameObject object = constructors.get("ground").construct(); instances.add(object); dynamicsWorld.addRigidBody(object.body, GROUND_FLAG, ALL_FLAG); } public void spawn () { GameObject obj = constructors.values[1 + MathUtils.random(constructors.size - 2)].construct(); obj.moving = true; obj.transform.setFromEulerAngles(MathUtils.random(360f), MathUtils.random(360f), MathUtils.random(360f)); obj.transform.trn(MathUtils.random(-2.5f, 2.5f), 9f, MathUtils.random(-2.5f, 2.5f)); obj.body.setWorldTransform(obj.transform); obj.body.setUserValue(instances.size); obj.body.setCollisionFlags(obj.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); instances.add(obj); dynamicsWorld.addRigidBody(obj.body, OBJECT_FLAG, GROUND_FLAG); } @Override public void render () { final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime()); dynamicsWorld.stepSimulation(delta, 5, 1f / 60f); for (GameObject obj : instances) obj.body.getWorldTransform(obj.transform); if ((spawnTimer -= delta) < 0) { spawn(); spawnTimer = 1.5f; } camController.update(); Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(cam); modelBatch.render(instances, environment); modelBatch.end(); } @Override public void dispose () { for (GameObject obj : instances) obj.dispose(); instances.clear(); for (GameObject.Constructor ctor : constructors.values()) ctor.dispose(); constructors.clear(); dynamicsWorld.dispose(); constraintSolver.dispose(); broadphase.dispose(); dispatcher.dispose(); collisionConfig.dispose(); contactListener.dispose(); modelBatch.dispose(); model.dispose(); } @Override public void pause () { } @Override public void resume () { } @Override public void resize (int width, int height) { } }
java
Apache-2.0
aa6611044582f2023709364a6af025c95a4f09ac
2026-01-05T02:42:28.833355Z
false
ogrodnek/csv-serde
https://github.com/ogrodnek/csv-serde/blob/dc9c22dfdfae7588fa7fa234ffe3f23607a7457d/src/test/java/com/bizo/hive/serde/csv/CSVSerdeTest.java
src/test/java/com/bizo/hive/serde/csv/CSVSerdeTest.java
package com.bizo.hive.serde.csv; import java.util.List; import java.util.Properties; import org.apache.hadoop.hive.serde.Constants; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public final class CSVSerdeTest { private final CSVSerde csv = new CSVSerde(); final Properties props = new Properties(); @Before public void setup() throws Exception { props.put(Constants.LIST_COLUMNS, "a,b,c"); props.put(Constants.LIST_COLUMN_TYPES, "string,string,string"); } @Test public void testDeserialize() throws Exception { csv.initialize(null, props); final Text in = new Text("hello,\"yes, okay\",1"); final List<String> row = (List<String>) csv.deserialize(in); assertEquals("hello", row.get(0)); assertEquals("yes, okay", row.get(1)); assertEquals("1", row.get(2)); } @Test public void testDeserializeCustomSeparators() throws Exception { props.put("separatorChar", "\t"); props.put("quoteChar", "'"); csv.initialize(null, props); final Text in = new Text("hello\t'yes\tokay'\t1"); final List<String> row = (List<String>) csv.deserialize(in); assertEquals("hello", row.get(0)); assertEquals("yes\tokay", row.get(1)); assertEquals("1", row.get(2)); } @Test public void testDeserializeCustomEscape() throws Exception { props.put("quoteChar", "'"); props.put("escapeChar", "\\"); csv.initialize(null, props); final Text in = new Text("hello,'yes\\'okay',1"); final List<String> row = (List<String>) csv.deserialize(in); assertEquals("hello", row.get(0)); assertEquals("yes'okay", row.get(1)); assertEquals("1", row.get(2)); } }
java
Apache-2.0
dc9c22dfdfae7588fa7fa234ffe3f23607a7457d
2026-01-05T02:42:31.333447Z
false
ogrodnek/csv-serde
https://github.com/ogrodnek/csv-serde/blob/dc9c22dfdfae7588fa7fa234ffe3f23607a7457d/src/main/java/com/bizo/hive/serde/csv/CSVSerde.java
src/main/java/com/bizo/hive/serde/csv/CSVSerde.java
package com.bizo.hive.serde.csv; import java.io.CharArrayReader; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.serde.serdeConstants; import org.apache.hadoop.hive.serde2.AbstractSerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.SerDeStats; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; /** * CSVSerde uses opencsv (http://opencsv.sourceforge.net/) to serialize/deserialize columns as CSV. * * @author Larry Ogrodnek <ogrodnek@gmail.com> */ public final class CSVSerde extends AbstractSerDe { private ObjectInspector inspector; private String[] outputFields; private int numCols; private List<String> row; private char separatorChar; private char quoteChar; private char escapeChar; @Override public void initialize(final Configuration conf, final Properties tbl) throws SerDeException { final List<String> columnNames = Arrays.asList(tbl.getProperty(serdeConstants.LIST_COLUMNS).split(",")); numCols = columnNames.size(); final List<ObjectInspector> columnOIs = new ArrayList<ObjectInspector>(numCols); for (int i=0; i< numCols; i++) { columnOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); } this.inspector = ObjectInspectorFactory.getStandardStructObjectInspector(columnNames, columnOIs); this.outputFields = new String[numCols]; row = new ArrayList<String>(numCols); for (int i=0; i< numCols; i++) { row.add(null); } separatorChar = getProperty(tbl, "separatorChar", CSVWriter.DEFAULT_SEPARATOR); quoteChar = getProperty(tbl, "quoteChar", CSVWriter.DEFAULT_QUOTE_CHARACTER); escapeChar = getProperty(tbl, "escapeChar", CSVWriter.DEFAULT_ESCAPE_CHARACTER); } private final char getProperty(final Properties tbl, final String property, final char def) { final String val = tbl.getProperty(property); if (val != null) { return val.charAt(0); } return def; } @Override public Writable serialize(Object obj, ObjectInspector objInspector) throws SerDeException { final StructObjectInspector outputRowOI = (StructObjectInspector) objInspector; final List<? extends StructField> outputFieldRefs = outputRowOI.getAllStructFieldRefs(); if (outputFieldRefs.size() != numCols) { throw new SerDeException("Cannot serialize the object because there are " + outputFieldRefs.size() + " fields but the table has " + numCols + " columns."); } // Get all data out. for (int c = 0; c < numCols; c++) { final Object field = outputRowOI.getStructFieldData(obj, outputFieldRefs.get(c)); final ObjectInspector fieldOI = outputFieldRefs.get(c).getFieldObjectInspector(); // The data must be of type String final StringObjectInspector fieldStringOI = (StringObjectInspector) fieldOI; // Convert the field to Java class String, because objects of String type // can be stored in String, Text, or some other classes. outputFields[c] = fieldStringOI.getPrimitiveJavaObject(field); } final StringWriter writer = new StringWriter(); final CSVWriter csv = newWriter(writer, separatorChar, quoteChar, escapeChar); try { csv.writeNext(outputFields); csv.close(); return new Text(writer.toString()); } catch (final IOException ioe) { throw new SerDeException(ioe); } } @Override public Object deserialize(final Writable blob) throws SerDeException { Text rowText = (Text) blob; CSVReader csv = null; try { csv = newReader(new CharArrayReader(rowText.toString().toCharArray()), separatorChar, quoteChar, escapeChar); final String[] read = csv.readNext(); for (int i=0; i< numCols; i++) { if (read != null && i < read.length) { row.set(i, read[i]); } else { row.set(i, null); } } return row; } catch (final Exception e) { throw new SerDeException(e); } finally { if (csv != null) { try { csv.close(); } catch (final Exception e) { // ignore } } } } private CSVReader newReader(final Reader reader, char separator, char quote, char escape) { // CSVReader will throw an exception if any of separator, quote, or escape is the same, but // the CSV format specifies that the escape character and quote char are the same... very weird if (CSVWriter.DEFAULT_ESCAPE_CHARACTER == escape) { return new CSVReader(reader, separator, quote); } else { return new CSVReader(reader, separator, quote, escape); } } private CSVWriter newWriter(final Writer writer, char separator, char quote, char escape) { if (CSVWriter.DEFAULT_ESCAPE_CHARACTER == escape) { return new CSVWriter(writer, separator, quote, ""); } else { return new CSVWriter(writer, separator, quote, escape, ""); } } @Override public ObjectInspector getObjectInspector() throws SerDeException { return inspector; } @Override public Class<? extends Writable> getSerializedClass() { return Text.class; } @Override public SerDeStats getSerDeStats() { return null; } }
java
Apache-2.0
dc9c22dfdfae7588fa7fa234ffe3f23607a7457d
2026-01-05T02:42:31.333447Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-gateway/src/test/java/org/apache/paimon/web/gateway/provider/ExecutorFactoryProviderTest.java
paimon-web-gateway/src/test/java/org/apache/paimon/web/gateway/provider/ExecutorFactoryProviderTest.java
/* * 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.paimon.web.gateway.provider; import org.apache.paimon.web.engine.flink.sql.gateway.executor.FlinkSqlGatewayExecutorFactory; import org.apache.paimon.web.engine.flink.sql.gateway.model.SessionEntity; import org.apache.paimon.web.gateway.config.ExecutionConfig; import org.apache.paimon.web.gateway.enums.EngineType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; /** Test for {@link ExecutorFactoryProvider}. */ public class ExecutorFactoryProviderTest { @Test public void testGetExecutorFactoryWithFlink() { ExecutionConfig config = ExecutionConfig.builder().sessionEntity(SessionEntity.builder().build()).build(); EngineType engineType = EngineType.fromName("FLINK"); ExecutorFactoryProvider executorFactoryProvider = new ExecutorFactoryProvider(config); assertSame( FlinkSqlGatewayExecutorFactory.class, executorFactoryProvider.getExecutorFactory(engineType).getClass()); } @Test public void testGetExecutorFactoryWithSpark() { ExecutionConfig config = ExecutionConfig.builder().sessionEntity(SessionEntity.builder().build()).build(); EngineType engineType = EngineType.fromName("SPARK"); ExecutorFactoryProvider executorFactoryProvider = new ExecutorFactoryProvider(config); assertThrows( UnsupportedOperationException.class, () -> executorFactoryProvider.getExecutorFactory(engineType)); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/provider/ExecutorFactoryProvider.java
paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/provider/ExecutorFactoryProvider.java
/* * 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.paimon.web.gateway.provider; import org.apache.paimon.web.engine.flink.common.executor.ExecutorFactory; import org.apache.paimon.web.engine.flink.sql.gateway.executor.FlinkSqlGatewayExecutorFactory; import org.apache.paimon.web.gateway.config.ExecutionConfig; import org.apache.paimon.web.gateway.enums.EngineType; /** ExecutorFactoryProvider is responsible for providing the appropriate ExecutorFactory. */ public class ExecutorFactoryProvider { private final ExecutionConfig executionConfig; public ExecutorFactoryProvider(ExecutionConfig executionConfig) { this.executionConfig = executionConfig; } public ExecutorFactory getExecutorFactory(EngineType type) { switch (type) { case FLINK: return new FlinkSqlGatewayExecutorFactory(executionConfig.getSessionEntity()); default: throw new UnsupportedOperationException( type + " engine is not currently supported."); } } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/config/ExecutionConfig.java
paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/config/ExecutionConfig.java
/* * 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.paimon.web.gateway.config; import org.apache.paimon.web.engine.flink.sql.gateway.model.SessionEntity; import lombok.Builder; import lombok.Getter; import java.util.Map; /** Configuration for execution context. */ @Builder @Getter public class ExecutionConfig { private boolean isStreaming; private SessionEntity sessionEntity; private Map<String, String> configs; }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/enums/EngineType.java
paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/enums/EngineType.java
/* * 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.paimon.web.gateway.enums; /** The {@code EngineType} enum defines the types of engines that can be supported. */ public enum EngineType { SPARK, FLINK; public static EngineType fromName(String name) { for (EngineType type : values()) { if (type.name().equals(name)) { return type; } } throw new IllegalArgumentException("Unknown engine type value: " + name); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/enums/DeploymentMode.java
paimon-web-gateway/src/main/java/org/apache/paimon/web/gateway/enums/DeploymentMode.java
/* * 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.paimon.web.gateway.enums; /** * The {@code DeploymentMode} enum defines the types of cluster deployment mode that can be * supported. */ public enum DeploymentMode { YARN_SESSION("yarn-session"), FLINK_SQL_GATEWAY("flink-sql-gateway"); private final String type; DeploymentMode(String type) { this.type = type; } public String getType() { return type; } public static DeploymentMode fromName(String name) { for (DeploymentMode type : values()) { if (type.getType().equals(name)) { return type; } } throw new IllegalArgumentException("Unknown deployment mode type value: " + name); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-common/src/main/java/org/apache/paimon/web/common/util/MapUtil.java
paimon-web-common/src/main/java/org/apache/paimon/web/common/util/MapUtil.java
/* * 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.paimon.web.common.util; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; /** Map util. */ public class MapUtil { private MapUtil() {} public static String getString(Map<String, ?> map, String key) { return Optional.ofNullable(map).map(e -> String.valueOf(e.get(key))).orElse(""); } public static <E> List<E> getList(Map<String, ?> map, String key) { return Optional.ofNullable(map).map(e -> (List<E>) map.get(key)).orElse(new ArrayList<>()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-common/src/main/java/org/apache/paimon/web/common/util/JSONUtils.java
paimon-web-common/src/main/java/org/apache/paimon/web/common/util/JSONUtils.java
/* * 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.paimon.web.common.util; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.POJONode; import com.google.common.base.Strings; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import java.io.IOException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; import static com.fasterxml.jackson.databind.DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL; import static com.fasterxml.jackson.databind.MapperFeature.REQUIRE_SETTERS_FOR_GETTERS; /** Json utils. */ @Slf4j public class JSONUtils { private static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true) .configure(READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) .configure(REQUIRE_SETTERS_FOR_GETTERS, true) .addModule( new SimpleModule() .addSerializer( LocalDateTime.class, new LocalDateTimeSerializer()) .addDeserializer( LocalDateTime.class, new LocalDateTimeDeserializer())) .defaultTimeZone(TimeZone.getDefault()) .defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) .build(); public static ObjectMapper getObjectMapper() { return OBJECT_MAPPER; } private JSONUtils() { throw new UnsupportedOperationException("Construct JSONUtils"); } public static synchronized void setTimeZone(TimeZone timeZone) { OBJECT_MAPPER.setTimeZone(timeZone); } public static ArrayNode createArrayNode() { return OBJECT_MAPPER.createArrayNode(); } public static ObjectNode createObjectNode() { return OBJECT_MAPPER.createObjectNode(); } public static String getString(JsonNode jsonNode, String fieldName) { return getString(jsonNode, fieldName, ""); } public static String getString(JsonNode jsonNode, String fieldName, String defaultValue) { if (jsonNode == null) { return defaultValue; } JsonNode node = jsonNode.get(fieldName); if (node == null || !node.isTextual()) { return defaultValue; } return node.asText(); } public static Integer getInteger(JsonNode jsonNode, String fieldName) { return getInteger(jsonNode, fieldName, 0); } public static Integer getInteger(JsonNode jsonNode, String fieldName, Integer defaultValue) { if (jsonNode == null) { return defaultValue; } JsonNode node = jsonNode.get(fieldName); if (node == null || !node.isInt()) { return defaultValue; } return node.asInt(); } public static List<String> getList(JsonNode jsonNode, String fieldName) { return getList(jsonNode, fieldName, String.class); } public static <E> List<E> getList(JsonNode jsonNode, String fieldName, Class<E> clazz) { if (jsonNode == null) { return new ArrayList<>(); } JsonNode child = jsonNode.get(fieldName); if (!(child instanceof ArrayNode) && !(child instanceof POJONode)) { return new ArrayList<>(); } List<?> childArray; if (child instanceof POJONode) { Object pojo = ((POJONode) child).getPojo(); childArray = (List<?>) pojo; } else { childArray = (List<?>) child; } List<E> result = new ArrayList<>(); childArray.forEach( e -> { result.add(JSONUtils.parseObject(JSONUtils.toJsonString(e), clazz)); }); return result; } /** * object to json string. * * @param object object * @return json string */ public static String toJsonString(Object object) { try { return OBJECT_MAPPER.writeValueAsString(object); } catch (Exception e) { throw new RuntimeException("Object json deserialization exception.", e); } } public static @Nullable <T> T parseObject(String json, Class<T> clazz) { if (Strings.isNullOrEmpty(json)) { return null; } try { return OBJECT_MAPPER.readValue(json, clazz); } catch (Exception e) { log.error("Parse object exception, jsonStr: {}, class: {}", json, clazz, e); } return null; } /** LocalDateTimeSerializer. */ public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public void serialize( LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.format(formatter)); } } /** LocalDateTimeDeserializer. */ public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public LocalDateTime deserialize(JsonParser p, DeserializationContext context) throws IOException { return LocalDateTime.parse(p.getValueAsString(), formatter); } } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-common/src/main/java/org/apache/paimon/web/common/annotation/VisibleForTesting.java
paimon-web-common/src/main/java/org/apache/paimon/web/common/annotation/VisibleForTesting.java
/* * 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.paimon.web.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * This annotations declares that a function, field, constructor, or entire type, is only visible * for testing purposes. * * <p>This annotation is typically attached when for example a method should be {@code private} * (because it is not intended to be called externally), but cannot be declared private, because * some tests need to have access to it. */ @Documented @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR}) public @interface VisibleForTesting {}
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/PaimonWebServerApplicationTests.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/PaimonWebServerApplicationTests.java
/* * 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.paimon.web.server; import org.springframework.boot.test.context.SpringBootTest; /** Paimon Web Server Application Tests. */ @SpringBootTest class PaimonWebServerApplicationTests {}
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/CatalogControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/CatalogControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.CatalogDTO; import org.apache.paimon.web.server.data.model.CatalogInfo; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** Test for {@link CatalogController}. */ @SpringBootTest @AutoConfigureMockMvc public class CatalogControllerTest extends ControllerTestBase { private static final String catalogPath = "/api/catalog"; private static final String catalogName = "testCatalog"; private Integer catalogId; @BeforeEach public void setup() throws Exception { CatalogDTO catalog = new CatalogDTO(); catalog.setType("filesystem"); catalog.setName(catalogName); catalog.setWarehouse(tempFile.toUri().toString()); catalog.setDelete(false); mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(catalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // get catalog id. String responseString = mockMvc.perform( MockMvcRequestBuilders.get(catalogPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<CatalogInfo>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<CatalogInfo>>>() {}); catalogId = r.getData().get(0).getId(); } @AfterEach public void after() throws Exception { CatalogDTO removeCatalog = new CatalogDTO(); removeCatalog.setId(catalogId); removeCatalog.setName(catalogName); mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/remove") .cookie(cookie) .content(ObjectMapperUtils.toJSON(removeCatalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testGetCatalog() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(catalogPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<CatalogInfo>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<CatalogInfo>>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(1, r.getData().size()); assertEquals(catalogName, r.getData().get(0).getCatalogName()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/ClusterControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/ClusterControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.engine.flink.common.status.HeartbeatStatus; import org.apache.paimon.web.engine.flink.sql.gateway.client.HeartbeatAction; import org.apache.paimon.web.engine.flink.sql.gateway.model.HeartbeatEntity; import org.apache.paimon.web.server.data.model.ClusterInfo; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.service.impl.ClusterServiceImpl; import org.apache.paimon.web.server.util.ObjectMapperUtils; import org.apache.paimon.web.server.util.SpringUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link ClusterController}. */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ClusterControllerTest extends ControllerTestBase { private static final String clusterPath = "/api/cluster"; private static final int clusterId = 1; private static final String clusterName = "flink_test_cluster"; @Test @Order(1) public void testAddCluster() throws Exception { ClusterInfo cluster = new ClusterInfo(); cluster.setId(clusterId); cluster.setClusterName(clusterName); cluster.setHost("127.0.0.1"); cluster.setPort(8083); cluster.setType("Flink"); cluster.setDeploymentMode("yarn-session"); cluster.setEnabled(true); mockMvc.perform( MockMvcRequestBuilders.post(clusterPath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(cluster)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); } @Test @Order(2) public void testGetCluster() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(clusterPath + "/" + clusterId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<ClusterInfo> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<ClusterInfo>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(clusterName, r.getData().getClusterName()); assertEquals("127.0.0.1", r.getData().getHost()); assertEquals(8083, r.getData().getPort()); assertEquals("Flink", r.getData().getType()); assertEquals("yarn-session", r.getData().getDeploymentMode()); assertTrue(r.getData().getEnabled()); } @Test @Order(3) public void testListClusters() throws Exception { List<ClusterInfo> clustersWithoutConditions = listClusters(""); assertTrue(clustersWithoutConditions.size() > 0); ClusterInfo clusterInfo = clustersWithoutConditions.get(0); assertEquals(clusterName, clusterInfo.getClusterName()); assertEquals("127.0.0.1", clusterInfo.getHost()); assertEquals(8083, clusterInfo.getPort()); assertEquals("Flink", clusterInfo.getType()); assertTrue(clusterInfo.getEnabled()); List<ClusterInfo> clustersWithConditionsFlink = listClusters("Flink"); assertTrue(clustersWithConditionsFlink.size() > 0); ClusterInfo clusterInfo1 = clustersWithConditionsFlink.get(0); assertEquals(clusterName, clusterInfo1.getClusterName()); assertEquals("127.0.0.1", clusterInfo1.getHost()); assertEquals(8083, clusterInfo1.getPort()); assertEquals("Flink", clusterInfo1.getType()); assertTrue(clusterInfo1.getEnabled()); List<ClusterInfo> clustersWithConditionsSpark = listClusters("Spark"); assertEquals(0, clustersWithConditionsSpark.size()); } @Test @Order(4) public void testUpdateCluster() throws Exception { String newClusterName = clusterName + "-edit"; ClusterInfo cluster = new ClusterInfo(); cluster.setId(clusterId); cluster.setClusterName(newClusterName); cluster.setHost("127.0.0.1"); cluster.setPort(8083); cluster.setType("Flink"); cluster.setEnabled(true); mockMvc.perform( MockMvcRequestBuilders.put(clusterPath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(cluster)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(clusterPath + "/" + clusterId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<ClusterInfo> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<ClusterInfo>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(r.getData().getClusterName(), newClusterName); } @Test @Order(5) public void testDeleteCluster() throws Exception { String delResponseString = mockMvc.perform( MockMvcRequestBuilders.delete( clusterPath + "/" + clusterId + "," + clusterId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(delResponseString, R.class); assertEquals(200, result.getCode()); } private List<ClusterInfo> listClusters(String params) throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(clusterPath + "/list") .cookie(cookie) .param("type", params) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<ClusterInfo> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<PageR<ClusterInfo>>() {}); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); return r.getData(); } @Test @Order(6) public void testCheckClusterHeartbeatOfFlinkSqlGateway() throws Exception { ClusterInfo cluster = ClusterInfo.builder() .clusterName("test") .enabled(true) .type("Flink") .deploymentMode("flink-sql-gateway") .host("127.0.0.1") .port(8083) .build(); String delResponseString = mockMvc.perform( MockMvcRequestBuilders.post(clusterPath + "/" + "check") .cookie(cookie) .content(ObjectMapperUtils.toJSON(cluster)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(delResponseString, R.class); assertNotNull(result, "result is null"); } @Test @Order(7) public void testCheckClusterHeartbeatOfFlinkSession() throws Exception { ClusterInfo cluster = ClusterInfo.builder() .clusterName("test") .enabled(true) .deploymentMode("yarn-session") .type("Flink") .host("127.0.0.1") .port(8083) .build(); String delResponseString = mockMvc.perform( MockMvcRequestBuilders.post(clusterPath + "/" + "check") .cookie(cookie) .content(ObjectMapperUtils.toJSON(cluster)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(delResponseString, R.class); assertNotNull(result, "result is null"); } @Test @Order(8) public void testCheckClusterHeartbeatStatus() { ClusterInfo cluster = ClusterInfo.builder() .clusterName("test") .enabled(true) .deploymentMode("yarn-session") .type("Flink") .host("127.0.0.1") .port(8083) .build(); ClusterServiceImpl bean = SpringUtils.getBean(ClusterServiceImpl.class); bean.checkClusterHeartbeatStatus(); HeartbeatEntity heartbeatEntityOfActive = HeartbeatEntity.builder() .status(HeartbeatStatus.ACTIVE.name()) .lastHeartbeat(System.currentTimeMillis()) .build(); bean.buildClusterInfo(cluster, heartbeatEntityOfActive); assertEquals(HeartbeatStatus.ACTIVE.name(), cluster.getHeartbeatStatus()); HeartbeatEntity heartbeatEntityOfUnreachable = HeartbeatEntity.builder().status(HeartbeatStatus.UNREACHABLE.name()).build(); bean.buildClusterInfo(cluster, heartbeatEntityOfUnreachable); assertEquals(HeartbeatStatus.UNREACHABLE.name(), cluster.getHeartbeatStatus()); HeartbeatEntity heartbeatEntityOfUnknown = HeartbeatEntity.builder().status(HeartbeatStatus.UNKNOWN.name()).build(); bean.buildClusterInfo(cluster, heartbeatEntityOfUnknown); assertEquals(HeartbeatStatus.UNKNOWN.name(), cluster.getHeartbeatStatus()); } @Test @Order(9) public void testGetHeartbeatActionFactory() throws Exception { ClusterInfo cluster1 = ClusterInfo.builder() .clusterName("test") .enabled(true) .deploymentMode("yarn-session") .type("Flink") .host("127.0.0.1") .port(8083) .build(); ClusterServiceImpl bean = SpringUtils.getBean(ClusterServiceImpl.class); HeartbeatAction actionFactoryOfYarnSession = bean.getHeartbeatActionFactory(cluster1); assertNotNull(actionFactoryOfYarnSession, "result is null"); ClusterInfo cluster2 = ClusterInfo.builder() .clusterName("test") .enabled(true) .deploymentMode("flink-sql-gateway") .type("Flink") .host("127.0.0.1") .port(8083) .build(); HeartbeatAction actionFactoryOfSqlGateway = bean.getHeartbeatActionFactory(cluster2); assertNotNull(actionFactoryOfSqlGateway, "result is null"); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/HistoryControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/HistoryControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.History; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.service.HistoryService; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link HistoryController}. */ @SpringBootTest @AutoConfigureMockMvc public class HistoryControllerTest extends ControllerTestBase { private static final String historyPath = "/api/history"; private static final int historyId = 1; private static final String historyName = "test"; @Autowired private HistoryService historyService; @BeforeEach public void setup() { History selectHistory = new History(); selectHistory.setId(historyId); selectHistory.setName(historyName); selectHistory.setTaskType("Flink"); selectHistory.setIsStreaming(false); selectHistory.setUid(1); selectHistory.setClusterId(1); selectHistory.setStatements("select * from table"); historyService.saveHistory(selectHistory); } @AfterEach public void after() { historyService.removeById(historyId); } @Test public void testSelectHistory() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(historyPath + "/" + historyId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<History> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<History>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(historyName, r.getData().getName()); assertEquals(1, r.getData().getUid()); assertEquals(1, r.getData().getClusterId()); assertEquals("Flink", r.getData().getTaskType()); assertEquals(false, r.getData().getIsStreaming()); assertEquals("select * from table", r.getData().getStatements()); } @Test public void testListClusters() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(historyPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<History> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<PageR<History>>() {}); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); History selectHistory = r.getData().get(0); assertEquals(historyName, selectHistory.getName()); assertEquals(1, selectHistory.getUid()); assertEquals(1, selectHistory.getClusterId()); assertEquals("Flink", selectHistory.getTaskType()); assertEquals(false, selectHistory.getIsStreaming()); assertEquals("select * from table", selectHistory.getStatements()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/JobControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/JobControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.constant.StatementsConstant; import org.apache.paimon.web.server.data.dto.JobSubmitDTO; import org.apache.paimon.web.server.data.dto.LoginDTO; import org.apache.paimon.web.server.data.dto.ResultFetchDTO; import org.apache.paimon.web.server.data.dto.StopJobDTO; import org.apache.paimon.web.server.data.model.ClusterInfo; import org.apache.paimon.web.server.data.model.History; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.JobStatisticsVO; import org.apache.paimon.web.server.data.vo.JobStatusVO; import org.apache.paimon.web.server.data.vo.JobVO; import org.apache.paimon.web.server.data.vo.ResultDataVO; import org.apache.paimon.web.server.service.ClusterService; import org.apache.paimon.web.server.service.HistoryService; import org.apache.paimon.web.server.util.ObjectMapperUtils; import org.apache.paimon.web.server.util.StringUtils; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockCookie; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Tests for {@link JobController}. */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class JobControllerTest extends FlinkSQLGatewayTestBase { private static final String loginPath = "/api/login"; private static final String logoutPath = "/api/logout"; private static final String jobPath = "/api/job"; @Value("${spring.application.name}") private String tokenName; @Autowired public MockMvc mockMvc; public static MockCookie cookie; @Autowired private ClusterService clusterService; @Autowired private HistoryService historyService; @BeforeEach public void before() throws Exception { LoginDTO login = new LoginDTO(); login.setUsername("admin"); login.setPassword("admin"); MockHttpServletResponse response = mockMvc.perform( MockMvcRequestBuilders.post(loginPath) .content(ObjectMapperUtils.toJSON(login)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); String result = response.getContentAsString(); R<?> r = ObjectMapperUtils.fromJSON(result, R.class); assertEquals(200, r.getCode()); assertTrue(StringUtils.isNotBlank(r.getData().toString())); cookie = (MockCookie) response.getCookie(tokenName); ClusterInfo cluster = ClusterInfo.builder() .clusterName("test_cluster") .host(targetAddress) .port(port) .enabled(true) .type("Flink") .deploymentMode("flink-sql-gateway") .build(); boolean res = clusterService.save(cluster); assertTrue(res); } @AfterEach public void after() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.post(logoutPath) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> r = ObjectMapperUtils.fromJSON(result, R.class); assertEquals(200, r.getCode()); QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); int res = clusterService.deleteClusterByIds(new Integer[] {one.getId()}); assertTrue(res > 0); } @Test @Order(1) public void testSubmitJob() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.statement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals("flink-job-test", r.getData().getJobName()); assertEquals("Flink", r.getData().getType()); assertEquals(1, r.getData().getUid()); } @Test @Order(2) public void testFetchResult() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-fetch-result"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); if (r.getData().getShouldFetchResult()) { ResultFetchDTO resultFetchDTO = new ResultFetchDTO(); resultFetchDTO.setSubmitId(r.getData().getSubmitId()); resultFetchDTO.setClusterId(r.getData().getClusterId()); resultFetchDTO.setSessionId(r.getData().getSessionId()); resultFetchDTO.setTaskType(r.getData().getType()); resultFetchDTO.setToken(r.getData().getToken()); String fetchResultString = mockMvc.perform( MockMvcRequestBuilders.post(jobPath + "/fetch") .cookie(cookie) .content(ObjectMapperUtils.toJSON(resultFetchDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<ResultDataVO> fetchResult = ObjectMapperUtils.fromJSON( fetchResultString, new TypeReference<R<ResultDataVO>>() {}); assertEquals(200, fetchResult.getCode()); assertEquals(1, fetchResult.getData().getToken()); } } @Test @Order(3) public void testListJobs() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-list-jobs"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); String listJobResponseStr = mockMvc.perform( MockMvcRequestBuilders.get(jobPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<JobVO>> listJobRes = ObjectMapperUtils.fromJSON( listJobResponseStr, new TypeReference<R<List<JobVO>>>() {}); assertEquals(200, listJobRes.getCode()); assertEquals(3, listJobRes.getData().size()); String jobs = listJobRes.getData().get(0).getJobName() + "," + listJobRes.getData().get(1).getJobName() + "," + listJobRes.getData().get(2).getJobName(); assertTrue(jobs.contains("flink-job-test-list-jobs")); } @Test @Order(4) public void testGetJobStatus() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-get-job-status"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); String listJobResponseStr = getJobStatus(r.getData().getJobId()); R<JobStatusVO> getJobStatusRes = ObjectMapperUtils.fromJSON( listJobResponseStr, new TypeReference<R<JobStatusVO>>() {}); assertEquals(200, getJobStatusRes.getCode()); assertEquals(r.getData().getJobId(), getJobStatusRes.getData().getJobId()); assertNotNull(getJobStatusRes.getData().getStatus()); } @Test @Order(5) public void testGetLogs() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-get-job-logs"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); String logsResponseStr = getLogs(); R<String> getJobLogsRes = ObjectMapperUtils.fromJSON(logsResponseStr, new TypeReference<R<String>>() {}); assertEquals(200, getJobLogsRes.getCode()); assertNotNull(getJobLogsRes.getData()); } @Test @Order(6) public void testStopJob() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-stop-job"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); String jobStatus = getJobStatus(r.getData().getJobId()); R<JobStatusVO> getJobStatusRes = ObjectMapperUtils.fromJSON(jobStatus, new TypeReference<R<JobStatusVO>>() {}); while (!getJobStatusRes.getData().getStatus().equals("RUNNING")) { refreshJob(); jobStatus = getJobStatus(r.getData().getJobId()); getJobStatusRes = ObjectMapperUtils.fromJSON(jobStatus, new TypeReference<R<JobStatusVO>>() {}); TimeUnit.SECONDS.sleep(1); } StopJobDTO stopJobDTO = new StopJobDTO(); stopJobDTO.setJobId(r.getData().getJobId()); stopJobDTO.setClusterId(r.getData().getClusterId()); stopJobDTO.setTaskType(r.getData().getType()); String stopJobString = mockMvc.perform( MockMvcRequestBuilders.post(jobPath + "/stop") .cookie(cookie) .content(ObjectMapperUtils.toJSON(stopJobDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> stopJobRes = ObjectMapperUtils.fromJSON(stopJobString, new TypeReference<R<Void>>() {}); assertEquals(200, stopJobRes.getCode()); jobStatus = getJobStatus(r.getData().getJobId()); getJobStatusRes = ObjectMapperUtils.fromJSON(jobStatus, new TypeReference<R<JobStatusVO>>() {}); assertEquals(200, getJobStatusRes.getCode()); assertEquals("CANCELED", getJobStatusRes.getData().getStatus()); } @Test @Order(7) public void testGetJobStatistics() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-get-job-statistics"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); refreshJob(); TimeUnit.MICROSECONDS.sleep(100); refreshJob(); String getJobStatisticsResponseStr = mockMvc.perform( MockMvcRequestBuilders.get(jobPath + "/statistics/get") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<JobStatisticsVO> getJobStatisticsRes = ObjectMapperUtils.fromJSON( getJobStatisticsResponseStr, new TypeReference<R<JobStatisticsVO>>() {}); assertEquals(200, getJobStatisticsRes.getCode()); assertEquals(7, getJobStatisticsRes.getData().getTotalNum()); assertEquals(6, getJobStatisticsRes.getData().getRunningNum()); assertEquals(1, getJobStatisticsRes.getData().getCanceledNum()); assertEquals(0, getJobStatisticsRes.getData().getFinishedNum()); assertEquals(0, getJobStatisticsRes.getData().getFailedNum()); } @Test @Order(8) public void testExecutionMode() { History history = historyService.list().get(0); assertTrue(history.getStatements().contains("SET 'execution.runtime-mode' = 'streaming';")); } @Test @Order(9) public void testClearLogs() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); JobSubmitDTO jobSubmitDTO = new JobSubmitDTO(); jobSubmitDTO.setJobName("flink-job-test-clear-job-logs"); jobSubmitDTO.setTaskType("Flink"); jobSubmitDTO.setStreaming(true); jobSubmitDTO.setClusterId(String.valueOf(one.getId())); jobSubmitDTO.setStatements(StatementsConstant.selectStatement); String responseString = submit(jobSubmitDTO); R<JobVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<JobVO>>() {}); assertEquals(200, r.getCode()); String logsResponseStr = clearLogs(); R<String> getJobLogRes = ObjectMapperUtils.fromJSON(logsResponseStr, new TypeReference<R<String>>() {}); assertEquals(200, getJobLogRes.getCode()); assertNotNull(getJobLogRes.getData()); assertEquals("Console:\n", getJobLogRes.getData()); } private String submit(JobSubmitDTO jobSubmitDTO) throws Exception { return mockMvc.perform( MockMvcRequestBuilders.post(jobPath + "/submit") .cookie(cookie) .content(ObjectMapperUtils.toJSON(jobSubmitDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); } private String getJobStatus(String jobId) throws Exception { return mockMvc.perform( MockMvcRequestBuilders.get(jobPath + "/status/get/" + jobId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); } private String getLogs() throws Exception { return mockMvc.perform( MockMvcRequestBuilders.get(jobPath + "/logs/get") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); } private String clearLogs() throws Exception { return mockMvc.perform( MockMvcRequestBuilders.get(jobPath + "/logs/clear") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); } private void refreshJob() throws Exception { mockMvc.perform( MockMvcRequestBuilders.post(jobPath + "/refresh") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/StatementControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/StatementControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.StatementInfo; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link StatementController}. */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class StatementControllerTest extends ControllerTestBase { private static final String statementPath = "/api/statement"; private static final int statementId = 1; private static final String statementName = "test_query"; @Test @Order(1) public void testAddStatement() throws Exception { StatementInfo statementInfo = new StatementInfo(); statementInfo.setId(statementId); statementInfo.setStatementName(statementName); statementInfo.setTaskType("Flink"); statementInfo.setIsStreaming(false); statementInfo.setStatements("select * from table"); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(statementPath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(statementInfo)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(responseString, R.class); assertEquals(200, result.getCode()); StatementInfo statement = getStatementInfo(); assertEquals(statementName, statement.getStatementName()); assertEquals(false, statement.getIsStreaming()); assertEquals("Flink", statement.getTaskType()); assertEquals("select * from table", statement.getStatements()); } @Test @Order(2) public void testGetStatement() throws Exception { StatementInfo statementInfo = getStatementInfo(); assertEquals(statementName, statementInfo.getStatementName()); assertEquals(false, statementInfo.getIsStreaming()); assertEquals("Flink", statementInfo.getTaskType()); assertEquals("select * from table", statementInfo.getStatements()); } @Test @Order(3) public void testListStatements() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(statementPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<StatementInfo> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<PageR<StatementInfo>>() {}); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); StatementInfo statementInfo = r.getData().get(0); assertEquals(statementName, statementInfo.getStatementName()); assertEquals(false, statementInfo.getIsStreaming()); assertEquals("Flink", statementInfo.getTaskType()); assertEquals("select * from table", statementInfo.getStatements()); } @Test @Order(4) public void testUpdateStatement() throws Exception { StatementInfo statementInfo = new StatementInfo(); statementInfo.setId(statementId); statementInfo.setStatements("select * from table limit 10"); mockMvc.perform( MockMvcRequestBuilders.put(statementPath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(statementInfo)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); assertNotNull(getStatementInfo()); assertEquals("select * from table limit 10", getStatementInfo().getStatements()); } @Test @Order(5) public void testDeleteStatement() throws Exception { String delResponseString = mockMvc.perform( MockMvcRequestBuilders.delete(statementPath + "/" + statementId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(delResponseString, R.class); assertEquals(200, result.getCode()); } private StatementInfo getStatementInfo() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(statementPath + "/" + statementId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<StatementInfo> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<StatementInfo>>() {}); assertEquals(200, r.getCode()); return r.getData(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/SysRoleControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/SysRoleControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.RoleWithUserDTO; import org.apache.paimon.web.server.data.model.SysRole; import org.apache.paimon.web.server.data.model.User; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link SysRoleController}. */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SysRoleControllerTest extends ControllerTestBase { private static final String rolePath = "/api/role"; private static final int roleId = 3; private static final String roleName = "test"; private static final String commonUserName = "common"; @Test @Order(1) public void testAddRole() throws Exception { SysRole sysRole = new SysRole(); sysRole.setId(roleId); sysRole.setRoleName(roleName); sysRole.setRoleKey(roleName); sysRole.setSort(3); sysRole.setEnabled(true); sysRole.setIsDelete(false); sysRole.setRemark(roleName); mockMvc.perform( MockMvcRequestBuilders.post(rolePath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(sysRole)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); } @Test @Order(2) public void testQueryRole() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/" + roleId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<SysRole> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<SysRole>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertNotNull(r.getData().getCreateTime()); assertNotNull(r.getData().getUpdateTime()); assertEquals(r.getData().getRoleName(), roleName); } private SysRole getRole(Integer roleId) throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/" + roleId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<SysRole> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<SysRole>>() {}); return r.getData(); } @Test @Order(3) public void testEditRole() throws Exception { String newRoleName = roleName + "-edit"; SysRole sysRole = new SysRole(); sysRole.setId(roleId); sysRole.setRoleName(newRoleName); sysRole.setRoleKey(newRoleName); sysRole.setSort(3); sysRole.setEnabled(true); sysRole.setIsDelete(false); sysRole.setRemark(newRoleName); mockMvc.perform( MockMvcRequestBuilders.put(rolePath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(sysRole)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/" + roleId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<SysRole> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<SysRole>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(r.getData().getRoleName(), newRoleName); } @Test @Order(4) public void testGetRoleList() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<SysRole> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<PageR<SysRole>>() {}); assertNotNull(r); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); SysRole firstRole = r.getData().get(0); assertEquals(1, firstRole.getId()); assertEquals("admin", firstRole.getRoleName()); assertEquals("admin", firstRole.getRoleKey()); assertEquals(1, firstRole.getSort()); assertTrue(firstRole.getEnabled()); assertFalse(firstRole.getIsDelete()); assertNotNull(firstRole.getCreateTime()); assertNotNull(firstRole.getUpdateTime()); SysRole secondRole = r.getData().get(1); assertEquals(2, secondRole.getId()); assertEquals("common", secondRole.getRoleName()); assertEquals("common", secondRole.getRoleKey()); assertEquals(2, secondRole.getSort()); assertTrue(secondRole.getEnabled()); assertFalse(secondRole.getIsDelete()); assertNotNull(secondRole.getCreateTime()); assertNotNull(secondRole.getUpdateTime()); SysRole thirdRole = r.getData().get(2); assertEquals(3, thirdRole.getId()); assertEquals("test-edit", thirdRole.getRoleName()); assertEquals("test-edit", thirdRole.getRoleKey()); assertEquals(3, thirdRole.getSort()); assertTrue(thirdRole.getEnabled()); assertFalse(thirdRole.getIsDelete()); assertNotNull(thirdRole.getCreateTime()); assertNotNull(thirdRole.getUpdateTime()); } @Test @Order(5) public void testChangeRoleStatus() throws Exception { SysRole sysRole = new SysRole(); sysRole.setId(2); sysRole.setEnabled(false); String responseString = mockMvc.perform( MockMvcRequestBuilders.put(rolePath + "/changeStatus") .cookie(cookie) .content(ObjectMapperUtils.toJSON(sysRole)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); SysRole changeRole = getRole(2); assertEquals(changeRole.getEnabled(), false); } @Test @Order(6) public void testSelectAllAuthUser() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.put(rolePath + "/authUser/selectAll") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .param("roleId", "3") .param("userIds", "1,2")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); List<User> expectResults = getAllLocatedUsers(roleId); assertNotNull(expectResults); } @Test @Order(7) public void testAllocatedList() throws Exception { RoleWithUserDTO roleWithUser = new RoleWithUserDTO(); roleWithUser.setRoleId(roleId); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/authUser/allocatedList") .cookie(cookie) .content(ObjectMapperUtils.toJSON(roleWithUser)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<User> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<PageR<User>>() {}); assertNotNull(r); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); User firstUser = r.getData().get(0); assertEquals(1, firstUser.getId()); assertEquals("admin", firstUser.getUsername()); assertEquals("Admin", firstUser.getNickname()); assertEquals("admin@paimon.com", firstUser.getEmail()); assertTrue(firstUser.getEnabled()); assertTrue(firstUser.isAdmin()); User secondUser = r.getData().get(1); assertEquals(2, secondUser.getId()); assertEquals("common", secondUser.getUsername()); assertEquals("common", secondUser.getNickname()); assertEquals("common@paimon.com", secondUser.getEmail()); assertTrue(secondUser.getEnabled()); assertFalse(secondUser.isAdmin()); } private List<User> getAllLocatedUsers(Integer roleId) throws Exception { RoleWithUserDTO roleWithUser = new RoleWithUserDTO(); roleWithUser.setRoleId(roleId); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/authUser/allocatedList") .cookie(cookie) .content(ObjectMapperUtils.toJSON(roleWithUser)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<?> r = ObjectMapperUtils.fromJSON(responseString, PageR.class); return (List<User>) r.getData(); } @Test @Order(8) public void testUnAllocatedList() throws Exception { RoleWithUserDTO roleWithUser = new RoleWithUserDTO(); roleWithUser.setRoleId(1); roleWithUser.setUsername(commonUserName); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(rolePath + "/authUser/unallocatedList") .cookie(cookie) .content(ObjectMapperUtils.toJSON(roleWithUser)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<User> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<PageR<User>>() {}); assertNotNull(r); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); User firstExpectUser = r.getData().get(0); assertEquals(2, firstExpectUser.getId()); assertEquals("common", firstExpectUser.getUsername()); assertEquals("common", firstExpectUser.getNickname()); assertEquals("common@paimon.com", firstExpectUser.getEmail()); assertTrue(firstExpectUser.getEnabled()); assertFalse(firstExpectUser.isAdmin()); } @Test @Order(9) public void testCancelAllAuthUser() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.put(rolePath + "/authUser/cancelAll") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .param("roleId", String.valueOf(roleId)) .param("userIds", "1,2")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); List<User> expectResults = getAllLocatedUsers(roleId); assertEquals(0, expectResults.size()); } @Test @Order(10) public void testDeleteRole() throws Exception { String delResponseString = mockMvc.perform( MockMvcRequestBuilders.delete(rolePath + "/" + roleId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(delResponseString, R.class); assertEquals(200, result.getCode()); SysRole deleteRole = getRole(roleId); assertNull(deleteRole); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/SessionControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/SessionControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.engine.flink.sql.gateway.model.SessionEntity; import org.apache.paimon.web.server.data.dto.LoginDTO; import org.apache.paimon.web.server.data.model.ClusterInfo; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.service.ClusterService; import org.apache.paimon.web.server.service.UserSessionManager; import org.apache.paimon.web.server.util.ObjectMapperUtils; import org.apache.paimon.web.server.util.StringUtils; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockCookie; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link SessionController}. */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SessionControllerTest extends FlinkSQLGatewayTestBase { private static final String loginPath = "/api/login"; private static final String logoutPath = "/api/logout"; private static final String sessionPath = "/api/session"; @Value("${spring.application.name}") private String tokenName; @Autowired public MockMvc mockMvc; public static MockCookie cookie; @Autowired private ClusterService clusterService; @Autowired private UserSessionManager sessionManager; @BeforeEach public void before() throws Exception { LoginDTO login = new LoginDTO(); login.setUsername("admin"); login.setPassword("admin"); MockHttpServletResponse response = mockMvc.perform( MockMvcRequestBuilders.post(loginPath) .content(ObjectMapperUtils.toJSON(login)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); String result = response.getContentAsString(); R<?> r = ObjectMapperUtils.fromJSON(result, R.class); assertEquals(200, r.getCode()); assertTrue(StringUtils.isNotBlank(r.getData().toString())); cookie = (MockCookie) response.getCookie(tokenName); } @AfterEach public void after() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.post(logoutPath) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> r = ObjectMapperUtils.fromJSON(result, R.class); assertEquals(200, r.getCode()); } @Test @Order(1) public void testCreateSession() throws Exception { ClusterInfo cluster = ClusterInfo.builder() .clusterName("test_cluster") .host(targetAddress) .port(port) .enabled(true) .type("Flink") .deploymentMode("flink-sql-gateway") .build(); boolean res = clusterService.save(cluster); assertTrue(res); QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(sessionPath + "/create") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); SessionEntity session = sessionManager.getSession("1" + "_" + one.getId()); assertEquals(session.getHost(), targetAddress); assertEquals(session.getPort(), port); } @Test @Order(2) public void testDropSession() throws Exception { QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("cluster_name", "test_cluster"); ClusterInfo one = clusterService.getOne(queryWrapper); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(sessionPath + "/drop") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); SessionEntity session = sessionManager.getSession("1" + "_" + one.getId()); assertNull(session); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/FlinkSQLGatewayTestBase.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/FlinkSQLGatewayTestBase.java
/* * 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.paimon.web.server.controller; import org.apache.commons.io.FileUtils; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.testutils.CommonTestUtils; import org.apache.flink.table.gateway.api.SqlGatewayService; import org.apache.flink.table.gateway.api.endpoint.SqlGatewayEndpointFactoryUtils; import org.apache.flink.table.gateway.rest.SqlGatewayRestEndpoint; import org.apache.flink.table.gateway.rest.util.SqlGatewayRestOptions; import org.apache.flink.table.gateway.service.SqlGatewayServiceImpl; import org.apache.flink.table.gateway.service.context.DefaultContext; import org.apache.flink.table.gateway.service.session.SessionManager; import org.apache.flink.test.junit5.MiniClusterExtension; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.rules.TemporaryFolder; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import static org.apache.flink.configuration.ConfigConstants.ENV_FLINK_CONF_DIR; import static org.apache.flink.table.gateway.api.endpoint.SqlGatewayEndpointFactoryUtils.getEndpointConfig; import static org.apache.flink.table.gateway.api.endpoint.SqlGatewayEndpointFactoryUtils.getSqlGatewayOptionPrefix; import static org.apache.flink.table.gateway.rest.SqlGatewayRestEndpointFactory.IDENTIFIER; import static org.apache.flink.table.gateway.rest.SqlGatewayRestEndpointFactory.rebuildRestEndpointOptions; import static org.apache.flink.util.Preconditions.checkNotNull; /** The base class for sql gateway test. */ public class FlinkSQLGatewayTestBase { @RegisterExtension @Order(1) private static final MiniClusterExtension MINI_CLUSTER = new MiniClusterExtension(); @RegisterExtension @Order(2) protected static final SqlGatewayServiceExtension SQL_GATEWAY_SERVICE_EXTENSION = new SqlGatewayServiceExtension(MINI_CLUSTER::getClientConfiguration); @Nullable protected static String targetAddress = null; @Nullable private static SqlGatewayRestEndpoint sqlGatewayRestEndpoint = null; protected static int port = 0; @BeforeAll static void start() throws Exception { final String address = InetAddress.getLoopbackAddress().getHostAddress(); Configuration config = getBaseConfig(getFlinkConfig(address, address, "0")); sqlGatewayRestEndpoint = new SqlGatewayRestEndpoint(config, SQL_GATEWAY_SERVICE_EXTENSION.getService()); sqlGatewayRestEndpoint.start(); InetSocketAddress serverAddress = checkNotNull(sqlGatewayRestEndpoint.getServerAddress()); targetAddress = serverAddress.getHostName(); port = serverAddress.getPort(); } @AfterAll static void stop() throws Exception { checkNotNull(sqlGatewayRestEndpoint); sqlGatewayRestEndpoint.close(); } private static Configuration getBaseConfig(Configuration flinkConf) { SqlGatewayEndpointFactoryUtils.DefaultEndpointFactoryContext context = new SqlGatewayEndpointFactoryUtils.DefaultEndpointFactoryContext( null, flinkConf, getEndpointConfig(flinkConf, IDENTIFIER)); return rebuildRestEndpointOptions(context.getEndpointOptions()); } private static Configuration getFlinkConfig( String address, String bindAddress, String portRange) { final Configuration config = new Configuration(); if (address != null) { config.setString( getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.ADDRESS.key()), address); } if (bindAddress != null) { config.setString( getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.BIND_ADDRESS.key()), bindAddress); } if (portRange != null) { config.setString( getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.PORT.key()), portRange); } return config; } private static String getSqlGatewayRestOptionFullName(String key) { return getSqlGatewayOptionPrefix(IDENTIFIER) + key; } /** A simple {@link Extension} to be used by tests that require a {@link SqlGatewayService}. */ static class SqlGatewayServiceExtension implements BeforeAllCallback, AfterAllCallback { private SqlGatewayService service; private SessionManager sessionManager; private TemporaryFolder temporaryFolder; private final Supplier<Configuration> configSupplier; private final Function<DefaultContext, SessionManager> sessionManagerCreator; public SqlGatewayServiceExtension(Supplier<Configuration> configSupplier) { this(configSupplier, SessionManager::create); } public SqlGatewayServiceExtension( Supplier<Configuration> configSupplier, Function<DefaultContext, SessionManager> sessionManagerCreator) { this.configSupplier = configSupplier; this.sessionManagerCreator = sessionManagerCreator; } @Override public void beforeAll(ExtensionContext context) throws Exception { final Map<String, String> originalEnv = System.getenv(); try { // prepare conf dir temporaryFolder = new TemporaryFolder(); temporaryFolder.create(); File confFolder = temporaryFolder.newFolder("conf"); File confYaml = new File(confFolder, "flink-conf.yaml"); if (!confYaml.createNewFile()) { throw new IOException("Can't create testing flink-conf.yaml file."); } FileUtils.write( confYaml, getFlinkConfContent(configSupplier.get().toMap()), StandardCharsets.UTF_8); // adjust the test environment for the purposes of this test Map<String, String> map = new HashMap<>(System.getenv()); map.put(ENV_FLINK_CONF_DIR, confFolder.getAbsolutePath()); CommonTestUtils.setEnv(map); sessionManager = sessionManagerCreator.apply( DefaultContext.load( new Configuration(), Collections.emptyList(), true, false)); } finally { CommonTestUtils.setEnv(originalEnv); } service = new SqlGatewayServiceImpl(sessionManager); sessionManager.start(); } @Override public void afterAll(ExtensionContext context) throws Exception { if (sessionManager != null) { sessionManager.stop(); } temporaryFolder.delete(); } public SqlGatewayService getService() { return service; } private String getFlinkConfContent(Map<String, String> flinkConf) { StringBuilder sb = new StringBuilder(); flinkConf.forEach((k, v) -> sb.append(k).append(": ").append(v).append("\n")); return sb.toString(); } } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/ControllerTestBase.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/ControllerTestBase.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.LoginDTO; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.util.ObjectMapperUtils; import org.apache.paimon.web.server.util.StringUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockCookie; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** ControllerTestBase. */ @SpringBootTest @AutoConfigureMockMvc public class ControllerTestBase { private static final String loginPath = "/api/login"; private static final String logoutPath = "/api/logout"; @Value("${spring.application.name}") private String tokenName; @Autowired public MockMvc mockMvc; public static MockCookie cookie; @TempDir java.nio.file.Path tempFile; @BeforeEach public void before() throws Exception { LoginDTO login = new LoginDTO(); login.setUsername("admin"); login.setPassword("admin"); MockHttpServletResponse response = mockMvc.perform( MockMvcRequestBuilders.post(loginPath) .content(ObjectMapperUtils.toJSON(login)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); String result = response.getContentAsString(); R<?> r = ObjectMapperUtils.fromJSON(result, R.class); assertEquals(200, r.getCode()); assertTrue(StringUtils.isNotBlank(r.getData().toString())); cookie = (MockCookie) response.getCookie(tokenName); } @AfterEach public void after() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.post(logoutPath) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> r = ObjectMapperUtils.fromJSON(result, R.class); assertEquals(200, r.getCode()); } protected R<?> getR(ResultActions perform) throws Exception { MockHttpServletResponse response = perform.andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); String result = response.getContentAsString(); return ObjectMapperUtils.fromJSON(result, R.class); } protected R<?> getR(MockHttpServletResponse response) throws Exception { String result = response.getContentAsString(); return ObjectMapperUtils.fromJSON(result, R.class); } protected <T> R<T> getR(MockHttpServletResponse response, TypeReference<R<T>> typeReference) throws Exception { String result = response.getContentAsString(); return ObjectMapperUtils.fromJSON(result, typeReference); } protected PageR<?> getPageR(MockHttpServletResponse response) throws Exception { String result = response.getContentAsString(); return ObjectMapperUtils.fromJSON(result, PageR.class); } protected <T> PageR<T> getPageR( MockHttpServletResponse response, TypeReference<PageR<T>> typeReference) throws Exception { String result = response.getContentAsString(); return ObjectMapperUtils.fromJSON(result, typeReference); } protected void checkMvcResult(MockHttpServletResponse response, int exceptedStatus) throws Exception { R<?> r = getR(response); assertEquals(exceptedStatus, r.getCode()); } protected void checkMvcPageResult(MockHttpServletResponse response, boolean exceptedStatus) throws Exception { PageR<?> pageR = getPageR(response); assertEquals(pageR.isSuccess(), exceptedStatus); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/CdcJobDefinitionControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/CdcJobDefinitionControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.api.enums.FlinkCdcSyncType; import org.apache.paimon.web.server.data.dto.CdcJobDefinitionDTO; import org.apache.paimon.web.server.data.dto.CdcJobSubmitDTO; import org.apache.paimon.web.server.data.dto.LoginDTO; import org.apache.paimon.web.server.data.model.CdcJobDefinition; import org.apache.paimon.web.server.data.model.ClusterInfo; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.UserInfoVO; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; /** Test for {@link CdcJobDefinitionController} . */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CdcJobDefinitionControllerTest extends ControllerTestBase { private static final String cdcJobDefinitionPath = "/api/cdc-job-definition"; private CdcJobDefinitionDTO cdcJobDefinitionDto() { CdcJobDefinitionDTO cdcJobDefinitionDTO = new CdcJobDefinitionDTO(); cdcJobDefinitionDTO.setName("1"); cdcJobDefinitionDTO.setCdcType(FlinkCdcSyncType.SINGLE_TABLE_SYNC.getValue()); cdcJobDefinitionDTO.setDescription("d"); cdcJobDefinitionDTO.setCreateUser("admin"); return cdcJobDefinitionDTO; } private CdcJobDefinitionDTO cdcDatabaseSyncJobDefinitionDto() { CdcJobDefinitionDTO cdcJobDefinitionDTO = new CdcJobDefinitionDTO(); cdcJobDefinitionDTO.setName("2"); cdcJobDefinitionDTO.setCdcType(FlinkCdcSyncType.ALL_DATABASES_SYNC.getValue()); cdcJobDefinitionDTO.setDescription("d"); cdcJobDefinitionDTO.setCreateUser("admin"); return cdcJobDefinitionDTO; } private CdcJobDefinitionDTO cdcJobDefinitionDtoForSearch() { CdcJobDefinitionDTO cdcJobDefinitionDTO = new CdcJobDefinitionDTO(); cdcJobDefinitionDTO.setName("21"); cdcJobDefinitionDTO.setCdcType(1); cdcJobDefinitionDTO.setConfig("d"); cdcJobDefinitionDTO.setDescription("d"); return cdcJobDefinitionDTO; } @Test @Order(1) public void testCreateCdcJob() throws Exception { testCreateCdcJob(cdcJobDefinitionDto()); checkCdcJobDefinitionAndSaSession(); } @Test @Order(2) public void testGetCdcJobDefinition() throws Exception { MockHttpServletResponse response = mockMvc.perform( MockMvcRequestBuilders.get(cdcJobDefinitionPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .param("currentPage", "1") .param("pageSize", "10") .param("withConfig", "true")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); PageR<CdcJobDefinition> result = getPageR(response, new TypeReference<PageR<CdcJobDefinition>>() {}); CdcJobDefinitionDTO cdcJobDefinitionDTO = cdcJobDefinitionDto(); assertEquals(1, result.getTotal()); MockHttpServletResponse getCdcJobDefinitionResponse = mockMvc.perform( MockMvcRequestBuilders.get( cdcJobDefinitionPath + "/" + result.getData().get(0).getId()) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); R<CdcJobDefinition> getResult = getR(getCdcJobDefinitionResponse, new TypeReference<R<CdcJobDefinition>>() {}); CdcJobDefinition cdcJobDefinition = getResult.getData(); CdcJobDefinition realRdcJobDefinition = CdcJobDefinition.builder() .name(cdcJobDefinitionDTO.getName()) .config(cdcJobDefinitionDTO.getConfig()) .cdcType(cdcJobDefinitionDTO.getCdcType()) .createUser(cdcJobDefinitionDTO.getCreateUser()) .description(cdcJobDefinitionDTO.getDescription()) .build(); assertEquals(realRdcJobDefinition.getName(), cdcJobDefinition.getName()); assertEquals(realRdcJobDefinition.getDescription(), cdcJobDefinition.getDescription()); assertEquals(realRdcJobDefinition.getConfig(), cdcJobDefinition.getConfig()); assertEquals(realRdcJobDefinition.getCreateUser(), cdcJobDefinition.getCreateUser()); } @Order(3) @Test public void testSearchCdcJobDefinition() throws Exception { testCreateCdcJob(cdcJobDefinitionDtoForSearch()); MockHttpServletResponse listAllResponse = mockMvc.perform( MockMvcRequestBuilders.get(cdcJobDefinitionPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .param("currentPage", "1") .param("pageSize", "10") .param("withConfig", "true")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); PageR<CdcJobDefinition> result = getPageR(listAllResponse, new TypeReference<PageR<CdcJobDefinition>>() {}); assertEquals(2, result.getTotal()); long searchNum1 = getSearchNum("1"); assertEquals(2, searchNum1); long searchNum2 = getSearchNum("21"); assertEquals(1, searchNum2); } private void testCreateCdcJob(CdcJobDefinitionDTO obj) throws Exception { MockHttpServletResponse response = mockMvc.perform( MockMvcRequestBuilders.post(cdcJobDefinitionPath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(obj)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); checkMvcResult(response, 200); } private long getSearchNum(String searchJobName) throws Exception { MockHttpServletResponse searchResponse = mockMvc.perform( MockMvcRequestBuilders.get(cdcJobDefinitionPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .param("jobName", searchJobName) .param("currentPage", "1") .param("pageSize", "10") .param("withConfig", "true")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); PageR<CdcJobDefinition> searchResult = getPageR(searchResponse, new TypeReference<PageR<CdcJobDefinition>>() {}); return searchResult.getTotal(); } @Order(4) @Test public void submitCdcJob() throws Exception { System.setProperty("FLINK_HOME", "/opt/flink"); System.setProperty("ACTION_JAR_PATH", "/opt/flink/jar"); ClusterInfo cluster = new ClusterInfo(); cluster.setId(1); cluster.setClusterName("clusterName"); cluster.setHost("127.0.0.1"); cluster.setPort(8083); cluster.setType("Flink"); cluster.setEnabled(true); mockMvc.perform( MockMvcRequestBuilders.post("/api/cluster") .cookie(cookie) .content(ObjectMapperUtils.toJSON(cluster)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); CdcJobDefinitionDTO cdcJobDefinitionDTO = cdcJobDefinitionDto(); CdcJobSubmitDTO cdcJobSubmitDTO = new CdcJobSubmitDTO(); cdcJobSubmitDTO.setClusterId("1"); mockMvc.perform( MockMvcRequestBuilders.get( cdcJobDefinitionPath + "/" + cdcJobDefinitionDTO.getId()) .cookie(cookie) .accept(MediaType.APPLICATION_JSON_VALUE) .content(ObjectMapperUtils.toJSON(cdcJobSubmitDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); } @Order(4) @Test public void submitDatabaseSyncCdcJob() throws Exception { System.setProperty("FLINK_HOME", "/opt/flink"); System.setProperty("ACTION_JAR_PATH", "/opt/flink/jar"); ClusterInfo cluster = new ClusterInfo(); cluster.setId(2); cluster.setClusterName("clusterName"); cluster.setHost("127.0.0.1"); cluster.setPort(8083); cluster.setType("Flink"); cluster.setEnabled(true); mockMvc.perform( MockMvcRequestBuilders.post("/api/cluster") .cookie(cookie) .content(ObjectMapperUtils.toJSON(cluster)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); CdcJobDefinitionDTO cdcJobDefinitionDTO = cdcDatabaseSyncJobDefinitionDto(); CdcJobSubmitDTO cdcJobSubmitDTO = new CdcJobSubmitDTO(); cdcJobSubmitDTO.setClusterId("2"); mockMvc.perform( MockMvcRequestBuilders.get( cdcJobDefinitionPath + "/" + cdcJobDefinitionDTO.getId()) .cookie(cookie) .accept(MediaType.APPLICATION_JSON_VALUE) .content(ObjectMapperUtils.toJSON(cdcJobSubmitDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); } private void checkCdcJobDefinitionAndSaSession() throws Exception { MockHttpServletResponse getCdcJobDefinitionResponse = mockMvc.perform( MockMvcRequestBuilders.get(cdcJobDefinitionPath + "/" + 1) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); R<CdcJobDefinition> getResult = getR(getCdcJobDefinitionResponse, new TypeReference<R<CdcJobDefinition>>() {}); LoginDTO login = new LoginDTO(); login.setUsername("admin"); login.setPassword("admin"); MockHttpServletResponse getLoginUserResponse = mockMvc.perform( MockMvcRequestBuilders.post("/api/login") .content(ObjectMapperUtils.toJSON(login)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse(); R<UserInfoVO> getLoginuser = getR(getLoginUserResponse, new TypeReference<R<UserInfoVO>>() {}); assertEquals( getResult.getData().getCreateUser(), getLoginuser.getData().getUser().getUsername()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/SysMenuControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/SysMenuControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.SysMenu; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.tree.TreeSelect; import org.apache.paimon.web.server.data.vo.RoleMenuTreeselectVO; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link SysMenuController}. */ @SpringBootTest @AutoConfigureMockMvc public class SysMenuControllerTest extends ControllerTestBase { private static final String menuPath = "/api/menu"; @Test public void testList() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.get(menuPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<SysMenu>> r = ObjectMapperUtils.fromJSON(result, new TypeReference<R<List<SysMenu>>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertTrue(r.getData().size() > 0); } @Test public void testGetInfo() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.get(menuPath + "/1") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<SysMenu> r = ObjectMapperUtils.fromJSON(result, new TypeReference<R<SysMenu>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(1, (int) r.getData().getId()); } @Test public void testGetTreeselect() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.get(menuPath + "/treeselect") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<TreeSelect>> r = ObjectMapperUtils.fromJSON(result, new TypeReference<R<List<TreeSelect>>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertTrue(r.getData().size() > 0); } @Test public void testGetRoleMenuTreeselect() throws Exception { String result = mockMvc.perform( MockMvcRequestBuilders.get(menuPath + "/roleMenuTreeselect/1") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<RoleMenuTreeselectVO> r = ObjectMapperUtils.fromJSON(result, new TypeReference<R<RoleMenuTreeselectVO>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertNotNull(r.getData().getMenus()); assertNotNull(r.getData().getCheckedKeys()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/PermissionTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/PermissionTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.data.vo.UserVO; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; /** Test of permission service. */ @SpringBootTest @AutoConfigureMockMvc public class PermissionTest extends ControllerTestBase { private static final String getUserPath = "/api/user"; @Test public void testNoPermission() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(getUserPath + "/" + 1) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<UserVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<UserVO>>() {}); assertEquals(Status.SUCCESS.getCode(), r.getCode()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/TableControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/TableControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.AlterTableDTO; import org.apache.paimon.web.server.data.dto.CatalogDTO; import org.apache.paimon.web.server.data.dto.DatabaseDTO; import org.apache.paimon.web.server.data.dto.TableDTO; import org.apache.paimon.web.server.data.model.CatalogInfo; import org.apache.paimon.web.server.data.model.TableColumn; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.TableVO; import org.apache.paimon.web.server.util.ObjectMapperUtils; import org.apache.paimon.web.server.util.PaimonDataType; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; /** Test for {@link TableController}. */ public class TableControllerTest extends ControllerTestBase { private static final String catalogPath = "/api/catalog"; private static final String databasePath = "/api/database"; private static final String tablePath = "/api/table"; private static final String catalogName = "paimon_catalog"; private static final String databaseName = "paimon_database"; private static final String tableName = "paimon_table"; private Integer catalogId; @BeforeEach public void setup() throws Exception { CatalogDTO catalog = new CatalogDTO(); catalog.setType("filesystem"); catalog.setName(catalogName); catalog.setWarehouse(tempFile.toUri().toString()); catalog.setDelete(false); // create catalog. mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(catalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // get catalog id. String responseString = mockMvc.perform( MockMvcRequestBuilders.get(catalogPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<CatalogInfo>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<CatalogInfo>>>() {}); catalogId = r.getData().get(0).getId(); // create database. DatabaseDTO database = new DatabaseDTO(); database.setCatalogId(catalogId); database.setName(databaseName); database.setCatalogName(catalogName); database.setIgnoreIfExists(true); mockMvc.perform( MockMvcRequestBuilders.post(databasePath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(database)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // create table. List<TableColumn> tableColumns = new ArrayList<>(); TableColumn id = TableColumn.builder() .field("id") .dataType(PaimonDataType.builder().type("INT").build()) .comment("pk") .isPk(true) .defaultValue("") .build(); TableColumn name = TableColumn.builder() .field("name") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("") .isPk(false) .defaultValue("") .build(); TableColumn age = TableColumn.builder() .field("age") .dataType(PaimonDataType.builder().type("INT").build()) .comment("") .isPk(false) .defaultValue("0") .build(); TableColumn createTime = TableColumn.builder() .field("create_time") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("partition key") .isPk(true) .defaultValue("0") .build(); tableColumns.add(id); tableColumns.add(name); tableColumns.add(age); tableColumns.add(createTime); List<String> partitionKey = Lists.newArrayList("create_time"); Map<String, String> tableOptions = ImmutableMap.of("bucket", "2"); TableDTO table = TableDTO.builder() .catalogName(catalogName) .databaseName(databaseName) .name(tableName) .tableColumns(tableColumns) .partitionKey(partitionKey) .tableOptions(tableOptions) .build(); mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(table)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); } @AfterEach public void after() throws Exception { mockMvc.perform( MockMvcRequestBuilders.delete( tablePath + "/drop/" + catalogName + "/" + databaseName + "/" + tableName) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)); CatalogDTO removeCatalog = new CatalogDTO(); removeCatalog.setId(catalogId); removeCatalog.setName(catalogName); mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/remove") .cookie(cookie) .content(ObjectMapperUtils.toJSON(removeCatalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testCreateTable() throws Exception { List<TableColumn> tableColumns = new ArrayList<>(); TableColumn id = TableColumn.builder() .field("f1") .dataType(PaimonDataType.builder().type("INT").build()) .build(); tableColumns.add(id); TableDTO table = TableDTO.builder() .catalogName(catalogName) .databaseName(databaseName) .name("test_table") .tableColumns(tableColumns) .build(); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(table)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); List<TableVO> tables = getTables(); assertFalse(tables.isEmpty()); assertEquals("test_table", tables.get(1).getName()); } @Test public void testAddColumn() throws Exception { List<TableColumn> tableColumns = new ArrayList<>(); TableColumn address = TableColumn.builder() .field("address") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("") .isPk(false) .defaultValue("") .build(); tableColumns.add(address); TableDTO table = TableDTO.builder() .catalogName(catalogName) .databaseName(databaseName) .name(tableName) .tableColumns(tableColumns) .partitionKey(Lists.newArrayList()) .tableOptions(Maps.newHashMap()) .build(); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/column/add") .cookie(cookie) .content(ObjectMapperUtils.toJSON(table)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); assertEquals(5, getColumns().size()); List<String> actualColumnNames = getColumns().stream().map(TableColumn::getField).collect(Collectors.toList()); List<String> expectedColumnNamesList = Arrays.asList("id", "name", "age", "create_time", "address"); assertEquals(expectedColumnNamesList, actualColumnNames); } @Test public void testDropColumn() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.delete( tablePath + "/column/drop/" + catalogName + "/" + databaseName + "/" + tableName + "/" + "name") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); assertEquals(3, getColumns().size()); List<String> actualColumnNames = getColumns().stream().map(TableColumn::getField).collect(Collectors.toList()); List<String> expectedColumnNamesList = Arrays.asList("id", "age", "create_time"); assertEquals(expectedColumnNamesList, actualColumnNames); // drop primary key. String responsePkStr = mockMvc.perform( MockMvcRequestBuilders.delete( tablePath + "/column/drop/" + catalogName + "/" + databaseName + "/" + tableName + "/" + "id") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .locale(Locale.US) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> pkRes = ObjectMapperUtils.fromJSON(responsePkStr, new TypeReference<R<Void>>() {}); assertEquals(10506, pkRes.getCode()); assertEquals("Exception calling Paimon Catalog API to drop a column.", pkRes.getMsg()); // drop partition key. String responsePartitionKeyStr = mockMvc.perform( MockMvcRequestBuilders.delete( tablePath + "/column/drop/" + catalogName + "/" + databaseName + "/" + tableName + "/" + "create_time") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .locale(Locale.US) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> partitionKeyRes = ObjectMapperUtils.fromJSON( responsePartitionKeyStr, new TypeReference<R<Void>>() {}); assertEquals(10506, partitionKeyRes.getCode()); assertEquals( "Exception calling Paimon Catalog API to drop a column.", partitionKeyRes.getMsg()); } @Test public void testAlterTable() throws Exception { // before modification. List<TableColumn> columns = getColumns(); assertEquals(4, columns.size()); List<String> actualColumnNames = columns.stream().map(TableColumn::getField).collect(Collectors.toList()); List<String> expectedColumnNamesList = Arrays.asList("id", "name", "age", "create_time"); assertEquals(expectedColumnNamesList, actualColumnNames); List<TableColumn> tableColumns = new ArrayList<>(); TableColumn id = TableColumn.builder() .id(0) .field("id") .dataType(PaimonDataType.builder().type("INT").build()) .comment("pk") .isPk(true) .defaultValue("") .sort(2) .build(); TableColumn name = TableColumn.builder() .id(1) .field("name") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("") .isPk(false) .defaultValue("") .sort(3) .build(); TableColumn age = TableColumn.builder() .id(2) .field("age1") .dataType(PaimonDataType.builder().type("BIGINT").build()) .comment("") .isPk(false) .defaultValue("0") .sort(0) .build(); TableColumn createTime = TableColumn.builder() .id(3) .field("create_time") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("partition key") .isPk(true) .defaultValue("1970-01-01 00:00:00") .sort(1) .build(); tableColumns.add(id); tableColumns.add(name); tableColumns.add(age); tableColumns.add(createTime); AlterTableDTO alterTableDTO = AlterTableDTO.builder() .catalogName(catalogName) .databaseName(databaseName) .tableName(tableName) .tableColumns(tableColumns) .build(); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/alter") .cookie(cookie) .content(ObjectMapperUtils.toJSON(alterTableDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); // after modification. columns = getColumns(); List<String> afterActualColumnNames = columns.stream().map(TableColumn::getField).collect(Collectors.toList()); List<String> afterExpectedColumnNamesList = Arrays.asList("age1", "create_time", "id", "name"); assertEquals(afterExpectedColumnNamesList, afterActualColumnNames); TableColumn age1Column = columns.stream() .filter(column -> "age1".equals(column.getField())) .findFirst() .orElse(null); assert age1Column != null; assertEquals("BIGINT", age1Column.getDataType().getType()); TableColumn createTimeColumn = columns.stream() .filter(column -> "create_time".equals(column.getField())) .findFirst() .orElse(null); assert createTimeColumn != null; assertEquals("1970-01-01 00:00:00", createTimeColumn.getDefaultValue()); } @Test public void testAddOption() throws Exception { Map<String, String> option = new HashMap<>(); option.put("bucket", "4"); TableDTO table = TableDTO.builder() .catalogName(catalogName) .databaseName(databaseName) .name(tableName) .tableColumns(Lists.newArrayList()) .partitionKey(Lists.newArrayList()) .tableOptions(option) .build(); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/option/add") .cookie(cookie) .content(ObjectMapperUtils.toJSON(table)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); } @Test public void testRemoveOption() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/option/remove") .cookie(cookie) .param("catalogName", catalogName) .param("databaseName", databaseName) .param("tableName", tableName) .param("key", "bucket") .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); } @Test public void testRenameTable() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/rename") .cookie(cookie) .param("catalogName", catalogName) .param("databaseName", databaseName) .param("fromTableName", tableName) .param("toTableName", "test_table_01") .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); assertEquals("test_table_01", getTables().get(0).getName()); mockMvc.perform( MockMvcRequestBuilders.delete( tablePath + "/drop/" + catalogName + "/" + databaseName + "/" + "test_table_01") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)); } @Test public void testListTables() throws Exception { TableDTO table = new TableDTO(); table.setCatalogId(catalogId); table.setDatabaseName(databaseName); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/list") .cookie(cookie) .content(ObjectMapperUtils.toJSON(table)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<TableVO>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<TableVO>>>() {}); assertEquals(200, r.getCode()); assertEquals(1, r.getData().size()); assertEquals(tableName, r.getData().get(0).getName()); } @Test public void testListColumns() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(tablePath + "/column/list") .cookie(cookie) .param("catalogName", catalogName) .param("databaseName", databaseName) .param("tableName", tableName) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<TableVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<TableVO>>() {}); assertEquals(200, r.getCode()); assertEquals(4, r.getData().getColumns().size()); } private List<TableColumn> getColumns() throws Exception { String contentAsString = mockMvc.perform( MockMvcRequestBuilders.get(tablePath + "/column/list") .cookie(cookie) .param("catalogName", catalogName) .param("databaseName", databaseName) .param("tableName", tableName) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<TableVO> columnRes = ObjectMapperUtils.fromJSON(contentAsString, new TypeReference<R<TableVO>>() {}); return columnRes.getData().getColumns(); } private List<TableVO> getTables() throws Exception { TableDTO table = new TableDTO(); table.setCatalogId(catalogId); table.setDatabaseName(databaseName); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/list") .cookie(cookie) .content(ObjectMapperUtils.toJSON(table)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<TableVO>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<TableVO>>>() {}); return r.getData(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/DatabaseControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/DatabaseControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.CatalogDTO; import org.apache.paimon.web.server.data.dto.DatabaseDTO; import org.apache.paimon.web.server.data.model.CatalogInfo; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.DatabaseVO; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** Test for {@link DatabaseController}. */ @SpringBootTest @AutoConfigureMockMvc public class DatabaseControllerTest extends ControllerTestBase { private static final String catalogPath = "/api/catalog"; private static final String databasePath = "/api/database"; private static final String databaseName = "test_db"; private static final String catalogName = "paimon_catalog"; private Integer catalogId; @BeforeEach public void setup() throws Exception { CatalogDTO catalog = new CatalogDTO(); catalog.setType("filesystem"); catalog.setName(catalogName); catalog.setWarehouse(tempFile.toUri().toString()); catalog.setDelete(false); // create catalog. mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(catalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // get catalog id. String responseString = mockMvc.perform( MockMvcRequestBuilders.get(catalogPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<CatalogInfo>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<CatalogInfo>>>() {}); catalogId = r.getData().get(0).getId(); // create database. DatabaseDTO database = new DatabaseDTO(); database.setCatalogId(catalogId); database.setName(databaseName); database.setCatalogName(catalogName); database.setIgnoreIfExists(true); mockMvc.perform( MockMvcRequestBuilders.post(databasePath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(database)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); } @AfterEach public void after() throws Exception { DatabaseDTO dropDatabase = new DatabaseDTO(); dropDatabase.setCatalogName(catalogName); dropDatabase.setCatalogId(catalogId); dropDatabase.setName(databaseName); dropDatabase.setIgnoreIfExists(true); dropDatabase.setCascade(true); mockMvc.perform( MockMvcRequestBuilders.post(databasePath + "/drop") .cookie(cookie) .content(ObjectMapperUtils.toJSON(dropDatabase)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); CatalogDTO removeCatalog = new CatalogDTO(); removeCatalog.setId(catalogId); removeCatalog.setName(catalogName); mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/remove") .cookie(cookie) .content(ObjectMapperUtils.toJSON(removeCatalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testListDatabases() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(databasePath + "/list") .cookie(cookie) .param("catalogId", String.valueOf(catalogId)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<DatabaseVO>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<DatabaseVO>>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(1, r.getData().size()); assertEquals(databaseName, r.getData().get(0).getName()); } @Test public void testDropDatabase() throws Exception { DatabaseDTO dropDatabase = new DatabaseDTO(); dropDatabase.setCatalogName(catalogName); dropDatabase.setCatalogId(catalogId); dropDatabase.setName(databaseName); dropDatabase.setIgnoreIfExists(true); dropDatabase.setCascade(true); String responseString = mockMvc.perform( MockMvcRequestBuilders.post(databasePath + "/drop") .cookie(cookie) .content(ObjectMapperUtils.toJSON(dropDatabase)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> remove = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, remove.getCode()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/MetadataControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/MetadataControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.data.BinaryString; import org.apache.paimon.data.GenericRow; import org.apache.paimon.table.Table; import org.apache.paimon.table.sink.BatchTableCommit; import org.apache.paimon.table.sink.BatchTableWrite; import org.apache.paimon.table.sink.BatchWriteBuilder; import org.apache.paimon.table.sink.CommitMessage; import org.apache.paimon.table.sink.CommitMessageImpl; import org.apache.paimon.web.api.catalog.PaimonService; import org.apache.paimon.web.server.data.dto.CatalogDTO; import org.apache.paimon.web.server.data.dto.DatabaseDTO; import org.apache.paimon.web.server.data.dto.MetadataDTO; import org.apache.paimon.web.server.data.dto.TableDTO; import org.apache.paimon.web.server.data.model.CatalogInfo; import org.apache.paimon.web.server.data.model.MetadataFieldsModel; import org.apache.paimon.web.server.data.model.MetadataOptionModel; import org.apache.paimon.web.server.data.model.TableColumn; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.DataFileVO; import org.apache.paimon.web.server.data.vo.ManifestsVO; import org.apache.paimon.web.server.data.vo.OptionVO; import org.apache.paimon.web.server.data.vo.SchemaVO; import org.apache.paimon.web.server.data.vo.SnapshotVO; import org.apache.paimon.web.server.util.ObjectMapperUtils; import org.apache.paimon.web.server.util.PaimonDataType; import org.apache.paimon.web.server.util.PaimonServiceUtils; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Tests for {@link MetadataController}. */ @SpringBootTest @AutoConfigureMockMvc public class MetadataControllerTest extends ControllerTestBase { private static final String catalogPath = "/api/catalog"; private static final String databasePath = "/api/database"; private static final String METADATA_PATH = "/api/metadata/query"; private static final String tablePath = "/api/table"; private static final String catalogName = "paimon_catalog"; private static final String databaseName = "paimon_database"; private static final String tableName = "paimon_table"; private Integer catalogId; private List<CommitMessage> messages; @BeforeEach public void setup() throws Exception { CatalogDTO catalog = new CatalogDTO(); catalog.setType("filesystem"); catalog.setName(catalogName); catalog.setWarehouse(tempFile.toUri().toString()); catalog.setDelete(false); // create catalog. mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(catalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // get catalog id. String responseString = mockMvc.perform( MockMvcRequestBuilders.get(catalogPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<CatalogInfo>> r = ObjectMapperUtils.fromJSON( responseString, new TypeReference<R<List<CatalogInfo>>>() {}); catalogId = r.getData().get(0).getId(); // create database. DatabaseDTO database = new DatabaseDTO(); database.setCatalogId(catalogId); database.setName(databaseName); database.setCatalogName(catalogName); database.setIgnoreIfExists(true); mockMvc.perform( MockMvcRequestBuilders.post(databasePath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(database)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // create table. List<TableColumn> tableColumns = new ArrayList<>(); TableColumn id = TableColumn.builder() .field("id") .dataType(PaimonDataType.builder().type("INT").build()) .comment("pk") .isPk(true) .defaultValue("") .build(); TableColumn name = TableColumn.builder() .field("name") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("") .isPk(false) .defaultValue("") .build(); TableColumn age = TableColumn.builder() .field("age") .dataType(PaimonDataType.builder().type("INT").build()) .comment("") .isPk(false) .defaultValue("0") .build(); TableColumn createTime = TableColumn.builder() .field("create_time") .dataType(PaimonDataType.builder().type("STRING").build()) .comment("partition key") .isPk(true) .defaultValue("0") .build(); tableColumns.add(id); tableColumns.add(name); tableColumns.add(age); tableColumns.add(createTime); List<String> partitionKey = Lists.newArrayList("create_time"); Map<String, String> tableOptions = ImmutableMap.of("bucket", "2"); TableDTO tableDTO = TableDTO.builder() .catalogName(catalogName) .databaseName(databaseName) .name(tableName) .tableColumns(tableColumns) .partitionKey(partitionKey) .tableOptions(tableOptions) .build(); mockMvc.perform( MockMvcRequestBuilders.post(tablePath + "/create") .cookie(cookie) .content(ObjectMapperUtils.toJSON(tableDTO)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); // insert CatalogInfo catalogInfo = CatalogInfo.builder() .catalogName(catalog.getName()) .catalogType(catalog.getType()) .warehouse(catalog.getWarehouse()) .build(); PaimonService paimonService = PaimonServiceUtils.getPaimonService(catalogInfo); Table table = paimonService.getTable(databaseName, tableName); BatchWriteBuilder writeBuilder = table.newBatchWriteBuilder().withOverwrite(); BatchTableWrite write = writeBuilder.newWrite(); GenericRow record1 = GenericRow.of( 1, BinaryString.fromString("Alice"), 24, BinaryString.fromString("2023-12-04 00:00:00")); GenericRow record2 = GenericRow.of( 2, BinaryString.fromString("Bob"), 28, BinaryString.fromString("2023-10-11 00:00:00")); GenericRow record3 = GenericRow.of( 3, BinaryString.fromString("Emily"), 32, BinaryString.fromString("2023-10-04 00:00:00")); write.write(record1); write.write(record2); write.write(record3); messages = write.prepareCommit(); BatchTableCommit commit = writeBuilder.newCommit(); commit.commit(messages); write.close(); commit.close(); } @AfterEach public void after() throws Exception { mockMvc.perform( MockMvcRequestBuilders.delete( tablePath + "/drop/" + catalogName + "/" + databaseName + "/" + tableName) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)); CatalogDTO removeCatalog = new CatalogDTO(); removeCatalog.setId(catalogId); removeCatalog.setName(catalogName); mockMvc.perform( MockMvcRequestBuilders.post(catalogPath + "/remove") .cookie(cookie) .content(ObjectMapperUtils.toJSON(removeCatalog)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testGetSchemaInfo() throws Exception { MetadataDTO metadata = new MetadataDTO(); metadata.setCatalogId(catalogId); metadata.setDatabaseName(databaseName); metadata.setTableName(tableName); String response = mockMvc.perform( MockMvcRequestBuilders.post(METADATA_PATH + "/schema") .cookie(cookie) .content(ObjectMapperUtils.toJSON(metadata)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<SchemaVO>> result = ObjectMapperUtils.fromJSON(response, new TypeReference<R<List<SchemaVO>>>() {}); List<SchemaVO> schemaVOS = result.getData(); assertEquals(200, result.getCode()); assertFalse(schemaVOS.isEmpty()); assertEquals(1, schemaVOS.size()); // Make assertions on each field of the SchemaVO class. SchemaVO schemaVO = schemaVOS.get(0); assertNotNull(schemaVO.getUpdateTime()); assertEquals(0, schemaVO.getSchemaId()); assertEquals("[\"id\",\"create_time\"]", schemaVO.getPrimaryKeys()); assertEquals("[\"create_time\"]", schemaVO.getPartitionKeys()); assertEquals("", schemaVO.getComment()); assertEquals(4, schemaVO.getFields().size()); ArrayList<MetadataFieldsModel> expectedFields = Lists.newArrayList( new MetadataFieldsModel(0, "id", "INT NOT NULL", "pk"), new MetadataFieldsModel(1, "name", "STRING NOT NULL", ""), new MetadataFieldsModel(2, "age", "INT NOT NULL", ""), new MetadataFieldsModel( 3, "create_time", "STRING NOT NULL", "partition key")); assertEquals(expectedFields, schemaVO.getFields()); assertEquals(3, schemaVO.getOption().size()); ArrayList<MetadataOptionModel> expectedOptions = Lists.newArrayList( new MetadataOptionModel("bucket", "2"), new MetadataOptionModel("FIELDS.create_time.default-value", "0"), new MetadataOptionModel("FIELDS.age.default-value", "0")); assertEquals(expectedOptions, schemaVO.getOption()); } @Test public void testGetManifestInfo() throws Exception { MetadataDTO metadata = new MetadataDTO(); metadata.setCatalogId(catalogId); metadata.setDatabaseName(databaseName); metadata.setTableName(tableName); String response = mockMvc.perform( MockMvcRequestBuilders.post(METADATA_PATH + "/manifest") .cookie(cookie) .content(ObjectMapperUtils.toJSON(metadata)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<ManifestsVO>> result = ObjectMapperUtils.fromJSON(response, new TypeReference<R<List<ManifestsVO>>>() {}); assertEquals(200, result.getCode()); List<ManifestsVO> manifestsVOS = result.getData(); assertFalse(manifestsVOS.isEmpty()); // Make assertions on each field of the ManifestsVO class. ManifestsVO manifestsVO = manifestsVOS.get(0); assertNotNull(manifestsVO.getFileName()); assertTrue(manifestsVO.getFileSize() > 0); assertEquals(3, manifestsVO.getNumAddedFiles()); assertEquals(0, manifestsVO.getNumDeletedFiles()); assertEquals(0, manifestsVO.getSchemaId()); } @Test public void testGetDataFileInfo() throws Exception { MetadataDTO metadata = new MetadataDTO(); metadata.setCatalogId(catalogId); metadata.setDatabaseName(databaseName); metadata.setTableName(tableName); String response = mockMvc.perform( MockMvcRequestBuilders.post(METADATA_PATH + "/dataFile") .cookie(cookie) .content(ObjectMapperUtils.toJSON(metadata)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<DataFileVO>> result = ObjectMapperUtils.fromJSON(response, new TypeReference<R<List<DataFileVO>>>() {}); assertEquals(200, result.getCode()); List<DataFileVO> dataFileVOS = result.getData(); assertFalse(dataFileVOS.isEmpty()); assertEquals(3, dataFileVOS.size()); // Make assertions on each field of the DataFileVO class. DataFileVO dataFileVO = dataFileVOS.get(0); CommitMessageImpl commitMessage = (CommitMessageImpl) messages.get(0); assertEquals("[2023-12-04 00:00:00]", dataFileVO.getPartition()); assertEquals(0, dataFileVO.getBucket()); assertNotNull(dataFileVO.getFilePath()); assertEquals("orc", dataFileVO.getFileFormat()); assertEquals(0, dataFileVO.getLevel()); assertEquals(1, dataFileVO.getRecordCount()); assertEquals( commitMessage.newFilesIncrement().newFiles().get(0).fileSize(), dataFileVO.getFileSizeInBytes()); assertEquals("[1]", dataFileVO.getMinKey()); assertEquals("[1]", dataFileVO.getMaxKey()); assertEquals("{age=0, create_time=0, id=0, name=0}", dataFileVO.getNullValueCounts()); assertEquals( "{age=24, create_time=2023-12-04 00:00, id=1, name=Alice}", dataFileVO.getMinValueStats()); assertEquals( "{age=24, create_time=2023-12-04 00:01, id=1, name=Alice}", dataFileVO.getMaxValueStats()); assertEquals(0, dataFileVO.getMinSequenceNumber()); assertEquals(0, dataFileVO.getMaxSequenceNumber()); assertEquals( commitMessage.newFilesIncrement().newFiles().get(0).creationTimeEpochMillis(), dataFileVO .getCreationTime() .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); List<String> actualPartitions = new ArrayList<>(); List<String> expectedPartitions = Lists.newArrayList( "[2023-12-04 00:00:00]", "[2023-10-11 00:00:00]", "[2023-10-04 00:00:00]"); dataFileVOS.forEach(item -> actualPartitions.add(item.getPartition())); assertEquals(actualPartitions, expectedPartitions); List<String> actualFilePaths = new ArrayList<>(); dataFileVOS.forEach(item -> actualFilePaths.add(item.getFilePath())); List<String> expectedFilePaths = new ArrayList<>(); messages.forEach( item -> { CommitMessageImpl message = (CommitMessageImpl) item; expectedFilePaths.add(message.newFilesIncrement().newFiles().get(0).fileName()); }); assertEquals(actualFilePaths, expectedFilePaths); } @Test public void testGetSnapshotInfo() throws Exception { MetadataDTO metadata = new MetadataDTO(); metadata.setCatalogId(catalogId); metadata.setDatabaseName(databaseName); metadata.setTableName(tableName); String response = mockMvc.perform( MockMvcRequestBuilders.post(METADATA_PATH + "/snapshot") .cookie(cookie) .content(ObjectMapperUtils.toJSON(metadata)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<SnapshotVO>> result = ObjectMapperUtils.fromJSON(response, new TypeReference<R<List<SnapshotVO>>>() {}); assertEquals(200, result.getCode()); List<SnapshotVO> snapshotVOS = result.getData(); assertFalse(snapshotVOS.isEmpty()); assertEquals(1, snapshotVOS.size()); // Make assertions on each field of the SnapshotVO class. SnapshotVO snapshotVO = snapshotVOS.get(0); assertEquals(1, snapshotVO.getSnapshotId()); assertEquals(0, snapshotVO.getSchemaId()); assertFalse(snapshotVO.getCommitUser().isEmpty()); assertEquals("OVERWRITE", snapshotVO.getCommitKind()); assertTrue(snapshotVO.getCommitIdentifier() > 0); assertTrue(snapshotVO.getCommitTime().isBefore(LocalDateTime.now())); assertEquals(0, snapshotVO.getSchemaId()); assertFalse(snapshotVO.getDeltaManifestList().isEmpty()); assertFalse(snapshotVO.getBaseManifestList().isEmpty()); assertEquals("", snapshotVO.getChangelogManifestList()); assertEquals(3, snapshotVO.getTotalRecordCount()); assertEquals(3, snapshotVO.getDeltaRecordCount()); assertEquals(0, snapshotVO.getChangelogRecordCount()); assertNull(snapshotVO.getWatermark()); } @Test public void testGetOptionInfo() throws Exception { MetadataDTO metadata = new MetadataDTO(); metadata.setCatalogId(catalogId); metadata.setDatabaseName(databaseName); metadata.setTableName(tableName); String response = mockMvc.perform( MockMvcRequestBuilders.post(METADATA_PATH + "/options") .cookie(cookie) .content(ObjectMapperUtils.toJSON(metadata)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<List<OptionVO>> result = ObjectMapperUtils.fromJSON(response, new TypeReference<R<List<OptionVO>>>() {}); assertEquals(200, result.getCode()); List<OptionVO> expected = Arrays.asList( new OptionVO("bucket", "2"), new OptionVO("FIELDS.create_time.default-value", "0"), new OptionVO("FIELDS.age.default-value", "0")); assertEquals(expected, result.getData()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/UserControllerTest.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/controller/UserControllerTest.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.enums.UserType; import org.apache.paimon.web.server.data.model.User; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.UserVO; import org.apache.paimon.web.server.mapper.UserMapper; import org.apache.paimon.web.server.util.ObjectMapperUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Test for {@link UserController}. */ @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class UserControllerTest extends ControllerTestBase { private static final String userPath = "/api/user"; private static final int userId = 3; private static final String username = "test"; @Autowired private UserMapper userMapper; @Test @Order(1) public void testAddUser() throws Exception { User user = new User(); user.setId(userId); user.setUsername(username); user.setNickname(username); user.setPassword("test"); user.setUserType(UserType.LOCAL); user.setEnabled(true); mockMvc.perform( MockMvcRequestBuilders.post(userPath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(user)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); } @Test @Order(2) public void testGetUser() throws Exception { UserVO user = getUser(userId); assertNotNull(user); assertEquals(user.getUsername(), username); assertNotNull(user.getCreateTime()); assertNotNull(user.getUpdateTime()); } @Test @Order(3) public void testUpdateUser() throws Exception { String newUserName = username + "-edit"; User user = new User(); user.setId(userId); user.setUsername(newUserName); user.setNickname(newUserName); user.setUserType(UserType.LOCAL); user.setEnabled(true); mockMvc.perform( MockMvcRequestBuilders.put(userPath) .cookie(cookie) .content(ObjectMapperUtils.toJSON(user)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(userPath + "/" + userId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<UserVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<UserVO>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertEquals(r.getData().getUsername(), newUserName); } @Test @Order(4) public void testAllocateRole() throws Exception { User user = new User(); user.setId(userId); user.setUsername(username); user.setNickname(username); user.setUserType(UserType.LOCAL); user.setEnabled(true); user.setRoleIds(new Integer[] {2}); mockMvc.perform( MockMvcRequestBuilders.post(userPath + "/allocate") .cookie(cookie) .content(ObjectMapperUtils.toJSON(user)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); String responseString = mockMvc.perform( MockMvcRequestBuilders.get(userPath + "/" + userId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<UserVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<UserVO>>() {}); assertEquals(200, r.getCode()); assertNotNull(r.getData()); assertTrue(r.getData().getRoles().size() > 0); assertEquals("common", r.getData().getRoles().get(0).getRoleName()); } @Test @Order(5) public void testListUsers() throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(userPath + "/list") .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); PageR<UserVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<PageR<UserVO>>() {}); assertTrue( r.getData() != null && ((r.getTotal() > 0 && r.getData().size() > 0) || (r.getTotal() == 0 && r.getData().size() == 0))); UserVO firstUser = r.getData().get(0); assertEquals("admin", firstUser.getUsername()); assertEquals("Admin", firstUser.getNickname()); assertEquals("admin@paimon.com", firstUser.getEmail()); assertEquals(UserType.LOCAL, firstUser.getUserType()); assertNotNull(firstUser.getCreateTime()); assertNotNull(firstUser.getUpdateTime()); assertTrue(firstUser.getEnabled()); UserVO secondUser = r.getData().get(1); assertEquals("common", secondUser.getUsername()); assertEquals("common", secondUser.getNickname()); assertEquals("common@paimon.com", secondUser.getEmail()); assertEquals(UserType.LOCAL, secondUser.getUserType()); assertNotNull(secondUser.getCreateTime()); assertNotNull(secondUser.getUpdateTime()); assertTrue(secondUser.getEnabled()); } @Test @Order(6) public void testChangeUserStatus() throws Exception { User user = new User(); user.setId(2); user.setEnabled(false); String responseString = mockMvc.perform( MockMvcRequestBuilders.put(userPath + "/changeStatus") .cookie(cookie) .content(ObjectMapperUtils.toJSON(user)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<Void> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<Void>>() {}); assertEquals(200, r.getCode()); UserVO changeUser = getUser(2); assertEquals(changeUser.getEnabled(), false); } @Test @Order(7) public void testDeleteUser() throws Exception { String delResponseString = mockMvc.perform( MockMvcRequestBuilders.delete( userPath + "/" + userId + "," + userId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<?> result = ObjectMapperUtils.fromJSON(delResponseString, R.class); assertEquals(200, result.getCode()); } @Test @Order(8) public void testChangePassword() throws Exception { User user = new User(); user.setId(2); user.setPassword("common"); mockMvc.perform( MockMvcRequestBuilders.post(userPath + "/change/password") .cookie(cookie) .content(ObjectMapperUtils.toJSON(user)) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); User newUser = userMapper.selectById(2); assertEquals("9efab2399c7c560b34de477b9aa0a465", newUser.getPassword()); } @Test @Order(9) public void testValidMobile() { String validMobile = "13411112222"; User user = new User(); user.setUsername(username); user.setMobile(validMobile); user.setRoleIds(new Integer[] {1}); user.setEmail("test@paimon.com"); Set<ConstraintViolation<User>> violations = getValidator().validate(user); assertTrue(violations.isEmpty()); } @Test @Order(10) public void testInvalidMobile() { String inValidMobile = "12311112222"; User user = new User(); user.setUsername(username); user.setMobile(inValidMobile); user.setRoleIds(new Integer[] {1}); user.setEmail("test@paimon.com"); Set<ConstraintViolation<User>> violations = getValidator().validate(user); assertEquals(1, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("invalid.phone.format", violation.getMessageTemplate()); } @Test @Order(11) public void testValidEmail() { String validEmail = "test@paimon.com"; User user = new User(); user.setUsername(username); user.setMobile("13311112222"); user.setRoleIds(new Integer[] {1}); user.setEmail(validEmail); Set<ConstraintViolation<User>> violations = getValidator().validate(user); assertTrue(violations.isEmpty()); } @Test @Order(12) public void testInvalidEmail() { String inValidEmail = "paimon.com"; User user = new User(); user.setUsername(username); user.setMobile("13311112222"); user.setRoleIds(new Integer[] {1}); user.setEmail(inValidEmail); Set<ConstraintViolation<User>> violations = getValidator().validate(user); assertEquals(1, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("invalid.email.format", violation.getMessageTemplate()); } private UserVO getUser(Integer userId) throws Exception { String responseString = mockMvc.perform( MockMvcRequestBuilders.get(userPath + "/" + userId) .cookie(cookie) .contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn() .getResponse() .getContentAsString(); R<UserVO> r = ObjectMapperUtils.fromJSON(responseString, new TypeReference<R<UserVO>>() {}); assertEquals(200, r.getCode()); return r.getData(); } private Validator getValidator() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); return factory.getValidator(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/util/LRUCacheTests.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/util/LRUCacheTests.java
/* * 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.paimon.web.server.util; import org.junit.Test; import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; /** lru cache test. */ public class LRUCacheTests { @Test public void testLRUCache() { LRUCache<String, String> lruCache = new LRUCache<>(5); for (int i = 0; i < 5; i++) { lruCache.put(String.valueOf(i), String.valueOf(i)); } assertEquals(lruCache.size(), 5); lruCache.put("6", "6"); assertEquals(lruCache.size(), 5); assertNull(lruCache.get("0")); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/constant/StatementsConstant.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/constant/StatementsConstant.java
/* * 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.paimon.web.server.constant; /** Statements constant. */ public class StatementsConstant { public static String statement = "CREATE TABLE IF NOT EXISTS t_order(\n" + " `order_id` BIGINT,\n" + " `product` BIGINT,\n" + " `amount` BIGINT,\n" + " `order_time` as CAST(CURRENT_TIMESTAMP AS TIMESTAMP(3)),\n" + " WATERMARK FOR order_time AS order_time-INTERVAL '2' SECOND\n" + ") WITH(\n" + " 'connector' = 'datagen',\n" + " 'rows-per-second' = '1',\n" + " 'fields.order_id.min' = '1',\n" + " 'fields.order_id.max' = '2',\n" + " 'fields.amount.min' = '1',\n" + " 'fields.amount.max' = '10',\n" + " 'fields.product.min' = '1',\n" + " 'fields.product.max' = '2'\n" + ");\n" + "CREATE TABLE IF NOT EXISTS sink_table(\n" + " `product` BIGINT,\n" + " `amount` BIGINT,\n" + " `order_time` TIMESTAMP(3),\n" + " `one_minute_sum` BIGINT\n" + ") WITH('connector' = 'print');\n" + "\n" + "INSERT INTO\n" + " sink_table\n" + "SELECT\n" + " product,\n" + " amount,\n" + " order_time,\n" + " 0 as one_minute_sum\n" + "FROM\n" + " t_order;"; public static String selectStatement = "CREATE TABLE IF NOT EXISTS t_order(\n" + " `order_id` BIGINT,\n" + " `product` BIGINT,\n" + " `amount` BIGINT,\n" + " `order_time` as CAST(CURRENT_TIMESTAMP AS TIMESTAMP(3)),\n" + " WATERMARK FOR order_time AS order_time-INTERVAL '2' SECOND\n" + ") WITH(\n" + " 'connector' = 'datagen',\n" + " 'rows-per-second' = '1',\n" + " 'fields.order_id.min' = '1',\n" + " 'fields.order_id.max' = '2',\n" + " 'fields.amount.min' = '1',\n" + " 'fields.amount.max' = '10',\n" + " 'fields.product.min' = '1',\n" + " 'fields.product.max' = '2'\n" + ");\n" + "SELECT * FROM t_order;"; }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/configurer/SaTokenConfigurerTests.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/configurer/SaTokenConfigurerTests.java
/* * 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.paimon.web.server.configurer; import org.apache.paimon.web.server.configrue.SaTokenConfigurer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertEquals; /** Test for {@link SaTokenConfigurer}. */ @SpringBootTest @AutoConfigureMockMvc public class SaTokenConfigurerTests { @Value("${interceptor.exclude.path.patterns}") private String[] excludePathPatterns; @Test @Order(1) public void testPathExclude() throws Exception { assertEquals(excludePathPatterns.length, 2); assertEquals(excludePathPatterns[0], "/api/login"); assertEquals(excludePathPatterns[1], "/ui/**"); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/test/java/org/apache/paimon/web/server/configurer/JacksonConfigTests.java
paimon-web-server/src/test/java/org/apache/paimon/web/server/configurer/JacksonConfigTests.java
/* * 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.paimon.web.server.configurer; import org.apache.paimon.web.server.configrue.JacksonConfig; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** Test for {@link JacksonConfig}. */ @SpringBootTest public class JacksonConfigTests { @Autowired private ObjectMapper objectMapper; private static final String DATE_TIME_FORMATTED_JSON_STR = "\"2024-06-26 13:01:30\""; private static final String DATE_TIME_UNFORMATTED_JSON_STR = "\"2024-06-26T13:01:30Z\""; private static final String DATE_FORMATTED_JSON_STR = "\"2024-06-26\""; private static final String TIME_FORMATTED_JSON_STR = "\"13:01:30\""; private static final String DATE_TIME_STR = "2024-06-26 13:01:30"; private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; @Test public void testLocalDateTimeSerialization() throws IOException { LocalDateTime dateTime = LocalDateTime.of(2024, 6, 26, 13, 1, 30); String json = objectMapper.writeValueAsString(dateTime); assertEquals(DATE_TIME_FORMATTED_JSON_STR, json); } @Test public void testLocalDateTimeDeserialization() throws IOException { LocalDateTime dateTime = objectMapper.readValue(DATE_TIME_FORMATTED_JSON_STR, LocalDateTime.class); assertEquals(LocalDateTime.of(2024, 6, 26, 13, 1, 30), dateTime); } @Test public void testInvalidLocalDateTimeDeserialization() { assertThrows( com.fasterxml.jackson.databind.exc.InvalidFormatException.class, () -> objectMapper.readValue(DATE_TIME_UNFORMATTED_JSON_STR, LocalDateTime.class)); } @Test public void testLocalDateSerialization() throws IOException { LocalDate dateTime = LocalDate.of(2024, 6, 26); String json = objectMapper.writeValueAsString(dateTime); assertEquals(DATE_FORMATTED_JSON_STR, json); } @Test public void testLocalDateDeserialization() throws IOException { LocalDate dateTime = objectMapper.readValue(DATE_FORMATTED_JSON_STR, LocalDate.class); assertEquals(LocalDate.of(2024, 6, 26), dateTime); } @Test public void testLocalTimeSerialization() throws IOException { LocalTime dateTime = LocalTime.of(13, 1, 30); String json = objectMapper.writeValueAsString(dateTime); assertEquals(TIME_FORMATTED_JSON_STR, json); } @Test public void testLocalTimeDeserialization() throws IOException { LocalTime dateTime = objectMapper.readValue(TIME_FORMATTED_JSON_STR, LocalTime.class); assertEquals(LocalTime.of(13, 1, 30), dateTime); } @Test public void testDateSerialization() throws IOException { Date date = parseDate(DATE_TIME_STR); String json = objectMapper.writeValueAsString(date); assertEquals(DATE_TIME_FORMATTED_JSON_STR, json); } @Test public void testDateDeserialization() throws IOException { Date date = parseDate(DATE_TIME_STR); Date dateDeserialized = objectMapper.readValue(DATE_TIME_FORMATTED_JSON_STR, Date.class); assertEquals(dateDeserialized, date); } private Date parseDate(String date) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(JacksonConfigTests.DATE_TIME_PATTERN); LocalDateTime localDateTime = LocalDateTime.parse(date, formatter); ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId); Instant instant = zonedDateTime.toInstant(); return Date.from(instant); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/PaimonWebServerApplication.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/PaimonWebServerApplication.java
/* * 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.paimon.web.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** Paimon Web Server Application. */ @SpringBootApplication @EnableScheduling public class PaimonWebServerApplication { public static void main(String[] args) { SpringApplication.run(PaimonWebServerApplication.class, args); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/HistoryController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/HistoryController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.History; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.service.HistoryService; import org.apache.paimon.web.server.util.PageSupport; import cn.dev33.satoken.annotation.SaCheckPermission; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** History api controller. */ @RestController @RequestMapping("/api/history") public class HistoryController { @Autowired private HistoryService historyService; @SaCheckPermission("playground:history:query") @GetMapping("/{id}") public R<History> getStatement(@PathVariable("id") Integer id) { return R.succeed(historyService.getById(id)); } @SaCheckPermission("playground:history:list") @GetMapping("/list") public PageR<History> listSelectHistories(History selectHistory) { IPage<History> page = PageSupport.startPage(); List<History> selectHistories = historyService.listHistories(page, selectHistory); return PageR.<History>builder() .success(true) .total(page.getTotal()) .data(selectHistories) .build(); } @SaCheckPermission("playground:history:query") @GetMapping("/all") public R<List<History>> all() { return R.succeed(historyService.list()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/CdcJobDefinitionController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/CdcJobDefinitionController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.CdcJobDefinitionDTO; import org.apache.paimon.web.server.data.dto.CdcJobSubmitDTO; import org.apache.paimon.web.server.data.model.CdcJobDefinition; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.service.CdcJobDefinitionService; import cn.dev33.satoken.annotation.SaCheckPermission; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; /** CdcJobDefinition api controller. */ @Slf4j @Validated @RestController @RequestMapping("/api/cdc-job-definition") public class CdcJobDefinitionController { private CdcJobDefinitionService cdcJobDefinitionService; public CdcJobDefinitionController(CdcJobDefinitionService cdcJobDefinitionService) { this.cdcJobDefinitionService = cdcJobDefinitionService; } @SaCheckPermission("cdc:job:create") @PostMapping("create") public R<Void> createCdcJob(@Valid @RequestBody CdcJobDefinitionDTO cdcJobDefinitionDTO) { return cdcJobDefinitionService.create(cdcJobDefinitionDTO); } @SaCheckPermission("cdc:job:update") @PutMapping("update") public R<Void> updateCdcJob(@Valid @RequestBody CdcJobDefinitionDTO cdcJobDefinitionDTO) { return cdcJobDefinitionService.update(cdcJobDefinitionDTO); } @SaCheckPermission("cdc:job:list") @GetMapping("list") public PageR<CdcJobDefinition> listAllCdcJob( @RequestParam(required = false) boolean withConfig, @RequestParam(required = false) String jobName, @RequestParam long currentPage, @RequestParam long pageSize) { return cdcJobDefinitionService.listAll(jobName, withConfig, currentPage, pageSize); } @SaCheckPermission("cdc:job:query") @GetMapping("/{id}") public R<CdcJobDefinition> getById(@PathVariable Integer id) { CdcJobDefinition cdcJobDefinition = cdcJobDefinitionService.getById(id); if (cdcJobDefinition == null) { return R.failed(); } return R.succeed(cdcJobDefinition); } @SaCheckPermission("cdc:job:delete") @DeleteMapping("{id}") public R<Void> deleteById(@PathVariable Integer id) { cdcJobDefinitionService.removeById(id); return R.succeed(); } @SaCheckPermission("cdc:job:submit") @PostMapping("{id}/submit") public R<Void> submit(@PathVariable Integer id, @RequestBody CdcJobSubmitDTO cdcJobSubmitDTO) { return cdcJobDefinitionService.submit(id, cdcJobSubmitDTO); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/LoginController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/LoginController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.LoginDTO; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.UserInfoVO; import org.apache.paimon.web.server.service.UserService; import cn.dev33.satoken.stp.SaTokenInfo; import cn.dev33.satoken.stp.StpUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** Login api controller. */ @Slf4j @RestController @RequestMapping("/api") public class LoginController { @Autowired private UserService userService; /** * login by username and password. * * @param loginDTO login info * @return token string */ @PostMapping("/login") public R<UserInfoVO> login(@RequestBody LoginDTO loginDTO) { return R.succeed(userService.login(loginDTO)); } /** * get token info. * * @return token info */ @GetMapping("/tokenInfo") public R<SaTokenInfo> tokenInfo() { return R.succeed(StpUtil.getTokenInfo()); } /** logout. */ @PostMapping("/logout") public R<Void> logout() { StpUtil.logout(StpUtil.getLoginIdAsInt()); return R.succeed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/MetadataController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/MetadataController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.MetadataDTO; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.vo.DataFileVO; import org.apache.paimon.web.server.data.vo.ManifestsVO; import org.apache.paimon.web.server.data.vo.OptionVO; import org.apache.paimon.web.server.data.vo.SchemaVO; import org.apache.paimon.web.server.data.vo.SnapshotVO; import org.apache.paimon.web.server.service.MetadataService; import cn.dev33.satoken.annotation.SaCheckPermission; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** Metadata api controller. */ @Slf4j @RestController @RequestMapping("/api/metadata/query") public class MetadataController { private final MetadataService metadataService; public MetadataController(MetadataService metadataService) { this.metadataService = metadataService; } @SaCheckPermission("metadata:schema:list") @PostMapping("/schema") public R<List<SchemaVO>> getSchemaInfo(@RequestBody MetadataDTO dto) { return R.succeed(metadataService.getSchema(dto)); } @SaCheckPermission("metadata:snapshot:list") @PostMapping("/snapshot") public R<List<SnapshotVO>> getSnapshotInfo(@RequestBody MetadataDTO dto) { return R.succeed(metadataService.getSnapshot(dto)); } @SaCheckPermission("metadata:manifest:list") @PostMapping("/manifest") public R<List<ManifestsVO>> getManifestInfo(@RequestBody MetadataDTO dto) { return R.succeed(metadataService.getManifest(dto)); } @SaCheckPermission("metadata:datafile:list") @PostMapping("/dataFile") public R<List<DataFileVO>> getDataFileInfo(@RequestBody MetadataDTO dto) { return R.succeed(metadataService.getDataFile(dto)); } @SaCheckPermission("metadata:options:list") @PostMapping("/options") public R<List<OptionVO>> getOptionInfo(@RequestBody MetadataDTO dto) { return R.succeed(metadataService.getOption(dto)); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/SessionController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/SessionController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.gateway.enums.DeploymentMode; import org.apache.paimon.web.server.data.dto.SessionDTO; import org.apache.paimon.web.server.data.model.ClusterInfo; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.service.ClusterService; import org.apache.paimon.web.server.service.SessionService; import cn.dev33.satoken.stp.StpUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** Session api controller. */ @Slf4j @RestController @RequestMapping("/api/session") public class SessionController { @Autowired private SessionService sessionService; @Autowired private ClusterService clusterService; @PostMapping("/create") @Retryable( value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 3000)) public R<Void> createSession() { if (!StpUtil.isLogin()) { return R.failed(Status.UNAUTHORIZED, "User must be logged in to access this resource"); } int uid = StpUtil.getLoginIdAsInt(); QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("deployment_mode", DeploymentMode.FLINK_SQL_GATEWAY.getType()); List<ClusterInfo> clusterInfos = clusterService.list(queryWrapper); for (ClusterInfo cluster : clusterInfos) { SessionDTO sessionDTO = new SessionDTO(); sessionDTO.setHost(cluster.getHost()); sessionDTO.setPort(cluster.getPort()); sessionDTO.setClusterId(cluster.getId()); sessionDTO.setUid(uid); sessionService.createSession(sessionDTO); } return R.succeed(); } @Recover public R<Void> recover(Exception e) { log.error("After retries failed to create session", e); return R.failed(); } @PostMapping("/drop") public R<Void> dropSession() { if (!StpUtil.isLogin()) { return R.failed(Status.UNAUTHORIZED, "User must be logged in to access this resource"); } int uid = StpUtil.getLoginIdAsInt(); QueryWrapper<ClusterInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("deployment_mode", DeploymentMode.FLINK_SQL_GATEWAY.getType()); List<ClusterInfo> clusterInfos = clusterService.list(queryWrapper); for (ClusterInfo cluster : clusterInfos) { SessionDTO sessionDTO = new SessionDTO(); sessionDTO.setHost(cluster.getHost()); sessionDTO.setPort(cluster.getPort()); sessionDTO.setClusterId(cluster.getId()); sessionDTO.setUid(uid); sessionService.closeSession(sessionDTO); } return R.succeed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/SysRoleController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/SysRoleController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.RoleWithUserDTO; import org.apache.paimon.web.server.data.model.SysRole; import org.apache.paimon.web.server.data.model.User; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.service.SysRoleService; import org.apache.paimon.web.server.service.UserService; import org.apache.paimon.web.server.util.PageSupport; import cn.dev33.satoken.annotation.SaCheckPermission; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; /** role controller. */ @Validated @RestController @RequestMapping("/api/role") public class SysRoleController { @Autowired private SysRoleService roleService; @Autowired private UserService userService; /** Obtain role views with pagination. */ @SaCheckPermission("system:role:list") @GetMapping("/list") public PageR<SysRole> listRoles(SysRole role) { IPage<SysRole> page = PageSupport.startPage(); List<SysRole> list = roleService.listRoles(page, role); return PageR.<SysRole>builder().success(true).total(page.getTotal()).data(list).build(); } /** Obtain detailed information based on role number. */ @SaCheckPermission("system:role:query") @GetMapping(value = "/{roleId}") public R<SysRole> getRole(@PathVariable Integer roleId) { return R.succeed(roleService.getRoleById(roleId)); } /** Add new role. */ @SaCheckPermission("system:role:add") @PostMapping public R<Void> add(@Valid @RequestBody SysRole role) { if (!roleService.checkRoleNameUnique(role)) { return R.failed(Status.ROLE_NAME_IS_EXIST, role.getRoleName()); } else if (!roleService.checkRoleKeyUnique(role)) { return R.failed(Status.ROLE_KEY_IS_EXIST, role.getRoleKey()); } return roleService.insertRole(role) > 0 ? R.succeed() : R.failed(); } /** Update role info. */ @SaCheckPermission("system:role:update") @PutMapping public R<Void> update(@Valid @RequestBody SysRole role) { roleService.checkRoleAllowed(role); if (!roleService.checkRoleNameUnique(role)) { return R.failed(Status.ROLE_NAME_IS_EXIST, role.getRoleName()); } else if (!roleService.checkRoleKeyUnique(role)) { return R.failed(Status.ROLE_KEY_IS_EXIST, role.getRoleKey()); } if (roleService.updateRole(role) > 0) { // TODO update user permissions cache return R.succeed(); } return R.failed(); } /** Update role status. */ @SaCheckPermission("system:role:update") @PutMapping("/changeStatus") public R<Void> changeStatus(@RequestBody SysRole role) { roleService.checkRoleAllowed(role); return roleService.updateRoleStatus(role) ? R.succeed() : R.failed(); } /** Delete role. */ @SaCheckPermission("system:role:delete") @DeleteMapping("/{roleIds}") public R<Void> delete(@PathVariable Integer[] roleIds) { return roleService.deleteRoleByIds(roleIds) > 0 ? R.succeed() : R.failed(); } /** Obtain a list of role selection boxes. */ @SaCheckPermission("system:role:query") @GetMapping("/all") public R<List<SysRole>> all() { return R.succeed(roleService.list()); } /** Query the list of assigned user roles. */ @SaCheckPermission("system:role:list") @GetMapping("/authUser/allocatedList") public PageR<User> allocatedList(@RequestBody RoleWithUserDTO roleWithUserDTO) { IPage<RoleWithUserDTO> page = PageSupport.startPage(); List<User> list = userService.selectAllocatedList(page, roleWithUserDTO); return PageR.<User>builder().success(true).total(page.getTotal()).data(list).build(); } /** Query the list of unassigned user roles. */ @SaCheckPermission("system:role:list") @GetMapping("/authUser/unallocatedList") public PageR<User> unallocatedList(@RequestBody RoleWithUserDTO roleWithUserDTO) { IPage<RoleWithUserDTO> page = PageSupport.startPage(); List<User> list = userService.selectUnallocatedList(page, roleWithUserDTO); return PageR.<User>builder().success(true).total(page.getTotal()).data(list).build(); } /** Batch Unauthorize User. */ @SaCheckPermission("system:role:update") @PutMapping("/authUser/cancelAll") public R<Void> cancelAuthUserAll(Integer roleId, Integer[] userIds) { return roleService.deleteAuthUsers(roleId, userIds) > 0 ? R.succeed() : R.failed(); } /** Batch Set User Authorization. */ @SaCheckPermission("system:role:update") @PutMapping("/authUser/selectAll") public R<Void> selectAuthUserAll(Integer roleId, Integer[] userIds) { return roleService.insertAuthUsers(roleId, userIds) > 0 ? R.succeed() : R.failed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/ClusterController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/ClusterController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.ClusterInfo; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.service.ClusterService; import org.apache.paimon.web.server.util.PageSupport; import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaIgnore; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; /** Cluster api controller. */ @Validated @RestController @RequestMapping("/api/cluster") public class ClusterController { @Autowired private ClusterService clusterService; @SaCheckPermission("system:cluster:query") @GetMapping("/{id}") public R<ClusterInfo> getCluster(@PathVariable("id") Integer id) { ClusterInfo clusterInfo = clusterService.getById(id); if (clusterInfo == null) { return R.failed(Status.CLUSTER_NOT_EXIST); } return R.succeed(clusterInfo); } @SaCheckPermission("system:cluster:list") @GetMapping("/list") public PageR<ClusterInfo> listClusters(ClusterInfo clusterInfo) { IPage<ClusterInfo> page = PageSupport.startPage(); List<ClusterInfo> clusterInfos = clusterService.listUsers(page, clusterInfo); return PageR.<ClusterInfo>builder() .success(true) .total(page.getTotal()) .data(clusterInfos) .build(); } @SaCheckPermission("system:cluster:add") @PostMapping public R<Void> add(@Valid @RequestBody ClusterInfo clusterInfo) { if (!clusterService.checkClusterNameUnique(clusterInfo)) { return R.failed(Status.CLUSTER_NAME_ALREADY_EXISTS, clusterInfo.getClusterName()); } return clusterService.save(clusterInfo) ? R.succeed() : R.failed(); } @SaCheckPermission("system:cluster:update") @PutMapping public R<Void> update(@Valid @RequestBody ClusterInfo clusterInfo) { if (!clusterService.checkClusterNameUnique(clusterInfo)) { return R.failed(Status.CLUSTER_NAME_ALREADY_EXISTS, clusterInfo.getClusterName()); } return clusterService.updateById(clusterInfo) ? R.succeed() : R.failed(); } @SaCheckPermission("system:cluster:delete") @DeleteMapping("/{clusterIds}") public R<Void> delete(@PathVariable Integer[] clusterIds) { return clusterService.deleteClusterByIds(clusterIds) > 0 ? R.succeed() : R.failed(); } @SaIgnore @PostMapping("/check") public R<Void> check(@Validated @RequestBody ClusterInfo clusterInfo) { return clusterService.checkClusterHeartbeatStatus(clusterInfo) ? R.succeed() : R.failed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/TableController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/TableController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.AlterTableDTO; import org.apache.paimon.web.server.data.dto.TableDTO; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.data.vo.TableVO; import org.apache.paimon.web.server.service.TableService; import cn.dev33.satoken.annotation.SaCheckPermission; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.stream.Collectors; /** Table api controller. */ @Slf4j @Validated @RestController @RequestMapping("/api/table") public class TableController { private final TableService tableService; public TableController(TableService tableService) { this.tableService = tableService; } /** * Creates a table in the database based on the provided TableInfo. * * @param tableDTO The TableDTO object containing information about the table * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:table:create") @PostMapping("/create") public R<Void> createTable(@Valid @RequestBody TableDTO tableDTO) { if (tableService.tableExists(tableDTO)) { return R.failed(Status.TABLE_NAME_IS_EXIST, tableDTO.getName()); } return tableService.createTable(tableDTO) ? R.succeed() : R.failed(Status.TABLE_CREATE_ERROR); } /** * Adds a column to the table. * * @param tableDTO The TableDTO object containing information about the table * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:column:add") @PostMapping("/column/add") public R<Void> addColumn(@RequestBody TableDTO tableDTO) { return tableService.addColumn(tableDTO) ? R.succeed() : R.failed(Status.TABLE_ADD_COLUMN_ERROR); } /** * Lists columns given a table. * * @param catalogName The name of the catalog * @param databaseName The name of the database * @param tableName The name of the table * @return Response object containing {@link TableVO} representing the table */ @SaCheckPermission("metadata:column:list") @GetMapping("/column/list") public R<TableVO> listColumns( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String tableName) { return R.succeed(tableService.listColumns(catalogName, databaseName, tableName)); } /** * Drops a column from a table. * * @param catalogName The name of the catalog * @param databaseName The name of the database * @param tableName The name of the table * @param columnName The name of the column to be dropped * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:column:drop") @DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}") public R<Void> dropColumn( @PathVariable String catalogName, @PathVariable String databaseName, @PathVariable String tableName, @PathVariable String columnName) { return tableService.dropColumn(catalogName, databaseName, tableName, columnName) ? R.succeed() : R.failed(Status.TABLE_DROP_COLUMN_ERROR); } /** * Modify a column in a table. * * @param alterTableDTO the DTO containing alteration details * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:table:update") @PostMapping("/alter") public R<Void> alterTable(@RequestBody AlterTableDTO alterTableDTO) { return tableService.alterTable(alterTableDTO) ? R.succeed() : R.failed(Status.TABLE_AlTER_COLUMN_ERROR); } /** * Adds options to a table. * * @param tableDTO The TableDTO object containing information about the table * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:option:add") @PostMapping("/option/add") public R<Void> addOption(@RequestBody TableDTO tableDTO) { return tableService.addOption(tableDTO) ? R.succeed() : R.failed(Status.TABLE_ADD_OPTION_ERROR); } /** * Removes an option from a table. * * @param catalogName The name of the catalog * @param databaseName The name of the database * @param tableName The name of the table * @param key The key of the option to be removed * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:option:remove") @PostMapping("/option/remove") public R<Void> removeOption( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String tableName, @RequestParam String key) { return tableService.removeOption(catalogName, databaseName, tableName, key) ? R.succeed() : R.failed(Status.TABLE_REMOVE_OPTION_ERROR); } /** * Drops a table from the specified database in the given catalog. * * @param catalogName The name of the catalog from which the table will be dropped * @param databaseName The name of the database from which the table will be dropped * @param tableName The name of the table to be dropped * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:table:drop") @DeleteMapping("/drop/{catalogName}/{databaseName}/{tableName}") public R<Void> dropTable( @PathVariable String catalogName, @PathVariable String databaseName, @PathVariable String tableName) { return tableService.dropTable(catalogName, databaseName, tableName) ? R.succeed() : R.failed(Status.TABLE_DROP_ERROR); } /** * Renames a table in the specified database of the given catalog. * * @param catalogName The name of the catalog where the table resides * @param databaseName The name of the database where the table resides * @param fromTableName The current name of the table to be renamed * @param toTableName The new name for the table * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:table:update") @PostMapping("/rename") public R<Void> renameTable( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String fromTableName, @RequestParam String toTableName) { return tableService.renameTable(catalogName, databaseName, fromTableName, toTableName) ? R.succeed() : R.failed(Status.TABLE_RENAME_ERROR); } /** * Lists tables given {@link TableDTO} condition. * * @return Response object containing a list of {@link TableVO} representing the tables */ @SaCheckPermission("metadata:table:list") @PostMapping("/list") public R<Object> listTables(@RequestBody TableDTO tableDTO) { List<TableVO> tables = tableService.listTables(tableDTO); if (Objects.nonNull(tableDTO.getCatalogId()) && Objects.nonNull(tableDTO.getDatabaseName())) { return R.succeed(tables); } else { TreeMap<Integer, Map<String, List<TableVO>>> collect = tables.stream() .collect( Collectors.groupingBy( TableVO::getCatalogId, TreeMap::new, Collectors.groupingBy(TableVO::getDatabaseName))); return R.succeed(collect); } } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/CatalogController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/CatalogController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.CatalogDTO; import org.apache.paimon.web.server.data.model.CatalogInfo; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.service.CatalogService; import cn.dev33.satoken.annotation.SaCheckPermission; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; /** Catalog api controller. */ @Slf4j @Validated @RestController @RequestMapping("/api/catalog") public class CatalogController { private final CatalogService catalogService; public CatalogController(CatalogService catalogService) { this.catalogService = catalogService; } /** * Create a catalog. * * @param catalogDTO The catalogDTO for the catalog * @return A response indicating the success or failure of the operation */ @SaCheckPermission("metadata:catalog:create") @PostMapping("/create") public R<Void> createCatalog(@Valid @RequestBody CatalogDTO catalogDTO) { try { if (catalogService.checkCatalogNameUnique(catalogDTO)) { return R.failed(Status.CATALOG_NAME_IS_EXIST, catalogDTO.getName()); } return catalogService.createCatalog(catalogDTO) ? R.succeed() : R.failed(); } catch (Exception e) { log.error("Exception with creating catalog.", e); return R.failed(Status.CATALOG_CREATE_ERROR); } } /** * Get all catalog information. * * @return The list of all catalogs */ @SaCheckPermission("metadata:catalog:list") @GetMapping("/list") public R<List<CatalogInfo>> getCatalog() { List<CatalogInfo> catalogs = catalogService.list(); return R.succeed(catalogs); } /** * Removes a catalog with given catalog name or catalog id. * * @param catalogDTO Given the catalog name or catalog id to remove catalog * @return A response indicating the success or failure of the operation */ @SaCheckPermission("metadata:catalog:remove") @PostMapping("/remove") public R<Void> removeCatalog(@RequestBody CatalogDTO catalogDTO) { boolean remove; if (StringUtils.isNotBlank(catalogDTO.getName())) { remove = catalogService.remove( Wrappers.lambdaQuery(CatalogInfo.class) .eq(CatalogInfo::getCatalogName, catalogDTO.getName())); } else { remove = catalogService.remove( Wrappers.lambdaQuery(CatalogInfo.class) .eq(CatalogInfo::getId, catalogDTO.getId())); } return remove ? R.succeed() : R.failed(Status.CATALOG_REMOVE_ERROR); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/DatabaseController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/DatabaseController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.DatabaseDTO; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.data.vo.DatabaseVO; import org.apache.paimon.web.server.service.DatabaseService; import cn.dev33.satoken.annotation.SaCheckPermission; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; /** Database api controller. */ @Slf4j @Validated @RestController @RequestMapping("/api/database") public class DatabaseController { private final DatabaseService databaseService; public DatabaseController(DatabaseService databaseService) { this.databaseService = databaseService; } /** * Creates a new database. * * @param databaseDTO The details of the database to create * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:database:create") @PostMapping("/create") public R<Void> createDatabase(@Valid @RequestBody DatabaseDTO databaseDTO) { if (databaseService.databaseExists(databaseDTO)) { return R.failed(Status.DATABASE_NAME_IS_EXIST, databaseDTO.getName()); } return databaseService.createDatabase(databaseDTO) ? R.succeed() : R.failed(Status.DATABASE_CREATE_ERROR); } /** * Lists databases given catalog id. * * @return The list of databases of given catalog id */ @SaCheckPermission("metadata:database:list") @GetMapping("/list") public R<List<DatabaseVO>> listDatabases( @RequestParam(value = "catalogId", required = false) Integer catalogId) { return R.succeed(databaseService.listDatabases(catalogId)); } /** * Removes the specified database. * * @param databaseDTO The database to be dropped * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("metadata:database:drop") @PostMapping("/drop") public R<Void> dropDatabase(@RequestBody DatabaseDTO databaseDTO) { return databaseService.dropDatabase(databaseDTO) ? R.succeed() : R.failed(Status.DATABASE_DROP_ERROR); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/StatementController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/StatementController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.StatementInfo; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.service.StatementService; import org.apache.paimon.web.server.util.PageSupport; import cn.dev33.satoken.annotation.SaCheckPermission; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** Statement api controller. */ @RestController @RequestMapping("/api/statement") public class StatementController { @Autowired private StatementService statementService; @SaCheckPermission("playground:statement:query") @GetMapping("/{id}") public R<StatementInfo> getStatement(@PathVariable("id") Integer id) { StatementInfo statementInfo = statementService.getById(id); if (statementInfo == null) { return R.failed(Status.STATEMENT_NOT_EXIST); } return R.succeed(statementInfo); } @SaCheckPermission("playground:statement:list") @GetMapping("/list") public PageR<StatementInfo> listStatements(StatementInfo statementInfo) { IPage<StatementInfo> page = PageSupport.startPage(); List<StatementInfo> statementInfos = statementService.listStatements(page, statementInfo); return PageR.<StatementInfo>builder() .success(true) .total(page.getTotal()) .data(statementInfos) .build(); } @SaCheckPermission("playground:statement:query") @GetMapping("/all") public R<List<StatementInfo>> all() { return R.succeed(statementService.list()); } @SaCheckPermission("playground:statement:add") @PostMapping public R<Void> add(@RequestBody StatementInfo statementInfo) { if (!statementService.checkStatementNameUnique(statementInfo)) { return R.failed(Status.STATEMENT_NAME_ALREADY_EXISTS, statementInfo); } return statementService.saveStatement(statementInfo) ? R.succeed() : R.failed(); } @SaCheckPermission("playground:statement:update") @PutMapping public R<Void> update(@RequestBody StatementInfo statementInfo) { if (!statementService.checkStatementNameUnique(statementInfo)) { return R.failed(Status.STATEMENT_NAME_ALREADY_EXISTS, statementInfo); } return statementService.updateById(statementInfo) ? R.succeed() : R.failed(); } @SaCheckPermission("system:cluster:delete") @DeleteMapping("/{statementId}") public R<Void> delete(@PathVariable Integer statementId) { return statementService.removeById(statementId) ? R.succeed() : R.failed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/SysMenuController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/SysMenuController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.constant.Constants; import org.apache.paimon.web.server.data.model.SysMenu; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.data.tree.TreeSelect; import org.apache.paimon.web.server.data.vo.RoleMenuTreeselectVO; import org.apache.paimon.web.server.data.vo.RouterVO; import org.apache.paimon.web.server.service.SysMenuService; import org.apache.paimon.web.server.util.StringUtils; import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.stp.StpUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** menu controller. */ @RestController @RequestMapping("/api/menu") public class SysMenuController { @Autowired private SysMenuService menuService; /** Get menu list. */ @SaCheckPermission("system:menu:list") @GetMapping("/list") public R<List<SysMenu>> list(SysMenu menu) { List<SysMenu> menus = menuService.selectMenuList(menu); return R.succeed(menus); } /** Get menu info by menuId. */ @SaCheckPermission("system:menu:query") @GetMapping(value = "/{menuId}") public R<SysMenu> getInfo(@PathVariable Integer menuId) { return R.succeed(menuService.selectMenuById(menuId)); } /** Get menu drop-down tree list. */ @GetMapping("/treeselect") public R<List<TreeSelect>> treeselect(SysMenu menu) { List<SysMenu> menus = menuService.selectMenuList(menu); return R.succeed(menuService.buildMenuTreeSelect(menus)); } /** Load the corresponding character menu list tree. */ @GetMapping(value = "/roleMenuTreeselect/{roleId}") public R<RoleMenuTreeselectVO> roleMenuTreeselect(@PathVariable("roleId") Integer roleId) { List<SysMenu> menus = menuService.selectMenuList(); List<TreeSelect> treeMenus = menuService.buildMenuTreeSelect(menus); List<Integer> checkedKeys = menuService.selectMenuListByRoleId(roleId); return R.succeed(new RoleMenuTreeselectVO(checkedKeys, treeMenus)); } /** add new menu. */ @SaCheckPermission("system:menu:add") @PostMapping public R<Void> add(@Validated @RequestBody SysMenu menu) { if (!menuService.checkMenuNameUnique(menu)) { return R.failed(Status.MENU_NAME_IS_EXIST, menu.getMenuName()); } else if (Constants.YES_FRAME == menu.getIsFrame() && !StringUtils.isHttp(menu.getPath())) { return R.failed(Status.MENU_PATH_INVALID, menu.getPath()); } return menuService.insertMenu(menu) ? R.succeed() : R.failed(); } /** update menu. */ @SaCheckPermission("system:menu:update") @PutMapping public R<Void> update(@Validated @RequestBody SysMenu menu) { if (!menuService.checkMenuNameUnique(menu)) { return R.failed(Status.MENU_NAME_IS_EXIST, menu.getMenuName()); } else if (Constants.YES_FRAME == menu.getIsFrame() && !StringUtils.isHttp(menu.getPath())) { return R.failed(Status.MENU_PATH_INVALID, menu.getPath()); } return menuService.updateMenu(menu) ? R.succeed() : R.failed(); } /** delete menu. */ @SaCheckPermission("system:menu:delete") @DeleteMapping("/{menuId}") public R<Void> delete(@PathVariable("menuId") Integer menuId) { if (menuService.hasChildByMenuId(menuId) || menuService.checkMenuExistRole(menuId)) { return R.failed(Status.MENU_IN_USED); } return menuService.deleteMenuById(menuId) ? R.succeed() : R.failed(); } /** Get router list. */ @GetMapping("/getRouters") public R<List<RouterVO>> getRouters() { int userId = StpUtil.getLoginIdAsInt(); List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId); return R.succeed(menuService.buildMenus(menus)); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/JobController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/JobController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.dto.JobSubmitDTO; import org.apache.paimon.web.server.data.dto.ResultFetchDTO; import org.apache.paimon.web.server.data.dto.StopJobDTO; import org.apache.paimon.web.server.data.model.JobInfo; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.data.vo.JobStatisticsVO; import org.apache.paimon.web.server.data.vo.JobStatusVO; import org.apache.paimon.web.server.data.vo.JobVO; import org.apache.paimon.web.server.data.vo.ResultDataVO; import org.apache.paimon.web.server.service.JobService; import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaIgnore; import cn.dev33.satoken.stp.StpUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** Job submit api controller. */ @Slf4j @RestController @RequestMapping("/api/job") public class JobController { @Autowired private JobService jobService; @SaCheckPermission("playground:job:submit") @PostMapping("/submit") public R<JobVO> submit(@RequestBody JobSubmitDTO jobSubmitDTO) { try { return R.succeed(jobService.submitJob(jobSubmitDTO)); } catch (Exception e) { log.error("Exception with submitting a job.", e); return R.failed(Status.JOB_SUBMIT_ERROR); } } @SaIgnore @PostMapping("/fetch") public R<ResultDataVO> fetchResult(@RequestBody ResultFetchDTO resultFetchDTO) { try { return R.succeed(jobService.fetchResult(resultFetchDTO)); } catch (Exception e) { log.error("Exception with fetching result data.", e); return R.failed(Status.RESULT_FETCH_ERROR); } } @SaCheckPermission("playground:job:list") @GetMapping("/list") public R<List<JobVO>> list() { return R.succeed(jobService.listJobs()); } @SaCheckPermission("playground:job:list") @GetMapping("/list/page") public R<List<JobVO>> listJobsByPage(int current, int size) { return R.succeed(jobService.listJobsByPage(current, size)); } @SaIgnore @GetMapping("/status/get/{jobId}") public R<JobStatusVO> getJobStatus(@PathVariable("jobId") String jobId) { JobInfo job = jobService.getJobById(jobId); JobStatusVO jobStatusVO = JobStatusVO.builder().jobId(job.getJobId()).status(job.getStatus()).build(); return R.succeed(jobStatusVO); } @SaCheckPermission("playground:job:query") @GetMapping("/statistics/get") public R<JobStatisticsVO> getJobStatistics() { return R.succeed(jobService.getJobStatistics()); } @SaIgnore @GetMapping("/logs/get") public R<String> getLogs() { return R.succeed(jobService.getLogsByUserId(StpUtil.getLoginIdAsString())); } @SaIgnore @GetMapping("/logs/clear") public R<String> clearLogs() { return R.succeed(jobService.clearLog(StpUtil.getLoginIdAsString())); } @SaCheckPermission("playground:job:stop") @PostMapping("/stop") public R<Void> stop(@RequestBody StopJobDTO stopJobDTO) { try { jobService.stop(stopJobDTO); return R.succeed(); } catch (Exception e) { log.error("Exception with stopping a job.", e); return R.failed(Status.JOB_STOP_ERROR); } } @SaIgnore @PostMapping("/refresh") public R<Void> refresh() { jobService.refreshJobStatus("Flink"); return R.succeed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/UserController.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/controller/UserController.java
/* * 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.paimon.web.server.controller; import org.apache.paimon.web.server.data.model.User; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import org.apache.paimon.web.server.data.result.enums.Status; import org.apache.paimon.web.server.data.vo.UserVO; import org.apache.paimon.web.server.service.UserService; import org.apache.paimon.web.server.util.PageSupport; import cn.dev33.satoken.annotation.SaCheckPermission; import com.baomidou.mybatisplus.core.metadata.IPage; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import static org.apache.paimon.web.server.data.result.enums.Status.USER_NOT_EXIST; /** User api controller. */ @Slf4j @Validated @RestController @RequestMapping("/api/user") public class UserController { @Autowired private UserService userService; /** * Get user by id. * * @param id user-id * @return {@link R} with {@link UserVO} */ @SaCheckPermission("system:user:query") @GetMapping("/{id}") public R<UserVO> getUser(@PathVariable("id") Integer id) { UserVO user = userService.getUserById(id); if (user == null) { return R.failed(USER_NOT_EXIST); } return R.succeed(user); } /** * Get user views with pagination. * * @param user filter conditions * @return paginated user view objects */ @SaCheckPermission("system:user:list") @GetMapping("/list") public PageR<UserVO> listUsers(User user) { IPage<User> page = PageSupport.startPage(); List<UserVO> list = userService.listUsers(page, user); return PageR.<UserVO>builder().success(true).total(page.getTotal()).data(list).build(); } /** * Add a new user. * * @param user the user to be added, must not be null * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("system:user:add") @PostMapping public R<Void> add(@Valid @RequestBody User user) { if (!userService.checkUserNameUnique(user)) { return R.failed(Status.USER_NAME_ALREADY_EXISTS, user.getUsername()); } return userService.insertUser(user) > 0 ? R.succeed() : R.failed(); } /** * Update an existing user's details. * * @param user the user with updated details, must not be null * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("system:user:update") @PutMapping public R<Void> update(@Valid @RequestBody User user) { if (!userService.checkUserNameUnique(user)) { return R.failed(Status.USER_NAME_ALREADY_EXISTS, user.getUsername()); } return userService.updateUser(user) > 0 ? R.succeed() : R.failed(); } /** * Delete one or more users by user ID. * * @param userIds an array of user IDs to be deleted * @return a {@code R<Void>} response indicating success or failure */ @SaCheckPermission("system:user:delete") @DeleteMapping("/{userIds}") public R<Void> delete(@PathVariable Integer[] userIds) { return userService.deleteUserByIds(userIds) > 0 ? R.succeed() : R.failed(); } /** * Changes a user's password. * * @param user the user object containing the new password * @return a response entity indicating success or failure */ @SaCheckPermission("system:user:change:password") @PostMapping("/change/password") public R<Void> changePassword(@Validated @RequestBody User user) { if (userService.getUserById(user.getId()) == null) { return R.failed(USER_NOT_EXIST); } return userService.changePassword(user) ? R.succeed() : R.failed(); } /** * Changes the status of a user via a PUT request. * * @param user the user object containing the new status information * @return a response object indicating success or failure */ @SaCheckPermission("system:user:update") @PutMapping("/changeStatus") public R<Void> changeStatus(@RequestBody User user) { return userService.updateUserStatus(user) ? R.succeed() : R.failed(); } /** * Allocates a role to a user. * * @param user the user to whom the role is to be allocated * @return a response object indicating success or failure */ @SaCheckPermission("system:user:update") @PostMapping("/allocate") public R<Void> allocateRole(@RequestBody User user) { return userService.allocateRole(user) > 0 ? R.succeed() : R.failed(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/MessageUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/MessageUtils.java
/* * 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.paimon.web.server.util; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import java.util.Arrays; import java.util.Objects; /** i18n util. */ public class MessageUtils { private static final MessageSource MESSAGE_SOURCE = SpringUtils.getBean(MessageSource.class); public MessageUtils() {} /** * According to messageKey and parameters, get the message and delegate to spring messageSource. * * @param code msg key * @return {@link String} internationalization information */ public static String getMsg(Object code) { return MESSAGE_SOURCE.getMessage( code.toString(), null, code.toString(), LocaleContextHolder.getLocale()); } /** * According to messageKey and parameters, get the message and delegate to spring messageSource. * * @param code msg key * @param messageArgs msg parameters * @return {@link String} internationalization information */ public static String getMsg(Object code, Object... messageArgs) { Object[] objs = Arrays.stream(messageArgs) .filter(Objects::nonNull) .map(MessageUtils::getMsg) .toArray(); return MESSAGE_SOURCE.getMessage( code.toString(), objs, code.toString(), LocaleContextHolder.getLocale()); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/PaimonDataType.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/PaimonDataType.java
/* * 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.paimon.web.server.util; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** Paimon data type. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class PaimonDataType { private String type; private boolean isNullable; private Integer precision; private Integer scale; }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/LRUCache.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/LRUCache.java
/* * 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.paimon.web.server.util; import java.util.LinkedHashMap; import java.util.Map; /** LRU Cache. */ public class LRUCache<K, V> extends LinkedHashMap<K, V> { private final int cacheSize; /** * Initialize LRUCache with cache size. * * @param cacheSize Cache size */ public LRUCache(int cacheSize) { // true means based on access order super((int) Math.ceil(cacheSize / 0.75) + 1, 0.75f, true); this.cacheSize = cacheSize; } /** * When map size over CACHE_SIZE, remove oldest entry. * * @param eldest The least recently accessed entry in the map * @return boolean value indicates whether the oldest entry should be removed */ @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > this.cacheSize; } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/StringUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/StringUtils.java
/* * 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.paimon.web.server.util; import org.apache.paimon.web.server.constant.Constants; /** common string utils. */ public class StringUtils extends org.apache.commons.lang3.StringUtils { public static boolean isHttp(String link) { return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/SpringUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/SpringUtils.java
/* * 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.paimon.web.server.util; import org.springframework.aop.framework.AopContext; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** spring utils. */ @Component public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware { /** Spring beanFactory. */ private static ConfigurableListableBeanFactory beanFactory; private static ApplicationContext applicationContext; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SpringUtils.beanFactory = beanFactory; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringUtils.applicationContext = applicationContext; } /** * Get bean by bean name. * * @param name bean name * @return An instance of a bean registered with the given name */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T) beanFactory.getBean(name); } /** * Get bean by bean class type. * * @param clz bean class * @return An instance of a bean registered with the given class */ public static <T> T getBean(Class<T> clz) throws BeansException { return (T) beanFactory.getBean(clz); } /** Get AOP proxy object. */ @SuppressWarnings("unchecked") public static <T> T getAopProxy(T invoker) { return (T) AopContext.currentProxy(); } /** * Get the current environment configuration, no configuration returned null. * * @return current envs */ public static String[] getActiveProfiles() { return applicationContext.getEnvironment().getActiveProfiles(); } /** * Get the current environment configuration. When there are multiple environment * configurations, only the first one is obtained. * * @return current env */ public static String getActiveProfile() { final String[] activeProfiles = getActiveProfiles(); return activeProfiles.length > 0 ? activeProfiles[0] : null; } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/LogUtil.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/LogUtil.java
/* * 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.paimon.web.server.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.time.LocalDateTime; /** log util. */ public class LogUtil { private static final Logger logger = LoggerFactory.getLogger(LogUtil.class); public static String getError(Throwable e) { String error = null; try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); error = sw.toString(); logger.error(error); } catch (IOException ioe) { ioe.printStackTrace(); } finally { return error; } } public static String getError(String msg, Throwable e) { String error = null; try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); LocalDateTime now = LocalDateTime.now(); error = now + ": " + msg + " \nError message:\n " + sw.toString(); logger.error(error); } catch (IOException ioe) { ioe.printStackTrace(); } finally { return error; } } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/LocalDateTimeUtil.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/LocalDateTimeUtil.java
/* * 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.paimon.web.server.util; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; /** Local date time util. */ public class LocalDateTimeUtil { public static LocalDateTime convertUtcStringToLocalDateTime(String utcTimeStr) { OffsetDateTime utcTime = OffsetDateTime.parse(utcTimeStr + "Z", DateTimeFormatter.ISO_OFFSET_DATE_TIME); ZonedDateTime beijingTime = utcTime.atZoneSameInstant(ZoneId.of("Asia/Shanghai")); return beijingTime.toLocalDateTime(); } public static String getFormattedDateTime(LocalDateTime time) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return time.format(formatter); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/PageSupport.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/PageSupport.java
/* * 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.paimon.web.server.util; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** Page support. */ public class PageSupport { private static final char SEPARATOR = '_'; /** pageNum. */ public static final String PAGE_NUM = "pageNum"; /** pageSize. */ public static final String PAGE_SIZE = "pageSize"; /** order column. */ public static final String ORDER_BY_COLUMN = "orderByColumn"; /** desc or asc. */ public static final String IS_ASC = "isAsc"; /** page params reasonable. */ public static final String REASONABLE = "reasonable"; public static <T> IPage<T> startPage() { Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM, 1); Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE, 10); Page<T> page = new Page<>(pageNum, pageSize); String orderBy = getOrderBy(); if (StringUtils.isNotEmpty(orderBy)) { OrderItem orderItem = new OrderItem(orderBy, isAsc()); page.addOrder(orderItem); } return page; } public static String getOrderBy() { String orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN); if (StringUtils.isEmpty(orderByColumn)) { return ""; } return toUnderScoreCase(orderByColumn); } public static boolean isAsc() { String isAsc = ServletUtils.getParameter(IS_ASC); return isAsc.equals("asc") || isAsc.equals("ascending"); } public static String toUnderScoreCase(String str) { if (StringUtils.isBlank(str)) { return null; } StringBuilder sb = new StringBuilder(); boolean preCharIsUpperCase = true; boolean curreCharIsUpperCase = true; boolean nexteCharIsUpperCase = true; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (i > 0) { preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); } else { preCharIsUpperCase = false; } curreCharIsUpperCase = Character.isUpperCase(c); if (i < (str.length() - 1)) { nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); } if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) { sb.append(SEPARATOR); } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) { sb.append(SEPARATOR); } sb.append(Character.toLowerCase(c)); } return sb.toString(); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/ObjectMapperUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/ObjectMapperUtils.java
/* * 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.paimon.web.server.util; import com.fasterxml.jackson.core.JsonFactoryBuilder; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.util.Collection; import java.util.Map; import static com.fasterxml.jackson.core.JsonFactory.Feature.INTERN_FIELD_NAMES; import static com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_COMMENTS; import static com.fasterxml.jackson.core.json.JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; import static com.fasterxml.jackson.databind.type.TypeFactory.defaultInstance; /** jackson common object mapper. */ public class ObjectMapperUtils { private static final String EMPTY_JSON = "{}"; private static final String EMPTY_ARRAY_JSON = "[]"; private static final ObjectMapper MAPPER; static { MAPPER = new ObjectMapper( new JsonFactoryBuilder() .configure(INTERN_FIELD_NAMES, false) .configure(ALLOW_UNESCAPED_CONTROL_CHARS, true) .build()); MAPPER.disable(FAIL_ON_UNKNOWN_PROPERTIES); MAPPER.enable(ALLOW_COMMENTS); MAPPER.registerModule(new ParameterNamesModule()); MAPPER.registerModule(new JavaTimeModule()); MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); } public static String toJSON(@Nullable Object obj) { if (obj == null) { return null; } try { return MAPPER.writeValueAsString(obj); } catch (JsonProcessingException e) { throw new UncheckedIOException(e); } } /** * Please do not use formatted JSON when outputting logs. * * <p>For better readability */ public static String toPrettyJson(@Nullable Object obj) { if (obj == null) { return null; } try { return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { throw new UncheckedIOException(e); } } public static void toJSON(@Nullable Object obj, OutputStream writer) { if (obj == null) { return; } try { MAPPER.writeValue(writer, obj); } catch (IOException e) { throw wrapException(e); } } public static <T> T fromJSON(@Nullable byte[] bytes, Class<T> valueType) { if (bytes == null) { return null; } try { return MAPPER.readValue(bytes, valueType); } catch (IOException e) { throw wrapException(e); } } private static RuntimeException wrapException(IOException e) { return new UncheckedIOException(e); } public static <T> T fromJSON(@Nullable String json, Class<T> valueType) { if (json == null) { return null; } try { return MAPPER.readValue(json, valueType); } catch (IOException e) { throw wrapException(e); } } public static <T> T fromJSON(@Nullable String json, TypeReference<T> type) { if (json == null) { return null; } try { return MAPPER.readValue(json, type); } catch (IOException e) { throw wrapException(e); } } public static <T> T fromJSON(Object value, Class<T> valueType) { if (value == null) { return null; } else if (value instanceof String) { return fromJSON((String) value, valueType); } else if (value instanceof byte[]) { return fromJSON((byte[]) value, valueType); } else { return null; } } public static <T> T value(Object rawValue, Class<T> type) { return MAPPER.convertValue(rawValue, type); } public static <T> T update(T rawValue, String newProperty) { try { return MAPPER.readerForUpdating(rawValue).readValue(newProperty); } catch (IOException e) { throw wrapException(e); } } public static <T> T value(Object rawValue, TypeReference<T> type) { return MAPPER.convertValue(rawValue, type); } public static <T> T value(Object rawValue, JavaType type) { return MAPPER.convertValue(rawValue, type); } public static <T> T unwrapJsonP(String raw, Class<T> type) { return fromJSON(unwrapJsonP(raw), type); } private static String unwrapJsonP(String raw) { raw = StringUtils.trim(raw); raw = StringUtils.removeEnd(raw, ";"); raw = raw.substring(raw.indexOf('(') + 1); raw = raw.substring(0, raw.lastIndexOf(')')); raw = StringUtils.trim(raw); return raw; } public static <E, T extends Collection<E>> T fromJSON( String json, Class<? extends Collection> collectionType, Class<E> valueType) { if (StringUtils.isEmpty(json)) { json = EMPTY_ARRAY_JSON; } try { return MAPPER.readValue( json, defaultInstance().constructCollectionType(collectionType, valueType)); } catch (IOException e) { throw wrapException(e); } } /** use {@link #fromJson(String)} instead. */ public static <K, V, T extends Map<K, V>> T fromJSON( String json, Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType) { if (StringUtils.isEmpty(json)) { json = EMPTY_JSON; } try { return MAPPER.readValue( json, defaultInstance().constructMapType(mapType, keyType, valueType)); } catch (IOException e) { throw wrapException(e); } } public static <T> T fromJSON(InputStream inputStream, Class<T> type) { try { return MAPPER.readValue(inputStream, type); } catch (IOException e) { throw wrapException(e); } } public static <E, T extends Collection<E>> T fromJSON( byte[] bytes, Class<? extends Collection> collectionType, Class<E> valueType) { try { return MAPPER.readValue( bytes, defaultInstance().constructCollectionType(collectionType, valueType)); } catch (IOException e) { throw wrapException(e); } } public static <E, T extends Collection<E>> T fromJSON( InputStream inputStream, Class<? extends Collection> collectionType, Class<E> valueType) { try { return MAPPER.readValue( inputStream, defaultInstance().constructCollectionType(collectionType, valueType)); } catch (IOException e) { throw wrapException(e); } } public static Map<String, Object> fromJson(InputStream is) { return fromJSON(is, Map.class, String.class, Object.class); } public static Map<String, Object> fromJson(String string) { return fromJSON(string, Map.class, String.class, Object.class); } public static Map<String, Object> fromJson(byte[] bytes) { return fromJSON(bytes, Map.class, String.class, Object.class); } /** use {@link #fromJson(byte[])} instead. */ public static <K, V, T extends Map<K, V>> T fromJSON( byte[] bytes, Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType) { try { return MAPPER.readValue( bytes, defaultInstance().constructMapType(mapType, keyType, valueType)); } catch (IOException e) { throw wrapException(e); } } /** use {@link #fromJson(InputStream)} instead. */ public static <K, V, T extends Map<K, V>> T fromJSON( InputStream inputStream, Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType) { try { return MAPPER.readValue( inputStream, defaultInstance().constructMapType(mapType, keyType, valueType)); } catch (IOException e) { throw wrapException(e); } } public static boolean isJSON(String jsonStr) { if (StringUtils.isBlank(jsonStr)) { return false; } try (JsonParser parser = new ObjectMapper().getFactory().createParser(jsonStr)) { while (parser.nextToken() != null) { // do nothing. } return true; } catch (IOException ioe) { return false; } } public static boolean isBadJSON(String jsonStr) { return !isJSON(jsonStr); } public static ObjectMapper mapper() { return MAPPER; } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/PaimonServiceUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/PaimonServiceUtils.java
/* * 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.paimon.web.server.util; import org.apache.paimon.web.api.catalog.PaimonService; import org.apache.paimon.web.api.catalog.PaimonServiceFactory; import org.apache.paimon.web.server.data.enums.CatalogMode; import org.apache.paimon.web.server.data.model.CatalogInfo; import org.apache.commons.lang3.StringUtils; /** Paimon Service util. */ public class PaimonServiceUtils { /** * Get a Paimon Service based on the provided CatalogInfo. * * @param catalogInfo The CatalogInfo object containing the catalog details. * @return The created PaimonService object. */ public static PaimonService getPaimonService(CatalogInfo catalogInfo) { PaimonService service; if (catalogInfo.getCatalogType().equalsIgnoreCase(CatalogMode.FILESYSTEM.getMode())) { service = PaimonServiceFactory.createFileSystemCatalogService( catalogInfo.getCatalogName(), catalogInfo.getWarehouse(), catalogInfo.getOptions()); } else if (catalogInfo.getCatalogType().equalsIgnoreCase(CatalogMode.HIVE.getMode())) { if (StringUtils.isNotBlank(catalogInfo.getHiveConfDir())) { service = PaimonServiceFactory.createHiveCatalogService( catalogInfo.getCatalogName(), catalogInfo.getWarehouse(), catalogInfo.getHiveUri(), catalogInfo.getHiveConfDir()); } else { service = PaimonServiceFactory.createHiveCatalogService( catalogInfo.getCatalogName(), catalogInfo.getWarehouse(), catalogInfo.getHiveUri(), null); } } else { service = PaimonServiceFactory.createFileSystemCatalogService( catalogInfo.getCatalogName(), catalogInfo.getWarehouse(), catalogInfo.getOptions()); } return service; } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/ServletUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/ServletUtils.java
/* * 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.paimon.web.server.util; import org.apache.commons.lang3.BooleanUtils; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** Servlet utils. */ public class ServletUtils { public static String getParameter(String name) { return getRequest().getParameter(name); } public static String getParameter(String name, String defaultValue) { String parameter = getRequest().getParameter(name); return StringUtils.isBlank(parameter) ? defaultValue : parameter; } public static Integer getParameterToInt(String name) { return Integer.parseInt(getRequest().getParameter(name)); } public static Integer getParameterToInt(String name, Integer defaultValue) { try { return Integer.parseInt(getRequest().getParameter(name)); } catch (Exception e) { return defaultValue; } } public static Boolean getParameterToBool(String name) { return BooleanUtils.toBoolean(getRequest().getParameter(name)); } public static Boolean getParameterToBool(String name, Boolean defaultValue) { try { return BooleanUtils.toBoolean(getRequest().getParameter(name)); } catch (Exception e) { return defaultValue; } } public static Map<String, String[]> getParams(ServletRequest request) { final Map<String, String[]> map = request.getParameterMap(); return Collections.unmodifiableMap(map); } public static Map<String, String> getParamMap(ServletRequest request) { Map<String, String> params = new HashMap<>(); for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) { params.put(entry.getKey(), StringUtils.join(entry.getValue(), ",")); } return params; } public static HttpServletRequest getRequest() { return getRequestAttributes().getRequest(); } public static HttpServletResponse getResponse() { return getRequestAttributes().getResponse(); } public static HttpSession getSession() { return getRequest().getSession(); } public static ServletRequestAttributes getRequestAttributes() { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); return (ServletRequestAttributes) attributes; } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/util/DataTypeConvertUtils.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/util/DataTypeConvertUtils.java
/* * 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.paimon.web.server.util; import org.apache.paimon.types.BigIntType; import org.apache.paimon.types.BinaryType; import org.apache.paimon.types.BooleanType; import org.apache.paimon.types.CharType; import org.apache.paimon.types.DataType; import org.apache.paimon.types.DateType; import org.apache.paimon.types.DecimalType; import org.apache.paimon.types.DoubleType; import org.apache.paimon.types.FloatType; import org.apache.paimon.types.IntType; import org.apache.paimon.types.LocalZonedTimestampType; import org.apache.paimon.types.SmallIntType; import org.apache.paimon.types.TimeType; import org.apache.paimon.types.TimestampType; import org.apache.paimon.types.TinyIntType; import org.apache.paimon.types.VarBinaryType; import org.apache.paimon.types.VarCharType; /** data type convert util. */ public class DataTypeConvertUtils { public static DataType convert(PaimonDataType type) { switch (type.getType()) { case "INT": return new IntType(type.isNullable()); case "TINYINT": return new TinyIntType(type.isNullable()); case "SMALLINT": return new SmallIntType(type.isNullable()); case "BIGINT": return new BigIntType(type.isNullable()); case "CHAR": return new CharType( type.isNullable(), type.getPrecision() > 0 ? type.getPrecision() : 1); case "VARCHAR": return new VarCharType( type.isNullable(), type.getPrecision() > 0 ? type.getPrecision() : 1); case "STRING": return new VarCharType(type.isNullable(), Integer.MAX_VALUE); case "BINARY": return new BinaryType( type.isNullable(), type.getPrecision() > 0 ? type.getPrecision() : 1); case "VARBINARY": return new VarBinaryType( type.isNullable(), type.getPrecision() > 0 ? type.getPrecision() : 1); case "DOUBLE": return new DoubleType(type.isNullable()); case "BOOLEAN": return new BooleanType(type.isNullable()); case "DATE": return new DateType(type.isNullable()); case "TIME": return new TimeType(type.isNullable(), 0); case "TIME(precision)": return new TimeType(type.isNullable(), type.getPrecision()); case "TIMESTAMP": return new TimestampType(type.isNullable(), 0); case "TIMESTAMP(precision)": return new TimestampType(type.isNullable(), type.getPrecision()); case "TIMESTAMP_MILLIS": return new TimestampType(type.isNullable(), 3); case "BYTES": return new VarBinaryType(type.isNullable(), 0); case "FLOAT": return new FloatType(type.isNullable()); case "DECIMAL": return new DecimalType(type.isNullable(), type.getPrecision(), type.getScale()); case "TIMESTAMP_WITH_LOCAL_TIME_ZONE": return new LocalZonedTimestampType(type.isNullable(), 0); case "TIMESTAMP_WITH_LOCAL_TIME_ZONE(precision)": return new LocalZonedTimestampType(type.isNullable(), type.getPrecision()); default: throw new RuntimeException("Invalid type: " + type); } } public static PaimonDataType fromPaimonType(DataType dataType) { if (dataType instanceof IntType) { return new PaimonDataType("INT", dataType.isNullable(), 0, 0); } else if (dataType instanceof TinyIntType) { return new PaimonDataType("TINYINT", dataType.isNullable(), 0, 0); } else if (dataType instanceof SmallIntType) { return new PaimonDataType("SMALLINT", dataType.isNullable(), 0, 0); } else if (dataType instanceof BigIntType) { return new PaimonDataType("BIGINT", dataType.isNullable(), 0, 0); } else if (dataType instanceof VarCharType) { VarCharType varCharType = (VarCharType) dataType; if (varCharType.getLength() == Integer.MAX_VALUE) { return new PaimonDataType("STRING", varCharType.isNullable(), 0, 0); } else { return new PaimonDataType( "VARCHAR", varCharType.isNullable(), varCharType.getLength(), 0); } } else if (dataType instanceof CharType) { CharType charType = (CharType) dataType; return new PaimonDataType("CHAR", charType.isNullable(), charType.getLength(), 0); } else if (dataType instanceof BinaryType) { BinaryType binaryType = (BinaryType) dataType; return new PaimonDataType("BINARY", binaryType.isNullable(), binaryType.getLength(), 0); } else if (dataType instanceof VarBinaryType) { VarBinaryType varBinaryType = (VarBinaryType) dataType; if (varBinaryType.getLength() == Integer.MAX_VALUE) { return new PaimonDataType( "BYTES", varBinaryType.isNullable(), varBinaryType.getLength(), 0); } else { return new PaimonDataType( "VARBINARY", varBinaryType.isNullable(), varBinaryType.getLength(), 0); } } else if (dataType instanceof DoubleType) { return new PaimonDataType("DOUBLE", dataType.isNullable(), 0, 0); } else if (dataType instanceof BooleanType) { return new PaimonDataType("BOOLEAN", dataType.isNullable(), 0, 0); } else if (dataType instanceof DateType) { return new PaimonDataType("DATE", dataType.isNullable(), 0, 0); } else if (dataType instanceof TimeType) { TimeType timeType = (TimeType) dataType; if (timeType.getPrecision() == 0) { return new PaimonDataType("TIME", timeType.isNullable(), 0, 0); } else { return new PaimonDataType( "TIME(precision)", timeType.isNullable(), timeType.getPrecision(), 0); } } else if (dataType instanceof TimestampType) { TimestampType timestampType = (TimestampType) dataType; if (timestampType.getPrecision() == 0) { return new PaimonDataType("TIMESTAMP", timestampType.isNullable(), 0, 0); } else if (timestampType.getPrecision() == 3) { return new PaimonDataType("TIMESTAMP_MILLIS", timestampType.isNullable(), 3, 0); } else { return new PaimonDataType( "TIMESTAMP(precision)", timestampType.isNullable(), timestampType.getPrecision(), 0); } } else if (dataType instanceof FloatType) { return new PaimonDataType("FLOAT", dataType.isNullable(), 0, 0); } else if (dataType instanceof DecimalType) { DecimalType decimalType = (DecimalType) dataType; return new PaimonDataType( "DECIMAL", decimalType.isNullable(), decimalType.getPrecision(), decimalType.getScale()); } else if (dataType instanceof LocalZonedTimestampType) { LocalZonedTimestampType localZonedTimestampType = (LocalZonedTimestampType) dataType; if (localZonedTimestampType.getPrecision() == 0) { return new PaimonDataType( "TIMESTAMP_WITH_LOCAL_TIME_ZONE", localZonedTimestampType.isNullable(), 0, 0); } else { return new PaimonDataType( "TIMESTAMP_WITH_LOCAL_TIME_ZONE(precision)", localZonedTimestampType.isNullable(), localZonedTimestampType.getPrecision(), 0); } } else { return new PaimonDataType("UNKNOWN", dataType.isNullable(), 0, 0); } } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/constant/MetadataConstant.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/constant/MetadataConstant.java
/* * 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.paimon.web.server.constant; /** Metadata constant. */ public class MetadataConstant { public static final String SNAPSHOTS = "snapshots"; public static final String SCHEMAS = "schemas"; public static final String OPTIONS = "options"; public static final String MANIFESTS = "manifests"; public static final String FILES = "files"; public static final String CONSUMER = "consumers"; public static final String TAGS = "tags"; public static final String METADATA_TABLE_FORMAT = "%s$%s"; }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/constant/Constants.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/constant/Constants.java
/* * 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.paimon.web.server.constant; /** Constants. */ public class Constants { /** admin id. */ public static final int ADMIN_ID = 1; /** all permission. */ public static final String ALL_PERMISSION = "*:*:*"; /** http url prefix. */ public static final String HTTP = "http://"; /** https url prefix. */ public static final String HTTPS = "https://"; /** WWW. */ public static final String WWW = "www"; /** Layout component flag. */ public static final String LAYOUT = "Layout"; /** ParentView component flag. */ public static final String PARENT_VIEW = "ParentView"; /** InnerLink component flag. */ public static final String INNER_LINK = "InnerLink"; /** Is frame: Yes. */ public static final int YES_FRAME = 0; /** Is frame: No. */ public static final int NO_FRAME = 1; }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/UserService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/UserService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.dto.LoginDTO; import org.apache.paimon.web.server.data.dto.RoleWithUserDTO; import org.apache.paimon.web.server.data.model.User; import org.apache.paimon.web.server.data.result.exception.BaseException; import org.apache.paimon.web.server.data.vo.UserInfoVO; import org.apache.paimon.web.server.data.vo.UserVO; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** User Service. */ public interface UserService extends IService<User> { /** * Get a user by ID. * * @param id the user ID * @return the UserVO or null if not found */ UserVO getUserById(Integer id); /** * Select users with pagination. * * @param page the pagination information * @param user the filter criteria * @return list of UserVO */ List<UserVO> listUsers(IPage<User> page, User user); /** * Check if the username is unique. * * @param user the user to check * @return true if unique, false otherwise */ boolean checkUserNameUnique(User user); /** * Login by username and password. * * @param loginDTO login params * @return {@link String} */ UserInfoVO login(LoginDTO loginDTO) throws BaseException; /** * Query the list of assigned user roles. * * @param page the pagination information * @param roleWithUserDTO query params * @return user list */ List<User> selectAllocatedList(IPage<RoleWithUserDTO> page, RoleWithUserDTO roleWithUserDTO); /** * Query the list of unassigned user roles. * * @param page the pagination information * @param roleWithUserDTO query params * @return user list */ List<User> selectUnallocatedList(IPage<RoleWithUserDTO> page, RoleWithUserDTO roleWithUserDTO); /** * Insert a new user. * * @param user the user to be inserted * @return the number of rows affected */ int insertUser(User user); /** * Update an existing user. * * @param user the user with updated information * @return the number of rows affected */ int updateUser(User user); /** * Delete users by user ID. * * @param userIds the ids of the users to delete * @return the number of rows affected */ int deleteUserByIds(Integer[] userIds); /** * Changes the user's password. * * @param user The user object containing the necessary password information. * @return true if the password was successfully changed, false otherwise. */ boolean changePassword(User user); /** * Updates the status of the specified user. * * @param user the user whose status needs to be updated * @return true if the update is successful, false otherwise */ boolean updateUserStatus(User user); /** * Allocates roles to a user. * * @param user the user to whom the role should be allocated * @return the number of rows affected */ int allocateRole(User user); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/TableService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/TableService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.dto.AlterTableDTO; import org.apache.paimon.web.server.data.dto.TableDTO; import org.apache.paimon.web.server.data.vo.TableVO; import java.util.List; /** Table service. */ public interface TableService { /** * Checks if the specified table exists. * * @param tableDTO The TableDTO object containing information about the table * @return true if the table exists, false otherwise */ boolean tableExists(TableDTO tableDTO); /** * Creates a table in the database given ${@link TableDTO}. * * @param tableDTO The TableDTO object containing information about the table * @return true if the operation is successful, false otherwise */ boolean createTable(TableDTO tableDTO); /** * Adds a column to the table. * * @param tableDTO The TableDTO object containing information about the table * @return true if the operation is successful, false otherwise */ boolean addColumn(TableDTO tableDTO); /** * Drops a column from a table. * * @param catalogName The name of the catalog * @param databaseName The name of the database * @param tableName The name of the table * @param columnName The name of the column to be dropped * @return true if the operation is successful, false otherwise */ boolean dropColumn( String catalogName, String databaseName, String tableName, String columnName); /** * Alters a table. * * @param alterTableDTO the DTO containing alteration details * @return true if the operation is successful, false otherwise */ boolean alterTable(AlterTableDTO alterTableDTO); /** * Adds options to a table. * * @param tableDTO The TableDTO object containing information about the table * @return true if the operation is successful, false otherwise */ boolean addOption(TableDTO tableDTO); /** * Removes an option from a table. * * @param catalogName The name of the catalog * @param databaseName The name of the database * @param tableName The name of the table * @param key The key of the option to be removed * @return true if the operation is successful, false otherwise */ boolean removeOption(String catalogName, String databaseName, String tableName, String key); /** * Drops a table from the specified database in the given catalog. * * @param catalogName The name of the catalog from which the table will be dropped * @param databaseName The name of the database from which the table will be dropped * @param tableName The name of the table to be dropped * @return true if the operation is successful, false otherwise */ boolean dropTable(String catalogName, String databaseName, String tableName); /** * Renames a table in the specified database of the given catalog. * * @param catalogName The name of the catalog where the table resides * @param databaseName The name of the database where the table resides * @param fromTableName The current name of the table to be renamed * @param toTableName The new name for the table * @return true if the operation is successful, false otherwise */ boolean renameTable( String catalogName, String databaseName, String fromTableName, String toTableName); /** * Lists tables given {@link TableDTO} condition. * * @return Response object containing a list of {@link TableVO} representing the tables */ List<TableVO> listTables(TableDTO tableDTO); /** * Retrieves the column details of a specific table within the specified catalog and database. * * @param catalogName The name of the catalog where the table is located * @param databaseName The name of the database where the table is located * @param tableName The name of the table whose columns are to be retrieved * @return A {@link TableVO} object containing the details of the columns of the specified table */ TableVO listColumns(String catalogName, String databaseName, String tableName); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/StatementService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/StatementService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.StatementInfo; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import org.apache.ibatis.annotations.Param; import java.util.List; /** Statement Service. */ public interface StatementService extends IService<StatementInfo> { /** * Check if the statement name is unique. * * @param statementInfo the statement to check * @return true if unique, false otherwise */ boolean checkStatementNameUnique(StatementInfo statementInfo); /** * Saves a statement information entity. * * @param statementInfo The statement information to save * @return true if the statement was saved successfully, false otherwise */ boolean saveStatement(StatementInfo statementInfo); /** * Retrieves a paginated list of statement information entities. * * @param page the pagination information * @param statement the filter criteria * @return A list of StatementInfo entities for the specified page */ List<StatementInfo> listStatements( IPage<StatementInfo> page, @Param("statement") StatementInfo statement); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/UserTenantService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/UserTenantService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.UserTenant; import com.baomidou.mybatisplus.extension.service.IService; /** Tenant Service. */ public interface UserTenantService extends IService<UserTenant> {}
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/TenantService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/TenantService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.Tenant; import com.baomidou.mybatisplus.extension.service.IService; /** Tenant Service. */ public interface TenantService extends IService<Tenant> {}
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/LdapService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/LdapService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.User; import java.util.Optional; /** ldap service. */ public interface LdapService { /** * get user info by ldap user identification. * * @param uid login name of ldap user * @return {@link Optional} of {@link User} when user not exist then return {@link * Optional#empty()} */ Optional<User> getUser(String uid); /** * authenticate by ldap. * * @param name login name of ldap user * @param password login password of ldap user * @return {@link Optional} of {@link User} when user authenticate failed then return {@link * Optional#empty()} */ Optional<User> authenticate(String name, String password); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/JobExecutorService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/JobExecutorService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.engine.flink.common.executor.Executor; import org.springframework.stereotype.Service; import java.util.concurrent.ConcurrentHashMap; /** Job executor service. */ @Service public class JobExecutorService { private final ConcurrentHashMap<String, Executor> executors = new ConcurrentHashMap<>(); public Executor getExecutor(String sessionId) { return executors.get(sessionId); } public void addExecutor(String sessionId, Executor executor) { executors.put(sessionId, executor); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/JobService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/JobService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.dto.JobSubmitDTO; import org.apache.paimon.web.server.data.dto.ResultFetchDTO; import org.apache.paimon.web.server.data.dto.StopJobDTO; import org.apache.paimon.web.server.data.model.JobInfo; import org.apache.paimon.web.server.data.vo.JobStatisticsVO; import org.apache.paimon.web.server.data.vo.JobVO; import org.apache.paimon.web.server.data.vo.ResultDataVO; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** Job Service. */ public interface JobService extends IService<JobInfo> { /** * Submits a new job based on the provided job submission data. * * @param jobSubmitDTO the data transfer object containing job submission details * @return the job view object after submission */ JobVO submitJob(JobSubmitDTO jobSubmitDTO); /** * Fetches the result of a job specified by the result fetch data transfer object. * * @param resultFetchDTO the data transfer object containing job result fetching details * @return result data view object containing the job results */ ResultDataVO fetchResult(ResultFetchDTO resultFetchDTO); /** * Lists all jobs. * * @return a list of job view objects */ List<JobVO> listJobs(); /** * Lists jobs in a paginated format. * * @param current the current page number * @param size the number of jobs per page * @return a list of job view objects for the specified page */ List<JobVO> listJobsByPage(int current, int size); /** * Retrieves detailed information about a job identified by its job ID. * * @param id the unique identifier of the job * @return job information object */ JobInfo getJobById(String id); /** * Retrieves statistics about jobs. * * @return a job statistics view object containing aggregated job data */ JobStatisticsVO getJobStatistics(); /** * Stops a job as specified by the stop job data transfer object. * * @param stopJobDTO the data transfer object containing job stopping details */ void stop(StopJobDTO stopJobDTO); /** * Refreshes the status of a job based on the specified task type. * * @param taskType the type of task for which the job status needs to be updated */ void refreshJobStatus(String taskType); /** * Fetches log entries for a given user ID. * * @param userId the user's ID * @return log entries as a string */ String getLogsByUserId(String userId); /** * Clears the log associated with the specified user. * * @param userId the user's ID * @return log entries as a string */ String clearLog(String userId); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/PermissionService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/PermissionService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.constant.Constants; import cn.dev33.satoken.stp.StpInterface; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** Permission service by sa-token. TODO add cache */ @Component public class PermissionService implements StpInterface { @Autowired private SysRoleService roleService; @Autowired private SysMenuService menuService; /** * Get permission list by user ID. * * @param userId user id * @param loginType login type * @return permission list */ @Override public List<String> getPermissionList(Object userId, String loginType) { Preconditions.checkArgument(userId != null); int userIdNum = Integer.parseInt(userId.toString()); Set<String> perms = new HashSet<String>(); if (userIdNum == Constants.ADMIN_ID) { perms.add(Constants.ALL_PERMISSION); } else { List<Integer> roles = roleService.selectRoleListByUserId(userIdNum); if (!CollectionUtils.isEmpty(roles)) { for (int roleId : roles) { Set<String> rolePerms = menuService.selectMenuPermsByRoleId(roleId); perms.addAll(rolePerms); } } else { perms.addAll(menuService.selectMenuPermsByUserId(userIdNum)); } } return new ArrayList<>(perms); } /** * Get role list by user ID. * * @param userId user ID * @param loginType login type * @return role list */ @Override public List<String> getRoleList(Object userId, String loginType) { Preconditions.checkArgument(userId != null); Set<String> roles = new HashSet<String>( roleService.selectRolePermissionByUserId( Integer.valueOf(userId.toString()))); return new ArrayList<>(roles); } }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/ClusterService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/ClusterService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.ClusterInfo; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import org.apache.ibatis.annotations.Param; import java.util.List; /** Cluster Service. */ public interface ClusterService extends IService<ClusterInfo> { List<ClusterInfo> listUsers(IPage<ClusterInfo> page, @Param("cluster") ClusterInfo cluster); boolean checkClusterNameUnique(ClusterInfo cluster); int deleteClusterByIds(Integer[] clusterIds); boolean checkClusterHeartbeatStatus(ClusterInfo clusterInfo); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/SysRoleService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/SysRoleService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.SysRole; import org.apache.paimon.web.server.data.model.UserRole; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; import java.util.Set; /** Role service. */ public interface SysRoleService extends IService<SysRole> { /** * Paging and querying role data based on conditions. * * @param page page params * @param role query params * @return role list */ List<SysRole> listRoles(IPage<SysRole> page, SysRole role); /** * Query role list based on user ID. * * @param userId user ID * @return role list */ List<SysRole> selectRolesByUserId(Integer userId); /** * Query role permissions based on user ID. * * @param userId user ID * @return permissions */ Set<String> selectRolePermissionByUserId(Integer userId); /** * Query user role list by user ID. * * @param userId user ID * @return role list */ List<Integer> selectRoleListByUserId(Integer userId); /** * Query role info by role ID. * * @param roleId role ID * @return role info */ SysRole getRoleById(Integer roleId); /** * Verify if the role name is unique. * * @param role role info * @return result */ boolean checkRoleNameUnique(SysRole role); /** * Verify whether role permissions are unique. * * @param role role info * @return result */ boolean checkRoleKeyUnique(SysRole role); /** * Verify whether the role allows operations. * * @param role role info */ boolean checkRoleAllowed(SysRole role); /** * Save role information. * * @param role role info * @return result */ int insertRole(SysRole role); /** * Update role information. * * @param role role info * @return result */ int updateRole(SysRole role); /** * Delete role through role ID. * * @param roleId role ID * @return result */ int deleteRoleById(Integer roleId); /** * Batch delete role information. * * @param roleIds role IDs * @return result */ int deleteRoleByIds(Integer[] roleIds); /** * Unauthorize user role. * * @param userRole user-role * @return result */ int deleteAuthUser(UserRole userRole); /** * Batch unauthorization of user roles. * * @param roleId role ID * @param userIds user IDs that needs to be unlicensed * @return 结果 */ int deleteAuthUsers(Integer roleId, Integer[] userIds); /** * Batch selection of authorized user roles. * * @param roleId role ID * @param userIds user IDs that needs to be deleted * @return result */ int insertAuthUsers(Integer roleId, Integer[] userIds); /** * Query the number of role usage through role ID. * * @param roleId role ID * @return result */ int countUserRoleByRoleId(Integer roleId); /** * Update Role Status. * * @param role role info * @return result */ boolean updateRoleStatus(SysRole role); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/CdcJobDefinitionService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/CdcJobDefinitionService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.dto.CdcJobDefinitionDTO; import org.apache.paimon.web.server.data.dto.CdcJobSubmitDTO; import org.apache.paimon.web.server.data.model.CdcJobDefinition; import org.apache.paimon.web.server.data.result.PageR; import org.apache.paimon.web.server.data.result.R; import com.baomidou.mybatisplus.extension.service.IService; /** Cdc Job Definition Service. */ public interface CdcJobDefinitionService extends IService<CdcJobDefinition> { R<Void> create(CdcJobDefinitionDTO cdcJobDefinitionDTO); PageR<CdcJobDefinition> listAll( String name, boolean withConfig, long currentPage, long pageSize); R<Void> update(CdcJobDefinitionDTO cdcJobDefinitionDTO); R<Void> submit(Integer id, CdcJobSubmitDTO cdcJobSubmitDTO); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/CatalogService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/CatalogService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.dto.CatalogDTO; import org.apache.paimon.web.server.data.model.CatalogInfo; import com.baomidou.mybatisplus.extension.service.IService; /** Catalog Service. */ public interface CatalogService extends IService<CatalogInfo> { /** * Verify if the catalog name is unique. * * @param catalog catalog info * @return result */ boolean checkCatalogNameUnique(CatalogDTO catalog); /** * Creates a catalog. * * @param catalogDTO the data transfer object for catalog creation * @return true if creation is successful, false otherwise */ boolean createCatalog(CatalogDTO catalogDTO); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false
apache/paimon-webui
https://github.com/apache/paimon-webui/blob/ef0db0b0189c2aa4f47056543fdb063120868ec2/paimon-web-server/src/main/java/org/apache/paimon/web/server/service/SysMenuService.java
paimon-web-server/src/main/java/org/apache/paimon/web/server/service/SysMenuService.java
/* * 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.paimon.web.server.service; import org.apache.paimon.web.server.data.model.SysMenu; import org.apache.paimon.web.server.data.tree.TreeSelect; import org.apache.paimon.web.server.data.vo.RouterVO; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; import java.util.Set; /** Menu service. */ public interface SysMenuService extends IService<SysMenu> { /** * Query menu list by user. * * @return menu list */ List<SysMenu> selectMenuList(); /** * Query menu list. * * @param menu query params * @return menu list */ List<SysMenu> selectMenuList(SysMenu menu); /** * Query permissions by user ID. * * @param userId user ID * @return permission List */ Set<String> selectMenuPermsByUserId(Integer userId); /** * Query permissions by role ID. * * @param roleId role ID * @return permission List */ Set<String> selectMenuPermsByRoleId(Integer roleId); /** * Query menu list by user ID. * * @param userId user ID * @return menu list */ List<SysMenu> selectMenuTreeByUserId(Integer userId); /** * Query menu tree information by role ID. * * @param roleId role ID * @return selected menu list */ List<Integer> selectMenuListByRoleId(Integer roleId); /** * Build router by menu. * * @param menus menu list * @return router list */ List<RouterVO> buildMenus(List<SysMenu> menus); /** * Builder menu tree. * * @param menus menu list * @return menu tree */ List<SysMenu> buildMenuTree(List<SysMenu> menus); /** * Builder tree select by menu. * * @param menus menu list * @return menu tree select */ List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus); /** * Query menu info by menu ID. * * @param menuId menu ID * @return menu info */ SysMenu selectMenuById(Integer menuId); /** * Is there a menu sub node present. * * @param menuId menu ID * @return result */ boolean hasChildByMenuId(Integer menuId); /** * Query menu usage quantity. * * @param menuId menu ID * @return result */ boolean checkMenuExistRole(Integer menuId); /** * Add menu. * * @param menu menu info * @return result */ boolean insertMenu(SysMenu menu); /** * Update menu. * * @param menu menu info * @return result */ boolean updateMenu(SysMenu menu); /** * Delete menu. * * @param menuId menu ID * @return result */ boolean deleteMenuById(Integer menuId); /** * Verify if the menu name is unique. * * @param menu menu info * @return result */ boolean checkMenuNameUnique(SysMenu menu); }
java
Apache-2.0
ef0db0b0189c2aa4f47056543fdb063120868ec2
2026-01-05T02:42:23.250368Z
false