repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
AlexAUT/Kroniax
core/src/com/alexaut/kroniax/Application.java
// Path: core/src/com/alexaut/kroniax/game/ProgressManager.java // public class ProgressManager { // private Preferences mUnlockedLevels; // // public ProgressManager() { // mUnlockedLevels = Gdx.app.getPreferences("progress"); // if (!mUnlockedLevels.contains("unlocked_levels")) { // mUnlockedLevels.putInteger("unlocked_levels", 1); // mUnlockedLevels.flush(); // } // } // // public int getUnlockedLevels() { // return mUnlockedLevels.getInteger("unlocked_levels"); // } // // public void finishedLevel(int lvlNumber) { // if (lvlNumber >= mUnlockedLevels.getInteger("unlocked_levels")) { // mUnlockedLevels.putInteger("unlocked_levels", lvlNumber + 1); // mUnlockedLevels.flush(); // } // } // } // // Path: core/src/com/alexaut/kroniax/screens/MenuScene.java // public class MenuScene implements Screen { // // private Application mApp; // // private MenuBackground mBackground; // private Gui mGui; // // private Music mMusic; // // private SpriteBatch mSpriteBatch; // private ShapeRenderer mShapeRenderer; // // public MenuScene(Application app) { // mApp = app; // // mBackground = new MenuBackground(); // mGui = new Gui(app); // // mSpriteBatch = app.getSpriteBatch(); // mShapeRenderer = app.getShapeRenderer(); // } // // @Override // public void show() { // mMusic = Gdx.audio.newMusic(Gdx.files.internal("data/music/PowerFight-ElectroTechnoBeat.ogg")); // mMusic.setVolume(0.75f); // if (mApp.isMusicEnabled()) // mMusic.play(); // mMusic.setLooping(true); // // mGui.show(); // mGui.fadeActiveIn(); // } // // @Override // public void render(float delta) { // mBackground.update(Gdx.graphics.getDeltaTime()); // mGui.update(Gdx.graphics.getDeltaTime()); // // Gdx.gl.glClearColor(0, 0, 0, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // // mStage.getViewport().setCamera(mCamera); // // mBackground.render(mSpriteBatch, mShapeRenderer); // // mSpriteBatch.begin(); // mGui.render(mSpriteBatch); // mSpriteBatch.end(); // } // // @Override // public void resize(int width, int height) { // mGui.updateViewport(width, height); // mBackground.updateViewport(width, height); // } // // @Override // public void pause() { // // TODO Auto-generated method stub // mMusic.pause(); // } // // @Override // public void resume() { // // TODO Auto-generated method stub // if (mApp.isMusicEnabled()) // mMusic.play(); // } // // @Override // public void hide() { // mGui.hide(); // mMusic.stop(); // } // // @Override // public void dispose() { // // TODO Auto-generated method stub // mGui.dispose(); // mBackground.dispose(); // mMusic.dispose(); // } // // public void updateMusicState() { // if (mApp.isMusicEnabled()) // mMusic.play(); // else // mMusic.stop(); // } // }
import com.alexaut.kroniax.game.ProgressManager; import com.alexaut.kroniax.screens.MenuScene; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.scenes.scene2d.ui.Skin;
package com.alexaut.kroniax; public class Application extends Game { private SpriteBatch mSpriteBatch; private ShapeRenderer mShapeRenderer; private Skin mSkin; private ProgressManager mProgressManager; private Preferences mSettings;
// Path: core/src/com/alexaut/kroniax/game/ProgressManager.java // public class ProgressManager { // private Preferences mUnlockedLevels; // // public ProgressManager() { // mUnlockedLevels = Gdx.app.getPreferences("progress"); // if (!mUnlockedLevels.contains("unlocked_levels")) { // mUnlockedLevels.putInteger("unlocked_levels", 1); // mUnlockedLevels.flush(); // } // } // // public int getUnlockedLevels() { // return mUnlockedLevels.getInteger("unlocked_levels"); // } // // public void finishedLevel(int lvlNumber) { // if (lvlNumber >= mUnlockedLevels.getInteger("unlocked_levels")) { // mUnlockedLevels.putInteger("unlocked_levels", lvlNumber + 1); // mUnlockedLevels.flush(); // } // } // } // // Path: core/src/com/alexaut/kroniax/screens/MenuScene.java // public class MenuScene implements Screen { // // private Application mApp; // // private MenuBackground mBackground; // private Gui mGui; // // private Music mMusic; // // private SpriteBatch mSpriteBatch; // private ShapeRenderer mShapeRenderer; // // public MenuScene(Application app) { // mApp = app; // // mBackground = new MenuBackground(); // mGui = new Gui(app); // // mSpriteBatch = app.getSpriteBatch(); // mShapeRenderer = app.getShapeRenderer(); // } // // @Override // public void show() { // mMusic = Gdx.audio.newMusic(Gdx.files.internal("data/music/PowerFight-ElectroTechnoBeat.ogg")); // mMusic.setVolume(0.75f); // if (mApp.isMusicEnabled()) // mMusic.play(); // mMusic.setLooping(true); // // mGui.show(); // mGui.fadeActiveIn(); // } // // @Override // public void render(float delta) { // mBackground.update(Gdx.graphics.getDeltaTime()); // mGui.update(Gdx.graphics.getDeltaTime()); // // Gdx.gl.glClearColor(0, 0, 0, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // // mStage.getViewport().setCamera(mCamera); // // mBackground.render(mSpriteBatch, mShapeRenderer); // // mSpriteBatch.begin(); // mGui.render(mSpriteBatch); // mSpriteBatch.end(); // } // // @Override // public void resize(int width, int height) { // mGui.updateViewport(width, height); // mBackground.updateViewport(width, height); // } // // @Override // public void pause() { // // TODO Auto-generated method stub // mMusic.pause(); // } // // @Override // public void resume() { // // TODO Auto-generated method stub // if (mApp.isMusicEnabled()) // mMusic.play(); // } // // @Override // public void hide() { // mGui.hide(); // mMusic.stop(); // } // // @Override // public void dispose() { // // TODO Auto-generated method stub // mGui.dispose(); // mBackground.dispose(); // mMusic.dispose(); // } // // public void updateMusicState() { // if (mApp.isMusicEnabled()) // mMusic.play(); // else // mMusic.stop(); // } // } // Path: core/src/com/alexaut/kroniax/Application.java import com.alexaut.kroniax.game.ProgressManager; import com.alexaut.kroniax.screens.MenuScene; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.scenes.scene2d.ui.Skin; package com.alexaut.kroniax; public class Application extends Game { private SpriteBatch mSpriteBatch; private ShapeRenderer mShapeRenderer; private Skin mSkin; private ProgressManager mProgressManager; private Preferences mSettings;
private MenuScene mMenuScene;
AlexAUT/Kroniax
android/src/com/alexaut/kroniax/android/AndroidLauncher.java
// Path: core/src/com/alexaut/kroniax/Application.java // public class Application extends Game { // // private SpriteBatch mSpriteBatch; // private ShapeRenderer mShapeRenderer; // // private Skin mSkin; // // private ProgressManager mProgressManager; // private Preferences mSettings; // // private MenuScene mMenuScene; // // @Override // public void create() { // mSpriteBatch = new SpriteBatch(); // mShapeRenderer = new ShapeRenderer(); // mSkin = new Skin(Gdx.files.internal("data/skins/menu.json")); // mProgressManager = new ProgressManager(); // mSettings = Gdx.app.getPreferences("settings"); // // mMenuScene = new MenuScene(this); // // setScreen(mMenuScene); // } // // @Override // public void dispose() { // // TODO Auto-generated method stub // super.dispose(); // mSpriteBatch.dispose(); // mShapeRenderer.dispose(); // mMenuScene.dispose(); // } // // @Override // public void pause() { // // TODO Auto-generated method stub // super.pause(); // } // // @Override // public void resume() { // // TODO Auto-generated method stub // super.resume(); // } // // @Override // public void render() { // // // TODO Auto-generated method stub // super.render(); // } // // @Override // public void resize(int width, int height) { // // TODO Auto-generated method stub // super.resize(width, height); // } // // public SpriteBatch getSpriteBatch() { // return mSpriteBatch; // } // // public ShapeRenderer getShapeRenderer() { // return mShapeRenderer; // } // // public Skin getGuiSkin() { // return mSkin; // } // // public ProgressManager getProgressManager() { // return mProgressManager; // } // // public MenuScene getMenuScene() { // return mMenuScene; // } // // public void toogleMusicEnabled() { // boolean current = mSettings.getBoolean("music", true); // mSettings.putBoolean("music", !current); // mSettings.flush(); // mMenuScene.updateMusicState(); // } // // public boolean isMusicEnabled() { // return mSettings.getBoolean("music", true); // } // // }
import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.alexaut.kroniax.Application;
package com.alexaut.kroniax.android; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// Path: core/src/com/alexaut/kroniax/Application.java // public class Application extends Game { // // private SpriteBatch mSpriteBatch; // private ShapeRenderer mShapeRenderer; // // private Skin mSkin; // // private ProgressManager mProgressManager; // private Preferences mSettings; // // private MenuScene mMenuScene; // // @Override // public void create() { // mSpriteBatch = new SpriteBatch(); // mShapeRenderer = new ShapeRenderer(); // mSkin = new Skin(Gdx.files.internal("data/skins/menu.json")); // mProgressManager = new ProgressManager(); // mSettings = Gdx.app.getPreferences("settings"); // // mMenuScene = new MenuScene(this); // // setScreen(mMenuScene); // } // // @Override // public void dispose() { // // TODO Auto-generated method stub // super.dispose(); // mSpriteBatch.dispose(); // mShapeRenderer.dispose(); // mMenuScene.dispose(); // } // // @Override // public void pause() { // // TODO Auto-generated method stub // super.pause(); // } // // @Override // public void resume() { // // TODO Auto-generated method stub // super.resume(); // } // // @Override // public void render() { // // // TODO Auto-generated method stub // super.render(); // } // // @Override // public void resize(int width, int height) { // // TODO Auto-generated method stub // super.resize(width, height); // } // // public SpriteBatch getSpriteBatch() { // return mSpriteBatch; // } // // public ShapeRenderer getShapeRenderer() { // return mShapeRenderer; // } // // public Skin getGuiSkin() { // return mSkin; // } // // public ProgressManager getProgressManager() { // return mProgressManager; // } // // public MenuScene getMenuScene() { // return mMenuScene; // } // // public void toogleMusicEnabled() { // boolean current = mSettings.getBoolean("music", true); // mSettings.putBoolean("music", !current); // mSettings.flush(); // mMenuScene.updateMusicState(); // } // // public boolean isMusicEnabled() { // return mSettings.getBoolean("music", true); // } // // } // Path: android/src/com/alexaut/kroniax/android/AndroidLauncher.java import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.alexaut.kroniax.Application; package com.alexaut.kroniax.android; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new Application(), config);
Vauff/Maunz-Discord
src/com/vauff/maunzdiscord/commands/templates/AbstractLegacyCommand.java
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // }
import com.vauff.maunzdiscord.objects.Await; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel;
package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractLegacyCommand<M extends MessageCreateEvent> extends AbstractCommand { /** * Executes this command * * @param event The event by which this command got triggered * @throws Exception If an exception gets thrown by any implementing methods */ public abstract void exe(M event, MessageChannel channel, User author) throws Exception; /** * Gets called when a reaction is added to a message defined prior in {@link AbstractLegacyCommand#waitForReaction(Snowflake, Snowflake)} * * @param event The event holding information about the added reaction * @param message The Message that was reacted to */ public void onReactionAdd(ReactionAddEvent event, Message message) throws Exception { } /** * Sets up this command to await a reaction by the user who triggered this command * * @param messageID The message which should get reacted on * @param userID The user who triggered this command */ public final void waitForReaction(Snowflake messageID, Snowflake userID) {
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // Path: src/com/vauff/maunzdiscord/commands/templates/AbstractLegacyCommand.java import com.vauff.maunzdiscord.objects.Await; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel; package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractLegacyCommand<M extends MessageCreateEvent> extends AbstractCommand { /** * Executes this command * * @param event The event by which this command got triggered * @throws Exception If an exception gets thrown by any implementing methods */ public abstract void exe(M event, MessageChannel channel, User author) throws Exception; /** * Gets called when a reaction is added to a message defined prior in {@link AbstractLegacyCommand#waitForReaction(Snowflake, Snowflake)} * * @param event The event holding information about the added reaction * @param message The Message that was reacted to */ public void onReactionAdd(ReactionAddEvent event, Message message) throws Exception { } /** * Sets up this command to await a reaction by the user who triggered this command * * @param messageID The message which should get reacted on * @param userID The user who triggered this command */ public final void waitForReaction(Snowflake messageID, Snowflake userID) {
AWAITED.put(messageID, new Await(userID, this));
Vauff/Maunz-Discord
src/com/vauff/maunzdiscord/commands/templates/AbstractCommand.java
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // }
import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import java.util.HashMap;
package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractCommand { /** * Holds all messages as keys which await a reaction by a specific user. * The values hold an instance of {@link Await} */
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // } // Path: src/com/vauff/maunzdiscord/commands/templates/AbstractCommand.java import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import java.util.HashMap; package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractCommand { /** * Holds all messages as keys which await a reaction by a specific user. * The values hold an instance of {@link Await} */
public static final HashMap<Snowflake, Await> AWAITED = new HashMap<>();
Vauff/Maunz-Discord
src/com/vauff/maunzdiscord/commands/templates/AbstractCommand.java
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // }
import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import java.util.HashMap;
package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractCommand { /** * Holds all messages as keys which await a reaction by a specific user. * The values hold an instance of {@link Await} */ public static final HashMap<Snowflake, Await> AWAITED = new HashMap<>(); /** * Enum holding the different bot permissions commands may require to use * * EVERYONE - No permission required * GUILD_ADMIN - ADMINISTRATOR or MANAGE_GUILD permission required * BOT_ADMIN - User must be listed in config.json botOwners */ public enum BotPermission { EVERYONE, GUILD_ADMIN, BOT_ADMIN } /** * Defines aliases that can be used to trigger the command. * The main alias should also be defined in here * * @return A string array of all valid aliases */ public abstract String[] getAliases(); /** * Helper method that returns the primary (first) alias * * @return The primary alias */ public final String getFirstAlias() { return getAliases()[0]; } /** * An array of CommandHelp objects that hold information about the command to display in /help * * @return An array of {@link CommandHelp} */
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // } // Path: src/com/vauff/maunzdiscord/commands/templates/AbstractCommand.java import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import java.util.HashMap; package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractCommand { /** * Holds all messages as keys which await a reaction by a specific user. * The values hold an instance of {@link Await} */ public static final HashMap<Snowflake, Await> AWAITED = new HashMap<>(); /** * Enum holding the different bot permissions commands may require to use * * EVERYONE - No permission required * GUILD_ADMIN - ADMINISTRATOR or MANAGE_GUILD permission required * BOT_ADMIN - User must be listed in config.json botOwners */ public enum BotPermission { EVERYONE, GUILD_ADMIN, BOT_ADMIN } /** * Defines aliases that can be used to trigger the command. * The main alias should also be defined in here * * @return A string array of all valid aliases */ public abstract String[] getAliases(); /** * Helper method that returns the primary (first) alias * * @return The primary alias */ public final String getFirstAlias() { return getAliases()[0]; } /** * An array of CommandHelp objects that hold information about the command to display in /help * * @return An array of {@link CommandHelp} */
public abstract CommandHelp[] getHelp();
Vauff/Maunz-Discord
src/com/vauff/maunzdiscord/commands/templates/AbstractSlashCommand.java
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // }
import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.discordjson.json.ApplicationCommandOptionData; import discord4j.discordjson.json.ApplicationCommandRequest; import java.util.ArrayList; import java.util.List; import java.util.Objects;
package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractSlashCommand<M extends ChatInputInteractionEvent> extends AbstractCommand { /** * Executes this command * * @param interaction The interaction that executing this command creates * @throws Exception If an exception gets thrown by any implementing methods */ public abstract void exe(M interaction, Guild guild, MessageChannel channel, User author) throws Exception; /** * Gets called when a reaction is added to a message defined prior in {@link AbstractSlashCommand#waitForReaction(Snowflake, Snowflake, ChatInputInteractionEvent)} * * @param reactionEvent The event holding information about the added reaction * @param interactionEvent The interaction event that triggered this * @param message The Message that was reacted to */ public void onReactionAdd(ReactionAddEvent reactionEvent, ChatInputInteractionEvent interactionEvent, Message message) throws Exception { } /** * Returns the ApplicationCommandRequest object for this command */ public abstract ApplicationCommandRequest getCommand(); /** * Defines the name used to trigger the command. * * @return A string containing the name of the command */ public abstract String getName(); /** * Sets up this command to await a reaction by the user who triggered this command * * @param messageID The message which should get reacted on * @param userID The user who triggered this command */ public final void waitForReaction(Snowflake messageID, Snowflake userID, ChatInputInteractionEvent event) {
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // } // Path: src/com/vauff/maunzdiscord/commands/templates/AbstractSlashCommand.java import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.discordjson.json.ApplicationCommandOptionData; import discord4j.discordjson.json.ApplicationCommandRequest; import java.util.ArrayList; import java.util.List; import java.util.Objects; package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractSlashCommand<M extends ChatInputInteractionEvent> extends AbstractCommand { /** * Executes this command * * @param interaction The interaction that executing this command creates * @throws Exception If an exception gets thrown by any implementing methods */ public abstract void exe(M interaction, Guild guild, MessageChannel channel, User author) throws Exception; /** * Gets called when a reaction is added to a message defined prior in {@link AbstractSlashCommand#waitForReaction(Snowflake, Snowflake, ChatInputInteractionEvent)} * * @param reactionEvent The event holding information about the added reaction * @param interactionEvent The interaction event that triggered this * @param message The Message that was reacted to */ public void onReactionAdd(ReactionAddEvent reactionEvent, ChatInputInteractionEvent interactionEvent, Message message) throws Exception { } /** * Returns the ApplicationCommandRequest object for this command */ public abstract ApplicationCommandRequest getCommand(); /** * Defines the name used to trigger the command. * * @return A string containing the name of the command */ public abstract String getName(); /** * Sets up this command to await a reaction by the user who triggered this command * * @param messageID The message which should get reacted on * @param userID The user who triggered this command */ public final void waitForReaction(Snowflake messageID, Snowflake userID, ChatInputInteractionEvent event) {
AWAITED.put(messageID, new Await(userID, this, event));
Vauff/Maunz-Discord
src/com/vauff/maunzdiscord/commands/templates/AbstractSlashCommand.java
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // }
import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.discordjson.json.ApplicationCommandOptionData; import discord4j.discordjson.json.ApplicationCommandRequest; import java.util.ArrayList; import java.util.List; import java.util.Objects;
package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractSlashCommand<M extends ChatInputInteractionEvent> extends AbstractCommand { /** * Executes this command * * @param interaction The interaction that executing this command creates * @throws Exception If an exception gets thrown by any implementing methods */ public abstract void exe(M interaction, Guild guild, MessageChannel channel, User author) throws Exception; /** * Gets called when a reaction is added to a message defined prior in {@link AbstractSlashCommand#waitForReaction(Snowflake, Snowflake, ChatInputInteractionEvent)} * * @param reactionEvent The event holding information about the added reaction * @param interactionEvent The interaction event that triggered this * @param message The Message that was reacted to */ public void onReactionAdd(ReactionAddEvent reactionEvent, ChatInputInteractionEvent interactionEvent, Message message) throws Exception { } /** * Returns the ApplicationCommandRequest object for this command */ public abstract ApplicationCommandRequest getCommand(); /** * Defines the name used to trigger the command. * * @return A string containing the name of the command */ public abstract String getName(); /** * Sets up this command to await a reaction by the user who triggered this command * * @param messageID The message which should get reacted on * @param userID The user who triggered this command */ public final void waitForReaction(Snowflake messageID, Snowflake userID, ChatInputInteractionEvent event) { AWAITED.put(messageID, new Await(userID, this, event)); } @Override public final String[] getAliases() { return new String[] { getName() }; } @Override
// Path: src/com/vauff/maunzdiscord/objects/Await.java // public class Await // { // private Snowflake id; // private AbstractCommand command; // private ChatInputInteractionEvent event; // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command} // */ // public Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event) // { // this.id = id; // this.command = command; // this.event = event; // } // // /** // * @param id An ID of a user who triggered the message or a message to be removed later on // * @param command The command with which to continue execution upon adding a reaction // */ // public Await(Snowflake id, AbstractCommand command) // { // this(id, command, null); // } // // /** // * @return The ID of the user who triggered the message or of the message to be removed later on // */ // public Snowflake getID() // { // return id; // } // // /** // * @return The command with which to continue execution upon adding a reaction // */ // public AbstractCommand getCommand() // { // return command; // } // // /** // * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand} // */ // public ChatInputInteractionEvent getInteractionEvent() // { // return event; // } // } // // Path: src/com/vauff/maunzdiscord/objects/CommandHelp.java // public class CommandHelp // { // private String arguments; // private String description; // // /** // * @param arguments Arguments available for this command // * @param description Description of what this command does // */ // public CommandHelp(String arguments, String description) // { // this.arguments = arguments; // this.description = description; // } // // /** // * @return The arguments available for this command // */ // public String getArguments() // { // return arguments; // } // // /** // * @return The description of what this command does // */ // public String getDescription() // { // return description; // } // // /** // * @param arguments The arguments available for this command // */ // public void setArguments(String arguments) // { // this.arguments = arguments; // } // } // Path: src/com/vauff/maunzdiscord/commands/templates/AbstractSlashCommand.java import com.vauff.maunzdiscord.objects.Await; import com.vauff.maunzdiscord.objects.CommandHelp; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.discordjson.json.ApplicationCommandOptionData; import discord4j.discordjson.json.ApplicationCommandRequest; import java.util.ArrayList; import java.util.List; import java.util.Objects; package com.vauff.maunzdiscord.commands.templates; public abstract class AbstractSlashCommand<M extends ChatInputInteractionEvent> extends AbstractCommand { /** * Executes this command * * @param interaction The interaction that executing this command creates * @throws Exception If an exception gets thrown by any implementing methods */ public abstract void exe(M interaction, Guild guild, MessageChannel channel, User author) throws Exception; /** * Gets called when a reaction is added to a message defined prior in {@link AbstractSlashCommand#waitForReaction(Snowflake, Snowflake, ChatInputInteractionEvent)} * * @param reactionEvent The event holding information about the added reaction * @param interactionEvent The interaction event that triggered this * @param message The Message that was reacted to */ public void onReactionAdd(ReactionAddEvent reactionEvent, ChatInputInteractionEvent interactionEvent, Message message) throws Exception { } /** * Returns the ApplicationCommandRequest object for this command */ public abstract ApplicationCommandRequest getCommand(); /** * Defines the name used to trigger the command. * * @return A string containing the name of the command */ public abstract String getName(); /** * Sets up this command to await a reaction by the user who triggered this command * * @param messageID The message which should get reacted on * @param userID The user who triggered this command */ public final void waitForReaction(Snowflake messageID, Snowflake userID, ChatInputInteractionEvent event) { AWAITED.put(messageID, new Await(userID, this, event)); } @Override public final String[] getAliases() { return new String[] { getName() }; } @Override
public final CommandHelp[] getHelp()
kite-sdk/kite-examples
logging-webapp/src/test/java/org/kitesdk/examples/logging/webapp/ITLoggingWebapp.java
// Path: logging/src/main/java/org/kitesdk/examples/logging/CreateDataset.java // public class CreateDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Create a dataset of events with the Avro schema // DatasetDescriptor descriptor = new DatasetDescriptor.Builder() // .schemaUri("resource:event.avsc") // .build(); // Datasets.create("dataset:hive:/tmp/data/default/events", descriptor); // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new CreateDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/DeleteDataset.java // public class DeleteDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Drop the events dataset // boolean success = Datasets.delete("dataset:hive:/tmp/data/default/events"); // // return success ? 0 : 1; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new DeleteDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/ReadDataset.java // public class ReadDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Load the events dataset // Dataset<GenericRecord> events = Datasets.load("dataset:hive:/tmp/data/default/events"); // // // Get a reader for the dataset and read all the events // DatasetReader<GenericRecord> reader = events.newReader(); // try { // for (GenericRecord event : reader) { // System.out.println(event); // } // } finally { // reader.close(); // } // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new ReadDataset(), args); // System.exit(rc); // } // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.flume.clients.log4jappender.Log4jAppender; import org.apache.hadoop.util.Tool; import org.apache.http.client.fluent.Request; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hamcrest.Matcher; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kitesdk.examples.logging.CreateDataset; import org.kitesdk.examples.logging.DeleteDataset; import org.kitesdk.examples.logging.ReadDataset; import org.kitesdk.minicluster.FlumeService; import org.kitesdk.minicluster.HdfsService; import org.kitesdk.minicluster.HiveService; import org.kitesdk.minicluster.MiniCluster; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString;
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.examples.logging.webapp; public class ITLoggingWebapp { @Rule public static TemporaryFolder folder = new TemporaryFolder(); private static MiniCluster cluster; private Tomcat tomcat; @BeforeClass public static void startCluster() throws Exception { cluster = new MiniCluster.Builder().workDir("target/kite-minicluster").clean(true) .addService(HdfsService.class) .addService(HiveService.class) .addService(FlumeService.class).flumeAgentName("tier1") .flumeConfiguration("resource:flume.properties") .build(); cluster.start(); Thread.sleep(5000L); configureLog4j(); } @Before public void setUp() throws Exception { try { // delete dataset in case it already exists
// Path: logging/src/main/java/org/kitesdk/examples/logging/CreateDataset.java // public class CreateDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Create a dataset of events with the Avro schema // DatasetDescriptor descriptor = new DatasetDescriptor.Builder() // .schemaUri("resource:event.avsc") // .build(); // Datasets.create("dataset:hive:/tmp/data/default/events", descriptor); // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new CreateDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/DeleteDataset.java // public class DeleteDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Drop the events dataset // boolean success = Datasets.delete("dataset:hive:/tmp/data/default/events"); // // return success ? 0 : 1; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new DeleteDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/ReadDataset.java // public class ReadDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Load the events dataset // Dataset<GenericRecord> events = Datasets.load("dataset:hive:/tmp/data/default/events"); // // // Get a reader for the dataset and read all the events // DatasetReader<GenericRecord> reader = events.newReader(); // try { // for (GenericRecord event : reader) { // System.out.println(event); // } // } finally { // reader.close(); // } // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new ReadDataset(), args); // System.exit(rc); // } // } // Path: logging-webapp/src/test/java/org/kitesdk/examples/logging/webapp/ITLoggingWebapp.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.flume.clients.log4jappender.Log4jAppender; import org.apache.hadoop.util.Tool; import org.apache.http.client.fluent.Request; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hamcrest.Matcher; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kitesdk.examples.logging.CreateDataset; import org.kitesdk.examples.logging.DeleteDataset; import org.kitesdk.examples.logging.ReadDataset; import org.kitesdk.minicluster.FlumeService; import org.kitesdk.minicluster.HdfsService; import org.kitesdk.minicluster.HiveService; import org.kitesdk.minicluster.MiniCluster; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString; /** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.examples.logging.webapp; public class ITLoggingWebapp { @Rule public static TemporaryFolder folder = new TemporaryFolder(); private static MiniCluster cluster; private Tomcat tomcat; @BeforeClass public static void startCluster() throws Exception { cluster = new MiniCluster.Builder().workDir("target/kite-minicluster").clean(true) .addService(HdfsService.class) .addService(HiveService.class) .addService(FlumeService.class).flumeAgentName("tier1") .flumeConfiguration("resource:flume.properties") .build(); cluster.start(); Thread.sleep(5000L); configureLog4j(); } @Before public void setUp() throws Exception { try { // delete dataset in case it already exists
run(any(Integer.class), any(String.class), new DeleteDataset());
kite-sdk/kite-examples
logging-webapp/src/test/java/org/kitesdk/examples/logging/webapp/ITLoggingWebapp.java
// Path: logging/src/main/java/org/kitesdk/examples/logging/CreateDataset.java // public class CreateDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Create a dataset of events with the Avro schema // DatasetDescriptor descriptor = new DatasetDescriptor.Builder() // .schemaUri("resource:event.avsc") // .build(); // Datasets.create("dataset:hive:/tmp/data/default/events", descriptor); // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new CreateDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/DeleteDataset.java // public class DeleteDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Drop the events dataset // boolean success = Datasets.delete("dataset:hive:/tmp/data/default/events"); // // return success ? 0 : 1; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new DeleteDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/ReadDataset.java // public class ReadDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Load the events dataset // Dataset<GenericRecord> events = Datasets.load("dataset:hive:/tmp/data/default/events"); // // // Get a reader for the dataset and read all the events // DatasetReader<GenericRecord> reader = events.newReader(); // try { // for (GenericRecord event : reader) { // System.out.println(event); // } // } finally { // reader.close(); // } // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new ReadDataset(), args); // System.exit(rc); // } // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.flume.clients.log4jappender.Log4jAppender; import org.apache.hadoop.util.Tool; import org.apache.http.client.fluent.Request; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hamcrest.Matcher; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kitesdk.examples.logging.CreateDataset; import org.kitesdk.examples.logging.DeleteDataset; import org.kitesdk.examples.logging.ReadDataset; import org.kitesdk.minicluster.FlumeService; import org.kitesdk.minicluster.HdfsService; import org.kitesdk.minicluster.HiveService; import org.kitesdk.minicluster.MiniCluster; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString;
} startTomcat(); } @AfterClass public static void stopCluster() { try { cluster.stop(); } catch (Exception e) { // ignore problems during shutdown } } private static void configureLog4j() throws Exception { // configuration is done programmatically and not in log4j.properties so that so we // can defer initialization to after the Flume Avro RPC source port is running Log4jAppender appender = new Log4jAppender(); appender.setName("flume"); appender.setHostname("localhost"); appender.setPort(41415); appender.setUnsafeMode(true); appender.activateOptions(); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").addAppender(appender); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").setLevel(Level.INFO); } @Test public void test() throws Exception {
// Path: logging/src/main/java/org/kitesdk/examples/logging/CreateDataset.java // public class CreateDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Create a dataset of events with the Avro schema // DatasetDescriptor descriptor = new DatasetDescriptor.Builder() // .schemaUri("resource:event.avsc") // .build(); // Datasets.create("dataset:hive:/tmp/data/default/events", descriptor); // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new CreateDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/DeleteDataset.java // public class DeleteDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Drop the events dataset // boolean success = Datasets.delete("dataset:hive:/tmp/data/default/events"); // // return success ? 0 : 1; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new DeleteDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/ReadDataset.java // public class ReadDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Load the events dataset // Dataset<GenericRecord> events = Datasets.load("dataset:hive:/tmp/data/default/events"); // // // Get a reader for the dataset and read all the events // DatasetReader<GenericRecord> reader = events.newReader(); // try { // for (GenericRecord event : reader) { // System.out.println(event); // } // } finally { // reader.close(); // } // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new ReadDataset(), args); // System.exit(rc); // } // } // Path: logging-webapp/src/test/java/org/kitesdk/examples/logging/webapp/ITLoggingWebapp.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.flume.clients.log4jappender.Log4jAppender; import org.apache.hadoop.util.Tool; import org.apache.http.client.fluent.Request; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hamcrest.Matcher; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kitesdk.examples.logging.CreateDataset; import org.kitesdk.examples.logging.DeleteDataset; import org.kitesdk.examples.logging.ReadDataset; import org.kitesdk.minicluster.FlumeService; import org.kitesdk.minicluster.HdfsService; import org.kitesdk.minicluster.HiveService; import org.kitesdk.minicluster.MiniCluster; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString; } startTomcat(); } @AfterClass public static void stopCluster() { try { cluster.stop(); } catch (Exception e) { // ignore problems during shutdown } } private static void configureLog4j() throws Exception { // configuration is done programmatically and not in log4j.properties so that so we // can defer initialization to after the Flume Avro RPC source port is running Log4jAppender appender = new Log4jAppender(); appender.setName("flume"); appender.setHostname("localhost"); appender.setPort(41415); appender.setUnsafeMode(true); appender.activateOptions(); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").addAppender(appender); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").setLevel(Level.INFO); } @Test public void test() throws Exception {
run(new CreateDataset());
kite-sdk/kite-examples
logging-webapp/src/test/java/org/kitesdk/examples/logging/webapp/ITLoggingWebapp.java
// Path: logging/src/main/java/org/kitesdk/examples/logging/CreateDataset.java // public class CreateDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Create a dataset of events with the Avro schema // DatasetDescriptor descriptor = new DatasetDescriptor.Builder() // .schemaUri("resource:event.avsc") // .build(); // Datasets.create("dataset:hive:/tmp/data/default/events", descriptor); // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new CreateDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/DeleteDataset.java // public class DeleteDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Drop the events dataset // boolean success = Datasets.delete("dataset:hive:/tmp/data/default/events"); // // return success ? 0 : 1; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new DeleteDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/ReadDataset.java // public class ReadDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Load the events dataset // Dataset<GenericRecord> events = Datasets.load("dataset:hive:/tmp/data/default/events"); // // // Get a reader for the dataset and read all the events // DatasetReader<GenericRecord> reader = events.newReader(); // try { // for (GenericRecord event : reader) { // System.out.println(event); // } // } finally { // reader.close(); // } // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new ReadDataset(), args); // System.exit(rc); // } // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.flume.clients.log4jappender.Log4jAppender; import org.apache.hadoop.util.Tool; import org.apache.http.client.fluent.Request; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hamcrest.Matcher; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kitesdk.examples.logging.CreateDataset; import org.kitesdk.examples.logging.DeleteDataset; import org.kitesdk.examples.logging.ReadDataset; import org.kitesdk.minicluster.FlumeService; import org.kitesdk.minicluster.HdfsService; import org.kitesdk.minicluster.HiveService; import org.kitesdk.minicluster.MiniCluster; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString;
@AfterClass public static void stopCluster() { try { cluster.stop(); } catch (Exception e) { // ignore problems during shutdown } } private static void configureLog4j() throws Exception { // configuration is done programmatically and not in log4j.properties so that so we // can defer initialization to after the Flume Avro RPC source port is running Log4jAppender appender = new Log4jAppender(); appender.setName("flume"); appender.setHostname("localhost"); appender.setPort(41415); appender.setUnsafeMode(true); appender.activateOptions(); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").addAppender(appender); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").setLevel(Level.INFO); } @Test public void test() throws Exception { run(new CreateDataset()); for (int i = 1; i <= 10; i++) { get("http://localhost:8080/logging-webapp/send?message=Hello-" + i); } Thread.sleep(40000); // wait for events to be flushed to HDFS
// Path: logging/src/main/java/org/kitesdk/examples/logging/CreateDataset.java // public class CreateDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Create a dataset of events with the Avro schema // DatasetDescriptor descriptor = new DatasetDescriptor.Builder() // .schemaUri("resource:event.avsc") // .build(); // Datasets.create("dataset:hive:/tmp/data/default/events", descriptor); // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new CreateDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/DeleteDataset.java // public class DeleteDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Drop the events dataset // boolean success = Datasets.delete("dataset:hive:/tmp/data/default/events"); // // return success ? 0 : 1; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new DeleteDataset(), args); // System.exit(rc); // } // } // // Path: logging/src/main/java/org/kitesdk/examples/logging/ReadDataset.java // public class ReadDataset extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // // // Load the events dataset // Dataset<GenericRecord> events = Datasets.load("dataset:hive:/tmp/data/default/events"); // // // Get a reader for the dataset and read all the events // DatasetReader<GenericRecord> reader = events.newReader(); // try { // for (GenericRecord event : reader) { // System.out.println(event); // } // } finally { // reader.close(); // } // // return 0; // } // // public static void main(String... args) throws Exception { // int rc = ToolRunner.run(new ReadDataset(), args); // System.exit(rc); // } // } // Path: logging-webapp/src/test/java/org/kitesdk/examples/logging/webapp/ITLoggingWebapp.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.flume.clients.log4jappender.Log4jAppender; import org.apache.hadoop.util.Tool; import org.apache.http.client.fluent.Request; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hamcrest.Matcher; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kitesdk.examples.logging.CreateDataset; import org.kitesdk.examples.logging.DeleteDataset; import org.kitesdk.examples.logging.ReadDataset; import org.kitesdk.minicluster.FlumeService; import org.kitesdk.minicluster.HdfsService; import org.kitesdk.minicluster.HiveService; import org.kitesdk.minicluster.MiniCluster; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.containsString; @AfterClass public static void stopCluster() { try { cluster.stop(); } catch (Exception e) { // ignore problems during shutdown } } private static void configureLog4j() throws Exception { // configuration is done programmatically and not in log4j.properties so that so we // can defer initialization to after the Flume Avro RPC source port is running Log4jAppender appender = new Log4jAppender(); appender.setName("flume"); appender.setHostname("localhost"); appender.setPort(41415); appender.setUnsafeMode(true); appender.activateOptions(); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").addAppender(appender); Logger.getLogger("org.kitesdk.examples.logging.webapp.LoggingServlet").setLevel(Level.INFO); } @Test public void test() throws Exception { run(new CreateDataset()); for (int i = 1; i <= 10; i++) { get("http://localhost:8080/logging-webapp/send?message=Hello-" + i); } Thread.sleep(40000); // wait for events to be flushed to HDFS
run(containsString("{\"id\": 10, \"message\": \"Hello-10\"}"), new ReadDataset());
RoboTricker/Transport-Pipes
src/main/java/de/robotricker/transportpipes/config/GeneralConf.java
// Path: src/main/java/de/robotricker/transportpipes/ResourcepackService.java // public class ResourcepackService implements Listener { // // private static String URL = "https://raw.githubusercontent.com/RoboTricker/Transport-Pipes/master/src/main/resources/wiki/resourcepack.zip"; // // private SentryService sentry; // private TransportPipes transportPipes; // private PlayerSettingsService playerSettingsService; // // private ResourcepackMode resourcepackMode; // private byte[] cachedHash; // private Set<Player> resourcepackPlayers; // private Set<Player> loadingResourcepackPlayers; // private Set<Player> waitingForAuthmeLogin; // // @Inject // public ResourcepackService(SentryService sentry, TransportPipes transportPipes, PlayerSettingsService playerSettingsService, GeneralConf generalConf) { // this.sentry = sentry; // this.transportPipes = transportPipes; // this.playerSettingsService = playerSettingsService; // this.resourcepackMode = generalConf.getResourcepackMode(); // if (resourcepackMode == ResourcepackMode.DEFAULT) { // cachedHash = calcSHA1Hash(URL); // } // resourcepackPlayers = new HashSet<>(); // loadingResourcepackPlayers = new HashSet<>(); // waitingForAuthmeLogin = new HashSet<>(); // // if (Bukkit.getPluginManager().isPluginEnabled("AuthMe")) { // Bukkit.getPluginManager().registerEvents(new Listener() { // @EventHandler // public void onAuthMeLogin(fr.xephi.authme.events.LoginEvent e) { // if (waitingForAuthmeLogin.remove(e.getPlayer())) { // loadResourcepackForPlayer(e.getPlayer()); // } // } // }, transportPipes); // } // } // // public byte[] getCachedHash() { // return cachedHash; // } // // public Set<Player> getResourcepackPlayers() { // return resourcepackPlayers; // } // // public ResourcepackMode getResourcepackMode() { // return resourcepackMode; // } // // @EventHandler // public void onJoin(PlayerJoinEvent e) { // if (getResourcepackMode() == ResourcepackMode.NONE) { // transportPipes.changeRenderSystem(e.getPlayer(), VanillaRenderSystem.getDisplayName()); // } else if (getResourcepackMode() == ResourcepackMode.DEFAULT) { // PlayerSettingsConf conf = playerSettingsService.getOrCreateSettingsConf(e.getPlayer()); // if (conf.getRenderSystemName().equalsIgnoreCase(ModelledRenderSystem.getDisplayName())) { // // transportPipes.changeRenderSystem(e.getPlayer(), VanillaRenderSystem.getDisplayName()); // // if (!Bukkit.getPluginManager().isPluginEnabled("AuthMe") || fr.xephi.authme.api.v3.AuthMeApi.getInstance().isAuthenticated(e.getPlayer())) { // transportPipes.runTaskSync(() -> loadResourcepackForPlayer(e.getPlayer())); // } else if (Bukkit.getPluginManager().isPluginEnabled("AuthMe") && !fr.xephi.authme.api.v3.AuthMeApi.getInstance().isAuthenticated(e.getPlayer())) { // waitingForAuthmeLogin.add(e.getPlayer()); // } // } // } // } // // @EventHandler // public void onResourcepackStatus(PlayerResourcePackStatusEvent e) { // if (getResourcepackMode() != ResourcepackMode.DEFAULT) { // return; // } // if (e.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED || e.getStatus() == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD) { // LangConf.Key.RESOURCEPACK_FAIL.sendMessage(e.getPlayer()); // loadingResourcepackPlayers.remove(e.getPlayer()); // } else if (e.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) { // resourcepackPlayers.add(e.getPlayer()); // if (loadingResourcepackPlayers.remove(e.getPlayer())) { // transportPipes.changeRenderSystem(e.getPlayer(), ModelledRenderSystem.getDisplayName()); // } // } // } // // public void loadResourcepackForPlayer(Player p) { // if (getResourcepackMode() == ResourcepackMode.DEFAULT) { // if (cachedHash == null) { // p.setResourcePack(URL); // } else { // p.setResourcePack(URL, cachedHash); // } // loadingResourcepackPlayers.add(p); // } // } // // private byte[] calcSHA1Hash(String resourcepackUrl) { // try { // URL url = new URL(resourcepackUrl); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("GET"); // if (connection.getContentLength() <= 0) { // return null; // } // byte[] resourcePackBytes = new byte[connection.getContentLength()]; // InputStream in = connection.getInputStream(); // // int b; // int i = 0; // while ((b = in.read()) != -1) { // resourcePackBytes[i] = (byte) b; // i++; // } // // in.close(); // // if (resourcePackBytes != null) { // MessageDigest md = MessageDigest.getInstance("SHA-1"); // return md.digest(resourcePackBytes); // } // } catch (NoSuchAlgorithmException | IOException e) { // e.printStackTrace(); // sentry.record(e); // } catch (Exception e) { // sentry.record(e); // } // return null; // } // // public enum ResourcepackMode { // DEFAULT, NONE, SERVER // } // // }
import de.robotricker.transportpipes.ResourcepackService; import org.bukkit.plugin.Plugin; import java.util.List; import javax.inject.Inject;
public boolean isDefaultShowItems() { return (boolean) read("default_show_items"); } public int getDefaultRenderDistance() { return (int) read("default_render_distance"); } @SuppressWarnings("unchecked") public List<String> getDisabledWorlds() { return (List<String>) read("disabled_worlds"); } public String getWrenchItem() { return (String) read("wrench.item"); } public boolean getWrenchGlowing() { return (boolean) read("wrench.glowing"); } public String getLanguage() { return (String) read("language"); } public int getShowHiddenDuctsTime() { return (int) read("show_hidden_ducts_time"); }
// Path: src/main/java/de/robotricker/transportpipes/ResourcepackService.java // public class ResourcepackService implements Listener { // // private static String URL = "https://raw.githubusercontent.com/RoboTricker/Transport-Pipes/master/src/main/resources/wiki/resourcepack.zip"; // // private SentryService sentry; // private TransportPipes transportPipes; // private PlayerSettingsService playerSettingsService; // // private ResourcepackMode resourcepackMode; // private byte[] cachedHash; // private Set<Player> resourcepackPlayers; // private Set<Player> loadingResourcepackPlayers; // private Set<Player> waitingForAuthmeLogin; // // @Inject // public ResourcepackService(SentryService sentry, TransportPipes transportPipes, PlayerSettingsService playerSettingsService, GeneralConf generalConf) { // this.sentry = sentry; // this.transportPipes = transportPipes; // this.playerSettingsService = playerSettingsService; // this.resourcepackMode = generalConf.getResourcepackMode(); // if (resourcepackMode == ResourcepackMode.DEFAULT) { // cachedHash = calcSHA1Hash(URL); // } // resourcepackPlayers = new HashSet<>(); // loadingResourcepackPlayers = new HashSet<>(); // waitingForAuthmeLogin = new HashSet<>(); // // if (Bukkit.getPluginManager().isPluginEnabled("AuthMe")) { // Bukkit.getPluginManager().registerEvents(new Listener() { // @EventHandler // public void onAuthMeLogin(fr.xephi.authme.events.LoginEvent e) { // if (waitingForAuthmeLogin.remove(e.getPlayer())) { // loadResourcepackForPlayer(e.getPlayer()); // } // } // }, transportPipes); // } // } // // public byte[] getCachedHash() { // return cachedHash; // } // // public Set<Player> getResourcepackPlayers() { // return resourcepackPlayers; // } // // public ResourcepackMode getResourcepackMode() { // return resourcepackMode; // } // // @EventHandler // public void onJoin(PlayerJoinEvent e) { // if (getResourcepackMode() == ResourcepackMode.NONE) { // transportPipes.changeRenderSystem(e.getPlayer(), VanillaRenderSystem.getDisplayName()); // } else if (getResourcepackMode() == ResourcepackMode.DEFAULT) { // PlayerSettingsConf conf = playerSettingsService.getOrCreateSettingsConf(e.getPlayer()); // if (conf.getRenderSystemName().equalsIgnoreCase(ModelledRenderSystem.getDisplayName())) { // // transportPipes.changeRenderSystem(e.getPlayer(), VanillaRenderSystem.getDisplayName()); // // if (!Bukkit.getPluginManager().isPluginEnabled("AuthMe") || fr.xephi.authme.api.v3.AuthMeApi.getInstance().isAuthenticated(e.getPlayer())) { // transportPipes.runTaskSync(() -> loadResourcepackForPlayer(e.getPlayer())); // } else if (Bukkit.getPluginManager().isPluginEnabled("AuthMe") && !fr.xephi.authme.api.v3.AuthMeApi.getInstance().isAuthenticated(e.getPlayer())) { // waitingForAuthmeLogin.add(e.getPlayer()); // } // } // } // } // // @EventHandler // public void onResourcepackStatus(PlayerResourcePackStatusEvent e) { // if (getResourcepackMode() != ResourcepackMode.DEFAULT) { // return; // } // if (e.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED || e.getStatus() == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD) { // LangConf.Key.RESOURCEPACK_FAIL.sendMessage(e.getPlayer()); // loadingResourcepackPlayers.remove(e.getPlayer()); // } else if (e.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) { // resourcepackPlayers.add(e.getPlayer()); // if (loadingResourcepackPlayers.remove(e.getPlayer())) { // transportPipes.changeRenderSystem(e.getPlayer(), ModelledRenderSystem.getDisplayName()); // } // } // } // // public void loadResourcepackForPlayer(Player p) { // if (getResourcepackMode() == ResourcepackMode.DEFAULT) { // if (cachedHash == null) { // p.setResourcePack(URL); // } else { // p.setResourcePack(URL, cachedHash); // } // loadingResourcepackPlayers.add(p); // } // } // // private byte[] calcSHA1Hash(String resourcepackUrl) { // try { // URL url = new URL(resourcepackUrl); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("GET"); // if (connection.getContentLength() <= 0) { // return null; // } // byte[] resourcePackBytes = new byte[connection.getContentLength()]; // InputStream in = connection.getInputStream(); // // int b; // int i = 0; // while ((b = in.read()) != -1) { // resourcePackBytes[i] = (byte) b; // i++; // } // // in.close(); // // if (resourcePackBytes != null) { // MessageDigest md = MessageDigest.getInstance("SHA-1"); // return md.digest(resourcePackBytes); // } // } catch (NoSuchAlgorithmException | IOException e) { // e.printStackTrace(); // sentry.record(e); // } catch (Exception e) { // sentry.record(e); // } // return null; // } // // public enum ResourcepackMode { // DEFAULT, NONE, SERVER // } // // } // Path: src/main/java/de/robotricker/transportpipes/config/GeneralConf.java import de.robotricker.transportpipes.ResourcepackService; import org.bukkit.plugin.Plugin; import java.util.List; import javax.inject.Inject; public boolean isDefaultShowItems() { return (boolean) read("default_show_items"); } public int getDefaultRenderDistance() { return (int) read("default_render_distance"); } @SuppressWarnings("unchecked") public List<String> getDisabledWorlds() { return (List<String>) read("disabled_worlds"); } public String getWrenchItem() { return (String) read("wrench.item"); } public boolean getWrenchGlowing() { return (boolean) read("wrench.glowing"); } public String getLanguage() { return (String) read("language"); } public int getShowHiddenDuctsTime() { return (int) read("show_hidden_ducts_time"); }
public ResourcepackService.ResourcepackMode getResourcepackMode() {
RoboTricker/Transport-Pipes
src/main/java/de/robotricker/transportpipes/rendersystems/VanillaRenderSystem.java
// Path: src/main/java/de/robotricker/transportpipes/duct/DuctRegister.java // public class DuctRegister { // // private List<BaseDuctType<? extends Duct>> baseDuctTypes; // // private TransportPipes plugin; // private GeneralConf generalConf; // // @Inject // public DuctRegister(TransportPipes plugin, GeneralConf generalConf) { // this.plugin = plugin; // this.generalConf = generalConf; // this.baseDuctTypes = new ArrayList<>(); // } // // public <T extends Duct> BaseDuctType<T> registerBaseDuctType(String name, Class<? extends DuctManager<T>> ductManagerClass, Class<? extends DuctFactory<T>> ductFactoryClass, Class<? extends ItemManager<T>> itemManagerClass) { // if (baseDuctTypes.stream().anyMatch(bdt -> bdt.getName().equalsIgnoreCase(name))) { // throw new IllegalArgumentException("BaseDuctType '" + name + "' already exists"); // } // BaseDuctType<T> baseDuctType = new BaseDuctType<>(name, plugin.getInjector().newInstance(ductManagerClass), plugin.getInjector().newInstance(ductFactoryClass), plugin.getInjector().newInstance(itemManagerClass)); // this.baseDuctTypes.add(baseDuctType); // baseDuctType.getDuctManager().registerDuctTypes(); // baseDuctType.getItemManager().registerItems(); // // if (generalConf.isCraftingEnabled()) { // baseDuctType.getDuctManager().registerRecipes(); // } // // return baseDuctType; // } // // public List<BaseDuctType<? extends Duct>> baseDuctTypes() { // return baseDuctTypes; // } // // public <T extends Duct> BaseDuctType<T> baseDuctTypeOf(String displayName) { // return (BaseDuctType<T>) baseDuctTypes().stream().filter(bdt -> bdt.getName().equalsIgnoreCase(displayName)).findAny().orElse(null); // } // // public void saveDuctTypeToNBTTag(DuctType ductType, CompoundTag ductTag) { // ductTag.putString("baseDuctType", ductType.getBaseDuctType().getName()); // ductTag.putString("ductType", ductType.getName()); // } // // public void saveBlockLocToNBTTag(BlockLocation blockLoc, CompoundTag ductTag) { // ductTag.putString("blockLoc", blockLoc.toString()); // } // // public DuctType loadDuctTypeFromNBTTag(CompoundTag ductTag) { // BaseDuctType bdt = baseDuctTypeOf(ductTag.getString("baseDuctType")); // if (bdt == null) { // return null; // } // return bdt.ductTypeOf(ductTag.getString("ductType")); // } // // public BlockLocation loadBlockLocFromNBTTag(CompoundTag ductTag) { // return BlockLocation.fromString(ductTag.getString("blockLoc")); // } // // } // // Path: src/main/java/de/robotricker/transportpipes/duct/types/BaseDuctType.java // public final class BaseDuctType<T extends Duct> { // // private String name; // private DuctManager<T> ductManager; // private DuctFactory<T> ductFactory; // private ItemManager<T> itemManager; // private VanillaRenderSystem vanillaRenderSystem; // private ModelledRenderSystem modelledRenderSystem; // // private List<DuctType> ductTypes; // // public BaseDuctType(String name, DuctManager<T> ductManager, DuctFactory<T> ductFactory, ItemManager<T> itemManager) { // this.name = name; // this.ductManager = ductManager; // this.ductFactory = ductFactory; // this.itemManager = itemManager; // this.ductTypes = new ArrayList<>(); // } // // public String getName() { // return name; // } // // public DuctManager<T> getDuctManager() { // return ductManager; // } // // public DuctFactory<T> getDuctFactory() { // return ductFactory; // } // // public ItemManager<T> getItemManager() { // return itemManager; // } // // public VanillaRenderSystem getVanillaRenderSystem() { // return vanillaRenderSystem; // } // // public ModelledRenderSystem getModelledRenderSystem() { // return modelledRenderSystem; // } // // public void setVanillaRenderSystem(VanillaRenderSystem vanillaRenderSystem) { // this.vanillaRenderSystem = vanillaRenderSystem; // } // // public void setModelledRenderSystem(ModelledRenderSystem modelledRenderSystem) { // this.modelledRenderSystem = modelledRenderSystem; // } // // public boolean is(String name) { // return this.name.equalsIgnoreCase(name); // } // // // **************************************************** // // DUCT MATERIAL // // **************************************************** // // public List<DuctType> ductTypes() { // return ductTypes; // } // // public <S extends DuctType> S ductTypeOf(String displayName) { // for (DuctType dt : ductTypes) { // if (dt.getName().equalsIgnoreCase(displayName)) { // return (S) dt; // } // } // return null; // } // // public void registerDuctType(DuctType ductType) { // if (ductTypes.stream().anyMatch(dt -> dt.getName().equalsIgnoreCase(ductType.getName()))) { // throw new IllegalArgumentException("DuctType '" + ductType.getName() + "' already exists"); // } // ductTypes.add(ductType); // } // // }
import org.bukkit.inventory.ItemStack; import de.robotricker.transportpipes.duct.DuctRegister; import de.robotricker.transportpipes.duct.types.BaseDuctType;
package de.robotricker.transportpipes.rendersystems; public abstract class VanillaRenderSystem extends RenderSystem { public VanillaRenderSystem(BaseDuctType baseDuctType) { super(baseDuctType); }
// Path: src/main/java/de/robotricker/transportpipes/duct/DuctRegister.java // public class DuctRegister { // // private List<BaseDuctType<? extends Duct>> baseDuctTypes; // // private TransportPipes plugin; // private GeneralConf generalConf; // // @Inject // public DuctRegister(TransportPipes plugin, GeneralConf generalConf) { // this.plugin = plugin; // this.generalConf = generalConf; // this.baseDuctTypes = new ArrayList<>(); // } // // public <T extends Duct> BaseDuctType<T> registerBaseDuctType(String name, Class<? extends DuctManager<T>> ductManagerClass, Class<? extends DuctFactory<T>> ductFactoryClass, Class<? extends ItemManager<T>> itemManagerClass) { // if (baseDuctTypes.stream().anyMatch(bdt -> bdt.getName().equalsIgnoreCase(name))) { // throw new IllegalArgumentException("BaseDuctType '" + name + "' already exists"); // } // BaseDuctType<T> baseDuctType = new BaseDuctType<>(name, plugin.getInjector().newInstance(ductManagerClass), plugin.getInjector().newInstance(ductFactoryClass), plugin.getInjector().newInstance(itemManagerClass)); // this.baseDuctTypes.add(baseDuctType); // baseDuctType.getDuctManager().registerDuctTypes(); // baseDuctType.getItemManager().registerItems(); // // if (generalConf.isCraftingEnabled()) { // baseDuctType.getDuctManager().registerRecipes(); // } // // return baseDuctType; // } // // public List<BaseDuctType<? extends Duct>> baseDuctTypes() { // return baseDuctTypes; // } // // public <T extends Duct> BaseDuctType<T> baseDuctTypeOf(String displayName) { // return (BaseDuctType<T>) baseDuctTypes().stream().filter(bdt -> bdt.getName().equalsIgnoreCase(displayName)).findAny().orElse(null); // } // // public void saveDuctTypeToNBTTag(DuctType ductType, CompoundTag ductTag) { // ductTag.putString("baseDuctType", ductType.getBaseDuctType().getName()); // ductTag.putString("ductType", ductType.getName()); // } // // public void saveBlockLocToNBTTag(BlockLocation blockLoc, CompoundTag ductTag) { // ductTag.putString("blockLoc", blockLoc.toString()); // } // // public DuctType loadDuctTypeFromNBTTag(CompoundTag ductTag) { // BaseDuctType bdt = baseDuctTypeOf(ductTag.getString("baseDuctType")); // if (bdt == null) { // return null; // } // return bdt.ductTypeOf(ductTag.getString("ductType")); // } // // public BlockLocation loadBlockLocFromNBTTag(CompoundTag ductTag) { // return BlockLocation.fromString(ductTag.getString("blockLoc")); // } // // } // // Path: src/main/java/de/robotricker/transportpipes/duct/types/BaseDuctType.java // public final class BaseDuctType<T extends Duct> { // // private String name; // private DuctManager<T> ductManager; // private DuctFactory<T> ductFactory; // private ItemManager<T> itemManager; // private VanillaRenderSystem vanillaRenderSystem; // private ModelledRenderSystem modelledRenderSystem; // // private List<DuctType> ductTypes; // // public BaseDuctType(String name, DuctManager<T> ductManager, DuctFactory<T> ductFactory, ItemManager<T> itemManager) { // this.name = name; // this.ductManager = ductManager; // this.ductFactory = ductFactory; // this.itemManager = itemManager; // this.ductTypes = new ArrayList<>(); // } // // public String getName() { // return name; // } // // public DuctManager<T> getDuctManager() { // return ductManager; // } // // public DuctFactory<T> getDuctFactory() { // return ductFactory; // } // // public ItemManager<T> getItemManager() { // return itemManager; // } // // public VanillaRenderSystem getVanillaRenderSystem() { // return vanillaRenderSystem; // } // // public ModelledRenderSystem getModelledRenderSystem() { // return modelledRenderSystem; // } // // public void setVanillaRenderSystem(VanillaRenderSystem vanillaRenderSystem) { // this.vanillaRenderSystem = vanillaRenderSystem; // } // // public void setModelledRenderSystem(ModelledRenderSystem modelledRenderSystem) { // this.modelledRenderSystem = modelledRenderSystem; // } // // public boolean is(String name) { // return this.name.equalsIgnoreCase(name); // } // // // **************************************************** // // DUCT MATERIAL // // **************************************************** // // public List<DuctType> ductTypes() { // return ductTypes; // } // // public <S extends DuctType> S ductTypeOf(String displayName) { // for (DuctType dt : ductTypes) { // if (dt.getName().equalsIgnoreCase(displayName)) { // return (S) dt; // } // } // return null; // } // // public void registerDuctType(DuctType ductType) { // if (ductTypes.stream().anyMatch(dt -> dt.getName().equalsIgnoreCase(ductType.getName()))) { // throw new IllegalArgumentException("DuctType '" + ductType.getName() + "' already exists"); // } // ductTypes.add(ductType); // } // // } // Path: src/main/java/de/robotricker/transportpipes/rendersystems/VanillaRenderSystem.java import org.bukkit.inventory.ItemStack; import de.robotricker.transportpipes.duct.DuctRegister; import de.robotricker.transportpipes.duct.types.BaseDuctType; package de.robotricker.transportpipes.rendersystems; public abstract class VanillaRenderSystem extends RenderSystem { public VanillaRenderSystem(BaseDuctType baseDuctType) { super(baseDuctType); }
public static ItemStack getItem(DuctRegister ductRegister) {
RoboTricker/Transport-Pipes
src/main/java/de/robotricker/transportpipes/PlayerSettingsService.java
// Path: src/main/java/de/robotricker/transportpipes/config/GeneralConf.java // public class GeneralConf extends Conf { // // @Inject // public GeneralConf(Plugin configPlugin) { // super(configPlugin, "config.yml", "config.yml", true); // } // // public int getMaxItemsPerPipe() { // return (int) read("max_items_per_pipe"); // } // // public boolean isCraftingEnabled() { // return (boolean) read("crafting_enabled"); // } // // @SuppressWarnings("unchecked") // public List<String> getAnticheatPlugins() { // return (List<String>) read("anticheat_plugins"); // } // // public String getDefaultRenderSystemName() { // return (String) read("default_render_system"); // } // // public boolean isDefaultShowItems() { // return (boolean) read("default_show_items"); // } // // public int getDefaultRenderDistance() { // return (int) read("default_render_distance"); // } // // @SuppressWarnings("unchecked") // public List<String> getDisabledWorlds() { // return (List<String>) read("disabled_worlds"); // } // // public String getWrenchItem() { // return (String) read("wrench.item"); // } // // public boolean getWrenchGlowing() { // return (boolean) read("wrench.glowing"); // } // // public String getLanguage() { // return (String) read("language"); // } // // public int getShowHiddenDuctsTime() { // return (int) read("show_hidden_ducts_time"); // } // // public ResourcepackService.ResourcepackMode getResourcepackMode() { // String url = (String) read("resourcepack_mode"); // if (url == null || url.equalsIgnoreCase("default")) { // return ResourcepackService.ResourcepackMode.DEFAULT; // } else if (url.equalsIgnoreCase("none")) { // return ResourcepackService.ResourcepackMode.NONE; // } else if (url.equalsIgnoreCase("server")) { // return ResourcepackService.ResourcepackMode.SERVER; // } // return ResourcepackService.ResourcepackMode.DEFAULT; // } // // } // // Path: src/main/java/de/robotricker/transportpipes/config/PlayerSettingsConf.java // public class PlayerSettingsConf extends Conf { // // private GeneralConf generalConf; // // public PlayerSettingsConf(TransportPipes transportPipes, GeneralConf generalConf, Player p) { // super(transportPipes, "playerconfig.yml", "playersettings/" + p.getUniqueId().toString() + ".yml", false); // this.generalConf = generalConf; // } // // public int getRenderDistance() { // if (!getYamlConf().contains("render_distance")) { // setRenderDistance(generalConf.getDefaultRenderDistance()); // } // return (int) read("render_distance"); // } // // public void setRenderDistance(int renderDistance) { // overrideAsync("render_distance", renderDistance); // } // // public String getRenderSystemName() { // if (!getYamlConf().contains("render_system")) { // setRenderSystemName(generalConf.getDefaultRenderSystemName()); // } // return (String) read("render_system"); // } // // public void setRenderSystemName(String name) { // overrideAsync("render_system", name); // } // // public RenderSystem getRenderSystem(BaseDuctType baseDuctType) { // return RenderSystem.getRenderSystem(getRenderSystemName(), baseDuctType); // } // // public boolean isShowItems() { // if (!getYamlConf().contains("show_items")) { // setShowItems(generalConf.isDefaultShowItems()); // } // return (int) read("show_items") == 1; // } // // public void setShowItems(boolean showItems) { // overrideAsync("show_items", showItems ? 1 : 0); // } // // }
import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import de.robotricker.transportpipes.config.GeneralConf; import de.robotricker.transportpipes.config.PlayerSettingsConf;
package de.robotricker.transportpipes; public class PlayerSettingsService { @Inject private TransportPipes transportPipes; @Inject
// Path: src/main/java/de/robotricker/transportpipes/config/GeneralConf.java // public class GeneralConf extends Conf { // // @Inject // public GeneralConf(Plugin configPlugin) { // super(configPlugin, "config.yml", "config.yml", true); // } // // public int getMaxItemsPerPipe() { // return (int) read("max_items_per_pipe"); // } // // public boolean isCraftingEnabled() { // return (boolean) read("crafting_enabled"); // } // // @SuppressWarnings("unchecked") // public List<String> getAnticheatPlugins() { // return (List<String>) read("anticheat_plugins"); // } // // public String getDefaultRenderSystemName() { // return (String) read("default_render_system"); // } // // public boolean isDefaultShowItems() { // return (boolean) read("default_show_items"); // } // // public int getDefaultRenderDistance() { // return (int) read("default_render_distance"); // } // // @SuppressWarnings("unchecked") // public List<String> getDisabledWorlds() { // return (List<String>) read("disabled_worlds"); // } // // public String getWrenchItem() { // return (String) read("wrench.item"); // } // // public boolean getWrenchGlowing() { // return (boolean) read("wrench.glowing"); // } // // public String getLanguage() { // return (String) read("language"); // } // // public int getShowHiddenDuctsTime() { // return (int) read("show_hidden_ducts_time"); // } // // public ResourcepackService.ResourcepackMode getResourcepackMode() { // String url = (String) read("resourcepack_mode"); // if (url == null || url.equalsIgnoreCase("default")) { // return ResourcepackService.ResourcepackMode.DEFAULT; // } else if (url.equalsIgnoreCase("none")) { // return ResourcepackService.ResourcepackMode.NONE; // } else if (url.equalsIgnoreCase("server")) { // return ResourcepackService.ResourcepackMode.SERVER; // } // return ResourcepackService.ResourcepackMode.DEFAULT; // } // // } // // Path: src/main/java/de/robotricker/transportpipes/config/PlayerSettingsConf.java // public class PlayerSettingsConf extends Conf { // // private GeneralConf generalConf; // // public PlayerSettingsConf(TransportPipes transportPipes, GeneralConf generalConf, Player p) { // super(transportPipes, "playerconfig.yml", "playersettings/" + p.getUniqueId().toString() + ".yml", false); // this.generalConf = generalConf; // } // // public int getRenderDistance() { // if (!getYamlConf().contains("render_distance")) { // setRenderDistance(generalConf.getDefaultRenderDistance()); // } // return (int) read("render_distance"); // } // // public void setRenderDistance(int renderDistance) { // overrideAsync("render_distance", renderDistance); // } // // public String getRenderSystemName() { // if (!getYamlConf().contains("render_system")) { // setRenderSystemName(generalConf.getDefaultRenderSystemName()); // } // return (String) read("render_system"); // } // // public void setRenderSystemName(String name) { // overrideAsync("render_system", name); // } // // public RenderSystem getRenderSystem(BaseDuctType baseDuctType) { // return RenderSystem.getRenderSystem(getRenderSystemName(), baseDuctType); // } // // public boolean isShowItems() { // if (!getYamlConf().contains("show_items")) { // setShowItems(generalConf.isDefaultShowItems()); // } // return (int) read("show_items") == 1; // } // // public void setShowItems(boolean showItems) { // overrideAsync("show_items", showItems ? 1 : 0); // } // // } // Path: src/main/java/de/robotricker/transportpipes/PlayerSettingsService.java import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import de.robotricker.transportpipes.config.GeneralConf; import de.robotricker.transportpipes.config.PlayerSettingsConf; package de.robotricker.transportpipes; public class PlayerSettingsService { @Inject private TransportPipes transportPipes; @Inject
private GeneralConf generalConf;
RoboTricker/Transport-Pipes
src/main/java/de/robotricker/transportpipes/PlayerSettingsService.java
// Path: src/main/java/de/robotricker/transportpipes/config/GeneralConf.java // public class GeneralConf extends Conf { // // @Inject // public GeneralConf(Plugin configPlugin) { // super(configPlugin, "config.yml", "config.yml", true); // } // // public int getMaxItemsPerPipe() { // return (int) read("max_items_per_pipe"); // } // // public boolean isCraftingEnabled() { // return (boolean) read("crafting_enabled"); // } // // @SuppressWarnings("unchecked") // public List<String> getAnticheatPlugins() { // return (List<String>) read("anticheat_plugins"); // } // // public String getDefaultRenderSystemName() { // return (String) read("default_render_system"); // } // // public boolean isDefaultShowItems() { // return (boolean) read("default_show_items"); // } // // public int getDefaultRenderDistance() { // return (int) read("default_render_distance"); // } // // @SuppressWarnings("unchecked") // public List<String> getDisabledWorlds() { // return (List<String>) read("disabled_worlds"); // } // // public String getWrenchItem() { // return (String) read("wrench.item"); // } // // public boolean getWrenchGlowing() { // return (boolean) read("wrench.glowing"); // } // // public String getLanguage() { // return (String) read("language"); // } // // public int getShowHiddenDuctsTime() { // return (int) read("show_hidden_ducts_time"); // } // // public ResourcepackService.ResourcepackMode getResourcepackMode() { // String url = (String) read("resourcepack_mode"); // if (url == null || url.equalsIgnoreCase("default")) { // return ResourcepackService.ResourcepackMode.DEFAULT; // } else if (url.equalsIgnoreCase("none")) { // return ResourcepackService.ResourcepackMode.NONE; // } else if (url.equalsIgnoreCase("server")) { // return ResourcepackService.ResourcepackMode.SERVER; // } // return ResourcepackService.ResourcepackMode.DEFAULT; // } // // } // // Path: src/main/java/de/robotricker/transportpipes/config/PlayerSettingsConf.java // public class PlayerSettingsConf extends Conf { // // private GeneralConf generalConf; // // public PlayerSettingsConf(TransportPipes transportPipes, GeneralConf generalConf, Player p) { // super(transportPipes, "playerconfig.yml", "playersettings/" + p.getUniqueId().toString() + ".yml", false); // this.generalConf = generalConf; // } // // public int getRenderDistance() { // if (!getYamlConf().contains("render_distance")) { // setRenderDistance(generalConf.getDefaultRenderDistance()); // } // return (int) read("render_distance"); // } // // public void setRenderDistance(int renderDistance) { // overrideAsync("render_distance", renderDistance); // } // // public String getRenderSystemName() { // if (!getYamlConf().contains("render_system")) { // setRenderSystemName(generalConf.getDefaultRenderSystemName()); // } // return (String) read("render_system"); // } // // public void setRenderSystemName(String name) { // overrideAsync("render_system", name); // } // // public RenderSystem getRenderSystem(BaseDuctType baseDuctType) { // return RenderSystem.getRenderSystem(getRenderSystemName(), baseDuctType); // } // // public boolean isShowItems() { // if (!getYamlConf().contains("show_items")) { // setShowItems(generalConf.isDefaultShowItems()); // } // return (int) read("show_items") == 1; // } // // public void setShowItems(boolean showItems) { // overrideAsync("show_items", showItems ? 1 : 0); // } // // }
import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import de.robotricker.transportpipes.config.GeneralConf; import de.robotricker.transportpipes.config.PlayerSettingsConf;
package de.robotricker.transportpipes; public class PlayerSettingsService { @Inject private TransportPipes transportPipes; @Inject private GeneralConf generalConf;
// Path: src/main/java/de/robotricker/transportpipes/config/GeneralConf.java // public class GeneralConf extends Conf { // // @Inject // public GeneralConf(Plugin configPlugin) { // super(configPlugin, "config.yml", "config.yml", true); // } // // public int getMaxItemsPerPipe() { // return (int) read("max_items_per_pipe"); // } // // public boolean isCraftingEnabled() { // return (boolean) read("crafting_enabled"); // } // // @SuppressWarnings("unchecked") // public List<String> getAnticheatPlugins() { // return (List<String>) read("anticheat_plugins"); // } // // public String getDefaultRenderSystemName() { // return (String) read("default_render_system"); // } // // public boolean isDefaultShowItems() { // return (boolean) read("default_show_items"); // } // // public int getDefaultRenderDistance() { // return (int) read("default_render_distance"); // } // // @SuppressWarnings("unchecked") // public List<String> getDisabledWorlds() { // return (List<String>) read("disabled_worlds"); // } // // public String getWrenchItem() { // return (String) read("wrench.item"); // } // // public boolean getWrenchGlowing() { // return (boolean) read("wrench.glowing"); // } // // public String getLanguage() { // return (String) read("language"); // } // // public int getShowHiddenDuctsTime() { // return (int) read("show_hidden_ducts_time"); // } // // public ResourcepackService.ResourcepackMode getResourcepackMode() { // String url = (String) read("resourcepack_mode"); // if (url == null || url.equalsIgnoreCase("default")) { // return ResourcepackService.ResourcepackMode.DEFAULT; // } else if (url.equalsIgnoreCase("none")) { // return ResourcepackService.ResourcepackMode.NONE; // } else if (url.equalsIgnoreCase("server")) { // return ResourcepackService.ResourcepackMode.SERVER; // } // return ResourcepackService.ResourcepackMode.DEFAULT; // } // // } // // Path: src/main/java/de/robotricker/transportpipes/config/PlayerSettingsConf.java // public class PlayerSettingsConf extends Conf { // // private GeneralConf generalConf; // // public PlayerSettingsConf(TransportPipes transportPipes, GeneralConf generalConf, Player p) { // super(transportPipes, "playerconfig.yml", "playersettings/" + p.getUniqueId().toString() + ".yml", false); // this.generalConf = generalConf; // } // // public int getRenderDistance() { // if (!getYamlConf().contains("render_distance")) { // setRenderDistance(generalConf.getDefaultRenderDistance()); // } // return (int) read("render_distance"); // } // // public void setRenderDistance(int renderDistance) { // overrideAsync("render_distance", renderDistance); // } // // public String getRenderSystemName() { // if (!getYamlConf().contains("render_system")) { // setRenderSystemName(generalConf.getDefaultRenderSystemName()); // } // return (String) read("render_system"); // } // // public void setRenderSystemName(String name) { // overrideAsync("render_system", name); // } // // public RenderSystem getRenderSystem(BaseDuctType baseDuctType) { // return RenderSystem.getRenderSystem(getRenderSystemName(), baseDuctType); // } // // public boolean isShowItems() { // if (!getYamlConf().contains("show_items")) { // setShowItems(generalConf.isDefaultShowItems()); // } // return (int) read("show_items") == 1; // } // // public void setShowItems(boolean showItems) { // overrideAsync("show_items", showItems ? 1 : 0); // } // // } // Path: src/main/java/de/robotricker/transportpipes/PlayerSettingsService.java import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import de.robotricker.transportpipes.config.GeneralConf; import de.robotricker.transportpipes.config.PlayerSettingsConf; package de.robotricker.transportpipes; public class PlayerSettingsService { @Inject private TransportPipes transportPipes; @Inject private GeneralConf generalConf;
private Map<Player, PlayerSettingsConf> cachedSettingsConfs;
mikaelhg/openblocks
src/main/java/edu/mit/blocks/renderable/RBHighlightHandler.java
// Path: src/main/java/edu/mit/blocks/workspace/RBParent.java // public interface RBParent { // // /** // * Add this Component the BlockLayer, which is understood to be above the // * HighlightLayer, although no guarantee is made about its order relative // * to any other layers this RBParent may have. // * @param c the Component to add // */ // public void addToBlockLayer(Component c); // // /** // * Add this Component to the HighlightLayer, which is understood to be // * directly and completely beneath the BlockLayer, such that all Components // * on the HighlightLayer are rendered behind ALL Components on the BlockLayer. // * @param c the Component to add // */ // public void addToHighlightLayer(Component c); // } // // Path: src/main/java/edu/mit/blocks/codeblockutil/GraphicsManager.java // public class GraphicsManager { // // /** get GraphicConfiguration for default screen - this should only be done once at startup **/ // private static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // private static GraphicsDevice gs = ge.getDefaultScreenDevice(); // public static GraphicsConfiguration gc = gs.getDefaultConfiguration(); // private static final int MAX_RECYCLED_IMAGES = 50; // private static int numRecycledImages = 0; // private static HashMap<Dimension, List<BufferedImage>> recycledImages = new HashMap<Dimension, List<BufferedImage>>(); // // /** // * Functionally equivalent to // * gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT) // * but allows reusing released images. // */ // public static BufferedImage getGCCompatibleImage(int width, int height) { // List<BufferedImage> imgList = recycledImages.get(new Dimension(width, height)); // if (imgList == null || imgList.isEmpty()) { // return gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); // } // numRecycledImages--; // BufferedImage img = imgList.remove(imgList.size() - 1); // // Clear the image // Graphics2D g2D = img.createGraphics(); // g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); // Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, width, height); // g2D.fill(rect); // return img; // } // // /** // * Add an image to the recycled images list (or if img = null, does nothing). // * Note: the passed variable should be immediately set to null to avoid aliasing bugs. // */ // public static void recycleGCCompatibleImage(BufferedImage img) { // if (img == null) { // return; // } // // Make sure we don't waste too much memory // if (numRecycledImages >= MAX_RECYCLED_IMAGES) { // recycledImages.clear(); // } // Dimension dim = new Dimension(img.getWidth(), img.getHeight()); // List<BufferedImage> imgList = recycledImages.get(dim); // if (imgList == null) { // imgList = new ArrayList<BufferedImage>(); // recycledImages.put(dim, imgList); // } // imgList.add(img); // } // }
import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.geom.Area; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.SwingUtilities; import edu.mit.blocks.workspace.RBParent; import edu.mit.blocks.codeblockutil.GraphicsManager;
public void repaint() { if (rb.isVisible()) { if (blockArea == null || blockArea != rb.getBlockArea() || (rb.getBlock() != null && rb.getBlock().hasFocus() != hasFocus)) { updateImage(); blockArea = rb.getBlockArea(); } // only update bounds on the Swing thread SwingUtilities.invokeLater(new Runnable() { public void run() { updateBounds(); } }); } super.repaint(); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(new Color(0, 0, 0, 0)); g2.fillRect(0, 0, getWidth(), getHeight()); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, HIGHLIGHT_ALPHA)); if (hImage != null) { g2.drawImage(hImage, 0, 0, null); } }
// Path: src/main/java/edu/mit/blocks/workspace/RBParent.java // public interface RBParent { // // /** // * Add this Component the BlockLayer, which is understood to be above the // * HighlightLayer, although no guarantee is made about its order relative // * to any other layers this RBParent may have. // * @param c the Component to add // */ // public void addToBlockLayer(Component c); // // /** // * Add this Component to the HighlightLayer, which is understood to be // * directly and completely beneath the BlockLayer, such that all Components // * on the HighlightLayer are rendered behind ALL Components on the BlockLayer. // * @param c the Component to add // */ // public void addToHighlightLayer(Component c); // } // // Path: src/main/java/edu/mit/blocks/codeblockutil/GraphicsManager.java // public class GraphicsManager { // // /** get GraphicConfiguration for default screen - this should only be done once at startup **/ // private static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // private static GraphicsDevice gs = ge.getDefaultScreenDevice(); // public static GraphicsConfiguration gc = gs.getDefaultConfiguration(); // private static final int MAX_RECYCLED_IMAGES = 50; // private static int numRecycledImages = 0; // private static HashMap<Dimension, List<BufferedImage>> recycledImages = new HashMap<Dimension, List<BufferedImage>>(); // // /** // * Functionally equivalent to // * gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT) // * but allows reusing released images. // */ // public static BufferedImage getGCCompatibleImage(int width, int height) { // List<BufferedImage> imgList = recycledImages.get(new Dimension(width, height)); // if (imgList == null || imgList.isEmpty()) { // return gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); // } // numRecycledImages--; // BufferedImage img = imgList.remove(imgList.size() - 1); // // Clear the image // Graphics2D g2D = img.createGraphics(); // g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); // Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, width, height); // g2D.fill(rect); // return img; // } // // /** // * Add an image to the recycled images list (or if img = null, does nothing). // * Note: the passed variable should be immediately set to null to avoid aliasing bugs. // */ // public static void recycleGCCompatibleImage(BufferedImage img) { // if (img == null) { // return; // } // // Make sure we don't waste too much memory // if (numRecycledImages >= MAX_RECYCLED_IMAGES) { // recycledImages.clear(); // } // Dimension dim = new Dimension(img.getWidth(), img.getHeight()); // List<BufferedImage> imgList = recycledImages.get(dim); // if (imgList == null) { // imgList = new ArrayList<BufferedImage>(); // recycledImages.put(dim, imgList); // } // imgList.add(img); // } // } // Path: src/main/java/edu/mit/blocks/renderable/RBHighlightHandler.java import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.geom.Area; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.SwingUtilities; import edu.mit.blocks.workspace.RBParent; import edu.mit.blocks.codeblockutil.GraphicsManager; public void repaint() { if (rb.isVisible()) { if (blockArea == null || blockArea != rb.getBlockArea() || (rb.getBlock() != null && rb.getBlock().hasFocus() != hasFocus)) { updateImage(); blockArea = rb.getBlockArea(); } // only update bounds on the Swing thread SwingUtilities.invokeLater(new Runnable() { public void run() { updateBounds(); } }); } super.repaint(); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(new Color(0, 0, 0, 0)); g2.fillRect(0, 0, getWidth(), getHeight()); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, HIGHLIGHT_ALPHA)); if (hImage != null) { g2.drawImage(hImage, 0, 0, null); } }
public void setParent(RBParent newParent) {
mikaelhg/openblocks
src/main/java/edu/mit/blocks/renderable/RBHighlightHandler.java
// Path: src/main/java/edu/mit/blocks/workspace/RBParent.java // public interface RBParent { // // /** // * Add this Component the BlockLayer, which is understood to be above the // * HighlightLayer, although no guarantee is made about its order relative // * to any other layers this RBParent may have. // * @param c the Component to add // */ // public void addToBlockLayer(Component c); // // /** // * Add this Component to the HighlightLayer, which is understood to be // * directly and completely beneath the BlockLayer, such that all Components // * on the HighlightLayer are rendered behind ALL Components on the BlockLayer. // * @param c the Component to add // */ // public void addToHighlightLayer(Component c); // } // // Path: src/main/java/edu/mit/blocks/codeblockutil/GraphicsManager.java // public class GraphicsManager { // // /** get GraphicConfiguration for default screen - this should only be done once at startup **/ // private static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // private static GraphicsDevice gs = ge.getDefaultScreenDevice(); // public static GraphicsConfiguration gc = gs.getDefaultConfiguration(); // private static final int MAX_RECYCLED_IMAGES = 50; // private static int numRecycledImages = 0; // private static HashMap<Dimension, List<BufferedImage>> recycledImages = new HashMap<Dimension, List<BufferedImage>>(); // // /** // * Functionally equivalent to // * gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT) // * but allows reusing released images. // */ // public static BufferedImage getGCCompatibleImage(int width, int height) { // List<BufferedImage> imgList = recycledImages.get(new Dimension(width, height)); // if (imgList == null || imgList.isEmpty()) { // return gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); // } // numRecycledImages--; // BufferedImage img = imgList.remove(imgList.size() - 1); // // Clear the image // Graphics2D g2D = img.createGraphics(); // g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); // Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, width, height); // g2D.fill(rect); // return img; // } // // /** // * Add an image to the recycled images list (or if img = null, does nothing). // * Note: the passed variable should be immediately set to null to avoid aliasing bugs. // */ // public static void recycleGCCompatibleImage(BufferedImage img) { // if (img == null) { // return; // } // // Make sure we don't waste too much memory // if (numRecycledImages >= MAX_RECYCLED_IMAGES) { // recycledImages.clear(); // } // Dimension dim = new Dimension(img.getWidth(), img.getHeight()); // List<BufferedImage> imgList = recycledImages.get(dim); // if (imgList == null) { // imgList = new ArrayList<BufferedImage>(); // recycledImages.put(dim, imgList); // } // imgList.add(img); // } // }
import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.geom.Area; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.SwingUtilities; import edu.mit.blocks.workspace.RBParent; import edu.mit.blocks.codeblockutil.GraphicsManager;
removeFromParent(); newParent.addToHighlightLayer(this); updateImage(); ((Container) newParent).validate(); } public void removeFromParent() { if (this.getParent() != null) { this.getParent().remove(this); } } public void updateImage() { if (GraphicsEnvironment.isHeadless()) { return; } // cache the focus so it'll know when it needs to redraw later. hasFocus = rb.getBlock().hasFocus(); Color color = null; if (hColor != null) { color = hColor; } else if (rb.getBlock().hasFocus()) { color = new Color(200, 200, 255); //Color.BLUE); } else if (isSearchResult) { color = new Color(255, 255, 120); //Color.YELLOW); } else if (rb.getBlock().isBad()) { color = new Color(255, 100, 100); //Color.RED); } else {
// Path: src/main/java/edu/mit/blocks/workspace/RBParent.java // public interface RBParent { // // /** // * Add this Component the BlockLayer, which is understood to be above the // * HighlightLayer, although no guarantee is made about its order relative // * to any other layers this RBParent may have. // * @param c the Component to add // */ // public void addToBlockLayer(Component c); // // /** // * Add this Component to the HighlightLayer, which is understood to be // * directly and completely beneath the BlockLayer, such that all Components // * on the HighlightLayer are rendered behind ALL Components on the BlockLayer. // * @param c the Component to add // */ // public void addToHighlightLayer(Component c); // } // // Path: src/main/java/edu/mit/blocks/codeblockutil/GraphicsManager.java // public class GraphicsManager { // // /** get GraphicConfiguration for default screen - this should only be done once at startup **/ // private static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // private static GraphicsDevice gs = ge.getDefaultScreenDevice(); // public static GraphicsConfiguration gc = gs.getDefaultConfiguration(); // private static final int MAX_RECYCLED_IMAGES = 50; // private static int numRecycledImages = 0; // private static HashMap<Dimension, List<BufferedImage>> recycledImages = new HashMap<Dimension, List<BufferedImage>>(); // // /** // * Functionally equivalent to // * gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT) // * but allows reusing released images. // */ // public static BufferedImage getGCCompatibleImage(int width, int height) { // List<BufferedImage> imgList = recycledImages.get(new Dimension(width, height)); // if (imgList == null || imgList.isEmpty()) { // return gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); // } // numRecycledImages--; // BufferedImage img = imgList.remove(imgList.size() - 1); // // Clear the image // Graphics2D g2D = img.createGraphics(); // g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); // Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, width, height); // g2D.fill(rect); // return img; // } // // /** // * Add an image to the recycled images list (or if img = null, does nothing). // * Note: the passed variable should be immediately set to null to avoid aliasing bugs. // */ // public static void recycleGCCompatibleImage(BufferedImage img) { // if (img == null) { // return; // } // // Make sure we don't waste too much memory // if (numRecycledImages >= MAX_RECYCLED_IMAGES) { // recycledImages.clear(); // } // Dimension dim = new Dimension(img.getWidth(), img.getHeight()); // List<BufferedImage> imgList = recycledImages.get(dim); // if (imgList == null) { // imgList = new ArrayList<BufferedImage>(); // recycledImages.put(dim, imgList); // } // imgList.add(img); // } // } // Path: src/main/java/edu/mit/blocks/renderable/RBHighlightHandler.java import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.geom.Area; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.SwingUtilities; import edu.mit.blocks.workspace.RBParent; import edu.mit.blocks.codeblockutil.GraphicsManager; removeFromParent(); newParent.addToHighlightLayer(this); updateImage(); ((Container) newParent).validate(); } public void removeFromParent() { if (this.getParent() != null) { this.getParent().remove(this); } } public void updateImage() { if (GraphicsEnvironment.isHeadless()) { return; } // cache the focus so it'll know when it needs to redraw later. hasFocus = rb.getBlock().hasFocus(); Color color = null; if (hColor != null) { color = hColor; } else if (rb.getBlock().hasFocus()) { color = new Color(200, 200, 255); //Color.BLUE); } else if (isSearchResult) { color = new Color(255, 255, 120); //Color.YELLOW); } else if (rb.getBlock().isBad()) { color = new Color(255, 100, 100); //Color.RED); } else {
GraphicsManager.recycleGCCompatibleImage(hImage);
brettwooldridge/NuProcess
src/test/java/com/zaxxer/nuprocess/DirectWriteTest.java
// Path: src/test/java/com/zaxxer/nuprocess/CatTest.java // private static byte[] getLotsOfBytes() // { // return getLotsOfBytes(6000); // }
import java.nio.ByteBuffer; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.Adler32; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static com.zaxxer.nuprocess.CatTest.getLotsOfBytes;
{ count.addAndGet(buffer.remaining()); buffer.position(buffer.limit()); } }; NuProcessBuilder pb = new NuProcessBuilder(processListener, command); NuProcess nuProcess = pb.start(); // TODO: given a large i (e.g. 1,000, 10,000), this unit test (testConsecutiveWrites) will // produce a side-effect on InterruptTest (has problem on Mac OS X, but works on Linux and Win32). // We do not reuse fork on surefire (reuseForks=false) to address this issue for now. for (int i = 0; i < 1000; i++) { ByteBuffer buffer = ByteBuffer.allocate(64); buffer.put("This is a test".getBytes()); buffer.flip(); nuProcess.writeStdin(buffer); } Thread.sleep(500); nuProcess.closeStdin(true); nuProcess.waitFor(20, TimeUnit.SECONDS); Assert.assertEquals("Count did not match", 14000, count.get()); } @Test public void lotOfDataSync() throws Exception { System.err.println("Starting test lotOfDataSync()");
// Path: src/test/java/com/zaxxer/nuprocess/CatTest.java // private static byte[] getLotsOfBytes() // { // return getLotsOfBytes(6000); // } // Path: src/test/java/com/zaxxer/nuprocess/DirectWriteTest.java import java.nio.ByteBuffer; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.Adler32; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static com.zaxxer.nuprocess.CatTest.getLotsOfBytes; { count.addAndGet(buffer.remaining()); buffer.position(buffer.limit()); } }; NuProcessBuilder pb = new NuProcessBuilder(processListener, command); NuProcess nuProcess = pb.start(); // TODO: given a large i (e.g. 1,000, 10,000), this unit test (testConsecutiveWrites) will // produce a side-effect on InterruptTest (has problem on Mac OS X, but works on Linux and Win32). // We do not reuse fork on surefire (reuseForks=false) to address this issue for now. for (int i = 0; i < 1000; i++) { ByteBuffer buffer = ByteBuffer.allocate(64); buffer.put("This is a test".getBytes()); buffer.flip(); nuProcess.writeStdin(buffer); } Thread.sleep(500); nuProcess.closeStdin(true); nuProcess.waitFor(20, TimeUnit.SECONDS); Assert.assertEquals("Count did not match", 14000, count.get()); } @Test public void lotOfDataSync() throws Exception { System.err.println("Starting test lotOfDataSync()");
final byte[] bytes = getLotsOfBytes(34632);
brettwooldridge/NuProcess
src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle;
/* * Copyright (C) 2013 Brett Wooldridge * * 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.zaxxer.nuprocess.windows; public final class ProcessCompletions implements Runnable { private static final int DEADPOOL_POLL_INTERVAL; private static final int LINGER_ITERATIONS; private static final Logger LOGGER = Logger.getLogger(ProcessCompletions.class.getCanonicalName()); private static final int STDOUT = 0; private static final int STDERR = 1; private final int lingerIterations;
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // } // Path: src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle; /* * Copyright (C) 2013 Brett Wooldridge * * 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.zaxxer.nuprocess.windows; public final class ProcessCompletions implements Runnable { private static final int DEADPOOL_POLL_INTERVAL; private static final int LINGER_ITERATIONS; private static final Logger LOGGER = Logger.getLogger(ProcessCompletions.class.getCanonicalName()); private static final int STDOUT = 0; private static final int STDERR = 1; private final int lingerIterations;
private HANDLE ioCompletionPort;
brettwooldridge/NuProcess
src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle;
/* * Copyright (C) 2013 Brett Wooldridge * * 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.zaxxer.nuprocess.windows; public final class ProcessCompletions implements Runnable { private static final int DEADPOOL_POLL_INTERVAL; private static final int LINGER_ITERATIONS; private static final Logger LOGGER = Logger.getLogger(ProcessCompletions.class.getCanonicalName()); private static final int STDOUT = 0; private static final int STDERR = 1; private final int lingerIterations; private HANDLE ioCompletionPort; private List<WindowsProcess> deadPool; private BlockingQueue<WindowsProcess> pendingPool; private BlockingQueue<WindowsProcess> wantsWrite; private Map<Long, WindowsProcess> completionKeyToProcessMap; private volatile CyclicBarrier startBarrier; private volatile boolean shutdown; private AtomicBoolean isRunning; private IntByReference numberOfBytes;
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // } // Path: src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle; /* * Copyright (C) 2013 Brett Wooldridge * * 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.zaxxer.nuprocess.windows; public final class ProcessCompletions implements Runnable { private static final int DEADPOOL_POLL_INTERVAL; private static final int LINGER_ITERATIONS; private static final Logger LOGGER = Logger.getLogger(ProcessCompletions.class.getCanonicalName()); private static final int STDOUT = 0; private static final int STDERR = 1; private final int lingerIterations; private HANDLE ioCompletionPort; private List<WindowsProcess> deadPool; private BlockingQueue<WindowsProcess> pendingPool; private BlockingQueue<WindowsProcess> wantsWrite; private Map<Long, WindowsProcess> completionKeyToProcessMap; private volatile CyclicBarrier startBarrier; private volatile boolean shutdown; private AtomicBoolean isRunning; private IntByReference numberOfBytes;
private ULONG_PTRByReference completionKey;
brettwooldridge/NuProcess
src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle;
finally { checkDeadPool(); } } void shutdown() { shutdown = true; Collection<WindowsProcess> processes = completionKeyToProcessMap.values(); for (WindowsProcess process : processes) { NuKernel32.TerminateProcess(process.getPidHandle(), Integer.MAX_VALUE - 1); process.onExit(Integer.MAX_VALUE - 1); } } CyclicBarrier getSpawnBarrier() { startBarrier = new CyclicBarrier(2); return startBarrier; } boolean checkAndSetRunning() { return isRunning.compareAndSet(false, true); } void wantWrite(final WindowsProcess process) { try { wantsWrite.put(process);
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // } // Path: src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle; finally { checkDeadPool(); } } void shutdown() { shutdown = true; Collection<WindowsProcess> processes = completionKeyToProcessMap.values(); for (WindowsProcess process : processes) { NuKernel32.TerminateProcess(process.getPidHandle(), Integer.MAX_VALUE - 1); process.onExit(Integer.MAX_VALUE - 1); } } CyclicBarrier getSpawnBarrier() { startBarrier = new CyclicBarrier(2); return startBarrier; } boolean checkAndSetRunning() { return isRunning.compareAndSet(false, true); } void wantWrite(final WindowsProcess process) { try { wantsWrite.put(process);
NuKernel32.PostQueuedCompletionStatus(ioCompletionPort, 0, new ULONG_PTR(0), null);
brettwooldridge/NuProcess
src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle;
try { wantsWrite.put(process); NuKernel32.PostQueuedCompletionStatus(ioCompletionPort, 0, new ULONG_PTR(0), null); } catch (InterruptedException e) { // ignore } } void registerProcess(final WindowsProcess process) { if (shutdown) { return; } try { pendingPool.put(process); NuKernel32.PostQueuedCompletionStatus(ioCompletionPort, 0, new ULONG_PTR(0), null); } catch (InterruptedException e) { // ignore } } private void queueWrite(final WindowsProcess process) { if (shutdown) { return; }
// Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class HANDLE extends PointerType // { // static final Pointer INVALID = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); // // public HANDLE() // { // } // // public HANDLE(Pointer p) // { // setPointer(p); // } // // @Override // public Object fromNative(Object nativeValue, FromNativeContext context) // { // if (nativeValue == null) { // return null; // } // // Pointer ptr = (Pointer) nativeValue; // if (INVALID.equals(ptr)) { // return INVALID_HANDLE_VALUE; // } // return new HANDLE(ptr); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTR extends IntegerType // { // public ULONG_PTR() // { // this(0); // } // // public ULONG_PTR(long value) // { // super(Native.POINTER_SIZE, value, true); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/NuWinNT.java // class ULONG_PTRByReference extends ByReference // { // public ULONG_PTRByReference() // { // this(new ULONG_PTR(0)); // } // // public ULONG_PTRByReference(ULONG_PTR value) // { // super(Native.POINTER_SIZE); // setValue(value); // } // // public void setValue(ULONG_PTR value) // { // if (Native.POINTER_SIZE == 4) { // getPointer().setInt(0, value.intValue()); // } // else { // getPointer().setLong(0, value.longValue()); // } // } // // public ULONG_PTR getValue() // { // return new ULONG_PTR(Native.POINTER_SIZE == 4 ? getPointer().getInt(0) : getPointer().getLong(0)); // } // } // // Path: src/main/java/com/zaxxer/nuprocess/windows/WindowsProcess.java // static final class PipeBundle // { // final OVERLAPPED overlapped; // final long ioCompletionKey; // final HANDLE pipeHandle; // ByteBuffer buffer; // boolean registered; // // PipeBundle(HANDLE pipeHandle, long ioCompletionKey) // { // this.pipeHandle = pipeHandle; // this.ioCompletionKey = ioCompletionKey; // // // The OVERLAPPED structure is required to make non-blocking ReadFile and WriteFile calls, // // but its state is never read from nor written to in Java, so we disable auto-sync so JNA // // doesn't waste time marshaling contents to/from native memory // overlapped = new OVERLAPPED(); // overlapped.setAutoSynch(false); // } // } // Path: src/main/java/com/zaxxer/nuprocess/windows/ProcessCompletions.java import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.zaxxer.nuprocess.internal.Constants; import com.zaxxer.nuprocess.windows.NuWinNT.HANDLE; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTR; import com.zaxxer.nuprocess.windows.NuWinNT.ULONG_PTRByReference; import com.zaxxer.nuprocess.windows.WindowsProcess.PipeBundle; try { wantsWrite.put(process); NuKernel32.PostQueuedCompletionStatus(ioCompletionPort, 0, new ULONG_PTR(0), null); } catch (InterruptedException e) { // ignore } } void registerProcess(final WindowsProcess process) { if (shutdown) { return; } try { pendingPool.put(process); NuKernel32.PostQueuedCompletionStatus(ioCompletionPort, 0, new ULONG_PTR(0), null); } catch (InterruptedException e) { // ignore } } private void queueWrite(final WindowsProcess process) { if (shutdown) { return; }
final PipeBundle stdinPipe = process.getStdinPipe();
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/ClassType.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/WriterPreferences.java // public class WriterPreferences { // private String indentationStep = " "; // private int indentationLevel = 0; // // private List<CustomAbstractTypeWriter> customWriters = new ArrayList<CustomAbstractTypeWriter>(); // private boolean useEnumPattern; // private boolean enumAsStringLiteralType = false; // private boolean constantsForStringLiteralTypeEnums = false; // /** sort types and vars in output */ // private boolean sort; // // public boolean isStringLiteralTypeForEnums() { // return enumAsStringLiteralType; // } // // public void useStringLiteralTypeForEnums(boolean withConstants) { // addWriter(new EnumTypeToStringLiteralTypeWriter()); // this.enumAsStringLiteralType = true; // this.constantsForStringLiteralTypeEnums = withConstants; // } // // public void useStringLiteralTypeForEnums() { // useStringLiteralTypeForEnums(false); // } // // public boolean isConstantsForStringLiteralTypeEnums() { // return this.constantsForStringLiteralTypeEnums; // } // // public void useEnumPattern() { // addWriter(new EnumTypeToEnumPatternWriter()); // useEnumPattern = true; // } // // public boolean isUseEnumPattern() { // return useEnumPattern; // } // // public void sort() { // sort = true; // } // // public boolean isSort() { // return sort; // } // // public void addWriter(CustomAbstractTypeWriter writer) { // this.customWriters.add(writer); // } // // public List<CustomAbstractTypeWriter> getCustomWriters() { // return customWriters; // } // // public boolean hasCustomWriter(AbstractNamedType type) { // return getCustomWriter(type) != null; // } // // public void writeDef(AbstractNamedType type, Writer writer) throws IOException { // getCustomWriter(type).writeDef(type, writer, this); // } // // public CustomAbstractTypeWriter getCustomWriter(AbstractNamedType type) { // for (CustomAbstractTypeWriter writer : customWriters) { // if (writer.accepts(type, this)) { // return writer; // } // } // return null; // } // // public String getIndentation() { // StringBuilder sb = new StringBuilder(); // int i = 0; // while (i++ < indentationLevel) { // sb.append(indentationStep); // } // return sb.toString(); // } // // public void setIndentationStep(String indentation) { // this.indentationStep = indentation; // } // // public void increaseIndentation() { // indentationLevel++; // } // // public void decreaseIndention() { // indentationLevel--; // } // // }
import java2typescript.jackson.module.writer.SortUtil; import java2typescript.jackson.module.writer.WriterPreferences; import static java.lang.String.format; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType;
/******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.grammar; public class ClassType extends AbstractNamedType { private Map<String, AbstractType> fields = new LinkedHashMap<String, AbstractType>(); private Map<String, FunctionType> methods = new LinkedHashMap<String, FunctionType>(); static private ClassType objectType = new ClassType("Object"); /** Root Object class */ static public ClassType getObjectClass() { return objectType; } public ClassType(String className) { super(className); } @Override
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/WriterPreferences.java // public class WriterPreferences { // private String indentationStep = " "; // private int indentationLevel = 0; // // private List<CustomAbstractTypeWriter> customWriters = new ArrayList<CustomAbstractTypeWriter>(); // private boolean useEnumPattern; // private boolean enumAsStringLiteralType = false; // private boolean constantsForStringLiteralTypeEnums = false; // /** sort types and vars in output */ // private boolean sort; // // public boolean isStringLiteralTypeForEnums() { // return enumAsStringLiteralType; // } // // public void useStringLiteralTypeForEnums(boolean withConstants) { // addWriter(new EnumTypeToStringLiteralTypeWriter()); // this.enumAsStringLiteralType = true; // this.constantsForStringLiteralTypeEnums = withConstants; // } // // public void useStringLiteralTypeForEnums() { // useStringLiteralTypeForEnums(false); // } // // public boolean isConstantsForStringLiteralTypeEnums() { // return this.constantsForStringLiteralTypeEnums; // } // // public void useEnumPattern() { // addWriter(new EnumTypeToEnumPatternWriter()); // useEnumPattern = true; // } // // public boolean isUseEnumPattern() { // return useEnumPattern; // } // // public void sort() { // sort = true; // } // // public boolean isSort() { // return sort; // } // // public void addWriter(CustomAbstractTypeWriter writer) { // this.customWriters.add(writer); // } // // public List<CustomAbstractTypeWriter> getCustomWriters() { // return customWriters; // } // // public boolean hasCustomWriter(AbstractNamedType type) { // return getCustomWriter(type) != null; // } // // public void writeDef(AbstractNamedType type, Writer writer) throws IOException { // getCustomWriter(type).writeDef(type, writer, this); // } // // public CustomAbstractTypeWriter getCustomWriter(AbstractNamedType type) { // for (CustomAbstractTypeWriter writer : customWriters) { // if (writer.accepts(type, this)) { // return writer; // } // } // return null; // } // // public String getIndentation() { // StringBuilder sb = new StringBuilder(); // int i = 0; // while (i++ < indentationLevel) { // sb.append(indentationStep); // } // return sb.toString(); // } // // public void setIndentationStep(String indentation) { // this.indentationStep = indentation; // } // // public void increaseIndentation() { // indentationLevel++; // } // // public void decreaseIndention() { // indentationLevel--; // } // // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/ClassType.java import java2typescript.jackson.module.writer.SortUtil; import java2typescript.jackson.module.writer.WriterPreferences; import static java.lang.String.format; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; /******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.grammar; public class ClassType extends AbstractNamedType { private Map<String, AbstractType> fields = new LinkedHashMap<String, AbstractType>(); private Map<String, FunctionType> methods = new LinkedHashMap<String, FunctionType>(); static private ClassType objectType = new ClassType("Object"); /** Root Object class */ static public ClassType getObjectClass() { return objectType; } public ClassType(String className) { super(className); } @Override
public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException {
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/rs/PeopleRestService.java
// Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // }
import java.util.Collection; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.example.model.Person; import com.example.services.PeopleService;
package com.example.rs; @Path("/people") public class PeopleRestService { @Inject
// Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // } // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java import java.util.Collection; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.example.model.Person; import com.example.services.PeopleService; package com.example.rs; @Path("/people") public class PeopleRestService { @Inject
private PeopleService peopleService;
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/rs/PeopleRestService.java
// Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // }
import java.util.Collection; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.example.model.Person; import com.example.services.PeopleService;
package com.example.rs; @Path("/people") public class PeopleRestService { @Inject private PeopleService peopleService; @Produces({ MediaType.APPLICATION_JSON }) @GET
// Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // } // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java import java.util.Collection; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.example.model.Person; import com.example.services.PeopleService; package com.example.rs; @Path("/people") public class PeopleRestService { @Inject private PeopleService peopleService; @Produces({ MediaType.APPLICATION_JSON }) @GET
public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) {
raphaeljolivet/java2typescript
java2typescript-jaxrs/src/test/java/java2typescript/jaxrs/DescriptorGeneratorTest.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // }
import com.example.rs.PeopleRestService; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Collections; import java2typescript.jackson.module.grammar.Module; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import org.junit.Before; import org.junit.Test;
/******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jaxrs; public class DescriptorGeneratorTest { private Writer out; static class MyObject { public String field; } @Path("/") static private interface ExampleService { @Path("/{id}") @POST public String aPostMethod(// @QueryParam("q1") String queryParam, // @PathParam("id") String id, // @FormParam("formParam") Integer formParam, // String postPayload); @Path("/{id}") @GET public void aGetMethod(// @QueryParam("q1") String queryParam, // @PathParam("id") String id, // @FormParam("formParam") Integer formParam, // MyObject postPayload); } @Before public void setUp() { out = new OutputStreamWriter(System.out); } @Test public void testJSGenerate() throws JsonGenerationException, JsonMappingException, IOException { ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator(
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // Path: java2typescript-jaxrs/src/test/java/java2typescript/jaxrs/DescriptorGeneratorTest.java import com.example.rs.PeopleRestService; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Collections; import java2typescript.jackson.module.grammar.Module; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import org.junit.Before; import org.junit.Test; /******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jaxrs; public class DescriptorGeneratorTest { private Writer out; static class MyObject { public String field; } @Path("/") static private interface ExampleService { @Path("/{id}") @POST public String aPostMethod(// @QueryParam("q1") String queryParam, // @PathParam("id") String id, // @FormParam("formParam") Integer formParam, // String postPayload); @Path("/{id}") @GET public void aGetMethod(// @QueryParam("q1") String queryParam, // @PathParam("id") String id, // @FormParam("formParam") Integer formParam, // MyObject postPayload); } @Before public void setUp() { out = new OutputStreamWriter(System.out); } @Test public void testJSGenerate() throws JsonGenerationException, JsonMappingException, IOException { ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator(
Collections.singletonList(PeopleRestService.class));
raphaeljolivet/java2typescript
java2typescript-jaxrs/src/test/java/java2typescript/jaxrs/DescriptorGeneratorTest.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // }
import com.example.rs.PeopleRestService; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Collections; import java2typescript.jackson.module.grammar.Module; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import org.junit.Before; import org.junit.Test;
@QueryParam("q1") String queryParam, // @PathParam("id") String id, // @FormParam("formParam") Integer formParam, // MyObject postPayload); } @Before public void setUp() { out = new OutputStreamWriter(System.out); } @Test public void testJSGenerate() throws JsonGenerationException, JsonMappingException, IOException { ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator( Collections.singletonList(PeopleRestService.class)); descGen.generateJavascript("moduleName", out); } @Test public void testTypescriptGenerate() throws JsonGenerationException, JsonMappingException, IOException { ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator( Collections.singletonList(PeopleRestService.class)); ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("custom-mapping"); mapper.registerModule(module);
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // Path: java2typescript-jaxrs/src/test/java/java2typescript/jaxrs/DescriptorGeneratorTest.java import com.example.rs.PeopleRestService; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Collections; import java2typescript.jackson.module.grammar.Module; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import org.junit.Before; import org.junit.Test; @QueryParam("q1") String queryParam, // @PathParam("id") String id, // @FormParam("formParam") Integer formParam, // MyObject postPayload); } @Before public void setUp() { out = new OutputStreamWriter(System.out); } @Test public void testJSGenerate() throws JsonGenerationException, JsonMappingException, IOException { ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator( Collections.singletonList(PeopleRestService.class)); descGen.generateJavascript("moduleName", out); } @Test public void testTypescriptGenerate() throws JsonGenerationException, JsonMappingException, IOException { ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator( Collections.singletonList(PeopleRestService.class)); ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("custom-mapping"); mapper.registerModule(module);
Module tsModule = descGen.generateTypeScript("modName");
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/EnumTypeToStringLiteralTypeWriter.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import static java.lang.String.format; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.base.AbstractNamedType;
package java2typescript.jackson.module.writer; /** * Another alternate way of converting Java enums. This writer will convert enums to what is known as a String Literal * Type in TypeScript (>=1.8). The advantage here is that the generated typescript definitions can be used with JSON * that has the string value of the corresponding java enum value, while still maintaining strong-typing. * More info: https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types * @author Andy Perlitch */ public class EnumTypeToStringLiteralTypeWriter implements CustomAbstractTypeWriter { private String enumConstantValuesClassSufix = "Values"; @Override
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/EnumTypeToStringLiteralTypeWriter.java import static java.lang.String.format; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.base.AbstractNamedType; package java2typescript.jackson.module.writer; /** * Another alternate way of converting Java enums. This writer will convert enums to what is known as a String Literal * Type in TypeScript (>=1.8). The advantage here is that the generated typescript definitions can be used with JSON * that has the string value of the corresponding java enum value, while still maintaining strong-typing. * More info: https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types * @author Andy Perlitch */ public class EnumTypeToStringLiteralTypeWriter implements CustomAbstractTypeWriter { private String enumConstantValuesClassSufix = "Values"; @Override
public boolean accepts(AbstractNamedType type, WriterPreferences preferences) {
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; import java2typescript.jackson.module.writer.InternalModuleFormatWriter;
/******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.grammar; public class Module { private String name;
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; import java2typescript.jackson.module.writer.InternalModuleFormatWriter; /******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.grammar; public class Module { private String name;
private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>();
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/EnumTypeToEnumPatternWriter.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java.io.IOException; import java.io.Writer; import java.util.List; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.base.AbstractNamedType;
package java2typescript.jackson.module.writer; /** * Alternative to writing Java enum type to TypeScript enum type. Usefult, if You have following goals:<br> * 1) JavaScript object containing field of "enum" must contain enum name instead of ordinal value. This is good for several reasons: a) easy to understand JSON content b) doesn't mess things up, if enum order changes in backend.<br> * 2) You'd still like to write TypeScript as if You were using real enums - type safety, etc.<br> * 3) You need to use "reflection" (instanceof) to detect if field is "enum" * @author Ats Uiboupin */ public class EnumTypeToEnumPatternWriter implements CustomAbstractTypeWriter { @Override
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/EnumTypeToEnumPatternWriter.java import java.io.IOException; import java.io.Writer; import java.util.List; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.base.AbstractNamedType; package java2typescript.jackson.module.writer; /** * Alternative to writing Java enum type to TypeScript enum type. Usefult, if You have following goals:<br> * 1) JavaScript object containing field of "enum" must contain enum name instead of ordinal value. This is good for several reasons: a) easy to understand JSON content b) doesn't mess things up, if enum order changes in backend.<br> * 2) You'd still like to write TypeScript as if You were using real enums - type safety, etc.<br> * 3) You need to use "reflection" (instanceof) to detect if field is "enum" * @author Ats Uiboupin */ public class EnumTypeToEnumPatternWriter implements CustomAbstractTypeWriter { @Override
public boolean accepts(AbstractNamedType type, WriterPreferences preferences) {
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/services/PeopleService.java
// Path: sample-web-app/src/main/java/com/example/exceptions/PersonAlreadyExistsException.java // public class PersonAlreadyExistsException extends WebApplicationException { // private static final long serialVersionUID = 6817489620338221395L; // // public PersonAlreadyExistsException( final String email ) { // super( // Response // .status( Status.CONFLICT ) // .entity( "Person already exists: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/exceptions/PersonNotFoundException.java // public class PersonNotFoundException extends WebApplicationException { // private static final long serialVersionUID = -2894269137259898072L; // // public PersonNotFoundException( final String email ) { // super( // Response // .status( Status.NOT_FOUND ) // .entity( "Person not found: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.stereotype.Service; import com.example.exceptions.PersonAlreadyExistsException; import com.example.exceptions.PersonNotFoundException; import com.example.model.Person;
package com.example.services; @Service public class PeopleService {
// Path: sample-web-app/src/main/java/com/example/exceptions/PersonAlreadyExistsException.java // public class PersonAlreadyExistsException extends WebApplicationException { // private static final long serialVersionUID = 6817489620338221395L; // // public PersonAlreadyExistsException( final String email ) { // super( // Response // .status( Status.CONFLICT ) // .entity( "Person already exists: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/exceptions/PersonNotFoundException.java // public class PersonNotFoundException extends WebApplicationException { // private static final long serialVersionUID = -2894269137259898072L; // // public PersonNotFoundException( final String email ) { // super( // Response // .status( Status.NOT_FOUND ) // .entity( "Person not found: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.stereotype.Service; import com.example.exceptions.PersonAlreadyExistsException; import com.example.exceptions.PersonNotFoundException; import com.example.model.Person; package com.example.services; @Service public class PeopleService {
private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >();
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/services/PeopleService.java
// Path: sample-web-app/src/main/java/com/example/exceptions/PersonAlreadyExistsException.java // public class PersonAlreadyExistsException extends WebApplicationException { // private static final long serialVersionUID = 6817489620338221395L; // // public PersonAlreadyExistsException( final String email ) { // super( // Response // .status( Status.CONFLICT ) // .entity( "Person already exists: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/exceptions/PersonNotFoundException.java // public class PersonNotFoundException extends WebApplicationException { // private static final long serialVersionUID = -2894269137259898072L; // // public PersonNotFoundException( final String email ) { // super( // Response // .status( Status.NOT_FOUND ) // .entity( "Person not found: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.stereotype.Service; import com.example.exceptions.PersonAlreadyExistsException; import com.example.exceptions.PersonNotFoundException; import com.example.model.Person;
package com.example.services; @Service public class PeopleService { private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); public Collection< Person > getPeople( int page, int pageSize ) { final Collection< Person > slice = new ArrayList< Person >( pageSize ); final Iterator< Person > iterator = persons.values().iterator(); for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { if( ++i > ( ( page - 1 ) * pageSize ) ) { slice.add( iterator.next() ); } } return slice; } public Person getByEmail( final String email ) { final Person person = persons.get( email ); if( person == null ) {
// Path: sample-web-app/src/main/java/com/example/exceptions/PersonAlreadyExistsException.java // public class PersonAlreadyExistsException extends WebApplicationException { // private static final long serialVersionUID = 6817489620338221395L; // // public PersonAlreadyExistsException( final String email ) { // super( // Response // .status( Status.CONFLICT ) // .entity( "Person already exists: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/exceptions/PersonNotFoundException.java // public class PersonNotFoundException extends WebApplicationException { // private static final long serialVersionUID = -2894269137259898072L; // // public PersonNotFoundException( final String email ) { // super( // Response // .status( Status.NOT_FOUND ) // .entity( "Person not found: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.stereotype.Service; import com.example.exceptions.PersonAlreadyExistsException; import com.example.exceptions.PersonNotFoundException; import com.example.model.Person; package com.example.services; @Service public class PeopleService { private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); public Collection< Person > getPeople( int page, int pageSize ) { final Collection< Person > slice = new ArrayList< Person >( pageSize ); final Iterator< Person > iterator = persons.values().iterator(); for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { if( ++i > ( ( page - 1 ) * pageSize ) ) { slice.add( iterator.next() ); } } return slice; } public Person getByEmail( final String email ) { final Person person = persons.get( email ); if( person == null ) {
throw new PersonNotFoundException( email );
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/services/PeopleService.java
// Path: sample-web-app/src/main/java/com/example/exceptions/PersonAlreadyExistsException.java // public class PersonAlreadyExistsException extends WebApplicationException { // private static final long serialVersionUID = 6817489620338221395L; // // public PersonAlreadyExistsException( final String email ) { // super( // Response // .status( Status.CONFLICT ) // .entity( "Person already exists: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/exceptions/PersonNotFoundException.java // public class PersonNotFoundException extends WebApplicationException { // private static final long serialVersionUID = -2894269137259898072L; // // public PersonNotFoundException( final String email ) { // super( // Response // .status( Status.NOT_FOUND ) // .entity( "Person not found: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.stereotype.Service; import com.example.exceptions.PersonAlreadyExistsException; import com.example.exceptions.PersonNotFoundException; import com.example.model.Person;
package com.example.services; @Service public class PeopleService { private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); public Collection< Person > getPeople( int page, int pageSize ) { final Collection< Person > slice = new ArrayList< Person >( pageSize ); final Iterator< Person > iterator = persons.values().iterator(); for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { if( ++i > ( ( page - 1 ) * pageSize ) ) { slice.add( iterator.next() ); } } return slice; } public Person getByEmail( final String email ) { final Person person = persons.get( email ); if( person == null ) { throw new PersonNotFoundException( email ); } return person; } public Person addPerson( final String email, final String firstName, final String lastName ) { final Person person = new Person( email ); person.setFirstName( firstName ); person.setLastName( lastName ); if( persons.putIfAbsent( email, person ) != null ) {
// Path: sample-web-app/src/main/java/com/example/exceptions/PersonAlreadyExistsException.java // public class PersonAlreadyExistsException extends WebApplicationException { // private static final long serialVersionUID = 6817489620338221395L; // // public PersonAlreadyExistsException( final String email ) { // super( // Response // .status( Status.CONFLICT ) // .entity( "Person already exists: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/exceptions/PersonNotFoundException.java // public class PersonNotFoundException extends WebApplicationException { // private static final long serialVersionUID = -2894269137259898072L; // // public PersonNotFoundException( final String email ) { // super( // Response // .status( Status.NOT_FOUND ) // .entity( "Person not found: " + email ) // .build() // ); // } // } // // Path: sample-web-app/src/main/java/com/example/model/Person.java // public class Person { // private String email; // private String firstName; // private String lastName; // // public Person() { // } // // public Person( final String email ) { // this.email = email; // } // // public Person( final String firstName, final String lastName ) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail( final String email ) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public void setFirstName( final String firstName ) { // this.firstName = firstName; // } // // public void setLastName( final String lastName ) { // this.lastName = lastName; // } // } // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.stereotype.Service; import com.example.exceptions.PersonAlreadyExistsException; import com.example.exceptions.PersonNotFoundException; import com.example.model.Person; package com.example.services; @Service public class PeopleService { private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); public Collection< Person > getPeople( int page, int pageSize ) { final Collection< Person > slice = new ArrayList< Person >( pageSize ); final Iterator< Person > iterator = persons.values().iterator(); for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { if( ++i > ( ( page - 1 ) * pageSize ) ) { slice.add( iterator.next() ); } } return slice; } public Person getByEmail( final String email ) { final Person person = persons.get( email ); if( person == null ) { throw new PersonNotFoundException( email ); } return person; } public Person addPerson( final String email, final String firstName, final String lastName ) { final Person person = new Person( email ); person.setFirstName( firstName ); person.setLastName( lastName ); if( persons.putIfAbsent( email, person ) != null ) {
throw new PersonAlreadyExistsException( email );
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/WriterPreferences.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java2typescript.jackson.module.grammar.base.AbstractNamedType;
package java2typescript.jackson.module.writer; public class WriterPreferences { private String indentationStep = " "; private int indentationLevel = 0; private List<CustomAbstractTypeWriter> customWriters = new ArrayList<CustomAbstractTypeWriter>(); private boolean useEnumPattern; private boolean enumAsStringLiteralType = false; private boolean constantsForStringLiteralTypeEnums = false; /** sort types and vars in output */ private boolean sort; public boolean isStringLiteralTypeForEnums() { return enumAsStringLiteralType; } public void useStringLiteralTypeForEnums(boolean withConstants) { addWriter(new EnumTypeToStringLiteralTypeWriter()); this.enumAsStringLiteralType = true; this.constantsForStringLiteralTypeEnums = withConstants; } public void useStringLiteralTypeForEnums() { useStringLiteralTypeForEnums(false); } public boolean isConstantsForStringLiteralTypeEnums() { return this.constantsForStringLiteralTypeEnums; } public void useEnumPattern() { addWriter(new EnumTypeToEnumPatternWriter()); useEnumPattern = true; } public boolean isUseEnumPattern() { return useEnumPattern; } public void sort() { sort = true; } public boolean isSort() { return sort; } public void addWriter(CustomAbstractTypeWriter writer) { this.customWriters.add(writer); } public List<CustomAbstractTypeWriter> getCustomWriters() { return customWriters; }
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/WriterPreferences.java import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java2typescript.jackson.module.grammar.base.AbstractNamedType; package java2typescript.jackson.module.writer; public class WriterPreferences { private String indentationStep = " "; private int indentationLevel = 0; private List<CustomAbstractTypeWriter> customWriters = new ArrayList<CustomAbstractTypeWriter>(); private boolean useEnumPattern; private boolean enumAsStringLiteralType = false; private boolean constantsForStringLiteralTypeEnums = false; /** sort types and vars in output */ private boolean sort; public boolean isStringLiteralTypeForEnums() { return enumAsStringLiteralType; } public void useStringLiteralTypeForEnums(boolean withConstants) { addWriter(new EnumTypeToStringLiteralTypeWriter()); this.enumAsStringLiteralType = true; this.constantsForStringLiteralTypeEnums = withConstants; } public void useStringLiteralTypeForEnums() { useStringLiteralTypeForEnums(false); } public boolean isConstantsForStringLiteralTypeEnums() { return this.constantsForStringLiteralTypeEnums; } public void useEnumPattern() { addWriter(new EnumTypeToEnumPatternWriter()); useEnumPattern = true; } public boolean isUseEnumPattern() { return useEnumPattern; } public void sort() { sort = true; } public boolean isSort() { return sort; } public void addWriter(CustomAbstractTypeWriter writer) { this.customWriters.add(writer); } public List<CustomAbstractTypeWriter> getCustomWriters() { return customWriters; }
public boolean hasCustomWriter(AbstractNamedType type) {
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/visitors/TSJsonFormatVisitorWrapper.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonBooleanFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonIntegerFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNullFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNumberFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonStringFormatVisitor; import java2typescript.jackson.module.Configuration;
/******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.visitors; public class TSJsonFormatVisitorWrapper extends ABaseTSJsonFormatVisitor implements JsonFormatVisitorWrapper { public TSJsonFormatVisitorWrapper(ABaseTSJsonFormatVisitor parentHolder, Configuration conf) { super(parentHolder, conf); }
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/visitors/TSJsonFormatVisitorWrapper.java import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonBooleanFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonIntegerFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNullFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNumberFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonStringFormatVisitor; import java2typescript.jackson.module.Configuration; /******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.visitors; public class TSJsonFormatVisitorWrapper extends ABaseTSJsonFormatVisitor implements JsonFormatVisitorWrapper { public TSJsonFormatVisitorWrapper(ABaseTSJsonFormatVisitor parentHolder, Configuration conf) { super(parentHolder, conf); }
public TSJsonFormatVisitorWrapper(Module module, Configuration conf) {
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/visitors/TSJsonFormatVisitorWrapper.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonBooleanFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonIntegerFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNullFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNumberFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonStringFormatVisitor; import java2typescript.jackson.module.Configuration;
/******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.visitors; public class TSJsonFormatVisitorWrapper extends ABaseTSJsonFormatVisitor implements JsonFormatVisitorWrapper { public TSJsonFormatVisitorWrapper(ABaseTSJsonFormatVisitor parentHolder, Configuration conf) { super(parentHolder, conf); } public TSJsonFormatVisitorWrapper(Module module, Configuration conf) { super(module, conf); } private <T extends ABaseTSJsonFormatVisitor<?>> T setTypeAndReturn(T actualVisitor) { type = actualVisitor.getType(); return actualVisitor; } /** Visit recursively the type, or return a cached response */ public static AbstractType getTSTypeForHandler(ABaseTSJsonFormatVisitor<?> baseVisitor, JsonFormatVisitable handler, JavaType typeHint, Configuration conf) throws JsonMappingException { AbstractType computedType = baseVisitor.getComputedTypes().get(typeHint); if (computedType != null) { return computedType; } TSJsonFormatVisitorWrapper visitor = new TSJsonFormatVisitorWrapper(baseVisitor, conf); handler.acceptJsonFormatVisitor(visitor, typeHint); baseVisitor.getComputedTypes().put(typeHint, visitor.getType()); return visitor.getType(); } /** Either Java simple name or @JsonTypeName annotation */ public String getName(JavaType type) { return conf.getNamingStrategy().getName(type); } private TSJsonObjectFormatVisitor useNamedClassOrParse(JavaType javaType) { String name = getName(javaType);
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/visitors/TSJsonFormatVisitorWrapper.java import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonBooleanFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonIntegerFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNullFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNumberFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonStringFormatVisitor; import java2typescript.jackson.module.Configuration; /******************************************************************************* * Copyright 2013 Raphael Jolivet * * 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 java2typescript.jackson.module.visitors; public class TSJsonFormatVisitorWrapper extends ABaseTSJsonFormatVisitor implements JsonFormatVisitorWrapper { public TSJsonFormatVisitorWrapper(ABaseTSJsonFormatVisitor parentHolder, Configuration conf) { super(parentHolder, conf); } public TSJsonFormatVisitorWrapper(Module module, Configuration conf) { super(module, conf); } private <T extends ABaseTSJsonFormatVisitor<?>> T setTypeAndReturn(T actualVisitor) { type = actualVisitor.getType(); return actualVisitor; } /** Visit recursively the type, or return a cached response */ public static AbstractType getTSTypeForHandler(ABaseTSJsonFormatVisitor<?> baseVisitor, JsonFormatVisitable handler, JavaType typeHint, Configuration conf) throws JsonMappingException { AbstractType computedType = baseVisitor.getComputedTypes().get(typeHint); if (computedType != null) { return computedType; } TSJsonFormatVisitorWrapper visitor = new TSJsonFormatVisitorWrapper(baseVisitor, conf); handler.acceptJsonFormatVisitor(visitor, typeHint); baseVisitor.getComputedTypes().put(typeHint, visitor.getType()); return visitor.getType(); } /** Either Java simple name or @JsonTypeName annotation */ public String getName(JavaType type) { return conf.getNamingStrategy().getName(type); } private TSJsonObjectFormatVisitor useNamedClassOrParse(JavaType javaType) { String name = getName(javaType);
AbstractNamedType namedType = getModule().getNamedTypes().get(name);
raphaeljolivet/java2typescript
java2typescript-jackson/src/test/java/java2typescript/jackson/module/StaticFieldExporterTest.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java2typescript.jackson.module.grammar.Module; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonTypeName;
/******************************************************************************* * Copyright 2014 Florian Benz * * 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 java2typescript.jackson.module; public class StaticFieldExporterTest { @JsonTypeName("ChangedEnumName") enum Enum { VAL1, VAL2, VAL3 } static class TestClass { public static final boolean MY_CONSTANT_BOOLEAN = true; public static final String MY_CONSTANT_STRING = "Test"; public static final int MY_CONSTANT_INT = 10; public static final double MY_CONSTANT_DOUBLE = 42.12; public static final Enum MY_CONSTANT_ENUM = Enum.VAL1; public static final Enum[] MY_CONSTANT_ENUM_ARRAY = new Enum[] { Enum.VAL1 }; public static final Enum[] MY_CONSTANT_ENUM_ARRAY_2 = new Enum[] { Enum.VAL1, Enum.VAL2 }; public static final String[] MY_CONSTANT_ARRAY = new String[] { "Test" }; public static final int[] MY_CONSTANT_INT_ARRAY = new int[] { 10, 12 }; public static final double[] MY_CONSTANT_DOUBLE_ARRAY = new double[] { 42.12 }; public static final boolean[] MY_CONSTANT_BOOLEAN_ARRAY = new boolean[] { true, false, true }; public String doNotExportAsStatic; } @Test public void testTypeScriptDefinition() throws IOException, IllegalArgumentException { Writer out = new StringWriter(); ArrayList<Class<?>> classesToConvert = new ArrayList<Class<?>>(); classesToConvert.add(TestClass.class);
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // Path: java2typescript-jackson/src/test/java/java2typescript/jackson/module/StaticFieldExporterTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java2typescript.jackson.module.grammar.Module; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonTypeName; /******************************************************************************* * Copyright 2014 Florian Benz * * 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 java2typescript.jackson.module; public class StaticFieldExporterTest { @JsonTypeName("ChangedEnumName") enum Enum { VAL1, VAL2, VAL3 } static class TestClass { public static final boolean MY_CONSTANT_BOOLEAN = true; public static final String MY_CONSTANT_STRING = "Test"; public static final int MY_CONSTANT_INT = 10; public static final double MY_CONSTANT_DOUBLE = 42.12; public static final Enum MY_CONSTANT_ENUM = Enum.VAL1; public static final Enum[] MY_CONSTANT_ENUM_ARRAY = new Enum[] { Enum.VAL1 }; public static final Enum[] MY_CONSTANT_ENUM_ARRAY_2 = new Enum[] { Enum.VAL1, Enum.VAL2 }; public static final String[] MY_CONSTANT_ARRAY = new String[] { "Test" }; public static final int[] MY_CONSTANT_INT_ARRAY = new int[] { 10, 12 }; public static final double[] MY_CONSTANT_DOUBLE_ARRAY = new double[] { 42.12 }; public static final boolean[] MY_CONSTANT_BOOLEAN_ARRAY = new boolean[] { true, false, true }; public String doNotExportAsStatic; } @Test public void testTypeScriptDefinition() throws IOException, IllegalArgumentException { Writer out = new StringWriter(); ArrayList<Class<?>> classesToConvert = new ArrayList<Class<?>>(); classesToConvert.add(TestClass.class);
Module module = new Module("mod");
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/ExternalModuleFormatWriter.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Map.Entry; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType;
package java2typescript.jackson.module.writer; /** * Generates TypeScript type definitions for given module in external module format */ public class ExternalModuleFormatWriter implements ModuleWriter { public WriterPreferences preferences = new WriterPreferences(); @Override
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/ExternalModuleFormatWriter.java import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Map.Entry; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; package java2typescript.jackson.module.writer; /** * Generates TypeScript type definitions for given module in external module format */ public class ExternalModuleFormatWriter implements ModuleWriter { public WriterPreferences preferences = new WriterPreferences(); @Override
public void write(Module module, Writer writer) throws IOException {
raphaeljolivet/java2typescript
java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/ExternalModuleFormatWriter.java
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // }
import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Map.Entry; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType;
package java2typescript.jackson.module.writer; /** * Generates TypeScript type definitions for given module in external module format */ public class ExternalModuleFormatWriter implements ModuleWriter { public WriterPreferences preferences = new WriterPreferences(); @Override public void write(Module module, Writer writer) throws IOException { writeModuleContent(module, writer); writer.flush(); } protected void writeModuleContent(Module module, Writer writer) throws IOException {
// Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/Module.java // public class Module { // // private String name; // // private Map<String, AbstractNamedType> namedTypes = new HashMap<String, AbstractNamedType>(); // // private Map<String, AbstractType> vars = new HashMap<String, AbstractType>(); // // public Module() { // } // // public Module(String name) { // this.name = name; // } // // public Map<String, AbstractNamedType> getNamedTypes() { // return namedTypes; // } // // public Map<String, AbstractType> getVars() { // return vars; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void write(Writer writer) throws IOException { // new InternalModuleFormatWriter().write(this, writer); // } // // } // // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/grammar/base/AbstractNamedType.java // abstract public class AbstractNamedType extends AbstractType { // // protected final String name; // // public AbstractNamedType(String className) { // this.name = className; // } // // @Override // public void write(Writer writer) throws IOException { // writer.write(name); // } // // public String getName() { // return name; // } // // public void writeDef(Writer writer, WriterPreferences preferences) throws IOException { // if(!preferences.hasCustomWriter(this)) { // writeDefInternal(writer, preferences); // } else { // preferences.writeDef(this, writer); // } // } // // abstract public void writeDefInternal(Writer writer, WriterPreferences preferences) throws IOException; // } // Path: java2typescript-jackson/src/main/java/java2typescript/jackson/module/writer/ExternalModuleFormatWriter.java import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Map.Entry; import java2typescript.jackson.module.grammar.EnumType; import java2typescript.jackson.module.grammar.Module; import java2typescript.jackson.module.grammar.base.AbstractNamedType; import java2typescript.jackson.module.grammar.base.AbstractType; package java2typescript.jackson.module.writer; /** * Generates TypeScript type definitions for given module in external module format */ public class ExternalModuleFormatWriter implements ModuleWriter { public WriterPreferences preferences = new WriterPreferences(); @Override public void write(Module module, Writer writer) throws IOException { writeModuleContent(module, writer); writer.flush(); } protected void writeModuleContent(Module module, Writer writer) throws IOException {
Collection<AbstractNamedType> namedTypes = module.getNamedTypes().values();
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/Starter.java
// Path: sample-web-app/src/main/java/com/example/config/AppConfig.java // @Configuration // public class AppConfig { // @Bean( destroyMethod = "shutdown" ) // public SpringBus cxf() { // return new SpringBus(); // } // // @Bean @DependsOn( "cxf" ) // public Server jaxRsServer() { // JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); // factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); // factory.setAddress( "/" + factory.getAddress() ); // factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); // return factory.create(); // } // // @Bean // public JaxRsApiApplication jaxRsApiApplication() { // return new JaxRsApiApplication(); // } // // @Bean // public PeopleRestService peopleRestService() { // return new PeopleRestService(); // } // // @Bean // public PeopleService peopleService() { // return new PeopleService(); // } // // @Bean // public JacksonJsonProvider jsonProvider() { // return new JacksonJsonProvider(); // } // }
import java.io.IOException; import java.net.URISyntaxException; import org.apache.cxf.transport.servlet.CXFServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import com.example.config.AppConfig;
package com.example; public class Starter { public static void main(final String[] args) throws Exception { Server server = new Server(8080); HandlerCollection handlerCollection = new HandlerCollection(); server.setHandler(handlerCollection); addSpringContext(handlerCollection); // Default one, resourceHandler takes everything addStaticContext(handlerCollection); server.start(); server.join(); } static private void addSpringContext(HandlerCollection collection) { final ServletHolder servletHolder = new ServletHolder(new CXFServlet()); final ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(servletHolder, "/rest/*"); context.addEventListener(new ContextLoaderListener()); context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
// Path: sample-web-app/src/main/java/com/example/config/AppConfig.java // @Configuration // public class AppConfig { // @Bean( destroyMethod = "shutdown" ) // public SpringBus cxf() { // return new SpringBus(); // } // // @Bean @DependsOn( "cxf" ) // public Server jaxRsServer() { // JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); // factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); // factory.setAddress( "/" + factory.getAddress() ); // factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); // return factory.create(); // } // // @Bean // public JaxRsApiApplication jaxRsApiApplication() { // return new JaxRsApiApplication(); // } // // @Bean // public PeopleRestService peopleRestService() { // return new PeopleRestService(); // } // // @Bean // public PeopleService peopleService() { // return new PeopleService(); // } // // @Bean // public JacksonJsonProvider jsonProvider() { // return new JacksonJsonProvider(); // } // } // Path: sample-web-app/src/main/java/com/example/Starter.java import java.io.IOException; import java.net.URISyntaxException; import org.apache.cxf.transport.servlet.CXFServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import com.example.config.AppConfig; package com.example; public class Starter { public static void main(final String[] args) throws Exception { Server server = new Server(8080); HandlerCollection handlerCollection = new HandlerCollection(); server.setHandler(handlerCollection); addSpringContext(handlerCollection); // Default one, resourceHandler takes everything addStaticContext(handlerCollection); server.start(); server.join(); } static private void addSpringContext(HandlerCollection collection) { final ServletHolder servletHolder = new ServletHolder(new CXFServlet()); final ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(servletHolder, "/rest/*"); context.addEventListener(new ContextLoaderListener()); context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
context.setInitParameter("contextConfigLocation", AppConfig.class.getName());
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/config/AppConfig.java
// Path: sample-web-app/src/main/java/com/example/rs/JaxRsApiApplication.java // @ApplicationPath( "api" ) // public class JaxRsApiApplication extends Application { // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // }
import java.util.Arrays; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService;
package com.example.config; @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean @DependsOn( "cxf" ) public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( "/" + factory.getAddress() ); factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); return factory.create(); } @Bean
// Path: sample-web-app/src/main/java/com/example/rs/JaxRsApiApplication.java // @ApplicationPath( "api" ) // public class JaxRsApiApplication extends Application { // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // } // Path: sample-web-app/src/main/java/com/example/config/AppConfig.java import java.util.Arrays; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService; package com.example.config; @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean @DependsOn( "cxf" ) public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( "/" + factory.getAddress() ); factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); return factory.create(); } @Bean
public JaxRsApiApplication jaxRsApiApplication() {
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/config/AppConfig.java
// Path: sample-web-app/src/main/java/com/example/rs/JaxRsApiApplication.java // @ApplicationPath( "api" ) // public class JaxRsApiApplication extends Application { // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // }
import java.util.Arrays; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService;
package com.example.config; @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean @DependsOn( "cxf" ) public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( "/" + factory.getAddress() ); factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); return factory.create(); } @Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); } @Bean
// Path: sample-web-app/src/main/java/com/example/rs/JaxRsApiApplication.java // @ApplicationPath( "api" ) // public class JaxRsApiApplication extends Application { // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // } // Path: sample-web-app/src/main/java/com/example/config/AppConfig.java import java.util.Arrays; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService; package com.example.config; @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean @DependsOn( "cxf" ) public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( "/" + factory.getAddress() ); factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); return factory.create(); } @Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); } @Bean
public PeopleRestService peopleRestService() {
raphaeljolivet/java2typescript
sample-web-app/src/main/java/com/example/config/AppConfig.java
// Path: sample-web-app/src/main/java/com/example/rs/JaxRsApiApplication.java // @ApplicationPath( "api" ) // public class JaxRsApiApplication extends Application { // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // }
import java.util.Arrays; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService;
package com.example.config; @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean @DependsOn( "cxf" ) public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( "/" + factory.getAddress() ); factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); return factory.create(); } @Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); } @Bean public PeopleRestService peopleRestService() { return new PeopleRestService(); } @Bean
// Path: sample-web-app/src/main/java/com/example/rs/JaxRsApiApplication.java // @ApplicationPath( "api" ) // public class JaxRsApiApplication extends Application { // } // // Path: sample-web-app/src/main/java/com/example/rs/PeopleRestService.java // @Path("/people") // public class PeopleRestService { // @Inject // private PeopleService peopleService; // // @Produces({ MediaType.APPLICATION_JSON }) // @GET // public Collection<Person> getPeopleList(@QueryParam("page") @DefaultValue("1") final int page) { // return peopleService.getPeople(page, 5); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @GET // public Person getPeople(@PathParam("email") final String email) { // return peopleService.getByEmail(email); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @POST // public Response addPerson(@Context final UriInfo uriInfo, @FormParam("email") final String email, // @FormParam("firstName") final String firstName, @FormParam("lastName") final String lastName) { // // peopleService.addPerson(email, firstName, lastName); // return Response.created(uriInfo.getRequestUriBuilder().path(email).build()).build(); // } // // @Produces({ MediaType.APPLICATION_JSON }) // @Path("/{email}") // @PUT // public Person updatePerson(@PathParam("email") final String email, @FormParam("firstName") final String firstName, // @FormParam("lastName") final String lastName) { // // final Person person = peopleService.getByEmail(email); // // if (firstName != null) { // person.setFirstName(firstName); // } // // if (lastName != null) { // person.setLastName(lastName); // } // // return person; // } // // @Path("/{email}") // @DELETE // public Response deletePerson(@PathParam("email") final String email) { // peopleService.removePerson(email); // return Response.ok().build(); // } // // } // // Path: sample-web-app/src/main/java/com/example/services/PeopleService.java // @Service // public class PeopleService { // private final ConcurrentMap< String, Person > persons = new ConcurrentHashMap< String, Person >(); // // public Collection< Person > getPeople( int page, int pageSize ) { // final Collection< Person > slice = new ArrayList< Person >( pageSize ); // // final Iterator< Person > iterator = persons.values().iterator(); // for( int i = 0; slice.size() < pageSize && iterator.hasNext(); ) { // if( ++i > ( ( page - 1 ) * pageSize ) ) { // slice.add( iterator.next() ); // } // } // // return slice; // } // // public Person getByEmail( final String email ) { // final Person person = persons.get( email ); // // if( person == null ) { // throw new PersonNotFoundException( email ); // } // // return person; // } // // public Person addPerson( final String email, final String firstName, final String lastName ) { // final Person person = new Person( email ); // person.setFirstName( firstName ); // person.setLastName( lastName ); // // if( persons.putIfAbsent( email, person ) != null ) { // throw new PersonAlreadyExistsException( email ); // } // // return person; // } // // public void removePerson( final String email ) { // if( persons.remove( email ) == null ) { // throw new PersonNotFoundException( email ); // } // } // } // Path: sample-web-app/src/main/java/com/example/config/AppConfig.java import java.util.Arrays; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService; package com.example.config; @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean @DependsOn( "cxf" ) public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( "/" + factory.getAddress() ); factory.setProviders( Arrays.< Object >asList( jsonProvider() ) ); return factory.create(); } @Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); } @Bean public PeopleRestService peopleRestService() { return new PeopleRestService(); } @Bean
public PeopleService peopleService() {
sw360/sw360rest
subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/vendor/VendorController.java
// Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/core/HalResource.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class HalResource<T> extends Resource<T> { // // private Map<String, Object> embeddedMap; // // public HalResource(T content, Link... links) { // super(content, links); // } // // @SuppressWarnings("unchecked") // public void addEmbeddedResource(String relation, Object embeddedResource) { // if (embeddedMap == null) { // embeddedMap = new HashMap<>(); // } // // Object embeddedResources = embeddedMap.get(relation); // boolean isPluralRelation = relation.endsWith("s"); // // // // // if a relation is plural, the content will always be rendered as an array // if(isPluralRelation) { // if (embeddedResources == null) { // embeddedResources = new ArrayList<>(); // } // ((List<Object>) embeddedResources).add(embeddedResource); // // // if a relation is singular, it would be a single object if there is only one object available // // Otherwise it would be rendered as array // } else { // if (embeddedResources == null) { // embeddedResources = embeddedResource; // } else { // if (embeddedResources instanceof List) { // ((List<Object>) embeddedResources).add(embeddedResource); // } else { // List<Object> embeddedResourcesList = new ArrayList<>(); // embeddedResourcesList.add(embeddedResources); // embeddedResourcesList.add(embeddedResource); // embeddedResources = embeddedResourcesList; // } // } // } // embeddedMap.put(relation, embeddedResources); // } // // @JsonProperty("_embedded") // public Map<String, Object> getEmbeddedRecources() { // return embeddedMap; // } // }
import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.sw360.datahandler.thrift.vendors.Vendor; import org.eclipse.sw360.rest.resourceserver.core.HalResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.BasePathAwareController; import org.springframework.data.rest.webmvc.RepositoryLinksResource; import org.springframework.hateoas.Resource; import org.springframework.hateoas.ResourceProcessor; import org.springframework.hateoas.Resources; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
/* * Copyright Siemens AG, 2017. Part of the SW360 Portal Vendor. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.vendor; @BasePathAwareController @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class VendorController implements ResourceProcessor<RepositoryLinksResource> { public static final String VENDORS_URL = "/vendors"; @NonNull private final Sw360VendorService vendorService; @RequestMapping(value = VENDORS_URL, method = RequestMethod.GET) public ResponseEntity<Resources<Resource<Vendor>>> getVendors(OAuth2Authentication oAuth2Authentication) { List<Vendor> vendors = vendorService.getVendors(); List<Resource<Vendor>> vendorResources = new ArrayList<>(); for (Vendor vendor : vendors) { // TODO Kai Tödter 2017-01-04 // Find better way to decrease details in list resources, // e.g. apply projections or Jackson Mixins vendor.setShortname(null); vendor.setType(null); vendor.setUrl(null); Resource<Vendor> vendorResource = new Resource<>(vendor); vendorResources.add(vendorResource); } Resources<Resource<Vendor>> resources = new Resources<>(vendorResources); return new ResponseEntity<>(resources, HttpStatus.OK); } @RequestMapping(VENDORS_URL + "/{id}") public ResponseEntity<Resource<Vendor>> getVendor( @PathVariable("id") String id, OAuth2Authentication oAuth2Authentication) { Vendor sw360Vendor = vendorService.getVendorById(id);
// Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/core/HalResource.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class HalResource<T> extends Resource<T> { // // private Map<String, Object> embeddedMap; // // public HalResource(T content, Link... links) { // super(content, links); // } // // @SuppressWarnings("unchecked") // public void addEmbeddedResource(String relation, Object embeddedResource) { // if (embeddedMap == null) { // embeddedMap = new HashMap<>(); // } // // Object embeddedResources = embeddedMap.get(relation); // boolean isPluralRelation = relation.endsWith("s"); // // // // // if a relation is plural, the content will always be rendered as an array // if(isPluralRelation) { // if (embeddedResources == null) { // embeddedResources = new ArrayList<>(); // } // ((List<Object>) embeddedResources).add(embeddedResource); // // // if a relation is singular, it would be a single object if there is only one object available // // Otherwise it would be rendered as array // } else { // if (embeddedResources == null) { // embeddedResources = embeddedResource; // } else { // if (embeddedResources instanceof List) { // ((List<Object>) embeddedResources).add(embeddedResource); // } else { // List<Object> embeddedResourcesList = new ArrayList<>(); // embeddedResourcesList.add(embeddedResources); // embeddedResourcesList.add(embeddedResource); // embeddedResources = embeddedResourcesList; // } // } // } // embeddedMap.put(relation, embeddedResources); // } // // @JsonProperty("_embedded") // public Map<String, Object> getEmbeddedRecources() { // return embeddedMap; // } // } // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/vendor/VendorController.java import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.sw360.datahandler.thrift.vendors.Vendor; import org.eclipse.sw360.rest.resourceserver.core.HalResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.BasePathAwareController; import org.springframework.data.rest.webmvc.RepositoryLinksResource; import org.springframework.hateoas.Resource; import org.springframework.hateoas.ResourceProcessor; import org.springframework.hateoas.Resources; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; /* * Copyright Siemens AG, 2017. Part of the SW360 Portal Vendor. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.vendor; @BasePathAwareController @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class VendorController implements ResourceProcessor<RepositoryLinksResource> { public static final String VENDORS_URL = "/vendors"; @NonNull private final Sw360VendorService vendorService; @RequestMapping(value = VENDORS_URL, method = RequestMethod.GET) public ResponseEntity<Resources<Resource<Vendor>>> getVendors(OAuth2Authentication oAuth2Authentication) { List<Vendor> vendors = vendorService.getVendors(); List<Resource<Vendor>> vendorResources = new ArrayList<>(); for (Vendor vendor : vendors) { // TODO Kai Tödter 2017-01-04 // Find better way to decrease details in list resources, // e.g. apply projections or Jackson Mixins vendor.setShortname(null); vendor.setType(null); vendor.setUrl(null); Resource<Vendor> vendorResource = new Resource<>(vendor); vendorResources.add(vendorResource); } Resources<Resource<Vendor>> resources = new Resources<>(vendorResources); return new ResponseEntity<>(resources, HttpStatus.OK); } @RequestMapping(VENDORS_URL + "/{id}") public ResponseEntity<Resource<Vendor>> getVendor( @PathVariable("id") String id, OAuth2Authentication oAuth2Authentication) { Vendor sw360Vendor = vendorService.getVendorById(id);
HalResource<Vendor> userHalResource = createHalVendor(sw360Vendor);
sw360/sw360rest
subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/integration/UserTest.java
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // }
import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given;
/* * Copyright Siemens AG, 2017. Part of the SW360 Portal Project. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.integration; public class UserTest extends IntegrationTestBase { @Value("${local.server.port}") private int port; @MockBean
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // } // Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/integration/UserTest.java import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; /* * Copyright Siemens AG, 2017. Part of the SW360 Portal Project. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.integration; public class UserTest extends IntegrationTestBase { @Value("${local.server.port}") private int port; @MockBean
private Sw360UserService userServiceMock;
sw360/sw360rest
subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/integration/UserTest.java
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // }
import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given;
@Before public void before() { List<User> userList = new ArrayList<>(); User user = new User(); user.setId("admin@sw360.org"); user.setEmail("admin@sw360.org"); user.setFullname("John Doe"); userList.add(user); user = new User(); user.setId("jane@sw360.org"); user.setEmail("jane@sw360.org"); user.setFullname("Jane Doe"); userList.add(user); given(this.userServiceMock.getAllUsers() ).willReturn(userList); } @Test public void should_get_all_users() throws IOException { HttpHeaders headers = getHeaders(port); ResponseEntity<String> response = new TestRestTemplate().exchange("http://localhost:" + port + "/api/users", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertThat(HttpStatus.OK, is(response.getStatusCode()));
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // } // Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/integration/UserTest.java import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; @Before public void before() { List<User> userList = new ArrayList<>(); User user = new User(); user.setId("admin@sw360.org"); user.setEmail("admin@sw360.org"); user.setFullname("John Doe"); userList.add(user); user = new User(); user.setId("jane@sw360.org"); user.setEmail("jane@sw360.org"); user.setFullname("Jane Doe"); userList.add(user); given(this.userServiceMock.getAllUsers() ).willReturn(userList); } @Test public void should_get_all_users() throws IOException { HttpHeaders headers = getHeaders(port); ResponseEntity<String> response = new TestRestTemplate().exchange("http://localhost:" + port + "/api/users", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertThat(HttpStatus.OK, is(response.getStatusCode()));
TestHelper.checkResponse(response.getBody(), "users", 2);
sw360/sw360rest
subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/UserSpec.java
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // }
import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.datahandler.thrift.users.UserGroup; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import static org.mockito.BDDMockito.given; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/* * Copyright Siemens AG, 2017. Part of the SW360 Portal Project. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.restdocs; public class UserSpec extends RestDocsSpecBase { @MockBean
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // } // Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/UserSpec.java import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.datahandler.thrift.users.UserGroup; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import static org.mockito.BDDMockito.given; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* * Copyright Siemens AG, 2017. Part of the SW360 Portal Project. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.restdocs; public class UserSpec extends RestDocsSpecBase { @MockBean
private Sw360UserService userServiceMock;
sw360/sw360rest
subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/UserSpec.java
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // }
import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.datahandler.thrift.users.UserGroup; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import static org.mockito.BDDMockito.given; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
user.setEmail("admin@sw360.org"); user.setId(Base64.getEncoder().encodeToString(user.getEmail().getBytes("utf-8"))); user.setType("user"); user.setUserGroup(UserGroup.ADMIN); user.setFullname("John Doe"); user.setGivenname("John"); user.setLastname("Doe"); user.setDepartment("SW360 Administration"); user.setWantsMailNotification(true); userList.add(user); given(this.userServiceMock.getUserByEmail("admin@sw360.org")).willReturn(user); User user2 = new User(); user2.setEmail("jane@sw360.org"); user2.setId(Base64.getEncoder().encodeToString(user.getEmail().getBytes("utf-8"))); user2.setType("user"); user2.setUserGroup(UserGroup.USER); user2.setFullname("Jane Doe"); user2.setGivenname("Jane"); user2.setLastname("Doe"); user2.setDepartment("SW360 BA"); user2.setWantsMailNotification(false); userList.add(user2); given(this.userServiceMock.getAllUsers()).willReturn(userList); } @Test public void should_document_get_users() throws Exception {
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/user/Sw360UserService.java // @Service // public class Sw360UserService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<User> getAllUsers() { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getAllUsers(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public User getUserByEmail(String email) { // try { // UserService.Iface sw360UserClient = getThriftUserClient(); // return sw360UserClient.getByEmail(email); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // private UserService.Iface getThriftUserClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/users/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new UserService.Client(protocol); // } // } // Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/UserSpec.java import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.datahandler.thrift.users.UserGroup; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.user.Sw360UserService; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import static org.mockito.BDDMockito.given; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; user.setEmail("admin@sw360.org"); user.setId(Base64.getEncoder().encodeToString(user.getEmail().getBytes("utf-8"))); user.setType("user"); user.setUserGroup(UserGroup.ADMIN); user.setFullname("John Doe"); user.setGivenname("John"); user.setLastname("Doe"); user.setDepartment("SW360 Administration"); user.setWantsMailNotification(true); userList.add(user); given(this.userServiceMock.getUserByEmail("admin@sw360.org")).willReturn(user); User user2 = new User(); user2.setEmail("jane@sw360.org"); user2.setId(Base64.getEncoder().encodeToString(user.getEmail().getBytes("utf-8"))); user2.setType("user"); user2.setUserGroup(UserGroup.USER); user2.setFullname("Jane Doe"); user2.setGivenname("Jane"); user2.setLastname("Doe"); user2.setDepartment("SW360 BA"); user2.setWantsMailNotification(false); userList.add(user2); given(this.userServiceMock.getAllUsers()).willReturn(userList); } @Test public void should_document_get_users() throws Exception {
String accessToken = TestHelper.getAccessToken(mockMvc, "admin@sw360.org", "sw360-password");
sw360/sw360rest
subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/LicenseSpec.java
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/license/Sw360LicenseService.java // @Service // @RequiredArgsConstructor(onConstructor = @__(@Autowired)) // public class Sw360LicenseService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<License> getLicenses() { // try { // LicenseService.Iface sw360LicenseClient = getThriftLicenseClient(); // return sw360LicenseClient.getLicenseSummary(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public License getLicenseById(String licenseId) { // try { // LicenseService.Iface sw360LicenseClient = getThriftLicenseClient(); // // TODO Kai Tödter 2017-01-26 // // What is the semantics of the second parameter (organization)? // return sw360LicenseClient.getByID(licenseId, "?"); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public License createLicense(License license, User sw360User) { // try { // LicenseService.Iface sw360LicenseClient = getThriftLicenseClient(); // license.setId(license.getShortname()); // List<License> licenses = sw360LicenseClient.addLicenses(Collections.singletonList(license), sw360User); // for(License newlicense: licenses) { // if(license.getFullname().equals(newlicense.getFullname())) { // return newlicense; // } // } // } catch (TException e) { // throw new RuntimeException(e); // } // return null; // } // // private LicenseService.Iface getThriftLicenseClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/licenses/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new LicenseService.Client(protocol); // } // }
import org.eclipse.sw360.datahandler.thrift.licenses.License; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.license.Sw360LicenseService; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import java.util.ArrayList; import java.util.List; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.eq; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/* * Copyright Siemens AG, 2017. Part of the SW360 Portal Project. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.restdocs; public class LicenseSpec extends RestDocsSpecBase { @MockBean
// Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/TestHelper.java // public class TestHelper { // // static public void checkResponse(String responseBody, String linkRelation, int embeddedArraySize) throws IOException { // JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); // // assertThat(responseBodyJsonNode.has("_embedded"), is(true)); // // JsonNode embeddedNode = responseBodyJsonNode.get("_embedded"); // assertThat(embeddedNode.has("sw360:" + linkRelation), is(true)); // // JsonNode sw360UsersNode = embeddedNode.get("sw360:" + linkRelation); // assertThat(sw360UsersNode.isArray(),is(true)); // assertThat(sw360UsersNode.size(),is(embeddedArraySize)); // // assertThat(responseBodyJsonNode.has("_links"), is(true)); // // JsonNode linksNode = responseBodyJsonNode.get("_links"); // assertThat(linksNode.has("curies"), is(true)); // // JsonNode curiesNode = linksNode.get("curies").get(0); // assertThat(curiesNode.get("href").asText(), endsWith("docs/html5/{rel}.html")); // assertThat(curiesNode.get("name").asText(), is("sw360")); // assertThat(curiesNode.get("templated").asBoolean(), is(true)); // } // // public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { // String authorizationHeaderValue = "Basic " // + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); // // MockHttpServletResponse response = mockMvc // .perform(post("/oauth/token") // .header("Authorization", authorizationHeaderValue) // .contentType(MediaType.APPLICATION_FORM_URLENCODED) // .param("client_id", "trusted-sw360-client") // .param("client_secret", "sw360-secret") // .param("username", username) // .param("password", password) // .param("grant_type", "password") // .param("scope", "sw360.read")) // .andReturn().getResponse(); // // return new ObjectMapper() // .readValue(response.getContentAsByteArray(), OAuthToken.class) // .accessToken; // } // // // @JsonIgnoreProperties(ignoreUnknown = true) // private static class OAuthToken { // @JsonProperty("access_token") // public String accessToken; // } // // } // // Path: subprojects/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/license/Sw360LicenseService.java // @Service // @RequiredArgsConstructor(onConstructor = @__(@Autowired)) // public class Sw360LicenseService { // @Value("${sw360.thrift-server-url:http://localhost:8080}") // private String thriftServerUrl; // // public List<License> getLicenses() { // try { // LicenseService.Iface sw360LicenseClient = getThriftLicenseClient(); // return sw360LicenseClient.getLicenseSummary(); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public License getLicenseById(String licenseId) { // try { // LicenseService.Iface sw360LicenseClient = getThriftLicenseClient(); // // TODO Kai Tödter 2017-01-26 // // What is the semantics of the second parameter (organization)? // return sw360LicenseClient.getByID(licenseId, "?"); // } catch (TException e) { // throw new RuntimeException(e); // } // } // // public License createLicense(License license, User sw360User) { // try { // LicenseService.Iface sw360LicenseClient = getThriftLicenseClient(); // license.setId(license.getShortname()); // List<License> licenses = sw360LicenseClient.addLicenses(Collections.singletonList(license), sw360User); // for(License newlicense: licenses) { // if(license.getFullname().equals(newlicense.getFullname())) { // return newlicense; // } // } // } catch (TException e) { // throw new RuntimeException(e); // } // return null; // } // // private LicenseService.Iface getThriftLicenseClient() throws TTransportException { // THttpClient thriftClient = new THttpClient(thriftServerUrl + "/licenses/thrift"); // TProtocol protocol = new TCompactProtocol(thriftClient); // return new LicenseService.Client(protocol); // } // } // Path: subprojects/resource-server/src/test/java/org/eclipse/sw360/rest/resourceserver/restdocs/LicenseSpec.java import org.eclipse.sw360.datahandler.thrift.licenses.License; import org.eclipse.sw360.rest.resourceserver.TestHelper; import org.eclipse.sw360.rest.resourceserver.license.Sw360LicenseService; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import java.util.ArrayList; import java.util.List; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.eq; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* * Copyright Siemens AG, 2017. Part of the SW360 Portal Project. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.rest.resourceserver.restdocs; public class LicenseSpec extends RestDocsSpecBase { @MockBean
private Sw360LicenseService licenseServiceMock;
messaginghub/pooled-jms
pooled-jms/src/main/java/org/messaginghub/pooled/jms/JmsPoolJcaConnectionFactory.java
// Path: pooled-jms/src/main/java/org/messaginghub/pooled/jms/pool/PooledJCAConnection.java // public class PooledJCAConnection extends PooledXAConnection { // // private final String name; // // public PooledJCAConnection(Connection connection, TransactionManager transactionManager, String name) { // super(connection, transactionManager); // this.name = name; // } // // @Override // protected XAResource createXaResource(JmsPoolSession session) throws JMSException { // XAResource xares = ((XASession)session.getInternalSession()).getXAResource(); // if (name != null) { // xares = new WrapperNamedXAResource(xares, name); // } // return xares; // } // }
import javax.jms.Connection; import org.messaginghub.pooled.jms.pool.PooledJCAConnection;
/* * 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.messaginghub.pooled.jms; public class JmsPoolJcaConnectionFactory extends JmsPoolXAConnectionFactory { private static final long serialVersionUID = -2470093537159318333L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override
// Path: pooled-jms/src/main/java/org/messaginghub/pooled/jms/pool/PooledJCAConnection.java // public class PooledJCAConnection extends PooledXAConnection { // // private final String name; // // public PooledJCAConnection(Connection connection, TransactionManager transactionManager, String name) { // super(connection, transactionManager); // this.name = name; // } // // @Override // protected XAResource createXaResource(JmsPoolSession session) throws JMSException { // XAResource xares = ((XASession)session.getInternalSession()).getXAResource(); // if (name != null) { // xares = new WrapperNamedXAResource(xares, name); // } // return xares; // } // } // Path: pooled-jms/src/main/java/org/messaginghub/pooled/jms/JmsPoolJcaConnectionFactory.java import javax.jms.Connection; import org.messaginghub.pooled.jms.pool.PooledJCAConnection; /* * 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.messaginghub.pooled.jms; public class JmsPoolJcaConnectionFactory extends JmsPoolXAConnectionFactory { private static final long serialVersionUID = -2470093537159318333L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override
protected PooledJCAConnection createPooledConnection(Connection connection) {
messaginghub/pooled-jms
pooled-jms/src/test/java/org/messaginghub/pooled/jms/JmsPoolQueueReceiverTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/mock/MockJMSQueueReceiver.java // public class MockJMSQueueReceiver extends MockJMSMessageConsumer implements AutoCloseable, QueueReceiver { // // protected MockJMSQueueReceiver(MockJMSSession session, String consumerId, MockJMSDestination destination, String messageSelector) throws JMSException { // super(session, consumerId, destination, messageSelector, false); // } // // @Override // public Queue getQueue() throws IllegalStateException { // checkClosed(); // return (Queue) this.destination; // } // }
import org.messaginghub.pooled.jms.mock.MockJMSQueueReceiver; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import javax.jms.IllegalStateException; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.jms.Session; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout;
assertNotNull(receiver.toString()); } @Test public void testGetQueue() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); QueueReceiver receiver = session.createReceiver(queue); assertNotNull(receiver.getQueue()); assertSame(queue, receiver.getQueue()); receiver.close(); try { receiver.getQueue(); fail("Cannot read topic on closed receiver"); } catch (IllegalStateException ise) {} } @Test public void testGetTopicSubscriber() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); JmsPoolQueueReceiver receiver = (JmsPoolQueueReceiver) session.createReceiver(queue); assertNotNull(receiver.getQueueReceiver());
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/mock/MockJMSQueueReceiver.java // public class MockJMSQueueReceiver extends MockJMSMessageConsumer implements AutoCloseable, QueueReceiver { // // protected MockJMSQueueReceiver(MockJMSSession session, String consumerId, MockJMSDestination destination, String messageSelector) throws JMSException { // super(session, consumerId, destination, messageSelector, false); // } // // @Override // public Queue getQueue() throws IllegalStateException { // checkClosed(); // return (Queue) this.destination; // } // } // Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/JmsPoolQueueReceiverTest.java import org.messaginghub.pooled.jms.mock.MockJMSQueueReceiver; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import javax.jms.IllegalStateException; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.jms.Session; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; assertNotNull(receiver.toString()); } @Test public void testGetQueue() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); QueueReceiver receiver = session.createReceiver(queue); assertNotNull(receiver.getQueue()); assertSame(queue, receiver.getQueue()); receiver.close(); try { receiver.getQueue(); fail("Cannot read topic on closed receiver"); } catch (IllegalStateException ise) {} } @Test public void testGetTopicSubscriber() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); JmsPoolQueueReceiver receiver = (JmsPoolQueueReceiver) session.createReceiver(queue); assertNotNull(receiver.getQueueReceiver());
assertTrue(receiver.getQueueReceiver() instanceof MockJMSQueueReceiver);
messaginghub/pooled-jms
pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionSessionCleanupTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // }
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; import org.apache.activemq.command.ActiveMQQueue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait;
directConn2.close(); } } catch (JMSException jms_exc) { } try { pooledConnFact.stop(); } catch (Throwable error) {} super.tearDown(); } private void produceMessages() throws Exception { Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); for (int i = 0; i < MESSAGE_COUNT; ++i) { producer.send(session.createTextMessage("Test Message: " + i)); } producer.close(); } @Test public void testLingeringPooledSessionsHoldingPrefetchedMessages() throws Exception { produceMessages(); Session pooledSession1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE); pooledSession1.createConsumer(queue); final QueueViewMBean view = getProxyToQueue(queue.getPhysicalName());
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // } // Path: pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionSessionCleanupTest.java import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; import org.apache.activemq.command.ActiveMQQueue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; directConn2.close(); } } catch (JMSException jms_exc) { } try { pooledConnFact.stop(); } catch (Throwable error) {} super.tearDown(); } private void produceMessages() throws Exception { Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); for (int i = 0; i < MESSAGE_COUNT; ++i) { producer.send(session.createTextMessage("Test Message: " + i)); } producer.close(); } @Test public void testLingeringPooledSessionsHoldingPrefetchedMessages() throws Exception { produceMessages(); Session pooledSession1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE); pooledSession1.createConsumer(queue); final QueueViewMBean view = getProxyToQueue(queue.getPhysicalName());
assertTrue(Wait.waitFor(new Wait.Condition() {
messaginghub/pooled-jms
pooled-jms/src/test/java/org/messaginghub/pooled/jms/JmsPoolConnectionFactoryMaximumActiveTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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.messaginghub.pooled.jms; /** * Checks the behavior of the PooledConnectionFactory when the maximum amount of sessions is being reached * (maximumActive). When using setBlockIfSessionPoolIsFull(true) on the ConnectionFactory, further requests for sessions * should block. If it does not block, its a bug. */ @Timeout(60) public class JmsPoolConnectionFactoryMaximumActiveTest extends JmsPoolTestSupport { public final static Logger LOG = LoggerFactory.getLogger(JmsPoolConnectionFactoryMaximumActiveTest.class); private static Connection connection = null; private static ConcurrentMap<Integer, Session> sessions = new ConcurrentHashMap<Integer, Session>(); public static void addSession(Session s) { sessions.put(s.hashCode(), s); } @BeforeEach public void setUp() throws Exception { sessions.clear(); } @Test public void testCreateSessionBlocksWhenMaxSessionsLoanedOutUntilReturned() throws Exception { cf = new JmsPoolConnectionFactory(); cf.setConnectionFactory(factory); cf.setMaxConnections(3); cf.setMaxSessionsPerConnection(1); cf.setBlockIfSessionPoolIsFull(true); connection = cf.createConnection(); // start test runner threads. It is expected that the second thread // blocks on the call to createSession() ExecutorService executor = Executors.newFixedThreadPool(1); final Future<Boolean> result1 = executor.submit(new SessionTakerAndReturner()); final Future<Boolean> result2 = executor.submit(new SessionTaker());
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // } // Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/JmsPoolConnectionFactoryMaximumActiveTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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.messaginghub.pooled.jms; /** * Checks the behavior of the PooledConnectionFactory when the maximum amount of sessions is being reached * (maximumActive). When using setBlockIfSessionPoolIsFull(true) on the ConnectionFactory, further requests for sessions * should block. If it does not block, its a bug. */ @Timeout(60) public class JmsPoolConnectionFactoryMaximumActiveTest extends JmsPoolTestSupport { public final static Logger LOG = LoggerFactory.getLogger(JmsPoolConnectionFactoryMaximumActiveTest.class); private static Connection connection = null; private static ConcurrentMap<Integer, Session> sessions = new ConcurrentHashMap<Integer, Session>(); public static void addSession(Session s) { sessions.put(s.hashCode(), s); } @BeforeEach public void setUp() throws Exception { sessions.clear(); } @Test public void testCreateSessionBlocksWhenMaxSessionsLoanedOutUntilReturned() throws Exception { cf = new JmsPoolConnectionFactory(); cf.setConnectionFactory(factory); cf.setMaxConnections(3); cf.setMaxSessionsPerConnection(1); cf.setBlockIfSessionPoolIsFull(true); connection = cf.createConnection(); // start test runner threads. It is expected that the second thread // blocks on the call to createSession() ExecutorService executor = Executors.newFixedThreadPool(1); final Future<Boolean> result1 = executor.submit(new SessionTakerAndReturner()); final Future<Boolean> result2 = executor.submit(new SessionTaker());
assertTrue(Wait.waitFor(new Wait.Condition() {
messaginghub/pooled-jms
pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // }
import javax.jms.Session; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.util.HashSet; import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.IllegalStateException; import javax.jms.JMSException;
// test: try to call setClientID() after start() // should result in an exception try { conn.start(); conn.setClientID("newID3"); fail("Calling setClientID() after start() mut raise a JMSException."); } catch (IllegalStateException ise) { LOG.debug("Correctly received " + ise); } finally { cf.stop(); } LOG.debug("Test finished."); } /** * Tests the behavior of the sessionPool of the PooledConnectionFactory when * maximum number of sessions are reached. * * @throws Exception */ @Test public void testCreateSessionDoesNotBlockWhenNotConfiguredTo() throws Exception { // using separate thread for testing so that we can interrupt the test // if the call to get a new session blocks. // start test runner thread ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<Boolean> result = executor.submit(new TestRunner());
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // } // Path: pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionTest.java import javax.jms.Session; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.util.HashSet; import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.IllegalStateException; import javax.jms.JMSException; // test: try to call setClientID() after start() // should result in an exception try { conn.start(); conn.setClientID("newID3"); fail("Calling setClientID() after start() mut raise a JMSException."); } catch (IllegalStateException ise) { LOG.debug("Correctly received " + ise); } finally { cf.stop(); } LOG.debug("Test finished."); } /** * Tests the behavior of the sessionPool of the PooledConnectionFactory when * maximum number of sessions are reached. * * @throws Exception */ @Test public void testCreateSessionDoesNotBlockWhenNotConfiguredTo() throws Exception { // using separate thread for testing so that we can interrupt the test // if the call to get a new session blocks. // start test runner thread ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<Boolean> result = executor.submit(new TestRunner());
boolean testPassed = Wait.waitFor(new Wait.Condition() {
messaginghub/pooled-jms
pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionFactoryMaximumActiveTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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.messaginghub.pooled.jms; /** * Checks the behavior of the PooledConnectionFactory when the maximum amount of sessions is being reached * (maximumActive). When using setBlockIfSessionPoolIsFull(true) on the ConnectionFactory, further requests for sessions * should block. If it does not block, its a bug. */ @Timeout(60) public class PooledConnectionFactoryMaximumActiveTest extends ActiveMQJmsPoolTestSupport { public final static Logger LOG = LoggerFactory.getLogger(PooledConnectionFactoryMaximumActiveTest.class); public static Connection connection = null; private static ConcurrentMap<Integer, Session> sessions = new ConcurrentHashMap<Integer, Session>(); public static void addSession(Session s) { sessions.put(s.hashCode(), s); } @Override @BeforeEach public void setUp(TestInfo info) throws Exception { super.setUp(info); sessions.clear(); } @Test public void testCreateSessionBlocksWhenMaxSessionsLoanedOutUntilReturned() throws Exception { JmsPoolConnectionFactory cf = createPooledConnectionFactory(); try { cf.setMaxConnections(3); cf.setMaxSessionsPerConnection(1); cf.setBlockIfSessionPoolIsFull(true); connection = cf.createConnection(); // start test runner threads. It is expected that the second thread // blocks on the call to createSession() ExecutorService executor = Executors.newFixedThreadPool(1); final Future<Boolean> result1 = executor.submit(new SessionTakerAndReturner()); final Future<Boolean> result2 = executor.submit(new SessionTaker());
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // } // Path: pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionFactoryMaximumActiveTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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.messaginghub.pooled.jms; /** * Checks the behavior of the PooledConnectionFactory when the maximum amount of sessions is being reached * (maximumActive). When using setBlockIfSessionPoolIsFull(true) on the ConnectionFactory, further requests for sessions * should block. If it does not block, its a bug. */ @Timeout(60) public class PooledConnectionFactoryMaximumActiveTest extends ActiveMQJmsPoolTestSupport { public final static Logger LOG = LoggerFactory.getLogger(PooledConnectionFactoryMaximumActiveTest.class); public static Connection connection = null; private static ConcurrentMap<Integer, Session> sessions = new ConcurrentHashMap<Integer, Session>(); public static void addSession(Session s) { sessions.put(s.hashCode(), s); } @Override @BeforeEach public void setUp(TestInfo info) throws Exception { super.setUp(info); sessions.clear(); } @Test public void testCreateSessionBlocksWhenMaxSessionsLoanedOutUntilReturned() throws Exception { JmsPoolConnectionFactory cf = createPooledConnectionFactory(); try { cf.setMaxConnections(3); cf.setMaxSessionsPerConnection(1); cf.setBlockIfSessionPoolIsFull(true); connection = cf.createConnection(); // start test runner threads. It is expected that the second thread // blocks on the call to createSession() ExecutorService executor = Executors.newFixedThreadPool(1); final Future<Boolean> result1 = executor.submit(new SessionTakerAndReturner()); final Future<Boolean> result2 = executor.submit(new SessionTaker());
assertTrue(Wait.waitFor(new Wait.Condition() {
messaginghub/pooled-jms
pooled-jms/src/test/java/org/messaginghub/pooled/jms/JmsPoolTopicSubscriberTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/mock/MockJMSTopicSubscriber.java // public class MockJMSTopicSubscriber extends MockJMSMessageConsumer implements TopicSubscriber { // // public MockJMSTopicSubscriber(MockJMSSession session, String consumerId, MockJMSDestination destination, String messageSelector, boolean noLocal) throws JMSException { // super(session, consumerId, destination, messageSelector, noLocal); // } // // @Override // public Topic getTopic() throws IllegalStateException { // checkClosed(); // return (Topic) this.destination; // } // // @Override // public boolean getNoLocal() throws JMSException { // checkClosed(); // return noLocal; // } // }
import org.messaginghub.pooled.jms.mock.MockJMSTopicSubscriber; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import javax.jms.IllegalStateException; import javax.jms.JMSException; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout;
subscriber.getTopic(); fail("Cannot read topic on closed subscriber"); } catch (IllegalStateException ise) {} } @Test public void testGetNoLocal() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTemporaryTopic(); TopicSubscriber subscriber = session.createDurableSubscriber(topic, "name", "color = red", true); assertTrue(subscriber.getNoLocal()); subscriber.close(); try { subscriber.getNoLocal(); fail("Cannot read state on closed subscriber"); } catch (IllegalStateException ise) {} } @Test public void testGetTopicSubscriber() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTemporaryTopic(); JmsPoolTopicSubscriber subscriber = (JmsPoolTopicSubscriber) session.createDurableSubscriber(topic, "name", "color = red", true); assertNotNull(subscriber.getTopicSubscriber());
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/mock/MockJMSTopicSubscriber.java // public class MockJMSTopicSubscriber extends MockJMSMessageConsumer implements TopicSubscriber { // // public MockJMSTopicSubscriber(MockJMSSession session, String consumerId, MockJMSDestination destination, String messageSelector, boolean noLocal) throws JMSException { // super(session, consumerId, destination, messageSelector, noLocal); // } // // @Override // public Topic getTopic() throws IllegalStateException { // checkClosed(); // return (Topic) this.destination; // } // // @Override // public boolean getNoLocal() throws JMSException { // checkClosed(); // return noLocal; // } // } // Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/JmsPoolTopicSubscriberTest.java import org.messaginghub.pooled.jms.mock.MockJMSTopicSubscriber; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import javax.jms.IllegalStateException; import javax.jms.JMSException; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; subscriber.getTopic(); fail("Cannot read topic on closed subscriber"); } catch (IllegalStateException ise) {} } @Test public void testGetNoLocal() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTemporaryTopic(); TopicSubscriber subscriber = session.createDurableSubscriber(topic, "name", "color = red", true); assertTrue(subscriber.getNoLocal()); subscriber.close(); try { subscriber.getNoLocal(); fail("Cannot read state on closed subscriber"); } catch (IllegalStateException ise) {} } @Test public void testGetTopicSubscriber() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTemporaryTopic(); JmsPoolTopicSubscriber subscriber = (JmsPoolTopicSubscriber) session.createDurableSubscriber(topic, "name", "color = red", true); assertNotNull(subscriber.getTopicSubscriber());
assertTrue(subscriber.getTopicSubscriber() instanceof MockJMSTopicSubscriber);
messaginghub/pooled-jms
pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionFactoryTest.java
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.JMSRuntimeException; import javax.jms.QueueConnectionFactory; import javax.jms.Session; import javax.jms.TopicConnectionFactory; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.command.ConnectionId; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
} finally { cf.stop(); } } @Test public void testConnectionsArePooledAsyncCreate() throws Exception { final JmsPoolConnectionFactory cf = createPooledConnectionFactory(); cf.setMaxConnections(1); final ConcurrentLinkedQueue<JmsPoolConnection> connections = new ConcurrentLinkedQueue<JmsPoolConnection>(); try { final JmsPoolConnection primary = (JmsPoolConnection) cf.createConnection(); final ExecutorService executor = Executors.newFixedThreadPool(10); final int numConnections = 100; for (int i = 0; i < numConnections; ++i) { executor.execute(new Runnable() { @Override public void run() { try { connections.add((JmsPoolConnection) cf.createConnection()); } catch (JMSException e) { } } }); }
// Path: pooled-jms/src/test/java/org/messaginghub/pooled/jms/util/Wait.java // public class Wait { // // public static final long MAX_WAIT_MILLIS = 30 * 1000; // public static final long SLEEP_MILLIS = 200; // // public interface Condition { // boolean isSatisfied() throws Exception; // } // // public static boolean waitFor(Condition condition) throws Exception { // return waitFor(condition, MAX_WAIT_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration) throws Exception { // return waitFor(condition, duration, SLEEP_MILLIS); // } // // public static boolean waitFor(final Condition condition, final long duration, final long sleepMillis) throws Exception { // // final long expiry = System.currentTimeMillis() + duration; // boolean conditionSatisfied = condition.isSatisfied(); // while (!conditionSatisfied && System.currentTimeMillis() < expiry) { // TimeUnit.MILLISECONDS.sleep(sleepMillis); // conditionSatisfied = condition.isSatisfied(); // } // return conditionSatisfied; // } // } // Path: pooled-jms-interop-tests/pooled-jms-activemq-tests/src/test/java/org/messaginghub/pooled/jms/PooledConnectionFactoryTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.JMSRuntimeException; import javax.jms.QueueConnectionFactory; import javax.jms.Session; import javax.jms.TopicConnectionFactory; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.command.ConnectionId; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.messaginghub.pooled.jms.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; } finally { cf.stop(); } } @Test public void testConnectionsArePooledAsyncCreate() throws Exception { final JmsPoolConnectionFactory cf = createPooledConnectionFactory(); cf.setMaxConnections(1); final ConcurrentLinkedQueue<JmsPoolConnection> connections = new ConcurrentLinkedQueue<JmsPoolConnection>(); try { final JmsPoolConnection primary = (JmsPoolConnection) cf.createConnection(); final ExecutorService executor = Executors.newFixedThreadPool(10); final int numConnections = 100; for (int i = 0; i < numConnections; ++i) { executor.execute(new Runnable() { @Override public void run() { try { connections.add((JmsPoolConnection) cf.createConnection()); } catch (JMSException e) { } } }); }
assertTrue(Wait.waitFor(new Wait.Condition() {
fcpauldiaz/Compilador
src/compiler/SymbolTable.java
// Path: src/gui/ANTGui.java // public static javax.swing.JTextPane jTextArea3;
import static gui.ANTGui.jTextArea3; import java.awt.Color; import java.util.HashMap; import java.util.Map; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument;
return null; } public Symbol findAllScopes(String nombreVar){ try{ for (Map.Entry<Integer, Symbol> entry : tabla.entrySet()) { int key = entry.getKey(); Symbol value = entry.getValue(); String varName = ((Type)value.getTipo()).getNombreVariable(); int ambito = value.getAmbito(); //System.out.println(varName); //System.out.println(nombreVar); if (varName.trim().equals(nombreVar.trim())) return value; } }catch(Exception e){} return null; } public void agregarLog(String mensaje, int linea, int columna, boolean error){
// Path: src/gui/ANTGui.java // public static javax.swing.JTextPane jTextArea3; // Path: src/compiler/SymbolTable.java import static gui.ANTGui.jTextArea3; import java.awt.Color; import java.util.HashMap; import java.util.Map; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; return null; } public Symbol findAllScopes(String nombreVar){ try{ for (Map.Entry<Integer, Symbol> entry : tabla.entrySet()) { int key = entry.getKey(); Symbol value = entry.getValue(); String varName = ((Type)value.getTipo()).getNombreVariable(); int ambito = value.getAmbito(); //System.out.println(varName); //System.out.println(nombreVar); if (varName.trim().equals(nombreVar.trim())) return value; } }catch(Exception e){} return null; } public void agregarLog(String mensaje, int linea, int columna, boolean error){
StyledDocument doc = jTextArea3.getStyledDocument();
fcpauldiaz/Compilador
src/compiler/DescriptiveErrorListener.java
// Path: src/gui/ANTGui.java // public static javax.swing.JTextPane jTextArea3;
import static gui.ANTGui.jTextArea3; import java.awt.Color; import java.util.Collections; import java.util.List; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer;
/** * Universidad Del Valle de Guatemala * 25-ene-2016 * Pablo Díaz 13203 */ package compiler; /** * * @author Pablo */ public class DescriptiveErrorListener extends BaseErrorListener { public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { List<String> stack = ((Parser)recognizer).getRuleInvocationStack(); Collections.reverse(stack); System.err.println("rule stack: "+stack); System.err.println("linea "+line+":"+charPositionInLine+" at "+ offendingSymbol+": "+msg); String rule = "rule stack: "+stack; String mensaje = "linea "+line+":"+charPositionInLine+" at "+ offendingSymbol+": "+msg + "\n\r"; agregarLog("Un error inesperado ha ocurrido " +"\n" + mensaje, line, charPositionInLine,true); } public void agregarLog(String mensaje, int linea, int columna, boolean error){
// Path: src/gui/ANTGui.java // public static javax.swing.JTextPane jTextArea3; // Path: src/compiler/DescriptiveErrorListener.java import static gui.ANTGui.jTextArea3; import java.awt.Color; import java.util.Collections; import java.util.List; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; /** * Universidad Del Valle de Guatemala * 25-ene-2016 * Pablo Díaz 13203 */ package compiler; /** * * @author Pablo */ public class DescriptiveErrorListener extends BaseErrorListener { public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { List<String> stack = ((Parser)recognizer).getRuleInvocationStack(); Collections.reverse(stack); System.err.println("rule stack: "+stack); System.err.println("linea "+line+":"+charPositionInLine+" at "+ offendingSymbol+": "+msg); String rule = "rule stack: "+stack; String mensaje = "linea "+line+":"+charPositionInLine+" at "+ offendingSymbol+": "+msg + "\n\r"; agregarLog("Un error inesperado ha ocurrido " +"\n" + mensaje, line, charPositionInLine,true); } public void agregarLog(String mensaje, int linea, int columna, boolean error){
StyledDocument doc = jTextArea3.getStyledDocument();
fcpauldiaz/Compilador
src/compiler/InterCodeTable.java
// Path: src/compiler/Visitor.java // public static SymbolTable tablaSimbolos;
import static compiler.Visitor.tablaSimbolos; import java.util.ArrayList; import java.util.Map;
if (sp != null){ if (i != (j+1)){ IntermediateCode c = copyArray.get(i); copyArray.remove(i); copyArray.add(j+1, c); j = j +1 ; }else{ j = i ; } } } this.arrayCode = copyArray; } public IntermediateCode searchCodeGlobal(String nombreVar){ for (int i = 0;i<this.arrayCode.size();i++){ IntermediateCode inter = this.arrayCode.get(i); String etiqueta = inter.getEtiqueta().substring(0,inter.getEtiqueta().indexOf("_")); if (inter.isGlobal()&&etiqueta.equals(nombreVar)){ return inter; } } return null; } public Symbol searchSymbolLastScope(String nombreVar){ ArrayList<Symbol> simbolos = new ArrayList();
// Path: src/compiler/Visitor.java // public static SymbolTable tablaSimbolos; // Path: src/compiler/InterCodeTable.java import static compiler.Visitor.tablaSimbolos; import java.util.ArrayList; import java.util.Map; if (sp != null){ if (i != (j+1)){ IntermediateCode c = copyArray.get(i); copyArray.remove(i); copyArray.add(j+1, c); j = j +1 ; }else{ j = i ; } } } this.arrayCode = copyArray; } public IntermediateCode searchCodeGlobal(String nombreVar){ for (int i = 0;i<this.arrayCode.size();i++){ IntermediateCode inter = this.arrayCode.get(i); String etiqueta = inter.getEtiqueta().substring(0,inter.getEtiqueta().indexOf("_")); if (inter.isGlobal()&&etiqueta.equals(nombreVar)){ return inter; } } return null; } public Symbol searchSymbolLastScope(String nombreVar){ ArrayList<Symbol> simbolos = new ArrayList();
for (Map.Entry<Integer, Symbol> entry : tablaSimbolos.getTabla().entrySet()) {
cdecker/BitDroid-Network
src/main/java/net/bitdroid/network/Event.java
// Path: src/main/java/net/bitdroid/network/messages/Message.java // public abstract class Message extends Event { // public abstract EventType getType(); // // /** // * @return the command // */ // public abstract String getCommand(); // private int payloadSize; // // public int getPayloadSize() { // return payloadSize; // } // // public void setPayloadSize(int size) { // this.payloadSize = size; // } // // public abstract void read(LittleEndianInputStream in) throws IOException; // public abstract void toWire(LittleEndianOutputStream leos) throws IOException; // // }
import net.bitdroid.network.messages.Message;
/** * Copyright 2011 Christian Decker * * 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. * * This file is part the BitDroidNetwork Project. */ package net.bitdroid.network; /** * @author cdecker * */ public class Event { /** * Indicates that apropriate actions have been taken to respond to the event. */ private boolean handled = false; /** * Should this be false the reactor will stop notifying event listeners. */ private boolean propagate = true; private EventType type; private PeerInfo origin; public static enum EventType { INCOMING_CONNECTION_TYPE, OUTGOING_CONNECTION_TYPE, FAILED_CONNECTION_TYPE, DISCONNECTED_TYPE, VERSION_TYPE, VERACK_TYPE, ADDR_TYPE, BLOCK_TYPE, GET_ADDR_TYPE, GET_DATA_TYPE, INVENTORY_TYPE, PING_TYPE, TRANSACTION_TYPE, UNKNOWN_TYPE, PART_TYPE // Used to indicate that the message is not a standalone message. }; public Event(PeerInfo origin, EventType type){ setOrigin(origin); setType(type); } public Event(){}
// Path: src/main/java/net/bitdroid/network/messages/Message.java // public abstract class Message extends Event { // public abstract EventType getType(); // // /** // * @return the command // */ // public abstract String getCommand(); // private int payloadSize; // // public int getPayloadSize() { // return payloadSize; // } // // public void setPayloadSize(int size) { // this.payloadSize = size; // } // // public abstract void read(LittleEndianInputStream in) throws IOException; // public abstract void toWire(LittleEndianOutputStream leos) throws IOException; // // } // Path: src/main/java/net/bitdroid/network/Event.java import net.bitdroid.network.messages.Message; /** * Copyright 2011 Christian Decker * * 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. * * This file is part the BitDroidNetwork Project. */ package net.bitdroid.network; /** * @author cdecker * */ public class Event { /** * Indicates that apropriate actions have been taken to respond to the event. */ private boolean handled = false; /** * Should this be false the reactor will stop notifying event listeners. */ private boolean propagate = true; private EventType type; private PeerInfo origin; public static enum EventType { INCOMING_CONNECTION_TYPE, OUTGOING_CONNECTION_TYPE, FAILED_CONNECTION_TYPE, DISCONNECTED_TYPE, VERSION_TYPE, VERACK_TYPE, ADDR_TYPE, BLOCK_TYPE, GET_ADDR_TYPE, GET_DATA_TYPE, INVENTORY_TYPE, PING_TYPE, TRANSACTION_TYPE, UNKNOWN_TYPE, PART_TYPE // Used to indicate that the message is not a standalone message. }; public Event(PeerInfo origin, EventType type){ setOrigin(origin); setType(type); } public Event(){}
public Event(PeerInfo o, EventType type, Message m){
cdecker/BitDroid-Network
src/test/java/net/bitdroid/network/wire/TestLittleEndianInputStream.java
// Path: src/main/java/net/bitdroid/utils/StringUtils.java // public class StringUtils { // // static final byte[] HEX_CHAR_TABLE = { // (byte)'0', (byte)'1', (byte)'2', (byte)'3', // (byte)'4', (byte)'5', (byte)'6', (byte)'7', // (byte)'8', (byte)'9', (byte)'a', (byte)'b', // (byte)'c', (byte)'d', (byte)'e', (byte)'f' // }; // // public static String getHexString(byte[] raw) // throws UnsupportedEncodingException // { // byte[] hex = new byte[2 * raw.length]; // int index = 0; // // for (byte b : raw) { // int v = b & 0xFF; // hex[index++] = HEX_CHAR_TABLE[v >>> 4]; // hex[index++] = HEX_CHAR_TABLE[v & 0xF]; // } // return new String(hex, "ASCII"); // } // // public static void reverse(byte[] b) { // int left = 0; // index of leftmost element // int right = b.length-1; // index of rightmost element // // while (left < right) { // // exchange the left and right elements // byte temp = b[left]; // b[left] = b[right]; // b[right] = temp; // // // move the bounds toward the center // left++; // right--; // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import net.bitdroid.utils.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test;
/** * Copyright 2011 Christian Decker * * 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. * * This file is part the BitDroidNetwork Project. */ package net.bitdroid.network.wire; /** * @author cdecker * */ public class TestLittleEndianInputStream { /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Test method for {@link net.bitdroid.network.wire.LittleEndianInputStream#readUnsignedShort()}. * @throws IOException */ @Test public void testReadUnsignedShort() throws IOException { byte b[] = new byte[]{(byte) 0xD4, (byte)0x7B}; LittleEndianInputStream leis = LittleEndianInputStream.wrap(b); assertEquals(31700, leis.readUnsignedShort()); } /** * Test method for {@link net.bitdroid.network.wire.LittleEndianInputStream#readUnsignedInt()}. * @throws IOException */ @Test public void testReadUnsignedInt() throws IOException { byte b[] = new byte[]{(byte) 0xD4, (byte)0x7B, (byte)0x00, (byte)0x00}; LittleEndianInputStream leis = LittleEndianInputStream.wrap(b); assertEquals(31700, leis.readUnsignedInt()); } /** * Test method for {@link net.bitdroid.network.wire.LittleEndianInputStream#readUnsignedLong()}. * @throws IOException */ @Test public void testReadUnsignedLong() throws IOException { BigInteger c = new BigInteger("1311768467463790320"); byte b[] = c.toByteArray();
// Path: src/main/java/net/bitdroid/utils/StringUtils.java // public class StringUtils { // // static final byte[] HEX_CHAR_TABLE = { // (byte)'0', (byte)'1', (byte)'2', (byte)'3', // (byte)'4', (byte)'5', (byte)'6', (byte)'7', // (byte)'8', (byte)'9', (byte)'a', (byte)'b', // (byte)'c', (byte)'d', (byte)'e', (byte)'f' // }; // // public static String getHexString(byte[] raw) // throws UnsupportedEncodingException // { // byte[] hex = new byte[2 * raw.length]; // int index = 0; // // for (byte b : raw) { // int v = b & 0xFF; // hex[index++] = HEX_CHAR_TABLE[v >>> 4]; // hex[index++] = HEX_CHAR_TABLE[v & 0xF]; // } // return new String(hex, "ASCII"); // } // // public static void reverse(byte[] b) { // int left = 0; // index of leftmost element // int right = b.length-1; // index of rightmost element // // while (left < right) { // // exchange the left and right elements // byte temp = b[left]; // b[left] = b[right]; // b[right] = temp; // // // move the bounds toward the center // left++; // right--; // } // } // // } // Path: src/test/java/net/bitdroid/network/wire/TestLittleEndianInputStream.java import static org.junit.Assert.assertEquals; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import net.bitdroid.utils.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Copyright 2011 Christian Decker * * 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. * * This file is part the BitDroidNetwork Project. */ package net.bitdroid.network.wire; /** * @author cdecker * */ public class TestLittleEndianInputStream { /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Test method for {@link net.bitdroid.network.wire.LittleEndianInputStream#readUnsignedShort()}. * @throws IOException */ @Test public void testReadUnsignedShort() throws IOException { byte b[] = new byte[]{(byte) 0xD4, (byte)0x7B}; LittleEndianInputStream leis = LittleEndianInputStream.wrap(b); assertEquals(31700, leis.readUnsignedShort()); } /** * Test method for {@link net.bitdroid.network.wire.LittleEndianInputStream#readUnsignedInt()}. * @throws IOException */ @Test public void testReadUnsignedInt() throws IOException { byte b[] = new byte[]{(byte) 0xD4, (byte)0x7B, (byte)0x00, (byte)0x00}; LittleEndianInputStream leis = LittleEndianInputStream.wrap(b); assertEquals(31700, leis.readUnsignedInt()); } /** * Test method for {@link net.bitdroid.network.wire.LittleEndianInputStream#readUnsignedLong()}. * @throws IOException */ @Test public void testReadUnsignedLong() throws IOException { BigInteger c = new BigInteger("1311768467463790320"); byte b[] = c.toByteArray();
StringUtils.reverse(b);
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/LivingEntityShopListener.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // }
import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.event.entity.CreeperPowerEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTeleportEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.PigZapEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.projectiles.ProjectileSource; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes;
package com.nisovin.shopkeepers; class LivingEntityShopListener implements Listener { // the radius around lightning strikes in which villagers turn into witches private static final int VILLAGER_ZAP_RADIUS = 7; // minecraft wiki says 3-4, we use 7 to be safe private final ShopkeepersPlugin plugin; LivingEntityShopListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) void onEntityInteract(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof LivingEntity)) return; LivingEntity shopEntity = (LivingEntity) event.getRightClicked(); Player player = event.getPlayer(); String playerName = player.getName(); Log.debug("Player " + playerName + " is interacting with entity at " + shopEntity.getLocation()); Shopkeeper shopkeeper = plugin.getShopkeeperByEntity(shopEntity); // also check for citizens npc shopkeepers if (event.isCancelled() && !Settings.bypassShopInteractionBlocking) { Log.debug(" Cancelled by another plugin"); } else if (shopkeeper != null) { // only trigger shopkeeper interaction for main-hand events:
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // } // Path: src/main/java/com/nisovin/shopkeepers/LivingEntityShopListener.java import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.event.entity.CreeperPowerEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTeleportEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.PigZapEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.projectiles.ProjectileSource; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes; package com.nisovin.shopkeepers; class LivingEntityShopListener implements Listener { // the radius around lightning strikes in which villagers turn into witches private static final int VILLAGER_ZAP_RADIUS = 7; // minecraft wiki says 3-4, we use 7 to be safe private final ShopkeepersPlugin plugin; LivingEntityShopListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) void onEntityInteract(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof LivingEntity)) return; LivingEntity shopEntity = (LivingEntity) event.getRightClicked(); Player player = event.getPlayer(); String playerName = player.getName(); Log.debug("Player " + playerName + " is interacting with entity at " + shopEntity.getLocation()); Shopkeeper shopkeeper = plugin.getShopkeeperByEntity(shopEntity); // also check for citizens npc shopkeepers if (event.isCancelled() && !Settings.bypassShopInteractionBlocking) { Log.debug(" Cancelled by another plugin"); } else if (shopkeeper != null) { // only trigger shopkeeper interaction for main-hand events:
if (NMSManager.getProvider().isMainHandInteraction(event)) {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/LivingEntityShopListener.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // }
import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.event.entity.CreeperPowerEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTeleportEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.PigZapEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.projectiles.ProjectileSource; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes;
package com.nisovin.shopkeepers; class LivingEntityShopListener implements Listener { // the radius around lightning strikes in which villagers turn into witches private static final int VILLAGER_ZAP_RADIUS = 7; // minecraft wiki says 3-4, we use 7 to be safe private final ShopkeepersPlugin plugin; LivingEntityShopListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) void onEntityInteract(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof LivingEntity)) return; LivingEntity shopEntity = (LivingEntity) event.getRightClicked(); Player player = event.getPlayer(); String playerName = player.getName(); Log.debug("Player " + playerName + " is interacting with entity at " + shopEntity.getLocation()); Shopkeeper shopkeeper = plugin.getShopkeeperByEntity(shopEntity); // also check for citizens npc shopkeepers if (event.isCancelled() && !Settings.bypassShopInteractionBlocking) { Log.debug(" Cancelled by another plugin"); } else if (shopkeeper != null) { // only trigger shopkeeper interaction for main-hand events: if (NMSManager.getProvider().isMainHandInteraction(event)) { shopkeeper.onPlayerInteraction(player); } // if citizens npc: don't cancel the event, let Citizens perform other actions as appropriate
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // } // Path: src/main/java/com/nisovin/shopkeepers/LivingEntityShopListener.java import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.event.entity.CreeperPowerEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTeleportEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.PigZapEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.projectiles.ProjectileSource; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes; package com.nisovin.shopkeepers; class LivingEntityShopListener implements Listener { // the radius around lightning strikes in which villagers turn into witches private static final int VILLAGER_ZAP_RADIUS = 7; // minecraft wiki says 3-4, we use 7 to be safe private final ShopkeepersPlugin plugin; LivingEntityShopListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) void onEntityInteract(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof LivingEntity)) return; LivingEntity shopEntity = (LivingEntity) event.getRightClicked(); Player player = event.getPlayer(); String playerName = player.getName(); Log.debug("Player " + playerName + " is interacting with entity at " + shopEntity.getLocation()); Shopkeeper shopkeeper = plugin.getShopkeeperByEntity(shopEntity); // also check for citizens npc shopkeepers if (event.isCancelled() && !Settings.bypassShopInteractionBlocking) { Log.debug(" Cancelled by another plugin"); } else if (shopkeeper != null) { // only trigger shopkeeper interaction for main-hand events: if (NMSManager.getProvider().isMainHandInteraction(event)) { shopkeeper.onPlayerInteraction(player); } // if citizens npc: don't cancel the event, let Citizens perform other actions as appropriate
if (shopkeeper.getShopObject().getObjectType() != DefaultShopObjectTypes.CITIZEN()) {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/Utils.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // }
import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.permissions.Permissible; import org.bukkit.util.Vector; import com.nisovin.shopkeepers.compat.NMSManager;
if (!item.hasItemMeta()) return false; itemMeta = item.getItemMeta(); if (itemMeta == null) return false; } if (!itemMeta.hasLore() || !lore.equals(itemMeta.getLore())) { return false; } } return true; } // save and load itemstacks from config, including attributes: /** * Saves the given {@link ItemStack} to the given configuration section. * Also saves the item's attributes in the same section at '{node}_attributes'. * * @param section * a configuration section * @param node * where to save the item stack inside the section * @param item * the item stack to save, can be null */ public static void saveItem(ConfigurationSection section, String node, ItemStack item) { assert section != null && node != null; section.set(node, item); // saving attributes manually, as they weren't saved by bukkit in the past:
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // Path: src/main/java/com/nisovin/shopkeepers/Utils.java import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.permissions.Permissible; import org.bukkit.util.Vector; import com.nisovin.shopkeepers.compat.NMSManager; if (!item.hasItemMeta()) return false; itemMeta = item.getItemMeta(); if (itemMeta == null) return false; } if (!itemMeta.hasLore() || !lore.equals(itemMeta.getLore())) { return false; } } return true; } // save and load itemstacks from config, including attributes: /** * Saves the given {@link ItemStack} to the given configuration section. * Also saves the item's attributes in the same section at '{node}_attributes'. * * @param section * a configuration section * @param node * where to save the item stack inside the section * @param item * the item stack to save, can be null */ public static void saveItem(ConfigurationSection section, String node, ItemStack item) { assert section != null && node != null; section.set(node, item); // saving attributes manually, as they weren't saved by bukkit in the past:
String attributes = NMSManager.getProvider().saveItemAttributesToString(item);
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/Settings.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // }
import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Material; import org.bukkit.configuration.Configuration; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; import com.google.common.base.Objects; import com.nisovin.shopkeepers.compat.NMSManager;
if (highCurrencyValue <= 0) highCurrencyItem = Material.AIR; // certain items cannot be of type AIR: if (shopCreationItem == Material.AIR) shopCreationItem = Material.MONSTER_EGG; if (hireItem == Material.AIR) hireItem = Material.EMERALD; if (currencyItem == Material.AIR) currencyItem = Material.EMERALD; return misses; } public static void loadLanguageConfiguration(Configuration config) { try { Field[] fields = Settings.class.getDeclaredFields(); for (Field field : fields) { if (field.getType() == String.class && field.getName().startsWith("msg")) { String configKey = toConfigKey(field.getName()); field.set(null, Utils.colorize(config.getString(configKey, (String) field.get(null)))); } } } catch (Exception e) { e.printStackTrace(); } } // item utilities: // creation item: public static ItemStack createShopCreationItem() { ItemStack creationItem = Utils.createItemStack(shopCreationItem, 1, (short) shopCreationItemData, shopCreationItemName, shopCreationItemLore); // apply spawn egg entity type:
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // Path: src/main/java/com/nisovin/shopkeepers/Settings.java import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Material; import org.bukkit.configuration.Configuration; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; import com.google.common.base.Objects; import com.nisovin.shopkeepers.compat.NMSManager; if (highCurrencyValue <= 0) highCurrencyItem = Material.AIR; // certain items cannot be of type AIR: if (shopCreationItem == Material.AIR) shopCreationItem = Material.MONSTER_EGG; if (hireItem == Material.AIR) hireItem = Material.EMERALD; if (currencyItem == Material.AIR) currencyItem = Material.EMERALD; return misses; } public static void loadLanguageConfiguration(Configuration config) { try { Field[] fields = Settings.class.getDeclaredFields(); for (Field field : fields) { if (field.getType() == String.class && field.getName().startsWith("msg")) { String configKey = toConfigKey(field.getName()); field.set(null, Utils.colorize(config.getString(configKey, (String) field.get(null)))); } } } catch (Exception e) { e.printStackTrace(); } } // item utilities: // creation item: public static ItemStack createShopCreationItem() { ItemStack creationItem = Utils.createItemStack(shopCreationItem, 1, (short) shopCreationItemData, shopCreationItemName, shopCreationItemLore); // apply spawn egg entity type:
if (shopCreationItem == Material.MONSTER_EGG && !Utils.isEmpty(shopCreationItemSpawnEggEntityType) && NMSManager.getProvider().supportsSpawnEggEntityType()) {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/CreateListener.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // }
import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes;
void onPlayerInteract(PlayerInteractEvent event) { // ignore our own fake interact event: if (event instanceof TestPlayerInteractEvent) return; // ignore if the player isn't right-clicking: Action action = event.getAction(); if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) return; // ignore creative mode players: final Player player = event.getPlayer(); if (player.getGameMode() == GameMode.CREATIVE) return; // make sure the item used is the shop creation item: final ItemStack itemInHand = event.getItem(); if (!Settings.isShopCreationItem(itemInHand)) { return; } // remember previous interaction result: Result useInteractedBlock = event.useInteractedBlock(); // prevent regular usage: // TODO are there items which would require canceling the event for left clicks or physical interaction as well? if (Settings.preventShopCreationItemRegularUsage && !Utils.hasPermission(player, ShopkeepersAPI.BYPASS_PERMISSION)) { Log.debug("Preventing normal shop creation item usage"); event.setCancelled(true); } // ignore off-hand interactions from this point on: // -> the item will only act as shop creation item if it is held in the main hand
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // } // Path: src/main/java/com/nisovin/shopkeepers/CreateListener.java import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes; void onPlayerInteract(PlayerInteractEvent event) { // ignore our own fake interact event: if (event instanceof TestPlayerInteractEvent) return; // ignore if the player isn't right-clicking: Action action = event.getAction(); if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) return; // ignore creative mode players: final Player player = event.getPlayer(); if (player.getGameMode() == GameMode.CREATIVE) return; // make sure the item used is the shop creation item: final ItemStack itemInHand = event.getItem(); if (!Settings.isShopCreationItem(itemInHand)) { return; } // remember previous interaction result: Result useInteractedBlock = event.useInteractedBlock(); // prevent regular usage: // TODO are there items which would require canceling the event for left clicks or physical interaction as well? if (Settings.preventShopCreationItemRegularUsage && !Utils.hasPermission(player, ShopkeepersAPI.BYPASS_PERMISSION)) { Log.debug("Preventing normal shop creation item usage"); event.setCancelled(true); } // ignore off-hand interactions from this point on: // -> the item will only act as shop creation item if it is held in the main hand
if (!NMSManager.getProvider().isMainHandInteraction(event)) {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/CreateListener.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // }
import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes;
} // TODO maybe always prevent normal usage, also for cases in which shop creation failed because of some // reason, and instead optionally allow normal usage when crouching? Or, if normal usage is not denied, // allow shop creation only when crouching? // Or handle chest selection and/or shop creation on left clicks only, instead of right clicks? // Or with MC 1.9: Normal usage if the item is in the off-hand } } } // returns true on success private boolean handleShopkeeperCreation(Player player, ShopType<?> shopType, ShopObjectType shopObjType, Block selectedChest, Block clickedBlock, BlockFace clickedBlockFace) { assert shopType != null && shopObjType != null; // has been check already if (selectedChest == null) { // clicked a location without having a chest selected: Utils.sendMessage(player, Settings.msgMustSelectChest); return false; } assert Utils.isChest(selectedChest.getType()); // we have checked that above // check for selected chest being too far away: if (!selectedChest.getWorld().equals(clickedBlock.getWorld()) || (int) selectedChest.getLocation().distanceSquared(clickedBlock.getLocation()) > (Settings.maxChestDistance * Settings.maxChestDistance)) { Utils.sendMessage(player, Settings.msgChestTooFar); return false; } // TODO move object type specific stuff into the object type instead
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // // Path: src/main/java/com/nisovin/shopkeepers/shopobjects/DefaultShopObjectTypes.java // public class DefaultShopObjectTypes { // // private final LivingEntityObjectTypes livingEntityObjectTypes = new LivingEntityObjectTypes(); // private final ShopObjectType signShopObjectType = new SignShopObjectType(); // private final ShopObjectType citizensShopObjectType = new CitizensShopObjectType(); // // // TODO maybe change object type permissions to 'shopkeeper.object.<type>'? // // public DefaultShopObjectTypes() { // } // // public List<ShopObjectType> getAllObjectTypes() { // List<ShopObjectType> shopObjectTypes = new ArrayList<ShopObjectType>(); // shopObjectTypes.addAll(livingEntityObjectTypes.getAllObjectTypes()); // shopObjectTypes.add(signShopObjectType); // shopObjectTypes.add(citizensShopObjectType); // return shopObjectTypes; // } // // public LivingEntityObjectTypes getLivingEntityObjectTypes() { // return livingEntityObjectTypes; // } // // public ShopObjectType getSignShopObjectType() { // return signShopObjectType; // } // // public ShopObjectType getCitizensShopObjectType() { // return citizensShopObjectType; // } // // // STATICS (for convenience): // // public static ShopObjectType SIGN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getSignShopObjectType(); // } // // public static ShopObjectType CITIZEN() { // return ShopkeepersPlugin.getInstance().getDefaultShopObjectTypes().getCitizensShopObjectType(); // } // } // Path: src/main/java/com/nisovin/shopkeepers/CreateListener.java import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import com.nisovin.shopkeepers.compat.NMSManager; import com.nisovin.shopkeepers.shopobjects.DefaultShopObjectTypes; } // TODO maybe always prevent normal usage, also for cases in which shop creation failed because of some // reason, and instead optionally allow normal usage when crouching? Or, if normal usage is not denied, // allow shop creation only when crouching? // Or handle chest selection and/or shop creation on left clicks only, instead of right clicks? // Or with MC 1.9: Normal usage if the item is in the off-hand } } } // returns true on success private boolean handleShopkeeperCreation(Player player, ShopType<?> shopType, ShopObjectType shopObjType, Block selectedChest, Block clickedBlock, BlockFace clickedBlockFace) { assert shopType != null && shopObjType != null; // has been check already if (selectedChest == null) { // clicked a location without having a chest selected: Utils.sendMessage(player, Settings.msgMustSelectChest); return false; } assert Utils.isChest(selectedChest.getType()); // we have checked that above // check for selected chest being too far away: if (!selectedChest.getWorld().equals(clickedBlock.getWorld()) || (int) selectedChest.getLocation().distanceSquared(clickedBlock.getLocation()) > (Settings.maxChestDistance * Settings.maxChestDistance)) { Utils.sendMessage(player, Settings.msgChestTooFar); return false; } // TODO move object type specific stuff into the object type instead
if (shopObjType == DefaultShopObjectTypes.SIGN() && !Utils.isWallSignFace(clickedBlockFace)) {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/events/CreatePlayerShopkeeperEvent.java
// Path: src/main/java/com/nisovin/shopkeepers/ShopType.java // public abstract class ShopType<T extends Shopkeeper> extends SelectableType { // // protected ShopType(String identifier, String permission) { // super(identifier, permission); // } // // /** // * Whether or not this shop type is a player shop type. // * // * @return false if it is an admin shop type // */ // public abstract boolean isPlayerShopType(); // TODO is this needed or could be hidden behind some abstraction? // // public abstract String getCreatedMessage(); // // public final ShopType<?> selectNext(Player player) { // return ShopkeepersPlugin.getInstance().getShopTypeRegistry().selectNext(player); // } // // /** // * Creates a shopkeeper of this type. // * This has to check that all data needed for the shop creation are given and valid. // * For example: the owner and chest argument might be null for creating admin shopkeepers // * while they are needed for player shops. // * Returning null indicates that something is preventing the shopkeeper creation. // * // * @param data // * a container holding the necessary arguments (spawn location, object type, owner, etc.) for creating // * this shopkeeper // * @return the created Shopkeeper // * @throws ShopkeeperCreateException // * if the shopkeeper could not be created // */ // public abstract T createShopkeeper(ShopCreationData data) throws ShopkeeperCreateException; // // /** // * Creates the shopkeeper of this type by loading the needed data from the given configuration section. // * // * @param config // * the config section to load the shopkeeper data from // * @return the created shopkeeper // * @throws ShopkeeperCreateException // * if the shopkeeper could not be loaded // */ // protected abstract T loadShopkeeper(ConfigurationSection config) throws ShopkeeperCreateException; // // /** // * This needs to be called right after the creation or loading of a shopkeeper. // * // * @param shopkeeper // * the freshly created shopkeeper // */ // protected void registerShopkeeper(T shopkeeper) { // shopkeeper.shopObject.onInit(); // ShopkeepersPlugin.getInstance().registerShopkeeper(shopkeeper); // } // // // common checks, which might be useful for extending classes: // // protected void commonPreChecks(ShopCreationData creationData) throws ShopkeeperCreateException { // // common null checks: // if (creationData == null || creationData.spawnLocation == null || creationData.objectType == null) { // throw new ShopkeeperCreateException("null"); // } // } // // protected void commonPlayerPreChecks(ShopCreationData creationData) throws ShopkeeperCreateException { // this.commonPreChecks(creationData); // if (creationData.creator == null || creationData.chest == null) { // throw new ShopkeeperCreateException("null"); // } // } // // protected void commonPreChecks(ConfigurationSection section) throws ShopkeeperCreateException { // // common null checks: // if (section == null) { // throw new ShopkeeperCreateException("null"); // } // } // }
import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import com.nisovin.shopkeepers.ShopCreationData; import com.nisovin.shopkeepers.ShopType;
package com.nisovin.shopkeepers.events; /** * This event is called whenever a player attempts to create a player shopkeeper. * * <p> * It is called before the max shops limits is checked for the player.<br> * The location, shopkeeper type, and player's max shops can be modified.<br> * If this event is cancelled, the shop will not be created. * </p> */ public class CreatePlayerShopkeeperEvent extends Event implements Cancellable { private final ShopCreationData creationData; private int maxShops; private boolean cancelled; public CreatePlayerShopkeeperEvent(ShopCreationData creationData, int maxShops) { this.creationData = creationData; this.maxShops = maxShops; } /** * Gets the raw shop creation data. * * <p> * Only modify the returned object if you know what you are doing. * </p> * * @return the raw shop creation data */ public ShopCreationData getShopCreationData() { return creationData; } /** * Gets the player trying to create the shop. * * @return the player */ public Player getPlayer() { return creationData.creator; } /** * Gets the chest block that will be backing this shop. * * @return the chest block */ public Block getChest() { return creationData.chest; } /** * Gets the location the villager will spawn at. * * @return the spawn location */ public Location getSpawnLocation() { return creationData.spawnLocation; } /** * Gets the type of shopkeeper that will spawn (ex: normal, book, buying, trading, etc.). * * @return the shopkeeper type */
// Path: src/main/java/com/nisovin/shopkeepers/ShopType.java // public abstract class ShopType<T extends Shopkeeper> extends SelectableType { // // protected ShopType(String identifier, String permission) { // super(identifier, permission); // } // // /** // * Whether or not this shop type is a player shop type. // * // * @return false if it is an admin shop type // */ // public abstract boolean isPlayerShopType(); // TODO is this needed or could be hidden behind some abstraction? // // public abstract String getCreatedMessage(); // // public final ShopType<?> selectNext(Player player) { // return ShopkeepersPlugin.getInstance().getShopTypeRegistry().selectNext(player); // } // // /** // * Creates a shopkeeper of this type. // * This has to check that all data needed for the shop creation are given and valid. // * For example: the owner and chest argument might be null for creating admin shopkeepers // * while they are needed for player shops. // * Returning null indicates that something is preventing the shopkeeper creation. // * // * @param data // * a container holding the necessary arguments (spawn location, object type, owner, etc.) for creating // * this shopkeeper // * @return the created Shopkeeper // * @throws ShopkeeperCreateException // * if the shopkeeper could not be created // */ // public abstract T createShopkeeper(ShopCreationData data) throws ShopkeeperCreateException; // // /** // * Creates the shopkeeper of this type by loading the needed data from the given configuration section. // * // * @param config // * the config section to load the shopkeeper data from // * @return the created shopkeeper // * @throws ShopkeeperCreateException // * if the shopkeeper could not be loaded // */ // protected abstract T loadShopkeeper(ConfigurationSection config) throws ShopkeeperCreateException; // // /** // * This needs to be called right after the creation or loading of a shopkeeper. // * // * @param shopkeeper // * the freshly created shopkeeper // */ // protected void registerShopkeeper(T shopkeeper) { // shopkeeper.shopObject.onInit(); // ShopkeepersPlugin.getInstance().registerShopkeeper(shopkeeper); // } // // // common checks, which might be useful for extending classes: // // protected void commonPreChecks(ShopCreationData creationData) throws ShopkeeperCreateException { // // common null checks: // if (creationData == null || creationData.spawnLocation == null || creationData.objectType == null) { // throw new ShopkeeperCreateException("null"); // } // } // // protected void commonPlayerPreChecks(ShopCreationData creationData) throws ShopkeeperCreateException { // this.commonPreChecks(creationData); // if (creationData.creator == null || creationData.chest == null) { // throw new ShopkeeperCreateException("null"); // } // } // // protected void commonPreChecks(ConfigurationSection section) throws ShopkeeperCreateException { // // common null checks: // if (section == null) { // throw new ShopkeeperCreateException("null"); // } // } // } // Path: src/main/java/com/nisovin/shopkeepers/events/CreatePlayerShopkeeperEvent.java import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import com.nisovin.shopkeepers.ShopCreationData; import com.nisovin.shopkeepers.ShopType; package com.nisovin.shopkeepers.events; /** * This event is called whenever a player attempts to create a player shopkeeper. * * <p> * It is called before the max shops limits is checked for the player.<br> * The location, shopkeeper type, and player's max shops can be modified.<br> * If this event is cancelled, the shop will not be created. * </p> */ public class CreatePlayerShopkeeperEvent extends Event implements Cancellable { private final ShopCreationData creationData; private int maxShops; private boolean cancelled; public CreatePlayerShopkeeperEvent(ShopCreationData creationData, int maxShops) { this.creationData = creationData; this.maxShops = maxShops; } /** * Gets the raw shop creation data. * * <p> * Only modify the returned object if you know what you are doing. * </p> * * @return the raw shop creation data */ public ShopCreationData getShopCreationData() { return creationData; } /** * Gets the player trying to create the shop. * * @return the player */ public Player getPlayer() { return creationData.creator; } /** * Gets the chest block that will be backing this shop. * * @return the chest block */ public Block getChest() { return creationData.chest; } /** * Gets the location the villager will spawn at. * * @return the spawn location */ public Location getSpawnLocation() { return creationData.spawnLocation; } /** * Gets the type of shopkeeper that will spawn (ex: normal, book, buying, trading, etc.). * * @return the shopkeeper type */
public ShopType<?> getType() {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java
// Path: src/main/java/com/nisovin/shopkeepers/Log.java // public class Log { // // public static Logger getLogger() { // return ShopkeepersPlugin.getInstance().getLogger(); // } // // public static void info(String message) { // if (message == null || message.isEmpty()) return; // getLogger().info(message); // } // // public static void debug(String message) { // if (Settings.debug) { // info(message); // } // } // // public static void warning(String message) { // getLogger().warning(message); // } // // public static void severe(String message) { // getLogger().severe(message); // } // } // // Path: src/main/java/com/nisovin/shopkeepers/compat/api/NMSCallProvider.java // public interface NMSCallProvider { // // public String getVersionId(); // // public boolean openTradeWindow(String title, List<ItemStack[]> recipes, Player player); // // public ItemStack[] getUsedTradingRecipe(MerchantInventory merchantInventory); // // public void overwriteLivingEntityAI(LivingEntity entity); // // public void setEntitySilent(Entity entity, boolean silent); // // public void setNoAI(LivingEntity bukkitEntity); // // public ItemStack loadItemAttributesFromString(ItemStack item, String data); // // public String saveItemAttributesToString(ItemStack item); // // public boolean isMainHandInteraction(PlayerInteractEvent event); // // public boolean isMainHandInteraction(PlayerInteractEntityEvent event); // // public boolean supportsSpawnEggEntityType(); // // public void setSpawnEggEntityType(ItemStack spawnEggItem, EntityType entityType); // // public EntityType getSpawnEggEntityType(ItemStack spawnEggItem); // }
import org.bukkit.plugin.Plugin; import com.nisovin.shopkeepers.Log; import com.nisovin.shopkeepers.compat.api.NMSCallProvider;
package com.nisovin.shopkeepers.compat; public final class NMSManager { private static NMSCallProvider provider; public static NMSCallProvider getProvider() { return NMSManager.provider; } public static void load(Plugin plugin) { final String packageName = plugin.getServer().getClass().getPackage().getName(); String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); try { final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); if (NMSCallProvider.class.isAssignableFrom(clazz)) { NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); } else { throw new Exception("Nope"); } } catch (final Exception e) {
// Path: src/main/java/com/nisovin/shopkeepers/Log.java // public class Log { // // public static Logger getLogger() { // return ShopkeepersPlugin.getInstance().getLogger(); // } // // public static void info(String message) { // if (message == null || message.isEmpty()) return; // getLogger().info(message); // } // // public static void debug(String message) { // if (Settings.debug) { // info(message); // } // } // // public static void warning(String message) { // getLogger().warning(message); // } // // public static void severe(String message) { // getLogger().severe(message); // } // } // // Path: src/main/java/com/nisovin/shopkeepers/compat/api/NMSCallProvider.java // public interface NMSCallProvider { // // public String getVersionId(); // // public boolean openTradeWindow(String title, List<ItemStack[]> recipes, Player player); // // public ItemStack[] getUsedTradingRecipe(MerchantInventory merchantInventory); // // public void overwriteLivingEntityAI(LivingEntity entity); // // public void setEntitySilent(Entity entity, boolean silent); // // public void setNoAI(LivingEntity bukkitEntity); // // public ItemStack loadItemAttributesFromString(ItemStack item, String data); // // public String saveItemAttributesToString(ItemStack item); // // public boolean isMainHandInteraction(PlayerInteractEvent event); // // public boolean isMainHandInteraction(PlayerInteractEntityEvent event); // // public boolean supportsSpawnEggEntityType(); // // public void setSpawnEggEntityType(ItemStack spawnEggItem, EntityType entityType); // // public EntityType getSpawnEggEntityType(ItemStack spawnEggItem); // } // Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java import org.bukkit.plugin.Plugin; import com.nisovin.shopkeepers.Log; import com.nisovin.shopkeepers.compat.api.NMSCallProvider; package com.nisovin.shopkeepers.compat; public final class NMSManager { private static NMSCallProvider provider; public static NMSCallProvider getProvider() { return NMSManager.provider; } public static void load(Plugin plugin) { final String packageName = plugin.getServer().getClass().getPackage().getName(); String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); try { final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); if (NMSCallProvider.class.isAssignableFrom(clazz)) { NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); } else { throw new Exception("Nope"); } } catch (final Exception e) {
Log.severe("Potentially incompatible server version: " + cbversion);
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/SignShopListener.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // }
import java.util.Iterator; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import com.nisovin.shopkeepers.compat.NMSManager;
package com.nisovin.shopkeepers; class SignShopListener implements Listener { private final ShopkeepersPlugin plugin; private Location cancelNextBlockPhysicsLoc = null; SignShopListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } void cancelNextBlockPhysics(Location location) { cancelNextBlockPhysicsLoc = location; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); Block block = event.getClickedBlock(); // check for sign shop if (event.getAction() == Action.RIGHT_CLICK_BLOCK && Utils.isSign(block.getType())) { Shopkeeper shopkeeper = plugin.getShopkeeperByBlock(block); if (shopkeeper != null) { // only trigger shopkeeper interaction for main-hand events:
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // Path: src/main/java/com/nisovin/shopkeepers/SignShopListener.java import java.util.Iterator; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import com.nisovin.shopkeepers.compat.NMSManager; package com.nisovin.shopkeepers; class SignShopListener implements Listener { private final ShopkeepersPlugin plugin; private Location cancelNextBlockPhysicsLoc = null; SignShopListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } void cancelNextBlockPhysics(Location location) { cancelNextBlockPhysicsLoc = location; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); Block block = event.getClickedBlock(); // check for sign shop if (event.getAction() == Action.RIGHT_CLICK_BLOCK && Utils.isSign(block.getType())) { Shopkeeper shopkeeper = plugin.getShopkeeperByBlock(block); if (shopkeeper != null) { // only trigger shopkeeper interaction for main-hand events:
if (NMSManager.getProvider().isMainHandInteraction(event)) {
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/VillagerInteractionListener.java
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // }
import java.util.Map; import org.bukkit.entity.Player; import org.bukkit.entity.Villager; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.nisovin.shopkeepers.compat.NMSManager;
package com.nisovin.shopkeepers; class VillagerInteractionListener implements Listener { private final ShopkeepersPlugin plugin; VillagerInteractionListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) void onEntityInteract(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof Villager)) return; Villager villager = (Villager) event.getRightClicked(); if (plugin.isShopkeeper(villager)) return; // shopkeeper interaction is handled elsewhere Log.debug("Interaction with Non-shopkeeper villager .."); if (villager.hasMetadata("NPC")) { // ignore any interaction with citizens2 NPCs Log.debug(" ignoring (probably citizens2) NPC"); return; } if (Settings.disableOtherVillagers) { // don't allow trading with other villagers event.setCancelled(true); Log.debug(" trade prevented"); } // only trigger hiring for main-hand events:
// Path: src/main/java/com/nisovin/shopkeepers/compat/NMSManager.java // public final class NMSManager { // // private static NMSCallProvider provider; // // public static NMSCallProvider getProvider() { // return NMSManager.provider; // } // // public static void load(Plugin plugin) { // final String packageName = plugin.getServer().getClass().getPackage().getName(); // String cbversion = packageName.substring(packageName.lastIndexOf('.') + 1); // try { // final Class<?> clazz = Class.forName("com.nisovin.shopkeepers.compat." + cbversion + ".NMSHandler"); // if (NMSCallProvider.class.isAssignableFrom(clazz)) { // NMSManager.provider = (NMSCallProvider) clazz.getConstructor().newInstance(); // } else { // throw new Exception("Nope"); // } // } catch (final Exception e) { // Log.severe("Potentially incompatible server version: " + cbversion); // Log.severe("Shopkeepers is trying to run in 'compatibility mode'."); // Log.info("Check for updates at: " + plugin.getDescription().getWebsite()); // // try { // NMSManager.provider = new FailedHandler(); // } catch (Exception e_u) { // // uncomment for debugging: // // e_u.printStackTrace(); // } // } // } // } // Path: src/main/java/com/nisovin/shopkeepers/VillagerInteractionListener.java import java.util.Map; import org.bukkit.entity.Player; import org.bukkit.entity.Villager; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.nisovin.shopkeepers.compat.NMSManager; package com.nisovin.shopkeepers; class VillagerInteractionListener implements Listener { private final ShopkeepersPlugin plugin; VillagerInteractionListener(ShopkeepersPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) void onEntityInteract(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof Villager)) return; Villager villager = (Villager) event.getRightClicked(); if (plugin.isShopkeeper(villager)) return; // shopkeeper interaction is handled elsewhere Log.debug("Interaction with Non-shopkeeper villager .."); if (villager.hasMetadata("NPC")) { // ignore any interaction with citizens2 NPCs Log.debug(" ignoring (probably citizens2) NPC"); return; } if (Settings.disableOtherVillagers) { // don't allow trading with other villagers event.setCancelled(true); Log.debug(" trade prevented"); } // only trigger hiring for main-hand events:
if (!NMSManager.getProvider().isMainHandInteraction(event)) return;
VanTamNguyen/Nand2Tetris
nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/CompilationEngine.java
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/symbol/Symbol.java // public class Symbol { // // public enum Kind { // STATIC("static"), FIELD("field"), ARGUMENT("argument"), LOCAL("local"); // // private String value; // // Kind(String s) { // this.value = s; // } // // public static Kind fromString(String s) { // if ("static".equals(s)) { // return STATIC; // } else if ("field".equals(s)) { // return FIELD; // } else if ("argument".equals(s)) { // return ARGUMENT; // } else if ("local".equals(s)) { // return LOCAL; // } else { // return null; // } // } // } // // private String name; // // private String type; // // private Kind kind; // // private int no; // // public Symbol(String name, String type, Kind kind, int no) { // this.name = name; // this.type = type; // this.kind = kind; // this.no = no; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Kind getKind() { // return kind; // } // // public void setKind(Kind kind) { // this.kind = kind; // } // // public int getNo() { // return no; // } // // public void setNo(int no) { // this.no = no; // } // }
import com.tamco.hack.compiler.lexical.Lexical; import com.tamco.hack.compiler.symbol.Symbol; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class CompilationEngine { private String clazzName;
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/symbol/Symbol.java // public class Symbol { // // public enum Kind { // STATIC("static"), FIELD("field"), ARGUMENT("argument"), LOCAL("local"); // // private String value; // // Kind(String s) { // this.value = s; // } // // public static Kind fromString(String s) { // if ("static".equals(s)) { // return STATIC; // } else if ("field".equals(s)) { // return FIELD; // } else if ("argument".equals(s)) { // return ARGUMENT; // } else if ("local".equals(s)) { // return LOCAL; // } else { // return null; // } // } // } // // private String name; // // private String type; // // private Kind kind; // // private int no; // // public Symbol(String name, String type, Kind kind, int no) { // this.name = name; // this.type = type; // this.kind = kind; // this.no = no; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Kind getKind() { // return kind; // } // // public void setKind(Kind kind) { // this.kind = kind; // } // // public int getNo() { // return no; // } // // public void setNo(int no) { // this.no = no; // } // } // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/CompilationEngine.java import com.tamco.hack.compiler.lexical.Lexical; import com.tamco.hack.compiler.symbol.Symbol; import java.util.HashMap; import java.util.List; import java.util.Map; package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class CompilationEngine { private String clazzName;
private List<Lexical> tokens;
VanTamNguyen/Nand2Tetris
nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/CompilationEngine.java
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/symbol/Symbol.java // public class Symbol { // // public enum Kind { // STATIC("static"), FIELD("field"), ARGUMENT("argument"), LOCAL("local"); // // private String value; // // Kind(String s) { // this.value = s; // } // // public static Kind fromString(String s) { // if ("static".equals(s)) { // return STATIC; // } else if ("field".equals(s)) { // return FIELD; // } else if ("argument".equals(s)) { // return ARGUMENT; // } else if ("local".equals(s)) { // return LOCAL; // } else { // return null; // } // } // } // // private String name; // // private String type; // // private Kind kind; // // private int no; // // public Symbol(String name, String type, Kind kind, int no) { // this.name = name; // this.type = type; // this.kind = kind; // this.no = no; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Kind getKind() { // return kind; // } // // public void setKind(Kind kind) { // this.kind = kind; // } // // public int getNo() { // return no; // } // // public void setNo(int no) { // this.no = no; // } // }
import com.tamco.hack.compiler.lexical.Lexical; import com.tamco.hack.compiler.symbol.Symbol; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class CompilationEngine { private String clazzName; private List<Lexical> tokens; private List<String> vmCommands; private int count = -1; private Lexical currentToken;
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/symbol/Symbol.java // public class Symbol { // // public enum Kind { // STATIC("static"), FIELD("field"), ARGUMENT("argument"), LOCAL("local"); // // private String value; // // Kind(String s) { // this.value = s; // } // // public static Kind fromString(String s) { // if ("static".equals(s)) { // return STATIC; // } else if ("field".equals(s)) { // return FIELD; // } else if ("argument".equals(s)) { // return ARGUMENT; // } else if ("local".equals(s)) { // return LOCAL; // } else { // return null; // } // } // } // // private String name; // // private String type; // // private Kind kind; // // private int no; // // public Symbol(String name, String type, Kind kind, int no) { // this.name = name; // this.type = type; // this.kind = kind; // this.no = no; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Kind getKind() { // return kind; // } // // public void setKind(Kind kind) { // this.kind = kind; // } // // public int getNo() { // return no; // } // // public void setNo(int no) { // this.no = no; // } // } // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/CompilationEngine.java import com.tamco.hack.compiler.lexical.Lexical; import com.tamco.hack.compiler.symbol.Symbol; import java.util.HashMap; import java.util.List; import java.util.Map; package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class CompilationEngine { private String clazzName; private List<Lexical> tokens; private List<String> vmCommands; private int count = -1; private Lexical currentToken;
private Map<String, Symbol> clazzSymbolTable;
VanTamNguyen/Nand2Tetris
nand2tetris/projects/10/Compiler/src/com/tamco/hack/compiler/JackAnalyzer.java
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // }
import com.tamco.hack.compiler.lexical.Lexical; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class JackAnalyzer { public static void main(String[] args) { File src1 = new File("../ArrayTest"); File src2 = new File("../Square"); File src3 = new File("../ExpressionLessSquare"); try { parseSource(src1); parseSource(src2); parseSource(src3); } catch (IOException e) { } } private static void parseSource(File sourceFolder) throws IOException { File[] sourceFiles = sourceFolder.listFiles(); for (File sourceFile : sourceFiles) { if (sourceFile.getName().endsWith(".jack")) { // Tokenize the source code file JackTokenizer tokenizer = new JackTokenizer(sourceFile);
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // Path: nand2tetris/projects/10/Compiler/src/com/tamco/hack/compiler/JackAnalyzer.java import com.tamco.hack.compiler.lexical.Lexical; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class JackAnalyzer { public static void main(String[] args) { File src1 = new File("../ArrayTest"); File src2 = new File("../Square"); File src3 = new File("../ExpressionLessSquare"); try { parseSource(src1); parseSource(src2); parseSource(src3); } catch (IOException e) { } } private static void parseSource(File sourceFolder) throws IOException { File[] sourceFiles = sourceFolder.listFiles(); for (File sourceFile : sourceFiles) { if (sourceFile.getName().endsWith(".jack")) { // Tokenize the source code file JackTokenizer tokenizer = new JackTokenizer(sourceFile);
List<Lexical> tokens = tokenizer.tokenize();
VanTamNguyen/Nand2Tetris
nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/JackCompiler.java
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // }
import com.tamco.hack.compiler.lexical.Lexical; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class JackCompiler { public static void main(String[] args) { File src1 = new File("../ArrayTest"); File src2 = new File("../Square"); File src3 = new File("../ExpressionLessSquare"); try { parseSource(src1); parseSource(src2); parseSource(src3); } catch (IOException e) { } } private static void parseSource(File sourceFolder) throws IOException { File[] sourceFiles = sourceFolder.listFiles(); for (File sourceFile : sourceFiles) { if (sourceFile.getName().endsWith(".jack")) { String className = sourceFile.getName().substring(0, sourceFile.getName().indexOf(".") + 1); // Tokenize the source code file JackTokenizer tokenizer = new JackTokenizer(sourceFile);
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/JackCompiler.java import com.tamco.hack.compiler.lexical.Lexical; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class JackCompiler { public static void main(String[] args) { File src1 = new File("../ArrayTest"); File src2 = new File("../Square"); File src3 = new File("../ExpressionLessSquare"); try { parseSource(src1); parseSource(src2); parseSource(src3); } catch (IOException e) { } } private static void parseSource(File sourceFolder) throws IOException { File[] sourceFiles = sourceFolder.listFiles(); for (File sourceFile : sourceFiles) { if (sourceFile.getName().endsWith(".jack")) { String className = sourceFile.getName().substring(0, sourceFile.getName().indexOf(".") + 1); // Tokenize the source code file JackTokenizer tokenizer = new JackTokenizer(sourceFile);
List<Lexical> tokens = tokenizer.tokenize();
VanTamNguyen/Nand2Tetris
nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/JackTokenizer.java
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // }
import com.tamco.hack.compiler.lexical.Lexical; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class JackTokenizer { private File sourceCode; public JackTokenizer(File sourceCode) { this.sourceCode = sourceCode; }
// Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/lexical/Lexical.java // public class Lexical { // // public static final List<String> keywords = Arrays.asList("class", "constructor", "function", // "method", "field", "static", "var", // "int", "char", "boolean", "void", "true", // "false", "null", "this", "let", "do", // "if", "else", "while", "return"); // // public static final List<String> symbols = Arrays.asList("{", "}", "(", ")", "[", "]", ".", // ",", ";", "+", "-", "*", "/", "&", // "|", "<", ">", "=", "~"); // // // public static enum Type { // keyword, // symbol, // integerConstant, // stringConstant, // identifier // } // // private Type type; // // private String lecical; // // public Lexical(Type type, String lecical) { // this.type = type; // this.lecical = lecical; // } // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public String getLecical() { // return lecical; // } // // public void setLecical(String lecical) { // this.lecical = lecical; // } // // public String toString() { // String lex = lecical.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); // return "<" + type.name() + "> " + lex + " </" + type.name() + ">"; // } // // public static Lexical fromString(String token) { // if (keywords.contains(token)) { // return new Lexical(Type.keyword, token); // } // // try { // Integer.parseInt(token); // return new Lexical(Type.integerConstant, token); // // } catch (NumberFormatException e) { // return new Lexical(Type.identifier, token); // } // } // } // Path: nand2tetris/projects/11/Compiler/src/com/tamco/hack/compiler/JackTokenizer.java import com.tamco.hack.compiler.lexical.Lexical; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; package com.tamco.hack.compiler; /** * Created by tam-co on 12/07/2017. */ public class JackTokenizer { private File sourceCode; public JackTokenizer(File sourceCode) { this.sourceCode = sourceCode; }
public List<Lexical> tokenize() throws IOException {
tudoNoob/poseidon
src/main/java/com/poseidon/advices/ControllerThrowsAdvice.java
// Path: src/main/java/com/poseidon/exception/MethodDeclarationException.java // public class MethodDeclarationException extends PoseidonException { // // // public MethodDeclarationException(String message) { // super(message); // // } // // }
import com.poseidon.exception.MethodDeclarationException; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import java.lang.reflect.Method;
package com.poseidon.advices; @Component @Aspect public class ControllerThrowsAdvice { @Before("execution(* com.poseidon.*.*Controller..*(..))") public void validateThrowsonController(JoinPoint joinPoint) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); Controller annotation = joinPoint.getTarget().getClass().getAnnotation(Controller.class); if(annotation == null){ return; } Class<?>[] exceptionTypes = method.getExceptionTypes(); if(exceptionTypes != null && exceptionTypes.length>0){
// Path: src/main/java/com/poseidon/exception/MethodDeclarationException.java // public class MethodDeclarationException extends PoseidonException { // // // public MethodDeclarationException(String message) { // super(message); // // } // // } // Path: src/main/java/com/poseidon/advices/ControllerThrowsAdvice.java import com.poseidon.exception.MethodDeclarationException; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import java.lang.reflect.Method; package com.poseidon.advices; @Component @Aspect public class ControllerThrowsAdvice { @Before("execution(* com.poseidon.*.*Controller..*(..))") public void validateThrowsonController(JoinPoint joinPoint) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); Controller annotation = joinPoint.getTarget().getClass().getAnnotation(Controller.class); if(annotation == null){ return; } Class<?>[] exceptionTypes = method.getExceptionTypes(); if(exceptionTypes != null && exceptionTypes.length>0){
throw new MethodDeclarationException("Nao pode declarar throws em um com.poseidon.controller.Controller: "+method.getName());
tudoNoob/poseidon
src/test/java/com/poseidon/model/UserViewTest.java
// Path: src/main/java/com/poseidon/builder/UsersBuilder.java // public class UsersBuilder { // // private Users myObject; // private List<Users> usersList; // // public UsersBuilder(){ // myObject= new Users(); // usersList= new ArrayList<>(); // } // // public Users build(){ // return myObject; // } // // public List<Users> buildAsList(){ // return usersList; // } // // public UsersBuilder add(){ // usersList.add(myObject); // myObject= new Users(); // return this; // } // // public UsersBuilder withPassword(String password){ // myObject.setPassword(password); // return this; // } // // public UsersBuilder withUsername(String username){ // myObject.setUsername(username); // return this; // } // // }
import com.poseidon.builder.UsersBuilder; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals;
package com.poseidon.model; @Test public class UserViewTest { ContaView contaView; Users user; @BeforeTest public void setUp() throws Exception {
// Path: src/main/java/com/poseidon/builder/UsersBuilder.java // public class UsersBuilder { // // private Users myObject; // private List<Users> usersList; // // public UsersBuilder(){ // myObject= new Users(); // usersList= new ArrayList<>(); // } // // public Users build(){ // return myObject; // } // // public List<Users> buildAsList(){ // return usersList; // } // // public UsersBuilder add(){ // usersList.add(myObject); // myObject= new Users(); // return this; // } // // public UsersBuilder withPassword(String password){ // myObject.setPassword(password); // return this; // } // // public UsersBuilder withUsername(String username){ // myObject.setUsername(username); // return this; // } // // } // Path: src/test/java/com/poseidon/model/UserViewTest.java import com.poseidon.builder.UsersBuilder; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; package com.poseidon.model; @Test public class UserViewTest { ContaView contaView; Users user; @BeforeTest public void setUp() throws Exception {
user = new UsersBuilder().withUsername("name").withPassword("123").build();
tudoNoob/poseidon
src/main/java/com/poseidon/WebSecurityConfig.java
// Path: src/main/java/com/poseidon/logout/CustomLogoutHandler.java // public class CustomLogoutHandler implements LogoutHandler { // // private Logger logger = Logger.getLogger(CustomLogoutHandler.class); // // @Override // public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { // authentication= null; // try { // response.sendRedirect("/loginPage"); // } catch (IOException e) { // logger.info("Erro ao tentar redirecionar para a pagina de login",e); // } // } // } // // Path: src/main/java/com/poseidon/logout/LogoutRequestMatcher.java // public class LogoutRequestMatcher implements RequestMatcher { // // @Override // public boolean matches(HttpServletRequest request) { // String requestURI = request.getRequestURI(); // if(requestURI.equals("/logout")){ // return true; // } // return false; // } // }
import com.poseidon.logout.CustomLogoutHandler; import com.poseidon.logout.LogoutRequestMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.header.writers.*; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter; import javax.sql.DataSource;
package com.poseidon; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/createSimpleUser","/createUser").permitAll(); http.authorizeRequests().antMatchers("/user/*").hasAnyRole("USER","ADMIN"); http.authorizeRequests().antMatchers("/admin/*").hasRole("ADMIN"); http.authorizeRequests() .antMatchers("/css/**","/jquery/**","/bootstrap/**","/jquery/images/**","/webjars/**").permitAll(); http.formLogin().loginPage("/loginPage").defaultSuccessUrl("/user/homePage").failureUrl("/login-Error") .permitAll().and().logout()
// Path: src/main/java/com/poseidon/logout/CustomLogoutHandler.java // public class CustomLogoutHandler implements LogoutHandler { // // private Logger logger = Logger.getLogger(CustomLogoutHandler.class); // // @Override // public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { // authentication= null; // try { // response.sendRedirect("/loginPage"); // } catch (IOException e) { // logger.info("Erro ao tentar redirecionar para a pagina de login",e); // } // } // } // // Path: src/main/java/com/poseidon/logout/LogoutRequestMatcher.java // public class LogoutRequestMatcher implements RequestMatcher { // // @Override // public boolean matches(HttpServletRequest request) { // String requestURI = request.getRequestURI(); // if(requestURI.equals("/logout")){ // return true; // } // return false; // } // } // Path: src/main/java/com/poseidon/WebSecurityConfig.java import com.poseidon.logout.CustomLogoutHandler; import com.poseidon.logout.LogoutRequestMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.header.writers.*; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter; import javax.sql.DataSource; package com.poseidon; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/createSimpleUser","/createUser").permitAll(); http.authorizeRequests().antMatchers("/user/*").hasAnyRole("USER","ADMIN"); http.authorizeRequests().antMatchers("/admin/*").hasRole("ADMIN"); http.authorizeRequests() .antMatchers("/css/**","/jquery/**","/bootstrap/**","/jquery/images/**","/webjars/**").permitAll(); http.formLogin().loginPage("/loginPage").defaultSuccessUrl("/user/homePage").failureUrl("/login-Error") .permitAll().and().logout()
.addLogoutHandler(new CustomLogoutHandler())
tudoNoob/poseidon
src/main/java/com/poseidon/WebSecurityConfig.java
// Path: src/main/java/com/poseidon/logout/CustomLogoutHandler.java // public class CustomLogoutHandler implements LogoutHandler { // // private Logger logger = Logger.getLogger(CustomLogoutHandler.class); // // @Override // public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { // authentication= null; // try { // response.sendRedirect("/loginPage"); // } catch (IOException e) { // logger.info("Erro ao tentar redirecionar para a pagina de login",e); // } // } // } // // Path: src/main/java/com/poseidon/logout/LogoutRequestMatcher.java // public class LogoutRequestMatcher implements RequestMatcher { // // @Override // public boolean matches(HttpServletRequest request) { // String requestURI = request.getRequestURI(); // if(requestURI.equals("/logout")){ // return true; // } // return false; // } // }
import com.poseidon.logout.CustomLogoutHandler; import com.poseidon.logout.LogoutRequestMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.header.writers.*; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter; import javax.sql.DataSource;
package com.poseidon; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/createSimpleUser","/createUser").permitAll(); http.authorizeRequests().antMatchers("/user/*").hasAnyRole("USER","ADMIN"); http.authorizeRequests().antMatchers("/admin/*").hasRole("ADMIN"); http.authorizeRequests() .antMatchers("/css/**","/jquery/**","/bootstrap/**","/jquery/images/**","/webjars/**").permitAll(); http.formLogin().loginPage("/loginPage").defaultSuccessUrl("/user/homePage").failureUrl("/login-Error") .permitAll().and().logout() .addLogoutHandler(new CustomLogoutHandler())
// Path: src/main/java/com/poseidon/logout/CustomLogoutHandler.java // public class CustomLogoutHandler implements LogoutHandler { // // private Logger logger = Logger.getLogger(CustomLogoutHandler.class); // // @Override // public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { // authentication= null; // try { // response.sendRedirect("/loginPage"); // } catch (IOException e) { // logger.info("Erro ao tentar redirecionar para a pagina de login",e); // } // } // } // // Path: src/main/java/com/poseidon/logout/LogoutRequestMatcher.java // public class LogoutRequestMatcher implements RequestMatcher { // // @Override // public boolean matches(HttpServletRequest request) { // String requestURI = request.getRequestURI(); // if(requestURI.equals("/logout")){ // return true; // } // return false; // } // } // Path: src/main/java/com/poseidon/WebSecurityConfig.java import com.poseidon.logout.CustomLogoutHandler; import com.poseidon.logout.LogoutRequestMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.header.writers.*; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter; import javax.sql.DataSource; package com.poseidon; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/createSimpleUser","/createUser").permitAll(); http.authorizeRequests().antMatchers("/user/*").hasAnyRole("USER","ADMIN"); http.authorizeRequests().antMatchers("/admin/*").hasRole("ADMIN"); http.authorizeRequests() .antMatchers("/css/**","/jquery/**","/bootstrap/**","/jquery/images/**","/webjars/**").permitAll(); http.formLogin().loginPage("/loginPage").defaultSuccessUrl("/user/homePage").failureUrl("/login-Error") .permitAll().and().logout() .addLogoutHandler(new CustomLogoutHandler())
.logoutRequestMatcher(new LogoutRequestMatcher()).invalidateHttpSession(true);
tudoNoob/poseidon
src/main/java/com/poseidon/dao/QuiropraxistaDao.java
// Path: src/main/java/com/poseidon/model/Quiropraxista.java // @Entity // public class Quiropraxista { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // private String nome; // // public Quiropraxista() { // // } // // public Quiropraxista(Integer id, String nome) { // this.id = id; // this.nome = nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // public String getNome() { // return nome; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId() { // return id; // } // // @Override // public String toString() { // return "Quiropraxista [id=" + id + ", nome=" + nome + "]"; // } // }
import com.poseidon.model.Quiropraxista; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository;
package com.poseidon.dao; @Repository @Qualifier()
// Path: src/main/java/com/poseidon/model/Quiropraxista.java // @Entity // public class Quiropraxista { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // private String nome; // // public Quiropraxista() { // // } // // public Quiropraxista(Integer id, String nome) { // this.id = id; // this.nome = nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // public String getNome() { // return nome; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId() { // return id; // } // // @Override // public String toString() { // return "Quiropraxista [id=" + id + ", nome=" + nome + "]"; // } // } // Path: src/main/java/com/poseidon/dao/QuiropraxistaDao.java import com.poseidon.model.Quiropraxista; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; package com.poseidon.dao; @Repository @Qualifier()
public interface QuiropraxistaDao extends CrudRepository<Quiropraxista, Integer>{
tudoNoob/poseidon
src/main/java/com/poseidon/advices/LogAspects.java
// Path: src/main/java/com/poseidon/model/AtributosClasse.java // public class AtributosClasse { // // private String metodoNome; // // private String argumentos; // // private String returnType; // // public static AtributosClasse builderAtributosClasse(JoinPoint joinPoint) { // AtributosClasse atributosClasse = new AtributosClasse(); // Signature signature = joinPoint.getSignature(); // String methodName = signature.getName(); // String arguments = Arrays.toString(joinPoint.getArgs()); // atributosClasse.setMetodoNome(methodName); // atributosClasse.setArgumentos(arguments); // // final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); // Method method = methodSignature.getMethod(); // atributosClasse.setReturnType(method.getReturnType().getName()); // // return atributosClasse; // }; // // public String getMetodoNome() { // return metodoNome; // } // // public void setMetodoNome(String metodoNome) { // this.metodoNome = metodoNome; // } // // public String getArgumentos() { // return argumentos; // } // // public void setArgumentos(String argumentos) { // this.argumentos = argumentos; // } // // public String getReturnType() { // return returnType; // } // // public void setReturnType(String returnType) { // this.returnType = returnType; // } // // @Override // public String toString() { // return "AtributosClasse [metodoNome=" + metodoNome + ", argumentos=" + argumentos + ", returnType=" + returnType // + "]"; // } // }
import com.poseidon.model.AtributosClasse; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;
package com.poseidon.advices; @Aspect @Component public class LogAspects { @Before("execution(* com.poseidon.*..*(..))") public void logServiceAccess(JoinPoint joinPoint) { Logger LOGGER = createLog(joinPoint);
// Path: src/main/java/com/poseidon/model/AtributosClasse.java // public class AtributosClasse { // // private String metodoNome; // // private String argumentos; // // private String returnType; // // public static AtributosClasse builderAtributosClasse(JoinPoint joinPoint) { // AtributosClasse atributosClasse = new AtributosClasse(); // Signature signature = joinPoint.getSignature(); // String methodName = signature.getName(); // String arguments = Arrays.toString(joinPoint.getArgs()); // atributosClasse.setMetodoNome(methodName); // atributosClasse.setArgumentos(arguments); // // final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); // Method method = methodSignature.getMethod(); // atributosClasse.setReturnType(method.getReturnType().getName()); // // return atributosClasse; // }; // // public String getMetodoNome() { // return metodoNome; // } // // public void setMetodoNome(String metodoNome) { // this.metodoNome = metodoNome; // } // // public String getArgumentos() { // return argumentos; // } // // public void setArgumentos(String argumentos) { // this.argumentos = argumentos; // } // // public String getReturnType() { // return returnType; // } // // public void setReturnType(String returnType) { // this.returnType = returnType; // } // // @Override // public String toString() { // return "AtributosClasse [metodoNome=" + metodoNome + ", argumentos=" + argumentos + ", returnType=" + returnType // + "]"; // } // } // Path: src/main/java/com/poseidon/advices/LogAspects.java import com.poseidon.model.AtributosClasse; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; package com.poseidon.advices; @Aspect @Component public class LogAspects { @Before("execution(* com.poseidon.*..*(..))") public void logServiceAccess(JoinPoint joinPoint) { Logger LOGGER = createLog(joinPoint);
AtributosClasse atributosClasse = criaAtributosClasse(joinPoint);
tudoNoob/poseidon
src/main/java/com/poseidon/utils/PoseidonUtils.java
// Path: src/main/java/com/poseidon/exception/DateSqlParseException.java // public class DateSqlParseException extends PoseidonException { // // private static final long serialVersionUID = 2205794616246894466L; // // // public DateSqlParseException(Throwable cause) { // super(cause); // // } // // // // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.poseidon.exception.DateSqlParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
package com.poseidon.utils; public class PoseidonUtils { private static final Logger LOGGER = LoggerFactory.getLogger(PoseidonUtils.class); public static java.sql.Date convertToDate(String toDate) { SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy"); Date parsed; java.sql.Date sql = null; try { parsed = format.parse(toDate); sql = new java.sql.Date(parsed.getTime()); } catch (ParseException e) { LOGGER.error("Falha na conversão da data.", e);
// Path: src/main/java/com/poseidon/exception/DateSqlParseException.java // public class DateSqlParseException extends PoseidonException { // // private static final long serialVersionUID = 2205794616246894466L; // // // public DateSqlParseException(Throwable cause) { // super(cause); // // } // // // // } // Path: src/main/java/com/poseidon/utils/PoseidonUtils.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.poseidon.exception.DateSqlParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; package com.poseidon.utils; public class PoseidonUtils { private static final Logger LOGGER = LoggerFactory.getLogger(PoseidonUtils.class); public static java.sql.Date convertToDate(String toDate) { SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy"); Date parsed; java.sql.Date sql = null; try { parsed = format.parse(toDate); sql = new java.sql.Date(parsed.getTime()); } catch (ParseException e) { LOGGER.error("Falha na conversão da data.", e);
throw new DateSqlParseException(e);
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ContaController.java
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // }
import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger;
package com.poseidon.controller; @Controller @RequestMapping("/admin") public class ContaController extends ControllerBase { public static final String ROLE_PREFIX = "ROLE_"; public static final String CONTAS_CLASS_NAME = "contas"; public static final String CONTA_VIEW_NAME = "Conta"; public static final String REDIRECT_ADMIN_CONTA = "redirect:/admin/conta"; @Autowired
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // Path: src/main/java/com/poseidon/controller/ContaController.java import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger; package com.poseidon.controller; @Controller @RequestMapping("/admin") public class ContaController extends ControllerBase { public static final String ROLE_PREFIX = "ROLE_"; public static final String CONTAS_CLASS_NAME = "contas"; public static final String CONTA_VIEW_NAME = "Conta"; public static final String REDIRECT_ADMIN_CONTA = "redirect:/admin/conta"; @Autowired
AuthoritiesRepository authoritiesRepository;
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ContaController.java
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // }
import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger;
package com.poseidon.controller; @Controller @RequestMapping("/admin") public class ContaController extends ControllerBase { public static final String ROLE_PREFIX = "ROLE_"; public static final String CONTAS_CLASS_NAME = "contas"; public static final String CONTA_VIEW_NAME = "Conta"; public static final String REDIRECT_ADMIN_CONTA = "redirect:/admin/conta"; @Autowired AuthoritiesRepository authoritiesRepository; @Autowired
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // Path: src/main/java/com/poseidon/controller/ContaController.java import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger; package com.poseidon.controller; @Controller @RequestMapping("/admin") public class ContaController extends ControllerBase { public static final String ROLE_PREFIX = "ROLE_"; public static final String CONTAS_CLASS_NAME = "contas"; public static final String CONTA_VIEW_NAME = "Conta"; public static final String REDIRECT_ADMIN_CONTA = "redirect:/admin/conta"; @Autowired AuthoritiesRepository authoritiesRepository; @Autowired
UserRepository userRepository;
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ContaController.java
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // }
import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger;
package com.poseidon.controller; @Controller @RequestMapping("/admin") public class ContaController extends ControllerBase { public static final String ROLE_PREFIX = "ROLE_"; public static final String CONTAS_CLASS_NAME = "contas"; public static final String CONTA_VIEW_NAME = "Conta"; public static final String REDIRECT_ADMIN_CONTA = "redirect:/admin/conta"; @Autowired AuthoritiesRepository authoritiesRepository; @Autowired UserRepository userRepository; private Logger logger = Logger.getLogger("ContaController"); @RequestMapping(value = "/cadastrarConta") @ViewName(name = REDIRECT_ADMIN_CONTA) @NotNullArgs public ModelAndView cadastrarConta(@ModelAttribute ContaView contaView, @ModelAttribute String role, ModelAndView modelAndView, RedirectAttributes redirectAttributes) { Users user = Users.createUser(contaView); userRepository.save(user); authoritiesRepository.save(new Authorities(user.getUsername(), new StringBuilder() .append(ROLE_PREFIX) .append(contaView.getRole()) .toString()));
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // Path: src/main/java/com/poseidon/controller/ContaController.java import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger; package com.poseidon.controller; @Controller @RequestMapping("/admin") public class ContaController extends ControllerBase { public static final String ROLE_PREFIX = "ROLE_"; public static final String CONTAS_CLASS_NAME = "contas"; public static final String CONTA_VIEW_NAME = "Conta"; public static final String REDIRECT_ADMIN_CONTA = "redirect:/admin/conta"; @Autowired AuthoritiesRepository authoritiesRepository; @Autowired UserRepository userRepository; private Logger logger = Logger.getLogger("ContaController"); @RequestMapping(value = "/cadastrarConta") @ViewName(name = REDIRECT_ADMIN_CONTA) @NotNullArgs public ModelAndView cadastrarConta(@ModelAttribute ContaView contaView, @ModelAttribute String role, ModelAndView modelAndView, RedirectAttributes redirectAttributes) { Users user = Users.createUser(contaView); userRepository.save(user); authoritiesRepository.save(new Authorities(user.getUsername(), new StringBuilder() .append(ROLE_PREFIX) .append(contaView.getRole()) .toString()));
this.buildRedirectFlashAttributes(redirectAttributes, CRUDViewEnum.IS_SAVE);
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ContaController.java
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // }
import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger;
@RequestMapping(value = "/cadastrarConta") @ViewName(name = REDIRECT_ADMIN_CONTA) @NotNullArgs public ModelAndView cadastrarConta(@ModelAttribute ContaView contaView, @ModelAttribute String role, ModelAndView modelAndView, RedirectAttributes redirectAttributes) { Users user = Users.createUser(contaView); userRepository.save(user); authoritiesRepository.save(new Authorities(user.getUsername(), new StringBuilder() .append(ROLE_PREFIX) .append(contaView.getRole()) .toString())); this.buildRedirectFlashAttributes(redirectAttributes, CRUDViewEnum.IS_SAVE); return modelAndView; } private void exibirConta(ModelAndView modelAndView) { Iterable<Users> contaList = userRepository.findAll(); List<ContaView> contasView = Lists.newArrayList(); for (Users user : contaList) { if ((user != null) && (user.getUsername() != null) && (!user.getUsername().isEmpty())) { Authorities authority = authoritiesRepository.findByUsername(user.getUsername());
// Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java // public class ContaViewBuilder { // // private ContaView myObject; // // public ContaViewBuilder(){ // myObject= new ContaView(); // } // // public ContaView build(){ // return myObject; // } // // public ContaViewBuilder convertUsersThroughContaView(Users users){ // myObject.setPassword(users.getPassword()); // myObject.setUsername(users.getUsername()); // return this; // } // // public ContaViewBuilder withAuthority(String authority){ // myObject.setRole(authority); // return this; // } // // // // // // } // // Path: src/main/java/com/poseidon/dao/AuthoritiesRepository.java // public interface AuthoritiesRepository extends CrudRepository<Authorities, Long>{ // // public Authorities findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/dao/UserRepository.java // public interface UserRepository extends CrudRepository<Users, Long> { // // public Users findByUsername(String username); // // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // Path: src/main/java/com/poseidon/controller/ContaController.java import com.google.common.collect.Lists; import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.builder.ContaViewBuilder; import com.poseidon.dao.AuthoritiesRepository; import com.poseidon.dao.UserRepository; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger; @RequestMapping(value = "/cadastrarConta") @ViewName(name = REDIRECT_ADMIN_CONTA) @NotNullArgs public ModelAndView cadastrarConta(@ModelAttribute ContaView contaView, @ModelAttribute String role, ModelAndView modelAndView, RedirectAttributes redirectAttributes) { Users user = Users.createUser(contaView); userRepository.save(user); authoritiesRepository.save(new Authorities(user.getUsername(), new StringBuilder() .append(ROLE_PREFIX) .append(contaView.getRole()) .toString())); this.buildRedirectFlashAttributes(redirectAttributes, CRUDViewEnum.IS_SAVE); return modelAndView; } private void exibirConta(ModelAndView modelAndView) { Iterable<Users> contaList = userRepository.findAll(); List<ContaView> contasView = Lists.newArrayList(); for (Users user : contaList) { if ((user != null) && (user.getUsername() != null) && (!user.getUsername().isEmpty())) { Authorities authority = authoritiesRepository.findByUsername(user.getUsername());
contasView.add(new ContaViewBuilder()
tudoNoob/poseidon
src/main/java/com/poseidon/model/Consulta.java
// Path: src/main/java/com/poseidon/utils/PoseidonUtils.java // public class PoseidonUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(PoseidonUtils.class); // // public static java.sql.Date convertToDate(String toDate) { // // SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy"); // Date parsed; // java.sql.Date sql = null; // try { // parsed = format.parse(toDate); // sql = new java.sql.Date(parsed.getTime()); // } catch (ParseException e) { // LOGGER.error("Falha na conversão da data.", e); // throw new DateSqlParseException(e); // } // // return sql; // } // // public static String convertDateToString(Date date) { // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // String stringFormatted = simpleDateFormat.format(date); // // return stringFormatted; // } // // public static java.sql.Date convertToDate(Date toDate) { // java.sql.Date sql = null; // sql = new java.sql.Date(toDate.getTime()); // // return sql; // } // // public static java.sql.Time convertToTime(Date toDate) { // java.sql.Time sql = null; // sql = new java.sql.Time(toDate.getTime()); // // return sql; // } // // public static String convertStringtoJSON(Object input) { // ObjectMapper mapper = new ObjectMapper(); // String result = ""; // try { // result = mapper.writeValueAsString(input); // } catch (JsonProcessingException e) { // LOGGER.info("Falha na conversão", e); // } // return result; // } // // public static String CADASTRO_SUCCESS = "Cadastro efetuado com sucesso."; // // public static String CADASTRO_ERROR = "Erro ao efetuar o cadastro."; // }
import com.poseidon.utils.PoseidonUtils; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Date;
public void setId_paciente(Integer id_paciente) { this.id_paciente = id_paciente; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } public Date getHorario_consulta() { return horario_consulta; } public Date getData_consulta() { return data_consulta; } public void setHorario_consulta(Date horario_consulta) { this.horario_consulta = horario_consulta; } public void setData_consulta(Date data_consulta) { this.data_consulta = data_consulta; } public Date getDataConsulta_For_SQL() {
// Path: src/main/java/com/poseidon/utils/PoseidonUtils.java // public class PoseidonUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(PoseidonUtils.class); // // public static java.sql.Date convertToDate(String toDate) { // // SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy"); // Date parsed; // java.sql.Date sql = null; // try { // parsed = format.parse(toDate); // sql = new java.sql.Date(parsed.getTime()); // } catch (ParseException e) { // LOGGER.error("Falha na conversão da data.", e); // throw new DateSqlParseException(e); // } // // return sql; // } // // public static String convertDateToString(Date date) { // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // String stringFormatted = simpleDateFormat.format(date); // // return stringFormatted; // } // // public static java.sql.Date convertToDate(Date toDate) { // java.sql.Date sql = null; // sql = new java.sql.Date(toDate.getTime()); // // return sql; // } // // public static java.sql.Time convertToTime(Date toDate) { // java.sql.Time sql = null; // sql = new java.sql.Time(toDate.getTime()); // // return sql; // } // // public static String convertStringtoJSON(Object input) { // ObjectMapper mapper = new ObjectMapper(); // String result = ""; // try { // result = mapper.writeValueAsString(input); // } catch (JsonProcessingException e) { // LOGGER.info("Falha na conversão", e); // } // return result; // } // // public static String CADASTRO_SUCCESS = "Cadastro efetuado com sucesso."; // // public static String CADASTRO_ERROR = "Erro ao efetuar o cadastro."; // } // Path: src/main/java/com/poseidon/model/Consulta.java import com.poseidon.utils.PoseidonUtils; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Date; public void setId_paciente(Integer id_paciente) { this.id_paciente = id_paciente; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } public Date getHorario_consulta() { return horario_consulta; } public Date getData_consulta() { return data_consulta; } public void setHorario_consulta(Date horario_consulta) { this.horario_consulta = horario_consulta; } public void setData_consulta(Date data_consulta) { this.data_consulta = data_consulta; } public Date getDataConsulta_For_SQL() {
return PoseidonUtils.convertToDate(data_consulta);
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ControllerBase.java
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // }
import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.lang.reflect.Field;
package com.poseidon.controller; public class ControllerBase { public static final String CRUDVIEW_CLASS_NAME = "crudview";
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // } // Path: src/main/java/com/poseidon/controller/ControllerBase.java import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.lang.reflect.Field; package com.poseidon.controller; public class ControllerBase { public static final String CRUDVIEW_CLASS_NAME = "crudview";
protected RedirectAttributes buildRedirectFlashAttributes(RedirectAttributes redirectAttributes, CRUDViewEnum crudViewEnum) {
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ControllerBase.java
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // }
import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.lang.reflect.Field;
package com.poseidon.controller; public class ControllerBase { public static final String CRUDVIEW_CLASS_NAME = "crudview"; protected RedirectAttributes buildRedirectFlashAttributes(RedirectAttributes redirectAttributes, CRUDViewEnum crudViewEnum) {
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // } // Path: src/main/java/com/poseidon/controller/ControllerBase.java import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.lang.reflect.Field; package com.poseidon.controller; public class ControllerBase { public static final String CRUDVIEW_CLASS_NAME = "crudview"; protected RedirectAttributes buildRedirectFlashAttributes(RedirectAttributes redirectAttributes, CRUDViewEnum crudViewEnum) {
Field[] fields = CRUDView.class.getDeclaredFields();
tudoNoob/poseidon
src/test/java/com/poseidon/controller/ControllerBaseTest.java
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/test/java/com/poseidon/utils/RedirectAttributesMock.java // public class RedirectAttributesMock implements RedirectAttributes { // // // private HashMap<String,Object> map=new HashMap<>(); // // @Override // public RedirectAttributes addAttribute(String s, Object o) { // return null; // } // // @Override // public RedirectAttributes addAttribute(Object o) { // return null; // } // // @Override // public RedirectAttributes addAllAttributes(Collection<?> collection) { // return null; // } // // @Override // public Model addAllAttributes(Map<String, ?> map) { // return null; // } // // @Override // public RedirectAttributes mergeAttributes(Map<String, ?> map) { // return null; // } // // @Override // public boolean containsAttribute(String s) { // return false; // } // // @Override // public Map<String, Object> asMap() { // return null; // } // // @Override // public RedirectAttributes addFlashAttribute(String s, Object o) { // map.put(s,o); // return this; // } // // @Override // public RedirectAttributes addFlashAttribute(Object o) { // return null; // } // // @Override // public Map<String, ?> getFlashAttributes() { // return map; // } // }
import com.poseidon.enums.CRUDViewEnum; import com.poseidon.utils.RedirectAttributesMock; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Map; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull;
package com.poseidon.controller; @Test public class ControllerBaseTest { private ControllerBase controllerBase; @BeforeMethod public void setUp(){ controllerBase= new ControllerBase(); } @Test public void shouldPutAllFalseExceptIsSave() {
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/test/java/com/poseidon/utils/RedirectAttributesMock.java // public class RedirectAttributesMock implements RedirectAttributes { // // // private HashMap<String,Object> map=new HashMap<>(); // // @Override // public RedirectAttributes addAttribute(String s, Object o) { // return null; // } // // @Override // public RedirectAttributes addAttribute(Object o) { // return null; // } // // @Override // public RedirectAttributes addAllAttributes(Collection<?> collection) { // return null; // } // // @Override // public Model addAllAttributes(Map<String, ?> map) { // return null; // } // // @Override // public RedirectAttributes mergeAttributes(Map<String, ?> map) { // return null; // } // // @Override // public boolean containsAttribute(String s) { // return false; // } // // @Override // public Map<String, Object> asMap() { // return null; // } // // @Override // public RedirectAttributes addFlashAttribute(String s, Object o) { // map.put(s,o); // return this; // } // // @Override // public RedirectAttributes addFlashAttribute(Object o) { // return null; // } // // @Override // public Map<String, ?> getFlashAttributes() { // return map; // } // } // Path: src/test/java/com/poseidon/controller/ControllerBaseTest.java import com.poseidon.enums.CRUDViewEnum; import com.poseidon.utils.RedirectAttributesMock; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Map; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; package com.poseidon.controller; @Test public class ControllerBaseTest { private ControllerBase controllerBase; @BeforeMethod public void setUp(){ controllerBase= new ControllerBase(); } @Test public void shouldPutAllFalseExceptIsSave() {
RedirectAttributes attributeRedirected = controllerBase.buildRedirectFlashAttributes(new RedirectAttributesMock(), CRUDViewEnum.IS_SAVE);
tudoNoob/poseidon
src/test/java/com/poseidon/controller/ControllerBaseTest.java
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/test/java/com/poseidon/utils/RedirectAttributesMock.java // public class RedirectAttributesMock implements RedirectAttributes { // // // private HashMap<String,Object> map=new HashMap<>(); // // @Override // public RedirectAttributes addAttribute(String s, Object o) { // return null; // } // // @Override // public RedirectAttributes addAttribute(Object o) { // return null; // } // // @Override // public RedirectAttributes addAllAttributes(Collection<?> collection) { // return null; // } // // @Override // public Model addAllAttributes(Map<String, ?> map) { // return null; // } // // @Override // public RedirectAttributes mergeAttributes(Map<String, ?> map) { // return null; // } // // @Override // public boolean containsAttribute(String s) { // return false; // } // // @Override // public Map<String, Object> asMap() { // return null; // } // // @Override // public RedirectAttributes addFlashAttribute(String s, Object o) { // map.put(s,o); // return this; // } // // @Override // public RedirectAttributes addFlashAttribute(Object o) { // return null; // } // // @Override // public Map<String, ?> getFlashAttributes() { // return map; // } // }
import com.poseidon.enums.CRUDViewEnum; import com.poseidon.utils.RedirectAttributesMock; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Map; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull;
package com.poseidon.controller; @Test public class ControllerBaseTest { private ControllerBase controllerBase; @BeforeMethod public void setUp(){ controllerBase= new ControllerBase(); } @Test public void shouldPutAllFalseExceptIsSave() {
// Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/test/java/com/poseidon/utils/RedirectAttributesMock.java // public class RedirectAttributesMock implements RedirectAttributes { // // // private HashMap<String,Object> map=new HashMap<>(); // // @Override // public RedirectAttributes addAttribute(String s, Object o) { // return null; // } // // @Override // public RedirectAttributes addAttribute(Object o) { // return null; // } // // @Override // public RedirectAttributes addAllAttributes(Collection<?> collection) { // return null; // } // // @Override // public Model addAllAttributes(Map<String, ?> map) { // return null; // } // // @Override // public RedirectAttributes mergeAttributes(Map<String, ?> map) { // return null; // } // // @Override // public boolean containsAttribute(String s) { // return false; // } // // @Override // public Map<String, Object> asMap() { // return null; // } // // @Override // public RedirectAttributes addFlashAttribute(String s, Object o) { // map.put(s,o); // return this; // } // // @Override // public RedirectAttributes addFlashAttribute(Object o) { // return null; // } // // @Override // public Map<String, ?> getFlashAttributes() { // return map; // } // } // Path: src/test/java/com/poseidon/controller/ControllerBaseTest.java import com.poseidon.enums.CRUDViewEnum; import com.poseidon.utils.RedirectAttributesMock; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Map; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; package com.poseidon.controller; @Test public class ControllerBaseTest { private ControllerBase controllerBase; @BeforeMethod public void setUp(){ controllerBase= new ControllerBase(); } @Test public void shouldPutAllFalseExceptIsSave() {
RedirectAttributes attributeRedirected = controllerBase.buildRedirectFlashAttributes(new RedirectAttributesMock(), CRUDViewEnum.IS_SAVE);
tudoNoob/poseidon
src/main/java/com/poseidon/advices/MetricAdvice.java
// Path: src/main/java/com/poseidon/model/AtributosClasse.java // public class AtributosClasse { // // private String metodoNome; // // private String argumentos; // // private String returnType; // // public static AtributosClasse builderAtributosClasse(JoinPoint joinPoint) { // AtributosClasse atributosClasse = new AtributosClasse(); // Signature signature = joinPoint.getSignature(); // String methodName = signature.getName(); // String arguments = Arrays.toString(joinPoint.getArgs()); // atributosClasse.setMetodoNome(methodName); // atributosClasse.setArgumentos(arguments); // // final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); // Method method = methodSignature.getMethod(); // atributosClasse.setReturnType(method.getReturnType().getName()); // // return atributosClasse; // }; // // public String getMetodoNome() { // return metodoNome; // } // // public void setMetodoNome(String metodoNome) { // this.metodoNome = metodoNome; // } // // public String getArgumentos() { // return argumentos; // } // // public void setArgumentos(String argumentos) { // this.argumentos = argumentos; // } // // public String getReturnType() { // return returnType; // } // // public void setReturnType(String returnType) { // this.returnType = returnType; // } // // @Override // public String toString() { // return "AtributosClasse [metodoNome=" + metodoNome + ", argumentos=" + argumentos + ", returnType=" + returnType // + "]"; // } // }
import com.poseidon.model.AtributosClasse; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.joda.time.DateTime; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
package com.poseidon.advices; @Component @Aspect public class MetricAdvice { private DateTime beforeMethodExecution=null; private DateTime afterMethodExecution=null; @Autowired private LogAspects logAspects; @Before("execution(* com.poseidon.*..*(..))") public void createTimeBeforeMethodExecution(JoinPoint joinPoint) { beforeMethodExecution= new DateTime(); } @After("execution(* com.poseidon.*..*(..))") public void calculatesMethodExecutionTime(JoinPoint joinPoint){
// Path: src/main/java/com/poseidon/model/AtributosClasse.java // public class AtributosClasse { // // private String metodoNome; // // private String argumentos; // // private String returnType; // // public static AtributosClasse builderAtributosClasse(JoinPoint joinPoint) { // AtributosClasse atributosClasse = new AtributosClasse(); // Signature signature = joinPoint.getSignature(); // String methodName = signature.getName(); // String arguments = Arrays.toString(joinPoint.getArgs()); // atributosClasse.setMetodoNome(methodName); // atributosClasse.setArgumentos(arguments); // // final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); // Method method = methodSignature.getMethod(); // atributosClasse.setReturnType(method.getReturnType().getName()); // // return atributosClasse; // }; // // public String getMetodoNome() { // return metodoNome; // } // // public void setMetodoNome(String metodoNome) { // this.metodoNome = metodoNome; // } // // public String getArgumentos() { // return argumentos; // } // // public void setArgumentos(String argumentos) { // this.argumentos = argumentos; // } // // public String getReturnType() { // return returnType; // } // // public void setReturnType(String returnType) { // this.returnType = returnType; // } // // @Override // public String toString() { // return "AtributosClasse [metodoNome=" + metodoNome + ", argumentos=" + argumentos + ", returnType=" + returnType // + "]"; // } // } // Path: src/main/java/com/poseidon/advices/MetricAdvice.java import com.poseidon.model.AtributosClasse; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.joda.time.DateTime; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; package com.poseidon.advices; @Component @Aspect public class MetricAdvice { private DateTime beforeMethodExecution=null; private DateTime afterMethodExecution=null; @Autowired private LogAspects logAspects; @Before("execution(* com.poseidon.*..*(..))") public void createTimeBeforeMethodExecution(JoinPoint joinPoint) { beforeMethodExecution= new DateTime(); } @After("execution(* com.poseidon.*..*(..))") public void calculatesMethodExecutionTime(JoinPoint joinPoint){
AtributosClasse atributosClasse = AtributosClasse.builderAtributosClasse(joinPoint);
tudoNoob/poseidon
src/main/java/com/poseidon/controller/LoginController.java
// Path: src/main/java/com/poseidon/model/ContaView.java // public class ContaView { // private String username; // // private String password; // // private String role; // // public ContaView() { // } // // public static ContaView buildContaView(Users user){ // ContaView view = new ContaView(); // view.setPassword(user.getPassword()); // view.setUsername(user.getUsername()); // return view; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public ContaView comPassword(String password){ // setPassword(password); // return this; // } // // public ContaView comUsername(String username){ // setUsername(username); // return this; // } // // public ContaView comRoles(String role){ // setRole(role); // return this; // } // // @Override // public String toString() { // return "UserView [username=" + username + ", password=" + password + ", role=" + role + "]"; // } // }
import com.poseidon.annotation.ViewName; import com.poseidon.model.ContaView; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;
package com.poseidon.controller; @Controller public class LoginController { @RequestMapping("/loginPage") @ViewName(name="login") public ModelAndView buildLoginPage(ModelAndView modelAndView){
// Path: src/main/java/com/poseidon/model/ContaView.java // public class ContaView { // private String username; // // private String password; // // private String role; // // public ContaView() { // } // // public static ContaView buildContaView(Users user){ // ContaView view = new ContaView(); // view.setPassword(user.getPassword()); // view.setUsername(user.getUsername()); // return view; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public ContaView comPassword(String password){ // setPassword(password); // return this; // } // // public ContaView comUsername(String username){ // setUsername(username); // return this; // } // // public ContaView comRoles(String role){ // setRole(role); // return this; // } // // @Override // public String toString() { // return "UserView [username=" + username + ", password=" + password + ", role=" + role + "]"; // } // } // Path: src/main/java/com/poseidon/controller/LoginController.java import com.poseidon.annotation.ViewName; import com.poseidon.model.ContaView; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; package com.poseidon.controller; @Controller public class LoginController { @RequestMapping("/loginPage") @ViewName(name="login") public ModelAndView buildLoginPage(ModelAndView modelAndView){
modelAndView.getModelMap().addAttribute("user", new ContaView());
tudoNoob/poseidon
src/main/java/com/poseidon/builder/ContaViewBuilder.java
// Path: src/main/java/com/poseidon/model/ContaView.java // public class ContaView { // private String username; // // private String password; // // private String role; // // public ContaView() { // } // // public static ContaView buildContaView(Users user){ // ContaView view = new ContaView(); // view.setPassword(user.getPassword()); // view.setUsername(user.getUsername()); // return view; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public ContaView comPassword(String password){ // setPassword(password); // return this; // } // // public ContaView comUsername(String username){ // setUsername(username); // return this; // } // // public ContaView comRoles(String role){ // setRole(role); // return this; // } // // @Override // public String toString() { // return "UserView [username=" + username + ", password=" + password + ", role=" + role + "]"; // } // } // // Path: src/main/java/com/poseidon/model/Users.java // @Entity // public class Users { // // @Id // @GeneratedValue // private Long id; // // private String username; // // private String password; // // private boolean enabled; // // public static Users createUser(ContaView userView) { // Users user = new Users(); // // user.username = userView.getUsername(); // user.password = userView.getPassword(); // user.enabled = true; // // return user; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // @Override // public String toString() { // return "Users [id=" + id + ", username=" + username + ", password=" + password + ", enabled=" + enabled + "]"; // } // // // }
import com.poseidon.model.ContaView; import com.poseidon.model.Users;
package com.poseidon.builder; /** * Created by wahrons on 2/5/16. */ public class ContaViewBuilder { private ContaView myObject; public ContaViewBuilder(){ myObject= new ContaView(); } public ContaView build(){ return myObject; }
// Path: src/main/java/com/poseidon/model/ContaView.java // public class ContaView { // private String username; // // private String password; // // private String role; // // public ContaView() { // } // // public static ContaView buildContaView(Users user){ // ContaView view = new ContaView(); // view.setPassword(user.getPassword()); // view.setUsername(user.getUsername()); // return view; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getRole() { // return role; // } // // public void setRole(String role) { // this.role = role; // } // // public ContaView comPassword(String password){ // setPassword(password); // return this; // } // // public ContaView comUsername(String username){ // setUsername(username); // return this; // } // // public ContaView comRoles(String role){ // setRole(role); // return this; // } // // @Override // public String toString() { // return "UserView [username=" + username + ", password=" + password + ", role=" + role + "]"; // } // } // // Path: src/main/java/com/poseidon/model/Users.java // @Entity // public class Users { // // @Id // @GeneratedValue // private Long id; // // private String username; // // private String password; // // private boolean enabled; // // public static Users createUser(ContaView userView) { // Users user = new Users(); // // user.username = userView.getUsername(); // user.password = userView.getPassword(); // user.enabled = true; // // return user; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // @Override // public String toString() { // return "Users [id=" + id + ", username=" + username + ", password=" + password + ", enabled=" + enabled + "]"; // } // // // } // Path: src/main/java/com/poseidon/builder/ContaViewBuilder.java import com.poseidon.model.ContaView; import com.poseidon.model.Users; package com.poseidon.builder; /** * Created by wahrons on 2/5/16. */ public class ContaViewBuilder { private ContaView myObject; public ContaViewBuilder(){ myObject= new ContaView(); } public ContaView build(){ return myObject; }
public ContaViewBuilder convertUsersThroughContaView(Users users){
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ConsultaController.java
// Path: src/main/java/com/poseidon/dao/ConsultaDao.java // @Repository // @Qualifier() // public interface ConsultaDao extends CrudRepository<Consulta, Integer> { // // } // // Path: src/main/java/com/poseidon/model/Consulta.java // @Entity // public class Consulta { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // private Integer id_quiropraxista; // private Integer id_paciente; // private Double valor; // private Date horario_consulta; // private Date data_consulta; // // public Consulta() { // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId_quiropraxista() { // return id_quiropraxista; // } // // public void setId_quiropraxista(Integer id_quiropraxista) { // this.id_quiropraxista = id_quiropraxista; // } // // public Integer getId_paciente() { // return id_paciente; // } // // public void setId_paciente(Integer id_paciente) { // this.id_paciente = id_paciente; // } // // public Double getValor() { // return valor; // } // // public void setValor(Double valor) { // this.valor = valor; // } // // public Date getHorario_consulta() { // return horario_consulta; // } // // public Date getData_consulta() { // return data_consulta; // } // // public void setHorario_consulta(Date horario_consulta) { // this.horario_consulta = horario_consulta; // } // // public void setData_consulta(Date data_consulta) { // this.data_consulta = data_consulta; // } // // public Date getDataConsulta_For_SQL() { // return PoseidonUtils.convertToDate(data_consulta); // } // // public Date getHorarioConsulta_For_SQL() { // return PoseidonUtils.convertToTime(horario_consulta); // } // // }
import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.ConsultaDao; import com.poseidon.model.Consulta; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.logging.Logger;
package com.poseidon.controller; @Controller public class ConsultaController { @Autowired
// Path: src/main/java/com/poseidon/dao/ConsultaDao.java // @Repository // @Qualifier() // public interface ConsultaDao extends CrudRepository<Consulta, Integer> { // // } // // Path: src/main/java/com/poseidon/model/Consulta.java // @Entity // public class Consulta { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // private Integer id_quiropraxista; // private Integer id_paciente; // private Double valor; // private Date horario_consulta; // private Date data_consulta; // // public Consulta() { // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId_quiropraxista() { // return id_quiropraxista; // } // // public void setId_quiropraxista(Integer id_quiropraxista) { // this.id_quiropraxista = id_quiropraxista; // } // // public Integer getId_paciente() { // return id_paciente; // } // // public void setId_paciente(Integer id_paciente) { // this.id_paciente = id_paciente; // } // // public Double getValor() { // return valor; // } // // public void setValor(Double valor) { // this.valor = valor; // } // // public Date getHorario_consulta() { // return horario_consulta; // } // // public Date getData_consulta() { // return data_consulta; // } // // public void setHorario_consulta(Date horario_consulta) { // this.horario_consulta = horario_consulta; // } // // public void setData_consulta(Date data_consulta) { // this.data_consulta = data_consulta; // } // // public Date getDataConsulta_For_SQL() { // return PoseidonUtils.convertToDate(data_consulta); // } // // public Date getHorarioConsulta_For_SQL() { // return PoseidonUtils.convertToTime(horario_consulta); // } // // } // Path: src/main/java/com/poseidon/controller/ConsultaController.java import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.ConsultaDao; import com.poseidon.model.Consulta; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.logging.Logger; package com.poseidon.controller; @Controller public class ConsultaController { @Autowired
private ConsultaDao consultaRepository;
tudoNoob/poseidon
src/main/java/com/poseidon/controller/ConsultaController.java
// Path: src/main/java/com/poseidon/dao/ConsultaDao.java // @Repository // @Qualifier() // public interface ConsultaDao extends CrudRepository<Consulta, Integer> { // // } // // Path: src/main/java/com/poseidon/model/Consulta.java // @Entity // public class Consulta { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // private Integer id_quiropraxista; // private Integer id_paciente; // private Double valor; // private Date horario_consulta; // private Date data_consulta; // // public Consulta() { // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId_quiropraxista() { // return id_quiropraxista; // } // // public void setId_quiropraxista(Integer id_quiropraxista) { // this.id_quiropraxista = id_quiropraxista; // } // // public Integer getId_paciente() { // return id_paciente; // } // // public void setId_paciente(Integer id_paciente) { // this.id_paciente = id_paciente; // } // // public Double getValor() { // return valor; // } // // public void setValor(Double valor) { // this.valor = valor; // } // // public Date getHorario_consulta() { // return horario_consulta; // } // // public Date getData_consulta() { // return data_consulta; // } // // public void setHorario_consulta(Date horario_consulta) { // this.horario_consulta = horario_consulta; // } // // public void setData_consulta(Date data_consulta) { // this.data_consulta = data_consulta; // } // // public Date getDataConsulta_For_SQL() { // return PoseidonUtils.convertToDate(data_consulta); // } // // public Date getHorarioConsulta_For_SQL() { // return PoseidonUtils.convertToTime(horario_consulta); // } // // }
import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.ConsultaDao; import com.poseidon.model.Consulta; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.logging.Logger;
package com.poseidon.controller; @Controller public class ConsultaController { @Autowired private ConsultaDao consultaRepository; private static Logger logger = Logger.getLogger("ConsultaController"); @RequestMapping("/consulta")
// Path: src/main/java/com/poseidon/dao/ConsultaDao.java // @Repository // @Qualifier() // public interface ConsultaDao extends CrudRepository<Consulta, Integer> { // // } // // Path: src/main/java/com/poseidon/model/Consulta.java // @Entity // public class Consulta { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // private Integer id_quiropraxista; // private Integer id_paciente; // private Double valor; // private Date horario_consulta; // private Date data_consulta; // // public Consulta() { // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId_quiropraxista() { // return id_quiropraxista; // } // // public void setId_quiropraxista(Integer id_quiropraxista) { // this.id_quiropraxista = id_quiropraxista; // } // // public Integer getId_paciente() { // return id_paciente; // } // // public void setId_paciente(Integer id_paciente) { // this.id_paciente = id_paciente; // } // // public Double getValor() { // return valor; // } // // public void setValor(Double valor) { // this.valor = valor; // } // // public Date getHorario_consulta() { // return horario_consulta; // } // // public Date getData_consulta() { // return data_consulta; // } // // public void setHorario_consulta(Date horario_consulta) { // this.horario_consulta = horario_consulta; // } // // public void setData_consulta(Date data_consulta) { // this.data_consulta = data_consulta; // } // // public Date getDataConsulta_For_SQL() { // return PoseidonUtils.convertToDate(data_consulta); // } // // public Date getHorarioConsulta_For_SQL() { // return PoseidonUtils.convertToTime(horario_consulta); // } // // } // Path: src/main/java/com/poseidon/controller/ConsultaController.java import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.ConsultaDao; import com.poseidon.model.Consulta; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.logging.Logger; package com.poseidon.controller; @Controller public class ConsultaController { @Autowired private ConsultaDao consultaRepository; private static Logger logger = Logger.getLogger("ConsultaController"); @RequestMapping("/consulta")
@ViewName(name = "Consulta")
tudoNoob/poseidon
src/main/java/com/poseidon/advices/ViewNameProcessAdvice.java
// Path: src/main/java/com/poseidon/exception/ViewNameException.java // public class ViewNameException extends PoseidonException { // // public ViewNameException(String message) { // super(message); // // } // // // }
import com.poseidon.annotation.ViewName; import com.poseidon.exception.ViewNameException; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ModelAndView; import java.lang.reflect.Method;
package com.poseidon.advices; /** * Esta classe ira processar a annotation ViewName. * @author ahrons * */ @Component @Aspect public class ViewNameProcessAdvice { @AfterReturning(pointcut = "execution(* com.poseidon.*.*Controller..*(..)))", returning = "result") public void processViewName(JoinPoint joinPoint, Object result) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); ViewName annotation = method.getAnnotation(ViewName.class); if(annotation == null){ return; } String errorView = annotation.errorView(); if(errorView!= null && !errorView.isEmpty()){ buildModelAndView(result, errorView); return; } String name = annotation.name(); Class<?> returnType = method.getReturnType(); if(!returnType.isAssignableFrom(ModelAndView.class)){
// Path: src/main/java/com/poseidon/exception/ViewNameException.java // public class ViewNameException extends PoseidonException { // // public ViewNameException(String message) { // super(message); // // } // // // } // Path: src/main/java/com/poseidon/advices/ViewNameProcessAdvice.java import com.poseidon.annotation.ViewName; import com.poseidon.exception.ViewNameException; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ModelAndView; import java.lang.reflect.Method; package com.poseidon.advices; /** * Esta classe ira processar a annotation ViewName. * @author ahrons * */ @Component @Aspect public class ViewNameProcessAdvice { @AfterReturning(pointcut = "execution(* com.poseidon.*.*Controller..*(..)))", returning = "result") public void processViewName(JoinPoint joinPoint, Object result) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); ViewName annotation = method.getAnnotation(ViewName.class); if(annotation == null){ return; } String errorView = annotation.errorView(); if(errorView!= null && !errorView.isEmpty()){ buildModelAndView(result, errorView); return; } String name = annotation.name(); Class<?> returnType = method.getReturnType(); if(!returnType.isAssignableFrom(ModelAndView.class)){
throw new ViewNameException("Para usar a annotation @ViewName é preciso que o metodo retorne ModelAndView.");
tudoNoob/poseidon
src/main/java/com/poseidon/controller/QuiropraxistaController.java
// Path: src/main/java/com/poseidon/dao/QuiropraxistaDao.java // @Repository // @Qualifier() // public interface QuiropraxistaDao extends CrudRepository<Quiropraxista, Integer>{ // public Quiropraxista findByNome(String nome); // public Quiropraxista findById(Integer id); // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/com/poseidon/model/Quiropraxista.java // @Entity // public class Quiropraxista { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // private String nome; // // public Quiropraxista() { // // } // // public Quiropraxista(Integer id, String nome) { // this.id = id; // this.nome = nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // public String getNome() { // return nome; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId() { // return id; // } // // @Override // public String toString() { // return "Quiropraxista [id=" + id + ", nome=" + nome + "]"; // } // }
import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.QuiropraxistaDao; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import com.poseidon.model.Quiropraxista; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger;
package com.poseidon.controller; @Controller @RequestMapping("/admin") public class QuiropraxistaController extends ControllerBase { public static final String REDIRECT_ADMIN_QUIROPRAXISTA = "redirect:/admin/quiropraxista";
// Path: src/main/java/com/poseidon/dao/QuiropraxistaDao.java // @Repository // @Qualifier() // public interface QuiropraxistaDao extends CrudRepository<Quiropraxista, Integer>{ // public Quiropraxista findByNome(String nome); // public Quiropraxista findById(Integer id); // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/com/poseidon/model/Quiropraxista.java // @Entity // public class Quiropraxista { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // private String nome; // // public Quiropraxista() { // // } // // public Quiropraxista(Integer id, String nome) { // this.id = id; // this.nome = nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // public String getNome() { // return nome; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId() { // return id; // } // // @Override // public String toString() { // return "Quiropraxista [id=" + id + ", nome=" + nome + "]"; // } // } // Path: src/main/java/com/poseidon/controller/QuiropraxistaController.java import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.QuiropraxistaDao; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import com.poseidon.model.Quiropraxista; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger; package com.poseidon.controller; @Controller @RequestMapping("/admin") public class QuiropraxistaController extends ControllerBase { public static final String REDIRECT_ADMIN_QUIROPRAXISTA = "redirect:/admin/quiropraxista";
public static final String QUIROPRAXISTA_VIEW_NAME = "Quiropraxista";
tudoNoob/poseidon
src/main/java/com/poseidon/controller/QuiropraxistaController.java
// Path: src/main/java/com/poseidon/dao/QuiropraxistaDao.java // @Repository // @Qualifier() // public interface QuiropraxistaDao extends CrudRepository<Quiropraxista, Integer>{ // public Quiropraxista findByNome(String nome); // public Quiropraxista findById(Integer id); // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/com/poseidon/model/Quiropraxista.java // @Entity // public class Quiropraxista { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // private String nome; // // public Quiropraxista() { // // } // // public Quiropraxista(Integer id, String nome) { // this.id = id; // this.nome = nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // public String getNome() { // return nome; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId() { // return id; // } // // @Override // public String toString() { // return "Quiropraxista [id=" + id + ", nome=" + nome + "]"; // } // }
import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.QuiropraxistaDao; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import com.poseidon.model.Quiropraxista; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger;
package com.poseidon.controller; @Controller @RequestMapping("/admin") public class QuiropraxistaController extends ControllerBase { public static final String REDIRECT_ADMIN_QUIROPRAXISTA = "redirect:/admin/quiropraxista"; public static final String QUIROPRAXISTA_VIEW_NAME = "Quiropraxista"; @Autowired
// Path: src/main/java/com/poseidon/dao/QuiropraxistaDao.java // @Repository // @Qualifier() // public interface QuiropraxistaDao extends CrudRepository<Quiropraxista, Integer>{ // public Quiropraxista findByNome(String nome); // public Quiropraxista findById(Integer id); // } // // Path: src/main/java/com/poseidon/enums/CRUDViewEnum.java // public enum CRUDViewEnum { // // IS_SAVE("isSave"), // IS_DELETE("isDelete"), // IS_UPDATE("isUpdate"), // IS_SEARCH("isSearch"); // // // // private String operation; // // CRUDViewEnum(String operation) { // this.operation=operation; // } // // public String getOperation() { // return operation; // } // } // // Path: src/main/java/com/poseidon/model/CRUDView.java // public class CRUDView { // // private String isSave; // // private String isUpdate; // // private String isSearch; // // private String isDelete; // // private String isToShowAll; // // public String getIsToShowAll() { // return isToShowAll; // } // // public void setIsToShowAll(String isToShowAll) { // this.isToShowAll = isToShowAll; // } // // public String getIsSave() { // return isSave; // } // // public void setIsSave(String isSave) { // this.isSave = isSave; // } // // public String getIsUpdate() { // return isUpdate; // } // // public void setIsUpdate(String isUpdate) { // this.isUpdate = isUpdate; // } // // public String getIsSearch() { // return isSearch; // } // // public void setIsSearch(String isSearch) { // this.isSearch = isSearch; // } // // public String getIsDelete() { // return isDelete; // } // // public void setIsDelete(String isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/com/poseidon/model/Quiropraxista.java // @Entity // public class Quiropraxista { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // private String nome; // // public Quiropraxista() { // // } // // public Quiropraxista(Integer id, String nome) { // this.id = id; // this.nome = nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // public String getNome() { // return nome; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getId() { // return id; // } // // @Override // public String toString() { // return "Quiropraxista [id=" + id + ", nome=" + nome + "]"; // } // } // Path: src/main/java/com/poseidon/controller/QuiropraxistaController.java import com.poseidon.annotation.NotNullArgs; import com.poseidon.annotation.ViewName; import com.poseidon.dao.QuiropraxistaDao; import com.poseidon.enums.CRUDViewEnum; import com.poseidon.model.CRUDView; import com.poseidon.model.Quiropraxista; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; import java.util.logging.Logger; package com.poseidon.controller; @Controller @RequestMapping("/admin") public class QuiropraxistaController extends ControllerBase { public static final String REDIRECT_ADMIN_QUIROPRAXISTA = "redirect:/admin/quiropraxista"; public static final String QUIROPRAXISTA_VIEW_NAME = "Quiropraxista"; @Autowired
QuiropraxistaDao quiropraxistaRepository;