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
|
---|---|---|---|---|---|---|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/ItemTargetCapabilityProvider.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/network/IItemNetwork.java
// public interface IItemNetwork extends IPositionedAddonsNetworkIngredients<ItemStack, Integer> {
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/capability/network/ItemNetworkConfig.java
// public class ItemNetworkConfig extends CapabilityConfig<IItemNetwork> {
//
// @CapabilityInject(IItemNetwork.class)
// public static Capability<IItemNetwork> CAPABILITY = null;
//
// public ItemNetworkConfig() {
// super(
// CommonCapabilities._instance,
// "itemNetwork",
// IItemNetwork.class,
// new DefaultCapabilityStorage<IItemNetwork>(),
// () -> new ItemNetwork(null)
// );
// }
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/predicate/IngredientPredicate.java
// public abstract class IngredientPredicate<T, M> implements Predicate<T>, ITunnelTransfer {
//
// private final IngredientComponent<T, M> ingredientComponent;
// private final T instance;
// private final M matchFlags;
// private final boolean blacklist;
// private final boolean empty;
// private final int maxQuantity;
// private final boolean exactQuantity;
//
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// T instance, M matchFlags, boolean blacklist, boolean empty,
// int maxQuantity, boolean exactQuantity) {
// this.ingredientComponent = ingredientComponent;
// this.instance = instance;
// this.matchFlags = matchFlags;
// this.blacklist = blacklist;
// this.empty = empty;
// this.maxQuantity = maxQuantity;
// this.exactQuantity = exactQuantity;
// }
//
// // Note: implementors of this method *should* override equals and hashcode.
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// boolean blacklist, boolean empty, int maxQuantity, boolean exactQuantity) {
// this(ingredientComponent, ingredientComponent.getMatcher().getEmptyInstance(), null,
// blacklist, empty, maxQuantity, exactQuantity);
// }
//
// public IngredientComponent<T, M> getIngredientComponent() {
// return ingredientComponent;
// }
//
// @Nonnull
// public T getInstance() {
// return instance;
// }
//
// public M getMatchFlags() {
// return matchFlags;
// }
//
// public boolean hasMatchFlags() {
// return matchFlags != null && !blacklist;
// }
//
// public boolean isBlacklist() {
// return blacklist;
// }
//
// public boolean isEmpty() {
// return empty;
// }
//
// public int getMaxQuantity() {
// return maxQuantity;
// }
//
// public boolean isExactQuantity() {
// return exactQuantity;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof IngredientPredicate)) {
// return false;
// }
// IngredientPredicate that = (IngredientPredicate) obj;
// return this.ingredientComponent == that.ingredientComponent
// && this.ingredientComponent.getMatcher().matchesExactly(this.instance, (T) that.instance)
// && Objects.equals(this.matchFlags, that.matchFlags)
// && this.blacklist == that.blacklist
// && this.empty == that.empty
// && this.maxQuantity == that.maxQuantity
// && this.exactQuantity == that.exactQuantity;
// }
//
// @Override
// public int hashCode() {
// return ingredientComponent.hashCode()
// ^ ingredientComponent.getMatcher().hash(instance)
// ^ Objects.hashCode(matchFlags)
// ^ (blacklist ? 1 : 0)
// ^ (empty ? 2 : 4)
// ^ maxQuantity
// ^ (exactQuantity ? 8 : 16);
// }
//
// public static enum EmptyBehaviour {
// ANY,
// NONE;
//
// public static EmptyBehaviour fromBoolean(boolean emptyIsAny) {
// return emptyIsAny ? ANY : NONE;
// }
// }
// }
|
import net.minecraft.item.ItemStack;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.api.network.IItemNetwork;
import org.cyclops.integratedtunnels.capability.network.ItemNetworkConfig;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import org.cyclops.integratedtunnels.core.predicate.IngredientPredicate;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public class ItemTargetCapabilityProvider extends ChanneledTargetCapabilityProvider<IItemNetwork, ItemStack, Integer>
implements IItemTarget {
private final ITunnelConnection connection;
private final int slot;
private final IngredientPredicate<ItemStack, Integer> itemStackMatcher;
private final PartTarget partTarget;
private final IAspectProperties properties;
public ItemTargetCapabilityProvider(ITunnelTransfer transfer, INetwork network, @Nullable ICapabilityProvider capabilityProvider,
Direction side, int slot,
IngredientPredicate<ItemStack, Integer> itemStackMatcher, PartTarget partTarget,
IAspectProperties properties, @Nullable PartStateRoundRobin<?> partState) {
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/network/IItemNetwork.java
// public interface IItemNetwork extends IPositionedAddonsNetworkIngredients<ItemStack, Integer> {
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/capability/network/ItemNetworkConfig.java
// public class ItemNetworkConfig extends CapabilityConfig<IItemNetwork> {
//
// @CapabilityInject(IItemNetwork.class)
// public static Capability<IItemNetwork> CAPABILITY = null;
//
// public ItemNetworkConfig() {
// super(
// CommonCapabilities._instance,
// "itemNetwork",
// IItemNetwork.class,
// new DefaultCapabilityStorage<IItemNetwork>(),
// () -> new ItemNetwork(null)
// );
// }
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/predicate/IngredientPredicate.java
// public abstract class IngredientPredicate<T, M> implements Predicate<T>, ITunnelTransfer {
//
// private final IngredientComponent<T, M> ingredientComponent;
// private final T instance;
// private final M matchFlags;
// private final boolean blacklist;
// private final boolean empty;
// private final int maxQuantity;
// private final boolean exactQuantity;
//
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// T instance, M matchFlags, boolean blacklist, boolean empty,
// int maxQuantity, boolean exactQuantity) {
// this.ingredientComponent = ingredientComponent;
// this.instance = instance;
// this.matchFlags = matchFlags;
// this.blacklist = blacklist;
// this.empty = empty;
// this.maxQuantity = maxQuantity;
// this.exactQuantity = exactQuantity;
// }
//
// // Note: implementors of this method *should* override equals and hashcode.
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// boolean blacklist, boolean empty, int maxQuantity, boolean exactQuantity) {
// this(ingredientComponent, ingredientComponent.getMatcher().getEmptyInstance(), null,
// blacklist, empty, maxQuantity, exactQuantity);
// }
//
// public IngredientComponent<T, M> getIngredientComponent() {
// return ingredientComponent;
// }
//
// @Nonnull
// public T getInstance() {
// return instance;
// }
//
// public M getMatchFlags() {
// return matchFlags;
// }
//
// public boolean hasMatchFlags() {
// return matchFlags != null && !blacklist;
// }
//
// public boolean isBlacklist() {
// return blacklist;
// }
//
// public boolean isEmpty() {
// return empty;
// }
//
// public int getMaxQuantity() {
// return maxQuantity;
// }
//
// public boolean isExactQuantity() {
// return exactQuantity;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof IngredientPredicate)) {
// return false;
// }
// IngredientPredicate that = (IngredientPredicate) obj;
// return this.ingredientComponent == that.ingredientComponent
// && this.ingredientComponent.getMatcher().matchesExactly(this.instance, (T) that.instance)
// && Objects.equals(this.matchFlags, that.matchFlags)
// && this.blacklist == that.blacklist
// && this.empty == that.empty
// && this.maxQuantity == that.maxQuantity
// && this.exactQuantity == that.exactQuantity;
// }
//
// @Override
// public int hashCode() {
// return ingredientComponent.hashCode()
// ^ ingredientComponent.getMatcher().hash(instance)
// ^ Objects.hashCode(matchFlags)
// ^ (blacklist ? 1 : 0)
// ^ (empty ? 2 : 4)
// ^ maxQuantity
// ^ (exactQuantity ? 8 : 16);
// }
//
// public static enum EmptyBehaviour {
// ANY,
// NONE;
//
// public static EmptyBehaviour fromBoolean(boolean emptyIsAny) {
// return emptyIsAny ? ANY : NONE;
// }
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/ItemTargetCapabilityProvider.java
import net.minecraft.item.ItemStack;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.api.network.IItemNetwork;
import org.cyclops.integratedtunnels.capability.network.ItemNetworkConfig;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import org.cyclops.integratedtunnels.core.predicate.IngredientPredicate;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public class ItemTargetCapabilityProvider extends ChanneledTargetCapabilityProvider<IItemNetwork, ItemStack, Integer>
implements IItemTarget {
private final ITunnelConnection connection;
private final int slot;
private final IngredientPredicate<ItemStack, Integer> itemStackMatcher;
private final PartTarget partTarget;
private final IAspectProperties properties;
public ItemTargetCapabilityProvider(ITunnelTransfer transfer, INetwork network, @Nullable ICapabilityProvider capabilityProvider,
Direction side, int slot,
IngredientPredicate<ItemStack, Integer> itemStackMatcher, PartTarget partTarget,
IAspectProperties properties, @Nullable PartStateRoundRobin<?> partState) {
|
super(network, capabilityProvider, side, network.getCapability(ItemNetworkConfig.CAPABILITY).orElse(null), partState,
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/TunnelAspects.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
// public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
// public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
// super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
// return FluidNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<FluidStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeFluidStack.ValueFluidStack fluidStack = variables.getValue(0, ValueTypes.OBJECT_FLUIDSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(fluidStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
// public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
// public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
// super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
// return ItemNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(itemStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
|
import com.google.common.collect.Iterators;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.commoncapabilities.api.capability.fluidhandler.FluidMatch;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectRead;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite;
import org.cyclops.integrateddynamics.core.evaluate.operator.Operators;
import org.cyclops.integrateddynamics.core.evaluate.operator.PositionedOperator;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integratedtunnels.Reference;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexFluid;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexItem;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* Collection of all tunnel aspects.
* @author rubensworks
*/
public class TunnelAspects {
public static void load() {}
public static final class Read {
public static final class Item {
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNT = TunnelAspectReadBuilders.Network.Item.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNELINDEX)
.handle(channel -> channel.stream().mapToLong(ItemStack::getCount).sum())
.handle(AspectReadBuilders.PROP_GET_LONG, "count")
.buildRead();
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNTMAX = TunnelAspectReadBuilders.Network.Item.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNEL)
.handle(IIngredientComponentStorage::getMaxQuantity)
.handle(AspectReadBuilders.PROP_GET_LONG, "countmax")
.buildRead();
public static final IAspectRead<ValueTypeList.ValueList, ValueTypeList>
LIST_ITEMSTACKS = TunnelAspectReadBuilders.Network.Item.BUILDER_LIST
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_LIST, "itemstacks")
.buildRead();
public static final IAspectRead<ValueTypeOperator.ValueOperator, ValueTypeOperator>
OPERATOR_GETITEMCOUNT = TunnelAspectReadBuilders.Network.Item.BUILDER_OPERATOR
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
// public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
// public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
// super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
// return FluidNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<FluidStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeFluidStack.ValueFluidStack fluidStack = variables.getValue(0, ValueTypes.OBJECT_FLUIDSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(fluidStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
// public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
// public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
// super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
// return ItemNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(itemStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/TunnelAspects.java
import com.google.common.collect.Iterators;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.commoncapabilities.api.capability.fluidhandler.FluidMatch;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectRead;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite;
import org.cyclops.integrateddynamics.core.evaluate.operator.Operators;
import org.cyclops.integrateddynamics.core.evaluate.operator.PositionedOperator;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integratedtunnels.Reference;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexFluid;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexItem;
package org.cyclops.integratedtunnels.part.aspect;
/**
* Collection of all tunnel aspects.
* @author rubensworks
*/
public class TunnelAspects {
public static void load() {}
public static final class Read {
public static final class Item {
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNT = TunnelAspectReadBuilders.Network.Item.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNELINDEX)
.handle(channel -> channel.stream().mapToLong(ItemStack::getCount).sum())
.handle(AspectReadBuilders.PROP_GET_LONG, "count")
.buildRead();
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNTMAX = TunnelAspectReadBuilders.Network.Item.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNEL)
.handle(IIngredientComponentStorage::getMaxQuantity)
.handle(AspectReadBuilders.PROP_GET_LONG, "countmax")
.buildRead();
public static final IAspectRead<ValueTypeList.ValueList, ValueTypeList>
LIST_ITEMSTACKS = TunnelAspectReadBuilders.Network.Item.BUILDER_LIST
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_LIST, "itemstacks")
.buildRead();
public static final IAspectRead<ValueTypeOperator.ValueOperator, ValueTypeOperator>
OPERATOR_GETITEMCOUNT = TunnelAspectReadBuilders.Network.Item.BUILDER_OPERATOR
|
.handle(input -> ValueTypeOperator.ValueOperator.of(new PositionedOperatorIngredientIndexItem(
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/TunnelAspects.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
// public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
// public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
// super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
// return FluidNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<FluidStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeFluidStack.ValueFluidStack fluidStack = variables.getValue(0, ValueTypes.OBJECT_FLUIDSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(fluidStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
// public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
// public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
// super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
// return ItemNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(itemStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
|
import com.google.common.collect.Iterators;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.commoncapabilities.api.capability.fluidhandler.FluidMatch;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectRead;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite;
import org.cyclops.integrateddynamics.core.evaluate.operator.Operators;
import org.cyclops.integrateddynamics.core.evaluate.operator.PositionedOperator;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integratedtunnels.Reference;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexFluid;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexItem;
|
.handle(channel -> channel.stream().mapToLong(ItemStack::getCount).sum())
.handle(AspectReadBuilders.PROP_GET_LONG, "count")
.buildRead();
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNTMAX = TunnelAspectReadBuilders.Network.Item.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNEL)
.handle(IIngredientComponentStorage::getMaxQuantity)
.handle(AspectReadBuilders.PROP_GET_LONG, "countmax")
.buildRead();
public static final IAspectRead<ValueTypeList.ValueList, ValueTypeList>
LIST_ITEMSTACKS = TunnelAspectReadBuilders.Network.Item.BUILDER_LIST
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_LIST, "itemstacks")
.buildRead();
public static final IAspectRead<ValueTypeOperator.ValueOperator, ValueTypeOperator>
OPERATOR_GETITEMCOUNT = TunnelAspectReadBuilders.Network.Item.BUILDER_OPERATOR
.handle(input -> ValueTypeOperator.ValueOperator.of(new PositionedOperatorIngredientIndexItem(
input.getLeft().getTarget().getPos(),
input.getLeft().getTarget().getSide(),
input.getRight().getValue(AspectReadBuilders.Network.PROPERTY_CHANNEL).getRawValue()
)))
.appendKind("countbyitem")
.buildRead();
public static final IAspectRead<ValueTypeInteger.ValueInteger, ValueTypeInteger>
INTEGER_INTERFACES = TunnelAspectReadBuilders.Network.Item.BUILDER_INTEGER
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNELINDEX)
.handle(channel -> Iterators.size(channel.getPositions(ItemStack.EMPTY, ItemMatch.ANY)))
.handle(AspectReadBuilders.PROP_GET_INTEGER, "interfaces")
.buildRead();
static {
Operators.REGISTRY.registerSerializer(new PositionedOperator.Serializer(
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
// public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
// public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
// super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
// return FluidNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<FluidStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeFluidStack.ValueFluidStack fluidStack = variables.getValue(0, ValueTypes.OBJECT_FLUIDSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(fluidStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
// public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
// public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
// super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
// return ItemNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(itemStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/TunnelAspects.java
import com.google.common.collect.Iterators;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.commoncapabilities.api.capability.fluidhandler.FluidMatch;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectRead;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite;
import org.cyclops.integrateddynamics.core.evaluate.operator.Operators;
import org.cyclops.integrateddynamics.core.evaluate.operator.PositionedOperator;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integratedtunnels.Reference;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexFluid;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexItem;
.handle(channel -> channel.stream().mapToLong(ItemStack::getCount).sum())
.handle(AspectReadBuilders.PROP_GET_LONG, "count")
.buildRead();
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNTMAX = TunnelAspectReadBuilders.Network.Item.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNEL)
.handle(IIngredientComponentStorage::getMaxQuantity)
.handle(AspectReadBuilders.PROP_GET_LONG, "countmax")
.buildRead();
public static final IAspectRead<ValueTypeList.ValueList, ValueTypeList>
LIST_ITEMSTACKS = TunnelAspectReadBuilders.Network.Item.BUILDER_LIST
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_LIST, "itemstacks")
.buildRead();
public static final IAspectRead<ValueTypeOperator.ValueOperator, ValueTypeOperator>
OPERATOR_GETITEMCOUNT = TunnelAspectReadBuilders.Network.Item.BUILDER_OPERATOR
.handle(input -> ValueTypeOperator.ValueOperator.of(new PositionedOperatorIngredientIndexItem(
input.getLeft().getTarget().getPos(),
input.getLeft().getTarget().getSide(),
input.getRight().getValue(AspectReadBuilders.Network.PROPERTY_CHANNEL).getRawValue()
)))
.appendKind("countbyitem")
.buildRead();
public static final IAspectRead<ValueTypeInteger.ValueInteger, ValueTypeInteger>
INTEGER_INTERFACES = TunnelAspectReadBuilders.Network.Item.BUILDER_INTEGER
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNELINDEX)
.handle(channel -> Iterators.size(channel.getPositions(ItemStack.EMPTY, ItemMatch.ANY)))
.handle(AspectReadBuilders.PROP_GET_INTEGER, "interfaces")
.buildRead();
static {
Operators.REGISTRY.registerSerializer(new PositionedOperator.Serializer(
|
PositionedOperatorIngredientIndexItem.class, new ResourceLocation(Reference.MOD_ID, "positioned_ingredient_index_item")));
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/TunnelAspects.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
// public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
// public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
// super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
// return FluidNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<FluidStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeFluidStack.ValueFluidStack fluidStack = variables.getValue(0, ValueTypes.OBJECT_FLUIDSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(fluidStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
// public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
// public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
// super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
// return ItemNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(itemStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
|
import com.google.common.collect.Iterators;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.commoncapabilities.api.capability.fluidhandler.FluidMatch;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectRead;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite;
import org.cyclops.integrateddynamics.core.evaluate.operator.Operators;
import org.cyclops.integrateddynamics.core.evaluate.operator.PositionedOperator;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integratedtunnels.Reference;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexFluid;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexItem;
|
INTEGER_INTERFACES = TunnelAspectReadBuilders.Network.Item.BUILDER_INTEGER
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNELINDEX)
.handle(channel -> Iterators.size(channel.getPositions(ItemStack.EMPTY, ItemMatch.ANY)))
.handle(AspectReadBuilders.PROP_GET_INTEGER, "interfaces")
.buildRead();
static {
Operators.REGISTRY.registerSerializer(new PositionedOperator.Serializer(
PositionedOperatorIngredientIndexItem.class, new ResourceLocation(Reference.MOD_ID, "positioned_ingredient_index_item")));
}
}
public static final class Fluid {
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNT = TunnelAspectReadBuilders.Network.Fluid.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Fluid.PROP_GET_CHANNELINDEX)
.handle(channel -> channel.stream().mapToLong(FluidStack::getAmount).sum())
.handle(AspectReadBuilders.PROP_GET_LONG, "count")
.buildRead();
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNTMAX = TunnelAspectReadBuilders.Network.Fluid.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Fluid.PROP_GET_CHANNEL)
.handle(IIngredientComponentStorage::getMaxQuantity)
.handle(AspectReadBuilders.PROP_GET_LONG, "countmax")
.buildRead();
public static final IAspectRead<ValueTypeList.ValueList, ValueTypeList>
LIST_FLUIDSTACKS = TunnelAspectReadBuilders.Network.Fluid.BUILDER_LIST
.handle(TunnelAspectReadBuilders.Network.Fluid.PROP_GET_LIST, "fluidstacks")
.buildRead();
public static final IAspectRead<ValueTypeOperator.ValueOperator, ValueTypeOperator>
OPERATOR_GETFLUIDCOUNT = TunnelAspectReadBuilders.Network.Fluid.BUILDER_OPERATOR
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
// public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
// public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
// super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
// return FluidNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<FluidStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeFluidStack.ValueFluidStack fluidStack = variables.getValue(0, ValueTypes.OBJECT_FLUIDSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(fluidStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
// public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
// public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
// super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
// }
//
// @Override
// protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
// return ItemNetworkConfig.CAPABILITY;
// }
//
// public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
// @Override
// public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
// ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
// return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
// .map(index -> index.getQuantity(itemStack.getRawValue()))
// .orElse(0L));
// }
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/TunnelAspects.java
import com.google.common.collect.Iterators;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.commoncapabilities.api.capability.fluidhandler.FluidMatch;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectRead;
import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite;
import org.cyclops.integrateddynamics.core.evaluate.operator.Operators;
import org.cyclops.integrateddynamics.core.evaluate.operator.PositionedOperator;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integratedtunnels.Reference;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexFluid;
import org.cyclops.integratedtunnels.part.aspect.operator.PositionedOperatorIngredientIndexItem;
INTEGER_INTERFACES = TunnelAspectReadBuilders.Network.Item.BUILDER_INTEGER
.handle(TunnelAspectReadBuilders.Network.Item.PROP_GET_CHANNELINDEX)
.handle(channel -> Iterators.size(channel.getPositions(ItemStack.EMPTY, ItemMatch.ANY)))
.handle(AspectReadBuilders.PROP_GET_INTEGER, "interfaces")
.buildRead();
static {
Operators.REGISTRY.registerSerializer(new PositionedOperator.Serializer(
PositionedOperatorIngredientIndexItem.class, new ResourceLocation(Reference.MOD_ID, "positioned_ingredient_index_item")));
}
}
public static final class Fluid {
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNT = TunnelAspectReadBuilders.Network.Fluid.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Fluid.PROP_GET_CHANNELINDEX)
.handle(channel -> channel.stream().mapToLong(FluidStack::getAmount).sum())
.handle(AspectReadBuilders.PROP_GET_LONG, "count")
.buildRead();
public static final IAspectRead<ValueTypeLong.ValueLong, ValueTypeLong>
LONG_COUNTMAX = TunnelAspectReadBuilders.Network.Fluid.BUILDER_LONG
.handle(TunnelAspectReadBuilders.Network.Fluid.PROP_GET_CHANNEL)
.handle(IIngredientComponentStorage::getMaxQuantity)
.handle(AspectReadBuilders.PROP_GET_LONG, "countmax")
.buildRead();
public static final IAspectRead<ValueTypeList.ValueList, ValueTypeList>
LIST_FLUIDSTACKS = TunnelAspectReadBuilders.Network.Fluid.BUILDER_LIST
.handle(TunnelAspectReadBuilders.Network.Fluid.PROP_GET_LIST, "fluidstacks")
.buildRead();
public static final IAspectRead<ValueTypeOperator.ValueOperator, ValueTypeOperator>
OPERATOR_GETFLUIDCOUNT = TunnelAspectReadBuilders.Network.Fluid.BUILDER_OPERATOR
|
.handle(input -> ValueTypeOperator.ValueOperator.of(new PositionedOperatorIngredientIndexFluid(
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/proxy/CommonProxy.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
|
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.cyclopscore.proxy.CommonProxyComponent;
import org.cyclops.integratedtunnels.IntegratedTunnels;
|
package org.cyclops.integratedtunnels.proxy;
/**
* Proxy for server and client side.
* @author rubensworks
*
*/
public class CommonProxy extends CommonProxyComponent {
@Override
public ModBase getMod() {
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/proxy/CommonProxy.java
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.cyclopscore.proxy.CommonProxyComponent;
import org.cyclops.integratedtunnels.IntegratedTunnels;
package org.cyclops.integratedtunnels.proxy;
/**
* Proxy for server and client side.
* @author rubensworks
*
*/
public class CommonProxy extends CommonProxyComponent {
@Override
public ModBase getMod() {
|
return IntegratedTunnels._instance;
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/core/part/ContainerInterfaceSettingsConfig.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
|
import net.minecraft.client.gui.IHasContainer;
import net.minecraft.client.gui.ScreenManager;
import net.minecraft.client.gui.screen.Screen;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.cyclops.cyclopscore.client.gui.ScreenFactorySafe;
import org.cyclops.cyclopscore.config.extendedconfig.GuiConfig;
import org.cyclops.cyclopscore.inventory.container.ContainerTypeData;
import org.cyclops.integrateddynamics.core.client.gui.container.ContainerScreenPartSettings;
import org.cyclops.integratedtunnels.IntegratedTunnels;
|
package org.cyclops.integratedtunnels.core.part;
/**
* Config for {@link ContainerInterfaceSettings}.
* @author rubensworks
*/
public class ContainerInterfaceSettingsConfig extends GuiConfig<ContainerInterfaceSettings> {
public ContainerInterfaceSettingsConfig() {
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/ContainerInterfaceSettingsConfig.java
import net.minecraft.client.gui.IHasContainer;
import net.minecraft.client.gui.ScreenManager;
import net.minecraft.client.gui.screen.Screen;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.cyclops.cyclopscore.client.gui.ScreenFactorySafe;
import org.cyclops.cyclopscore.config.extendedconfig.GuiConfig;
import org.cyclops.cyclopscore.inventory.container.ContainerTypeData;
import org.cyclops.integrateddynamics.core.client.gui.container.ContainerScreenPartSettings;
import org.cyclops.integratedtunnels.IntegratedTunnels;
package org.cyclops.integratedtunnels.core.part;
/**
* Config for {@link ContainerInterfaceSettings}.
* @author rubensworks
*/
public class ContainerInterfaceSettingsConfig extends GuiConfig<ContainerInterfaceSettings> {
public ContainerInterfaceSettingsConfig() {
|
super(IntegratedTunnels._instance,
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/RegistryEntries.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/ContainerInterfaceSettings.java
// public class ContainerInterfaceSettings extends ContainerPartSettings {
//
// private final int lastChannelInterfaceValueId;
//
// public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, PacketBuffer packetBuffer) {
// this(id, playerInventory, new Inventory(0), PartHelpers.readPartTarget(packetBuffer), Optional.empty(), PartHelpers.readPart(packetBuffer));
// }
//
// public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, IInventory inventory,
// PartTarget target, Optional<IPartContainer> partContainer, IPartType partType) {
// super(RegistryEntries.CONTAINER_INTERFACE_SETTINGS, id, playerInventory, inventory, target, partContainer, partType);
// lastChannelInterfaceValueId = getNextValueId();
// }
//
// @Override
// protected int getPlayerInventoryOffsetY() {
// return 134;
// }
//
// @Override
// protected void initializeValues() {
// super.initializeValues();
// ValueNotifierHelpers.setValue(this, lastChannelInterfaceValueId, ((IPartTypeInterfacePositionedAddon.IState) getPartState()).getChannelInterface());
// }
//
// public int getLastChannelInterfaceValueId() {
// return lastChannelInterfaceValueId;
// }
//
// public int getLastChannelInterfaceValue() {
// return ValueNotifierHelpers.getValueInt(this, lastChannelInterfaceValueId);
// }
//
// @Override
// protected void updatePartSettings() {
// super.updatePartSettings();
// ((IPartTypeInterfacePositionedAddon.IState) getPartState()).setChannelInterface(getLastChannelInterfaceValue());
// }
// }
|
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.item.Item;
import net.minecraftforge.registries.ObjectHolder;
import org.cyclops.integratedtunnels.core.part.ContainerInterfaceSettings;
|
package org.cyclops.integratedtunnels;
/**
* Referenced registry entries.
* @author rubensworks
*/
public class RegistryEntries {
@ObjectHolder("integratedtunnels:part_interface_item")
public static final Item ITEM_PART_INTERFACE = null;
@ObjectHolder("integratedtunnels:dummy_pickaxe")
public static final Item ITEM_DUMMY_PICKAXE = null;
@ObjectHolder("integratedtunnels:part_interface_settings")
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/ContainerInterfaceSettings.java
// public class ContainerInterfaceSettings extends ContainerPartSettings {
//
// private final int lastChannelInterfaceValueId;
//
// public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, PacketBuffer packetBuffer) {
// this(id, playerInventory, new Inventory(0), PartHelpers.readPartTarget(packetBuffer), Optional.empty(), PartHelpers.readPart(packetBuffer));
// }
//
// public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, IInventory inventory,
// PartTarget target, Optional<IPartContainer> partContainer, IPartType partType) {
// super(RegistryEntries.CONTAINER_INTERFACE_SETTINGS, id, playerInventory, inventory, target, partContainer, partType);
// lastChannelInterfaceValueId = getNextValueId();
// }
//
// @Override
// protected int getPlayerInventoryOffsetY() {
// return 134;
// }
//
// @Override
// protected void initializeValues() {
// super.initializeValues();
// ValueNotifierHelpers.setValue(this, lastChannelInterfaceValueId, ((IPartTypeInterfacePositionedAddon.IState) getPartState()).getChannelInterface());
// }
//
// public int getLastChannelInterfaceValueId() {
// return lastChannelInterfaceValueId;
// }
//
// public int getLastChannelInterfaceValue() {
// return ValueNotifierHelpers.getValueInt(this, lastChannelInterfaceValueId);
// }
//
// @Override
// protected void updatePartSettings() {
// super.updatePartSettings();
// ((IPartTypeInterfacePositionedAddon.IState) getPartState()).setChannelInterface(getLastChannelInterfaceValue());
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/RegistryEntries.java
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.item.Item;
import net.minecraftforge.registries.ObjectHolder;
import org.cyclops.integratedtunnels.core.part.ContainerInterfaceSettings;
package org.cyclops.integratedtunnels;
/**
* Referenced registry entries.
* @author rubensworks
*/
public class RegistryEntries {
@ObjectHolder("integratedtunnels:part_interface_item")
public static final Item ITEM_PART_INTERFACE = null;
@ObjectHolder("integratedtunnels:dummy_pickaxe")
public static final Item ITEM_DUMMY_PICKAXE = null;
@ObjectHolder("integratedtunnels:part_interface_settings")
|
public static final ContainerType<ContainerInterfaceSettings> CONTAINER_INTERFACE_SETTINGS = null;
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/core/part/ContainerScreenInterfaceSettings.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
|
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import org.cyclops.cyclopscore.client.gui.component.input.WidgetNumberField;
import org.cyclops.cyclopscore.helper.Helpers;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.cyclopscore.helper.ValueNotifierHelpers;
import org.cyclops.integrateddynamics.core.client.gui.container.ContainerScreenPartSettings;
import org.cyclops.integratedtunnels.Reference;
import org.lwjgl.glfw.GLFW;
|
package org.cyclops.integratedtunnels.core.part;
/**
* @author rubensworks
*/
public class ContainerScreenInterfaceSettings extends ContainerScreenPartSettings<ContainerInterfaceSettings> {
private WidgetNumberField numberFieldChannelInterface = null;
public ContainerScreenInterfaceSettings(ContainerInterfaceSettings container, PlayerInventory inventory, ITextComponent title) {
super(container, inventory, title);
}
@Override
protected ResourceLocation constructGuiTexture() {
|
// Path: src/main/java/org/cyclops/integratedtunnels/Reference.java
// @SuppressWarnings("javadoc")
// public class Reference {
//
// // Mod info
// public static final String MOD_ID = "integratedtunnels";
// public static final String GA_TRACKING_ID = "UA-65307010-10";
// public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/IntegratedTunnels.txt";
//
// // MOD ID's
// public static final String MOD_FORGE = "forge";
// public static final String MOD_CYCLOPSCORE = "cyclopscore";
// public static final String MOD_INTEGRATEDDYNAMICS = "integrateddynamics";
// }
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/ContainerScreenInterfaceSettings.java
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import org.cyclops.cyclopscore.client.gui.component.input.WidgetNumberField;
import org.cyclops.cyclopscore.helper.Helpers;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.cyclopscore.helper.ValueNotifierHelpers;
import org.cyclops.integrateddynamics.core.client.gui.container.ContainerScreenPartSettings;
import org.cyclops.integratedtunnels.Reference;
import org.lwjgl.glfw.GLFW;
package org.cyclops.integratedtunnels.core.part;
/**
* @author rubensworks
*/
public class ContainerScreenInterfaceSettings extends ContainerScreenPartSettings<ContainerInterfaceSettings> {
private WidgetNumberField numberFieldChannelInterface = null;
public ContainerScreenInterfaceSettings(ContainerInterfaceSettings container, PlayerInventory inventory, ITextComponent title) {
super(container, inventory, title);
}
@Override
protected ResourceLocation constructGuiTexture() {
|
return new ResourceLocation(Reference.MOD_ID, "textures/gui/part_interface_settings.png");
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/ChanneledTarget.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
|
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.network.IPartPosIteratorHandler;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetwork;
import org.cyclops.integrateddynamics.core.network.PartPosIteratorHandlerRoundRobin;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* A helper class for movement targets with a certain network type.
* @author rubensworks
*/
public abstract class ChanneledTarget<N extends IPositionedAddonsNetwork, T> implements IChanneledTarget<N, T> {
private final INetwork network;
private final N channeledNetwork;
@Nullable
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/ChanneledTarget.java
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.network.IPartPosIteratorHandler;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetwork;
import org.cyclops.integrateddynamics.core.network.PartPosIteratorHandlerRoundRobin;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* A helper class for movement targets with a certain network type.
* @author rubensworks
*/
public abstract class ChanneledTarget<N extends IPositionedAddonsNetwork, T> implements IChanneledTarget<N, T> {
private final INetwork network;
private final N channeledNetwork;
@Nullable
|
private final PartStateRoundRobin<?> partState;
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/EnergyTargetCapabilityProvider.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/Capabilities.java
// public class Capabilities {
// @CapabilityInject(IEnergyNetwork.class)
// public static Capability<IEnergyNetwork> NETWORK_ENERGY = null;
// @CapabilityInject(IFluidNetwork.class)
// public static Capability<IFluidNetwork> NETWORK_FLUID = null;
// @CapabilityInject(IInventoryState.class)
// public static Capability<IInventoryState> INVENTORY_STATE = null;
// @CapabilityInject(ISlotlessItemHandler.class)
// public static Capability<ISlotlessItemHandler> SLOTLESS_ITEMHANDLER = null;
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
|
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.IEnergyNetwork;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.Capabilities;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public class EnergyTargetCapabilityProvider extends ChanneledTargetCapabilityProvider<IEnergyNetwork, Long, Boolean>
implements IEnergyTarget {
// TODO: in next breaking change, migrate to long values
private final int amount;
private final boolean exactAmount;
public EnergyTargetCapabilityProvider(@Nullable ICapabilityProvider capabilityProvider, Direction side, INetwork network,
IAspectProperties properties,
|
// Path: src/main/java/org/cyclops/integratedtunnels/Capabilities.java
// public class Capabilities {
// @CapabilityInject(IEnergyNetwork.class)
// public static Capability<IEnergyNetwork> NETWORK_ENERGY = null;
// @CapabilityInject(IFluidNetwork.class)
// public static Capability<IFluidNetwork> NETWORK_FLUID = null;
// @CapabilityInject(IInventoryState.class)
// public static Capability<IInventoryState> INVENTORY_STATE = null;
// @CapabilityInject(ISlotlessItemHandler.class)
// public static Capability<ISlotlessItemHandler> SLOTLESS_ITEMHANDLER = null;
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/EnergyTargetCapabilityProvider.java
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.IEnergyNetwork;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.Capabilities;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public class EnergyTargetCapabilityProvider extends ChanneledTargetCapabilityProvider<IEnergyNetwork, Long, Boolean>
implements IEnergyTarget {
// TODO: in next breaking change, migrate to long values
private final int amount;
private final boolean exactAmount;
public EnergyTargetCapabilityProvider(@Nullable ICapabilityProvider capabilityProvider, Direction side, INetwork network,
IAspectProperties properties,
|
int amount, @Nullable PartStateRoundRobin<?> partStateEnergy) {
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/EnergyTargetCapabilityProvider.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/Capabilities.java
// public class Capabilities {
// @CapabilityInject(IEnergyNetwork.class)
// public static Capability<IEnergyNetwork> NETWORK_ENERGY = null;
// @CapabilityInject(IFluidNetwork.class)
// public static Capability<IFluidNetwork> NETWORK_FLUID = null;
// @CapabilityInject(IInventoryState.class)
// public static Capability<IInventoryState> INVENTORY_STATE = null;
// @CapabilityInject(ISlotlessItemHandler.class)
// public static Capability<ISlotlessItemHandler> SLOTLESS_ITEMHANDLER = null;
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
|
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.IEnergyNetwork;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.Capabilities;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public class EnergyTargetCapabilityProvider extends ChanneledTargetCapabilityProvider<IEnergyNetwork, Long, Boolean>
implements IEnergyTarget {
// TODO: in next breaking change, migrate to long values
private final int amount;
private final boolean exactAmount;
public EnergyTargetCapabilityProvider(@Nullable ICapabilityProvider capabilityProvider, Direction side, INetwork network,
IAspectProperties properties,
int amount, @Nullable PartStateRoundRobin<?> partStateEnergy) {
|
// Path: src/main/java/org/cyclops/integratedtunnels/Capabilities.java
// public class Capabilities {
// @CapabilityInject(IEnergyNetwork.class)
// public static Capability<IEnergyNetwork> NETWORK_ENERGY = null;
// @CapabilityInject(IFluidNetwork.class)
// public static Capability<IFluidNetwork> NETWORK_FLUID = null;
// @CapabilityInject(IInventoryState.class)
// public static Capability<IInventoryState> INVENTORY_STATE = null;
// @CapabilityInject(ISlotlessItemHandler.class)
// public static Capability<ISlotlessItemHandler> SLOTLESS_ITEMHANDLER = null;
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/EnergyTargetCapabilityProvider.java
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.IEnergyNetwork;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.Capabilities;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public class EnergyTargetCapabilityProvider extends ChanneledTargetCapabilityProvider<IEnergyNetwork, Long, Boolean>
implements IEnergyTarget {
// TODO: in next breaking change, migrate to long values
private final int amount;
private final boolean exactAmount;
public EnergyTargetCapabilityProvider(@Nullable ICapabilityProvider capabilityProvider, Direction side, INetwork network,
IAspectProperties properties,
int amount, @Nullable PartStateRoundRobin<?> partStateEnergy) {
|
super(network, capabilityProvider, side, network.getCapability(Capabilities.NETWORK_ENERGY).orElse(null), partStateEnergy,
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/IItemTarget.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/network/IItemNetwork.java
// public interface IItemNetwork extends IPositionedAddonsNetworkIngredients<ItemStack, Integer> {
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/predicate/IngredientPredicate.java
// public abstract class IngredientPredicate<T, M> implements Predicate<T>, ITunnelTransfer {
//
// private final IngredientComponent<T, M> ingredientComponent;
// private final T instance;
// private final M matchFlags;
// private final boolean blacklist;
// private final boolean empty;
// private final int maxQuantity;
// private final boolean exactQuantity;
//
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// T instance, M matchFlags, boolean blacklist, boolean empty,
// int maxQuantity, boolean exactQuantity) {
// this.ingredientComponent = ingredientComponent;
// this.instance = instance;
// this.matchFlags = matchFlags;
// this.blacklist = blacklist;
// this.empty = empty;
// this.maxQuantity = maxQuantity;
// this.exactQuantity = exactQuantity;
// }
//
// // Note: implementors of this method *should* override equals and hashcode.
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// boolean blacklist, boolean empty, int maxQuantity, boolean exactQuantity) {
// this(ingredientComponent, ingredientComponent.getMatcher().getEmptyInstance(), null,
// blacklist, empty, maxQuantity, exactQuantity);
// }
//
// public IngredientComponent<T, M> getIngredientComponent() {
// return ingredientComponent;
// }
//
// @Nonnull
// public T getInstance() {
// return instance;
// }
//
// public M getMatchFlags() {
// return matchFlags;
// }
//
// public boolean hasMatchFlags() {
// return matchFlags != null && !blacklist;
// }
//
// public boolean isBlacklist() {
// return blacklist;
// }
//
// public boolean isEmpty() {
// return empty;
// }
//
// public int getMaxQuantity() {
// return maxQuantity;
// }
//
// public boolean isExactQuantity() {
// return exactQuantity;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof IngredientPredicate)) {
// return false;
// }
// IngredientPredicate that = (IngredientPredicate) obj;
// return this.ingredientComponent == that.ingredientComponent
// && this.ingredientComponent.getMatcher().matchesExactly(this.instance, (T) that.instance)
// && Objects.equals(this.matchFlags, that.matchFlags)
// && this.blacklist == that.blacklist
// && this.empty == that.empty
// && this.maxQuantity == that.maxQuantity
// && this.exactQuantity == that.exactQuantity;
// }
//
// @Override
// public int hashCode() {
// return ingredientComponent.hashCode()
// ^ ingredientComponent.getMatcher().hash(instance)
// ^ Objects.hashCode(matchFlags)
// ^ (blacklist ? 1 : 0)
// ^ (empty ? 2 : 4)
// ^ maxQuantity
// ^ (exactQuantity ? 8 : 16);
// }
//
// public static enum EmptyBehaviour {
// ANY,
// NONE;
//
// public static EmptyBehaviour fromBoolean(boolean emptyIsAny) {
// return emptyIsAny ? ANY : NONE;
// }
// }
// }
|
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.api.network.IItemNetwork;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import org.cyclops.integratedtunnels.core.predicate.IngredientPredicate;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public interface IItemTarget extends IChanneledTarget<IItemNetwork, ItemStack> {
public IIngredientComponentStorage<ItemStack, Integer> getItemChannel();
public IIngredientComponentStorage<ItemStack, Integer> getStorage();
public int getSlot();
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/network/IItemNetwork.java
// public interface IItemNetwork extends IPositionedAddonsNetworkIngredients<ItemStack, Integer> {
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/predicate/IngredientPredicate.java
// public abstract class IngredientPredicate<T, M> implements Predicate<T>, ITunnelTransfer {
//
// private final IngredientComponent<T, M> ingredientComponent;
// private final T instance;
// private final M matchFlags;
// private final boolean blacklist;
// private final boolean empty;
// private final int maxQuantity;
// private final boolean exactQuantity;
//
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// T instance, M matchFlags, boolean blacklist, boolean empty,
// int maxQuantity, boolean exactQuantity) {
// this.ingredientComponent = ingredientComponent;
// this.instance = instance;
// this.matchFlags = matchFlags;
// this.blacklist = blacklist;
// this.empty = empty;
// this.maxQuantity = maxQuantity;
// this.exactQuantity = exactQuantity;
// }
//
// // Note: implementors of this method *should* override equals and hashcode.
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// boolean blacklist, boolean empty, int maxQuantity, boolean exactQuantity) {
// this(ingredientComponent, ingredientComponent.getMatcher().getEmptyInstance(), null,
// blacklist, empty, maxQuantity, exactQuantity);
// }
//
// public IngredientComponent<T, M> getIngredientComponent() {
// return ingredientComponent;
// }
//
// @Nonnull
// public T getInstance() {
// return instance;
// }
//
// public M getMatchFlags() {
// return matchFlags;
// }
//
// public boolean hasMatchFlags() {
// return matchFlags != null && !blacklist;
// }
//
// public boolean isBlacklist() {
// return blacklist;
// }
//
// public boolean isEmpty() {
// return empty;
// }
//
// public int getMaxQuantity() {
// return maxQuantity;
// }
//
// public boolean isExactQuantity() {
// return exactQuantity;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof IngredientPredicate)) {
// return false;
// }
// IngredientPredicate that = (IngredientPredicate) obj;
// return this.ingredientComponent == that.ingredientComponent
// && this.ingredientComponent.getMatcher().matchesExactly(this.instance, (T) that.instance)
// && Objects.equals(this.matchFlags, that.matchFlags)
// && this.blacklist == that.blacklist
// && this.empty == that.empty
// && this.maxQuantity == that.maxQuantity
// && this.exactQuantity == that.exactQuantity;
// }
//
// @Override
// public int hashCode() {
// return ingredientComponent.hashCode()
// ^ ingredientComponent.getMatcher().hash(instance)
// ^ Objects.hashCode(matchFlags)
// ^ (blacklist ? 1 : 0)
// ^ (empty ? 2 : 4)
// ^ maxQuantity
// ^ (exactQuantity ? 8 : 16);
// }
//
// public static enum EmptyBehaviour {
// ANY,
// NONE;
//
// public static EmptyBehaviour fromBoolean(boolean emptyIsAny) {
// return emptyIsAny ? ANY : NONE;
// }
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/IItemTarget.java
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.api.network.IItemNetwork;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import org.cyclops.integratedtunnels.core.predicate.IngredientPredicate;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public interface IItemTarget extends IChanneledTarget<IItemNetwork, ItemStack> {
public IIngredientComponentStorage<ItemStack, Integer> getItemChannel();
public IIngredientComponentStorage<ItemStack, Integer> getStorage();
public int getSlot();
|
public IngredientPredicate<ItemStack, Integer> getItemStackMatcher();
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/IItemTarget.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/network/IItemNetwork.java
// public interface IItemNetwork extends IPositionedAddonsNetworkIngredients<ItemStack, Integer> {
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/predicate/IngredientPredicate.java
// public abstract class IngredientPredicate<T, M> implements Predicate<T>, ITunnelTransfer {
//
// private final IngredientComponent<T, M> ingredientComponent;
// private final T instance;
// private final M matchFlags;
// private final boolean blacklist;
// private final boolean empty;
// private final int maxQuantity;
// private final boolean exactQuantity;
//
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// T instance, M matchFlags, boolean blacklist, boolean empty,
// int maxQuantity, boolean exactQuantity) {
// this.ingredientComponent = ingredientComponent;
// this.instance = instance;
// this.matchFlags = matchFlags;
// this.blacklist = blacklist;
// this.empty = empty;
// this.maxQuantity = maxQuantity;
// this.exactQuantity = exactQuantity;
// }
//
// // Note: implementors of this method *should* override equals and hashcode.
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// boolean blacklist, boolean empty, int maxQuantity, boolean exactQuantity) {
// this(ingredientComponent, ingredientComponent.getMatcher().getEmptyInstance(), null,
// blacklist, empty, maxQuantity, exactQuantity);
// }
//
// public IngredientComponent<T, M> getIngredientComponent() {
// return ingredientComponent;
// }
//
// @Nonnull
// public T getInstance() {
// return instance;
// }
//
// public M getMatchFlags() {
// return matchFlags;
// }
//
// public boolean hasMatchFlags() {
// return matchFlags != null && !blacklist;
// }
//
// public boolean isBlacklist() {
// return blacklist;
// }
//
// public boolean isEmpty() {
// return empty;
// }
//
// public int getMaxQuantity() {
// return maxQuantity;
// }
//
// public boolean isExactQuantity() {
// return exactQuantity;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof IngredientPredicate)) {
// return false;
// }
// IngredientPredicate that = (IngredientPredicate) obj;
// return this.ingredientComponent == that.ingredientComponent
// && this.ingredientComponent.getMatcher().matchesExactly(this.instance, (T) that.instance)
// && Objects.equals(this.matchFlags, that.matchFlags)
// && this.blacklist == that.blacklist
// && this.empty == that.empty
// && this.maxQuantity == that.maxQuantity
// && this.exactQuantity == that.exactQuantity;
// }
//
// @Override
// public int hashCode() {
// return ingredientComponent.hashCode()
// ^ ingredientComponent.getMatcher().hash(instance)
// ^ Objects.hashCode(matchFlags)
// ^ (blacklist ? 1 : 0)
// ^ (empty ? 2 : 4)
// ^ maxQuantity
// ^ (exactQuantity ? 8 : 16);
// }
//
// public static enum EmptyBehaviour {
// ANY,
// NONE;
//
// public static EmptyBehaviour fromBoolean(boolean emptyIsAny) {
// return emptyIsAny ? ANY : NONE;
// }
// }
// }
|
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.api.network.IItemNetwork;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import org.cyclops.integratedtunnels.core.predicate.IngredientPredicate;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public interface IItemTarget extends IChanneledTarget<IItemNetwork, ItemStack> {
public IIngredientComponentStorage<ItemStack, Integer> getItemChannel();
public IIngredientComponentStorage<ItemStack, Integer> getStorage();
public int getSlot();
public IngredientPredicate<ItemStack, Integer> getItemStackMatcher();
public PartTarget getPartTarget();
public IAspectProperties getProperties();
public ITunnelConnection getConnection();
public static IItemTarget ofCapabilityProvider(ITunnelTransfer transfer, PartTarget partTarget, IAspectProperties properties,
IngredientPredicate<ItemStack, Integer> itemStackMatcher, int slot) {
PartPos center = partTarget.getCenter();
PartPos target = partTarget.getTarget();
INetwork network = IChanneledTarget.getNetworkChecked(center);
TileEntity tile = target.getPos().getWorld(true).getTileEntity(target.getPos().getBlockPos());
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/network/IItemNetwork.java
// public interface IItemNetwork extends IPositionedAddonsNetworkIngredients<ItemStack, Integer> {
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/core/predicate/IngredientPredicate.java
// public abstract class IngredientPredicate<T, M> implements Predicate<T>, ITunnelTransfer {
//
// private final IngredientComponent<T, M> ingredientComponent;
// private final T instance;
// private final M matchFlags;
// private final boolean blacklist;
// private final boolean empty;
// private final int maxQuantity;
// private final boolean exactQuantity;
//
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// T instance, M matchFlags, boolean blacklist, boolean empty,
// int maxQuantity, boolean exactQuantity) {
// this.ingredientComponent = ingredientComponent;
// this.instance = instance;
// this.matchFlags = matchFlags;
// this.blacklist = blacklist;
// this.empty = empty;
// this.maxQuantity = maxQuantity;
// this.exactQuantity = exactQuantity;
// }
//
// // Note: implementors of this method *should* override equals and hashcode.
// public IngredientPredicate(IngredientComponent<T, M> ingredientComponent,
// boolean blacklist, boolean empty, int maxQuantity, boolean exactQuantity) {
// this(ingredientComponent, ingredientComponent.getMatcher().getEmptyInstance(), null,
// blacklist, empty, maxQuantity, exactQuantity);
// }
//
// public IngredientComponent<T, M> getIngredientComponent() {
// return ingredientComponent;
// }
//
// @Nonnull
// public T getInstance() {
// return instance;
// }
//
// public M getMatchFlags() {
// return matchFlags;
// }
//
// public boolean hasMatchFlags() {
// return matchFlags != null && !blacklist;
// }
//
// public boolean isBlacklist() {
// return blacklist;
// }
//
// public boolean isEmpty() {
// return empty;
// }
//
// public int getMaxQuantity() {
// return maxQuantity;
// }
//
// public boolean isExactQuantity() {
// return exactQuantity;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof IngredientPredicate)) {
// return false;
// }
// IngredientPredicate that = (IngredientPredicate) obj;
// return this.ingredientComponent == that.ingredientComponent
// && this.ingredientComponent.getMatcher().matchesExactly(this.instance, (T) that.instance)
// && Objects.equals(this.matchFlags, that.matchFlags)
// && this.blacklist == that.blacklist
// && this.empty == that.empty
// && this.maxQuantity == that.maxQuantity
// && this.exactQuantity == that.exactQuantity;
// }
//
// @Override
// public int hashCode() {
// return ingredientComponent.hashCode()
// ^ ingredientComponent.getMatcher().hash(instance)
// ^ Objects.hashCode(matchFlags)
// ^ (blacklist ? 1 : 0)
// ^ (empty ? 2 : 4)
// ^ maxQuantity
// ^ (exactQuantity ? 8 : 16);
// }
//
// public static enum EmptyBehaviour {
// ANY,
// NONE;
//
// public static EmptyBehaviour fromBoolean(boolean emptyIsAny) {
// return emptyIsAny ? ANY : NONE;
// }
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/IItemTarget.java
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.api.network.IItemNetwork;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import org.cyclops.integratedtunnels.core.predicate.IngredientPredicate;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public interface IItemTarget extends IChanneledTarget<IItemNetwork, ItemStack> {
public IIngredientComponentStorage<ItemStack, Integer> getItemChannel();
public IIngredientComponentStorage<ItemStack, Integer> getStorage();
public int getSlot();
public IngredientPredicate<ItemStack, Integer> getItemStackMatcher();
public PartTarget getPartTarget();
public IAspectProperties getProperties();
public ITunnelConnection getConnection();
public static IItemTarget ofCapabilityProvider(ITunnelTransfer transfer, PartTarget partTarget, IAspectProperties properties,
IngredientPredicate<ItemStack, Integer> itemStackMatcher, int slot) {
PartPos center = partTarget.getCenter();
PartPos target = partTarget.getTarget();
INetwork network = IChanneledTarget.getNetworkChecked(center);
TileEntity tile = target.getPos().getWorld(true).getTileEntity(target.getPos().getBlockPos());
|
PartStateRoundRobin<?> partState = IChanneledTarget.getPartState(center);
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/capability/network/FluidNetworkConfig.java
// public class FluidNetworkConfig extends CapabilityConfig<IFluidNetwork> {
//
// @CapabilityInject(IFluidNetwork.class)
// public static Capability<IFluidNetwork> CAPABILITY = null;
//
// public FluidNetworkConfig() {
// super(
// CommonCapabilities._instance,
// "fluidNetwork",
// IFluidNetwork.class,
// new DefaultCapabilityStorage<IFluidNetwork>(),
// () -> new FluidNetwork(null)
// );
// }
//
// }
|
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeFluidStack;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypeLong;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
import org.cyclops.integratedtunnels.capability.network.FluidNetworkConfig;
|
package org.cyclops.integratedtunnels.part.aspect.operator;
/**
* @author rubensworks
*/
public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
}
@Override
protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
|
// Path: src/main/java/org/cyclops/integratedtunnels/capability/network/FluidNetworkConfig.java
// public class FluidNetworkConfig extends CapabilityConfig<IFluidNetwork> {
//
// @CapabilityInject(IFluidNetwork.class)
// public static Capability<IFluidNetwork> CAPABILITY = null;
//
// public FluidNetworkConfig() {
// super(
// CommonCapabilities._instance,
// "fluidNetwork",
// IFluidNetwork.class,
// new DefaultCapabilityStorage<IFluidNetwork>(),
// () -> new FluidNetwork(null)
// );
// }
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexFluid.java
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.FluidStack;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeFluidStack;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypeLong;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
import org.cyclops.integratedtunnels.capability.network.FluidNetworkConfig;
package org.cyclops.integratedtunnels.part.aspect.operator;
/**
* @author rubensworks
*/
public class PositionedOperatorIngredientIndexFluid extends PositionedOperatorIngredientIndex<FluidStack, Integer> {
public PositionedOperatorIngredientIndexFluid(DimPos pos, Direction side, int channel) {
super("countbyfluid", new Function(), ValueTypes.OBJECT_FLUIDSTACK, ValueTypes.LONG, pos, side, channel);
}
@Override
protected Capability<? extends IPositionedAddonsNetworkIngredients<FluidStack, Integer>> getNetworkCapability() {
|
return FluidNetworkConfig.CAPABILITY;
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/IEnergyTarget.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
|
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.IEnergyNetwork;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public interface IEnergyTarget extends IChanneledTarget<IEnergyNetwork, Long> {
public IIngredientComponentStorage<Long, Boolean> getEnergyChannel();
public IIngredientComponentStorage<Long, Boolean> getStorage();
public int getAmount();
public boolean isExactAmount();
public static IEnergyTarget ofTile(PartTarget partTarget, IAspectProperties properties, int amount) {
PartPos center = partTarget.getCenter();
PartPos target = partTarget.getTarget();
INetwork network = IChanneledTarget.getNetworkChecked(center);
TileEntity tile = target.getPos().getWorld(true).getTileEntity(target.getPos().getBlockPos());
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/IEnergyTarget.java
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.IEnergyNetwork;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* @author rubensworks
*/
public interface IEnergyTarget extends IChanneledTarget<IEnergyNetwork, Long> {
public IIngredientComponentStorage<Long, Boolean> getEnergyChannel();
public IIngredientComponentStorage<Long, Boolean> getStorage();
public int getAmount();
public boolean isExactAmount();
public static IEnergyTarget ofTile(PartTarget partTarget, IAspectProperties properties, int amount) {
PartPos center = partTarget.getCenter();
PartPos target = partTarget.getTarget();
INetwork network = IChanneledTarget.getNetworkChecked(center);
TileEntity tile = target.getPos().getWorld(true).getTileEntity(target.getPos().getBlockPos());
|
PartStateRoundRobin<?> partState = IChanneledTarget.getPartState(center);
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/ChanneledTargetCapabilityProvider.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
|
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetwork;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
|
package org.cyclops.integratedtunnels.part.aspect;
/**
* A helper class for movement targets with a certain network type and a capability provider as target.
* @author rubensworks
*/
public abstract class ChanneledTargetCapabilityProvider<N extends IPositionedAddonsNetwork, T, M> extends ChanneledTarget<N, T> {
private final ICapabilityProvider capabilityProvider;
private final Direction side;
private IIngredientComponentStorage<T, M> storage = null;
public ChanneledTargetCapabilityProvider(INetwork network, @Nullable ICapabilityProvider capabilityProvider, Direction side,
|
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartStateRoundRobin.java
// public class PartStateRoundRobin<P extends IPartTypeWriter> extends PartStateWriterBase<P> {
//
// private IPartPosIteratorHandler partPosIteratorHandler = null;
//
// public PartStateRoundRobin(int inventorySize) {
// super(inventorySize);
// }
//
// public void setPartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
// this.partPosIteratorHandler = partPosIteratorHandler;
// }
//
// public IPartPosIteratorHandler getPartPosIteratorHandler() {
// return partPosIteratorHandler;
// }
// }
// Path: src/main/java/org/cyclops/integratedtunnels/part/aspect/ChanneledTargetCapabilityProvider.java
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.integrateddynamics.api.network.INetwork;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetwork;
import org.cyclops.integratedtunnels.core.part.PartStateRoundRobin;
import javax.annotation.Nullable;
package org.cyclops.integratedtunnels.part.aspect;
/**
* A helper class for movement targets with a certain network type and a capability provider as target.
* @author rubensworks
*/
public abstract class ChanneledTargetCapabilityProvider<N extends IPositionedAddonsNetwork, T, M> extends ChanneledTarget<N, T> {
private final ICapabilityProvider capabilityProvider;
private final Direction side;
private IIngredientComponentStorage<T, M> storage = null;
public ChanneledTargetCapabilityProvider(INetwork network, @Nullable ICapabilityProvider capabilityProvider, Direction side,
|
N channeledNetwork, @Nullable PartStateRoundRobin<?> partState, int channel,
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/core/part/ContainerInterfaceSettings.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/RegistryEntries.java
// public class RegistryEntries {
//
// @ObjectHolder("integratedtunnels:part_interface_item")
// public static final Item ITEM_PART_INTERFACE = null;
// @ObjectHolder("integratedtunnels:dummy_pickaxe")
// public static final Item ITEM_DUMMY_PICKAXE = null;
//
// @ObjectHolder("integratedtunnels:part_interface_settings")
// public static final ContainerType<ContainerInterfaceSettings> CONTAINER_INTERFACE_SETTINGS = null;
//
// }
|
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.network.PacketBuffer;
import org.cyclops.cyclopscore.helper.ValueNotifierHelpers;
import org.cyclops.integrateddynamics.api.part.IPartContainer;
import org.cyclops.integrateddynamics.api.part.IPartType;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
import org.cyclops.integrateddynamics.core.inventory.container.ContainerPartSettings;
import org.cyclops.integratedtunnels.RegistryEntries;
import java.util.Optional;
|
package org.cyclops.integratedtunnels.core.part;
/**
* @author rubensworks
*/
public class ContainerInterfaceSettings extends ContainerPartSettings {
private final int lastChannelInterfaceValueId;
public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, PacketBuffer packetBuffer) {
this(id, playerInventory, new Inventory(0), PartHelpers.readPartTarget(packetBuffer), Optional.empty(), PartHelpers.readPart(packetBuffer));
}
public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, IInventory inventory,
PartTarget target, Optional<IPartContainer> partContainer, IPartType partType) {
|
// Path: src/main/java/org/cyclops/integratedtunnels/RegistryEntries.java
// public class RegistryEntries {
//
// @ObjectHolder("integratedtunnels:part_interface_item")
// public static final Item ITEM_PART_INTERFACE = null;
// @ObjectHolder("integratedtunnels:dummy_pickaxe")
// public static final Item ITEM_DUMMY_PICKAXE = null;
//
// @ObjectHolder("integratedtunnels:part_interface_settings")
// public static final ContainerType<ContainerInterfaceSettings> CONTAINER_INTERFACE_SETTINGS = null;
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/ContainerInterfaceSettings.java
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.network.PacketBuffer;
import org.cyclops.cyclopscore.helper.ValueNotifierHelpers;
import org.cyclops.integrateddynamics.api.part.IPartContainer;
import org.cyclops.integrateddynamics.api.part.IPartType;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
import org.cyclops.integrateddynamics.core.inventory.container.ContainerPartSettings;
import org.cyclops.integratedtunnels.RegistryEntries;
import java.util.Optional;
package org.cyclops.integratedtunnels.core.part;
/**
* @author rubensworks
*/
public class ContainerInterfaceSettings extends ContainerPartSettings {
private final int lastChannelInterfaceValueId;
public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, PacketBuffer packetBuffer) {
this(id, playerInventory, new Inventory(0), PartHelpers.readPartTarget(packetBuffer), Optional.empty(), PartHelpers.readPart(packetBuffer));
}
public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, IInventory inventory,
PartTarget target, Optional<IPartContainer> partContainer, IPartType partType) {
|
super(RegistryEntries.CONTAINER_INTERFACE_SETTINGS, id, playerInventory, inventory, target, partContainer, partType);
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/core/part/PartTypeTunnelAspects.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
|
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.integrateddynamics.api.part.PartRenderPosition;
import org.cyclops.integrateddynamics.api.part.write.IPartStateWriter;
import org.cyclops.integrateddynamics.api.part.write.IPartTypeWriter;
import org.cyclops.integrateddynamics.core.part.write.PartTypeWriteBase;
import org.cyclops.integratedtunnels.IntegratedTunnels;
|
package org.cyclops.integratedtunnels.core.part;
/**
* Base part for a tunnels with aspects.
* @author rubensworks
*/
public abstract class PartTypeTunnelAspects<P extends IPartTypeWriter<P, S>, S extends IPartStateWriter<P>> extends PartTypeWriteBase<P, S> {
public PartTypeTunnelAspects(String name) {
this(name, new PartRenderPosition(0.25F, 0.25F, 0.375F, 0.375F));
}
protected PartTypeTunnelAspects(String name, PartRenderPosition partRenderPosition) {
super(name, partRenderPosition);
}
@Override
public ModBase getMod() {
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartTypeTunnelAspects.java
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.integrateddynamics.api.part.PartRenderPosition;
import org.cyclops.integrateddynamics.api.part.write.IPartStateWriter;
import org.cyclops.integrateddynamics.api.part.write.IPartTypeWriter;
import org.cyclops.integrateddynamics.core.part.write.PartTypeWriteBase;
import org.cyclops.integratedtunnels.IntegratedTunnels;
package org.cyclops.integratedtunnels.core.part;
/**
* Base part for a tunnels with aspects.
* @author rubensworks
*/
public abstract class PartTypeTunnelAspects<P extends IPartTypeWriter<P, S>, S extends IPartStateWriter<P>> extends PartTypeWriteBase<P, S> {
public PartTypeTunnelAspects(String name) {
this(name, new PartRenderPosition(0.25F, 0.25F, 0.375F, 0.375F));
}
protected PartTypeTunnelAspects(String name, PartRenderPosition partRenderPosition) {
super(name, partRenderPosition);
}
@Override
public ModBase getMod() {
|
return IntegratedTunnels._instance;
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/core/part/PartTypeTunnel.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
|
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import org.apache.commons.lang3.tuple.Triple;
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.integrateddynamics.api.part.IPartContainer;
import org.cyclops.integrateddynamics.api.part.IPartState;
import org.cyclops.integrateddynamics.api.part.IPartType;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartRenderPosition;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
import org.cyclops.integrateddynamics.core.part.PartTypeBase;
import org.cyclops.integratedtunnels.IntegratedTunnels;
import javax.annotation.Nullable;
import java.util.Optional;
|
package org.cyclops.integratedtunnels.core.part;
/**
* Base part for a tunnel.
* @author rubensworks
*/
public abstract class PartTypeTunnel<P extends IPartType<P, S>, S extends IPartState<P>> extends PartTypeBase<P, S> {
public PartTypeTunnel(String name) {
super(name, new PartRenderPosition(0.25F, 0.25F, 0.375F, 0.375F));
}
@Override
public ModBase getMod() {
|
// Path: src/main/java/org/cyclops/integratedtunnels/IntegratedTunnels.java
// @Mod(Reference.MOD_ID)
// public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> {
//
// /**
// * The unique instance of this mod.
// */
// public static IntegratedTunnels _instance;
//
// public IntegratedTunnels() {
// super(Reference.MOD_ID, (instance) -> _instance = instance);
//
// // Registries
// getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance());
// getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance());
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate);
// }
//
// public void onRegistriesCreate(RegistryEvent.NewRegistry event) {
// TunnelIngredientComponentCapabilities.load();
// TunnelAspects.load();
// PartTypes.load();
// BlockBreakHandlers.load();
// BlockPlaceHandlers.load();
// }
//
// @Override
// protected void setup(FMLCommonSetupEvent event) {
// super.setup(event);
//
// MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors());
//
// // Initialize info book
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual",
// "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml");
// IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class)
// .registerSection(
// OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials",
// "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml");
//
// // Register value list proxies
// TunnelValueTypeListProxyFactories.load();
//
// // Inject aspects into ID parts
// AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList(
// TunnelAspects.Read.Item.LONG_COUNT,
// TunnelAspects.Read.Item.LONG_COUNTMAX,
// TunnelAspects.Read.Item.LIST_ITEMSTACKS,
// TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT,
// TunnelAspects.Read.Item.INTEGER_INTERFACES,
//
// TunnelAspects.Read.Fluid.LONG_COUNT,
// TunnelAspects.Read.Fluid.LONG_COUNTMAX,
// TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS,
// TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT,
// TunnelAspects.Read.Fluid.INTEGER_INTERFACES
// ));
// }
//
// @Override
// public ItemGroup constructDefaultItemGroup() {
// return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE);
// }
//
// @Override
// public void onConfigsRegister(ConfigHandler configHandler) {
// super.onConfigsRegister(configHandler);
//
// configHandler.addConfigurable(new GeneralConfig());
//
// configHandler.addConfigurable(new ItemNetworkConfig());
// configHandler.addConfigurable(new FluidNetworkConfig());
//
// configHandler.addConfigurable(new ItemDummyPickAxeConfig());
//
// configHandler.addConfigurable(new ContainerInterfaceSettingsConfig());
// }
//
// @Override
// @OnlyIn(Dist.CLIENT)
// protected IClientProxy constructClientProxy() {
// return new ClientProxy();
// }
//
// @Override
// protected ICommonProxy constructCommonProxy() {
// return new CommonProxy();
// }
//
// /**
// * Log a new info message for this mod.
// * @param message The message to show.
// */
// public static void clog(String message) {
// clog(Level.INFO, message);
// }
//
// /**
// * Log a new message of the given level for this mod.
// * @param level The level in which the message must be shown.
// * @param message The message to show.
// */
// public static void clog(Level level, String message) {
// IntegratedTunnels._instance.getLoggerHelper().log(level, message);
// }
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/core/part/PartTypeTunnel.java
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import org.apache.commons.lang3.tuple.Triple;
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.integrateddynamics.api.part.IPartContainer;
import org.cyclops.integrateddynamics.api.part.IPartState;
import org.cyclops.integrateddynamics.api.part.IPartType;
import org.cyclops.integrateddynamics.api.part.PartPos;
import org.cyclops.integrateddynamics.api.part.PartRenderPosition;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
import org.cyclops.integrateddynamics.core.part.PartTypeBase;
import org.cyclops.integratedtunnels.IntegratedTunnels;
import javax.annotation.Nullable;
import java.util.Optional;
package org.cyclops.integratedtunnels.core.part;
/**
* Base part for a tunnel.
* @author rubensworks
*/
public abstract class PartTypeTunnel<P extends IPartType<P, S>, S extends IPartState<P>> extends PartTypeBase<P, S> {
public PartTypeTunnel(String name) {
super(name, new PartRenderPosition(0.25F, 0.25F, 0.375F, 0.375F));
}
@Override
public ModBase getMod() {
|
return IntegratedTunnels._instance;
|
CyclopsMC/IntegratedTunnels
|
src/main/java/org/cyclops/integratedtunnels/core/world/BlockBreakHandlerRegistry.java
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/world/IBlockBreakHandler.java
// public interface IBlockBreakHandler {
//
// /**
// * If this can handle the given block state.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// * @return If this can handle the given block state.
// */
// public boolean shouldApply(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// /**
// * Get the dropping items of the given block.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// * @return A list of itemstacks where each element must be removable.
// */
// public NonNullList<ItemStack> getDrops(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// /**
// * Break the given block.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// */
// public void breakBlock(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/api/world/IBlockBreakHandlerRegistry.java
// public interface IBlockBreakHandlerRegistry extends IRegistry {
//
// /**
// * Add a block breaking handler.
// * Multiple handlers can exist for a block.
// * @param block A block.
// * @param breakAction A handler.
// * @return The registered handler.
// */
// public IBlockBreakHandler register(Block block, IBlockBreakHandler breakAction);
//
// /**
// * @return All registered block breaking handlers.
// */
// public Collection<IBlockBreakHandler> getHandlers();
//
// /**
// * @param block A block.
// * @return All registered block breaking handlers for the given block.
// */
// public Collection<IBlockBreakHandler> getHandlers(Block block);
//
// /**
// * Get the first possible block breaking handler for the given block state.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// * @return A block breaking handler or null.
// */
// @Nullable
// public IBlockBreakHandler getHandler(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// }
|
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.cyclops.integratedtunnels.api.world.IBlockBreakHandler;
import org.cyclops.integratedtunnels.api.world.IBlockBreakHandlerRegistry;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
|
package org.cyclops.integratedtunnels.core.world;
/**
* Implementation of {@link IBlockBreakHandlerRegistry}.
* @author rubensworks
*/
public class BlockBreakHandlerRegistry implements IBlockBreakHandlerRegistry {
private static BlockBreakHandlerRegistry INSTANCE = new BlockBreakHandlerRegistry();
|
// Path: src/main/java/org/cyclops/integratedtunnels/api/world/IBlockBreakHandler.java
// public interface IBlockBreakHandler {
//
// /**
// * If this can handle the given block state.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// * @return If this can handle the given block state.
// */
// public boolean shouldApply(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// /**
// * Get the dropping items of the given block.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// * @return A list of itemstacks where each element must be removable.
// */
// public NonNullList<ItemStack> getDrops(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// /**
// * Break the given block.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// */
// public void breakBlock(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// }
//
// Path: src/main/java/org/cyclops/integratedtunnels/api/world/IBlockBreakHandlerRegistry.java
// public interface IBlockBreakHandlerRegistry extends IRegistry {
//
// /**
// * Add a block breaking handler.
// * Multiple handlers can exist for a block.
// * @param block A block.
// * @param breakAction A handler.
// * @return The registered handler.
// */
// public IBlockBreakHandler register(Block block, IBlockBreakHandler breakAction);
//
// /**
// * @return All registered block breaking handlers.
// */
// public Collection<IBlockBreakHandler> getHandlers();
//
// /**
// * @param block A block.
// * @return All registered block breaking handlers for the given block.
// */
// public Collection<IBlockBreakHandler> getHandlers(Block block);
//
// /**
// * Get the first possible block breaking handler for the given block state.
// * @param blockState The block state.
// * @param world The world.
// * @param pos The block position.
// * @param player The breaking player.
// * @return A block breaking handler or null.
// */
// @Nullable
// public IBlockBreakHandler getHandler(BlockState blockState, World world, BlockPos pos, PlayerEntity player);
//
// }
// Path: src/main/java/org/cyclops/integratedtunnels/core/world/BlockBreakHandlerRegistry.java
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.cyclops.integratedtunnels.api.world.IBlockBreakHandler;
import org.cyclops.integratedtunnels.api.world.IBlockBreakHandlerRegistry;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
package org.cyclops.integratedtunnels.core.world;
/**
* Implementation of {@link IBlockBreakHandlerRegistry}.
* @author rubensworks
*/
public class BlockBreakHandlerRegistry implements IBlockBreakHandlerRegistry {
private static BlockBreakHandlerRegistry INSTANCE = new BlockBreakHandlerRegistry();
|
private final Multimap<Block, IBlockBreakHandler> handlers = Multimaps.newSetMultimap(Maps.<Block, Collection<IBlockBreakHandler>>newIdentityHashMap(), Sets::newIdentityHashSet);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/hooks/GitHubTagSCMHeadEvent.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
|
import com.github.kostyasha.github.integration.branch.webhook.BranchInfo;
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Collections;
import java.util.Map;
|
package com.github.kostyasha.github.integration.multibranch.hooks;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubTagSCMHeadEvent extends GitHubScmHeadEvent<BranchInfo> {
public GitHubTagSCMHeadEvent(@NonNull Type type, long timestamp, @NonNull BranchInfo payload, @CheckForNull String origin) {
super(type, timestamp, payload, origin);
}
@NonNull
@Override
protected String getSourceRepo() {
return getPayload().getRepo();
}
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
if (!isMatch(source)) {
return Collections.emptyMap();
}
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/hooks/GitHubTagSCMHeadEvent.java
import com.github.kostyasha.github.integration.branch.webhook.BranchInfo;
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Collections;
import java.util.Map;
package com.github.kostyasha.github.integration.multibranch.hooks;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubTagSCMHeadEvent extends GitHubScmHeadEvent<BranchInfo> {
public GitHubTagSCMHeadEvent(@NonNull Type type, long timestamp, @NonNull BranchInfo payload, @CheckForNull String origin) {
super(type, timestamp, payload, origin);
}
@NonNull
@Override
protected String getSourceRepo() {
return getPayload().getRepo();
}
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
if (!isMatch(source)) {
return Collections.emptyMap();
}
|
return Collections.singletonMap(new GitHubTagSCMHead(getPayload().getBranchName(), source.getId()), null);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/GitHubBranchCause.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
|
import com.github.kostyasha.github.integration.branch.data.GitHubBranchEnv;
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import hudson.model.ParameterValue;
import hudson.model.Run;
import jenkins.scm.api.SCMSourceOwner;
import org.kohsuke.github.GHBranch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.List;
import static org.apache.commons.io.FileUtils.writeStringToFile;
|
this(remoteBranch.getName(), remoteBranch.getSHA1());
withReason(reason);
withSkip(skip);
withLocalRepo(localRepo);
withRemoteData(remoteBranch);
}
public GitHubBranchCause(@NonNull String branchName, String commitSha) {
super(commitSha, "refs/heads/" + branchName);
this.branchName = branchName;
}
/**
* Copy constructor
*/
public GitHubBranchCause(GitHubBranchCause cause) {
super(cause);
this.branchName = cause.getBranchName();
}
public String getBranchName() {
return branchName;
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubBranchEnv.getParams(this, params);
}
@Override
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/GitHubBranchCause.java
import com.github.kostyasha.github.integration.branch.data.GitHubBranchEnv;
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import hudson.model.ParameterValue;
import hudson.model.Run;
import jenkins.scm.api.SCMSourceOwner;
import org.kohsuke.github.GHBranch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.List;
import static org.apache.commons.io.FileUtils.writeStringToFile;
this(remoteBranch.getName(), remoteBranch.getSHA1());
withReason(reason);
withSkip(skip);
withLocalRepo(localRepo);
withRemoteData(remoteBranch);
}
public GitHubBranchCause(@NonNull String branchName, String commitSha) {
super(commitSha, "refs/heads/" + branchName);
this.branchName = branchName;
}
/**
* Copy constructor
*/
public GitHubBranchCause(GitHubBranchCause cause) {
super(cause);
this.branchName = cause.getBranchName();
}
public String getBranchName() {
return branchName;
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubBranchEnv.getParams(this, params);
}
@Override
|
public GitHubSCMHead<GitHubBranchCause> createSCMHead(String sourceId) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/GitHubBranchCause.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
|
import com.github.kostyasha.github.integration.branch.data.GitHubBranchEnv;
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import hudson.model.ParameterValue;
import hudson.model.Run;
import jenkins.scm.api.SCMSourceOwner;
import org.kohsuke.github.GHBranch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.List;
import static org.apache.commons.io.FileUtils.writeStringToFile;
|
withReason(reason);
withSkip(skip);
withLocalRepo(localRepo);
withRemoteData(remoteBranch);
}
public GitHubBranchCause(@NonNull String branchName, String commitSha) {
super(commitSha, "refs/heads/" + branchName);
this.branchName = branchName;
}
/**
* Copy constructor
*/
public GitHubBranchCause(GitHubBranchCause cause) {
super(cause);
this.branchName = cause.getBranchName();
}
public String getBranchName() {
return branchName;
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubBranchEnv.getParams(this, params);
}
@Override
public GitHubSCMHead<GitHubBranchCause> createSCMHead(String sourceId) {
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/GitHubBranchCause.java
import com.github.kostyasha.github.integration.branch.data.GitHubBranchEnv;
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import hudson.model.ParameterValue;
import hudson.model.Run;
import jenkins.scm.api.SCMSourceOwner;
import org.kohsuke.github.GHBranch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.List;
import static org.apache.commons.io.FileUtils.writeStringToFile;
withReason(reason);
withSkip(skip);
withLocalRepo(localRepo);
withRemoteData(remoteBranch);
}
public GitHubBranchCause(@NonNull String branchName, String commitSha) {
super(commitSha, "refs/heads/" + branchName);
this.branchName = branchName;
}
/**
* Copy constructor
*/
public GitHubBranchCause(GitHubBranchCause cause) {
super(cause);
this.branchName = cause.getBranchName();
}
public String getBranchName() {
return branchName;
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubBranchEnv.getParams(this, params);
}
@Override
public GitHubSCMHead<GitHubBranchCause> createSCMHead(String sourceId) {
|
return new GitHubBranchSCMHead(branchName, sourceId);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/fs/GitHubSCMFileSystem.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
|
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.revision.GitHubSCMRevision;
import jenkins.scm.api.SCMFile;
import jenkins.scm.api.SCMFileSystem;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHRepository;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
|
package com.github.kostyasha.github.integration.multibranch.fs;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubSCMFileSystem extends SCMFileSystem {
private final GHRepository remoteRepo;
private final GHCommit commit;
private volatile TreeCache tree;
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/fs/GitHubSCMFileSystem.java
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.revision.GitHubSCMRevision;
import jenkins.scm.api.SCMFile;
import jenkins.scm.api.SCMFileSystem;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHRepository;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
package com.github.kostyasha.github.integration.multibranch.fs;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubSCMFileSystem extends SCMFileSystem {
private final GHRepository remoteRepo;
private final GHCommit commit;
private volatile TreeCache tree;
|
protected GitHubSCMFileSystem(@NonNull GHRepository remoteRepo, GitHubSCMHead<?> head, GitHubSCMRevision rev) throws IOException {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/category/GitHubBranchSCMHeadCategory.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
|
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.util.NonLocalizable;
import org.jvnet.localizer.Localizable;
import edu.umd.cs.findbugs.annotations.NonNull;
|
package com.github.kostyasha.github.integration.multibranch.category;
public class GitHubBranchSCMHeadCategory extends GitHubSCMHeadCategory {
public static final GitHubBranchSCMHeadCategory BRANCH = new GitHubBranchSCMHeadCategory(new NonLocalizable("Branches"));
public GitHubBranchSCMHeadCategory(@NonNull String urlName, Localizable pronoun) {
super(urlName, pronoun);
}
public GitHubBranchSCMHeadCategory(Localizable pronoun) {
super(pronoun);
}
@Override
public boolean isMatch(@NonNull SCMHead instance) {
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/category/GitHubBranchSCMHeadCategory.java
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.util.NonLocalizable;
import org.jvnet.localizer.Localizable;
import edu.umd.cs.findbugs.annotations.NonNull;
package com.github.kostyasha.github.integration.multibranch.category;
public class GitHubBranchSCMHeadCategory extends GitHubSCMHeadCategory {
public static final GitHubBranchSCMHeadCategory BRANCH = new GitHubBranchSCMHeadCategory(new NonLocalizable("Branches"));
public GitHubBranchSCMHeadCategory(@NonNull String urlName, Localizable pronoun) {
super(urlName, pronoun);
}
public GitHubBranchSCMHeadCategory(Localizable pronoun) {
super(pronoun);
}
@Override
public boolean isMatch(@NonNull SCMHead instance) {
|
return instance instanceof GitHubBranchSCMHead;
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/handler/GitHubHandler.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/generic/GitHubCause.java
// public abstract class GitHubCause<T extends GitHubCause<T>> extends Cause {
// private static final Logger LOG = LoggerFactory.getLogger(GitHubCause.class);
//
// private boolean skip;
// private String reason;
//
// /**
// * Doesn't exist for deleted branch.
// */
// @CheckForNull
// private URL htmlUrl;
//
// @CheckForNull
// private String title;
//
// private String gitUrl;
// private String sshUrl;
//
// private String pollingLog;
//
// private transient Object remoteData;
//
// public GitHubCause withLocalRepo(@NonNull GitHubRepository localRepo) {
// withGitUrl(localRepo.getGitUrl());
// withSshUrl(localRepo.getSshUrl());
// withHtmlUrl(localRepo.getGithubUrl());
// return this;
// }
//
// /**
// * When set and event got positive condition says to skip job triggering.
// */
// public boolean isSkip() {
// return skip;
// }
//
// public GitHubCause<T> withSkip(boolean skip) {
// this.skip = skip;
// return this;
// }
//
// /**
// * For printing branch url on left builds panel (build description).
// */
// @CheckForNull
// public URL getHtmlUrl() {
// return htmlUrl;
// }
//
// public GitHubCause<T> withHtmlUrl(URL htmlUrl) {
// this.htmlUrl = htmlUrl;
// return this;
// }
//
// public String getGitUrl() {
// return gitUrl;
// }
//
// public GitHubCause<T> withGitUrl(String gitUrl) {
// this.gitUrl = gitUrl;
// return this;
// }
//
// public String getSshUrl() {
// return sshUrl;
// }
//
// public GitHubCause<T> withSshUrl(String sshUrl) {
// this.sshUrl = sshUrl;
// return this;
// }
//
// public String getPollingLog() {
// return pollingLog;
// }
//
// public GitHubCause<T> withPollingLog(String pollingLog) {
// this.pollingLog = pollingLog;
// return this;
// }
//
// public void setPollingLog(String pollingLog) {
// this.pollingLog = pollingLog;
// }
//
// public void setPollingLogFile(File logFile) throws IOException {
// this.pollingLog = readFileToString(logFile);
// }
//
// public String getReason() {
// return reason;
// }
//
// public GitHubCause<T> withReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public Object getRemoteData() {
// return remoteData;
// }
//
// public GitHubCause<T> withRemoteData(Object remoteData) {
// this.remoteData = remoteData;
// return this;
// }
//
// /**
// * @return the title of the cause, never null.
// */
// @NonNull
// public String getTitle() {
// return nonNull(title) ? title : "";
// }
//
// public GitHubCause<T> withTitle(String title) {
// this.title = title;
// return this;
// }
//
// /**
// * @return at most the first 30 characters of the title, or
// */
// public String getAbbreviatedTitle() {
// return abbreviate(getTitle(), 30);
// }
//
// public abstract void fillParameters(List<ParameterValue> params);
//
// public abstract GitHubSCMHead<T> createSCMHead(String sourceId);
//
// @SuppressWarnings("unchecked")
// public GitHubSCMRevision createSCMRevision(String sourceId) {
// return createSCMHead(sourceId).createSCMRevision((T) this).setRemoteData(getRemoteData());
// }
//
// public static <T extends GitHubCause<T>> T skipTrigger(List<? extends T> causes) {
// if (isNull(causes)) {
// return null;
// }
// T cause = causes.stream()
// .filter(GitHubCause::isSkip)
// .findFirst()
// .orElse(null);
//
// return cause;
// }
// }
|
import com.github.kostyasha.github.integration.generic.GitHubCause;
import hudson.model.AbstractDescribableImpl;
import hudson.model.TaskListener;
import org.kohsuke.github.GitHub;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.stream.Stream;
import static org.jenkinsci.plugins.github.pullrequest.utils.IOUtils.forEachIo;
|
package com.github.kostyasha.github.integration.multibranch.handler;
/**
* @author Kanstantsin Shautsou
*/
public abstract class GitHubHandler extends AbstractDescribableImpl<GitHubHandler> {
public abstract void handle(@NonNull GitHubSourceContext context) throws IOException;
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/generic/GitHubCause.java
// public abstract class GitHubCause<T extends GitHubCause<T>> extends Cause {
// private static final Logger LOG = LoggerFactory.getLogger(GitHubCause.class);
//
// private boolean skip;
// private String reason;
//
// /**
// * Doesn't exist for deleted branch.
// */
// @CheckForNull
// private URL htmlUrl;
//
// @CheckForNull
// private String title;
//
// private String gitUrl;
// private String sshUrl;
//
// private String pollingLog;
//
// private transient Object remoteData;
//
// public GitHubCause withLocalRepo(@NonNull GitHubRepository localRepo) {
// withGitUrl(localRepo.getGitUrl());
// withSshUrl(localRepo.getSshUrl());
// withHtmlUrl(localRepo.getGithubUrl());
// return this;
// }
//
// /**
// * When set and event got positive condition says to skip job triggering.
// */
// public boolean isSkip() {
// return skip;
// }
//
// public GitHubCause<T> withSkip(boolean skip) {
// this.skip = skip;
// return this;
// }
//
// /**
// * For printing branch url on left builds panel (build description).
// */
// @CheckForNull
// public URL getHtmlUrl() {
// return htmlUrl;
// }
//
// public GitHubCause<T> withHtmlUrl(URL htmlUrl) {
// this.htmlUrl = htmlUrl;
// return this;
// }
//
// public String getGitUrl() {
// return gitUrl;
// }
//
// public GitHubCause<T> withGitUrl(String gitUrl) {
// this.gitUrl = gitUrl;
// return this;
// }
//
// public String getSshUrl() {
// return sshUrl;
// }
//
// public GitHubCause<T> withSshUrl(String sshUrl) {
// this.sshUrl = sshUrl;
// return this;
// }
//
// public String getPollingLog() {
// return pollingLog;
// }
//
// public GitHubCause<T> withPollingLog(String pollingLog) {
// this.pollingLog = pollingLog;
// return this;
// }
//
// public void setPollingLog(String pollingLog) {
// this.pollingLog = pollingLog;
// }
//
// public void setPollingLogFile(File logFile) throws IOException {
// this.pollingLog = readFileToString(logFile);
// }
//
// public String getReason() {
// return reason;
// }
//
// public GitHubCause<T> withReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public Object getRemoteData() {
// return remoteData;
// }
//
// public GitHubCause<T> withRemoteData(Object remoteData) {
// this.remoteData = remoteData;
// return this;
// }
//
// /**
// * @return the title of the cause, never null.
// */
// @NonNull
// public String getTitle() {
// return nonNull(title) ? title : "";
// }
//
// public GitHubCause<T> withTitle(String title) {
// this.title = title;
// return this;
// }
//
// /**
// * @return at most the first 30 characters of the title, or
// */
// public String getAbbreviatedTitle() {
// return abbreviate(getTitle(), 30);
// }
//
// public abstract void fillParameters(List<ParameterValue> params);
//
// public abstract GitHubSCMHead<T> createSCMHead(String sourceId);
//
// @SuppressWarnings("unchecked")
// public GitHubSCMRevision createSCMRevision(String sourceId) {
// return createSCMHead(sourceId).createSCMRevision((T) this).setRemoteData(getRemoteData());
// }
//
// public static <T extends GitHubCause<T>> T skipTrigger(List<? extends T> causes) {
// if (isNull(causes)) {
// return null;
// }
// T cause = causes.stream()
// .filter(GitHubCause::isSkip)
// .findFirst()
// .orElse(null);
//
// return cause;
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/handler/GitHubHandler.java
import com.github.kostyasha.github.integration.generic.GitHubCause;
import hudson.model.AbstractDescribableImpl;
import hudson.model.TaskListener;
import org.kohsuke.github.GitHub;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.stream.Stream;
import static org.jenkinsci.plugins.github.pullrequest.utils.IOUtils.forEachIo;
package com.github.kostyasha.github.integration.multibranch.handler;
/**
* @author Kanstantsin Shautsou
*/
public abstract class GitHubHandler extends AbstractDescribableImpl<GitHubHandler> {
public abstract void handle(@NonNull GitHubSourceContext context) throws IOException;
|
protected void processCauses(GitHubSourceContext context, Stream<? extends GitHubCause<?>> causeStream) throws IOException {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelAddPublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements addition of labels (one or many) to GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelAddPublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelAddPublisher.class);
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelAddPublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements addition of labels (one or many) to GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelAddPublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelAddPublisher.class);
|
private GitHubPRLabel labelProperty;
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelAddPublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements addition of labels (one or many) to GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelAddPublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelAddPublisher.class);
private GitHubPRLabel labelProperty;
@DataBoundConstructor
public GitHubPRLabelAddPublisher(GitHubPRLabel labelProperty,
StatusVerifier statusVerifier,
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelAddPublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements addition of labels (one or many) to GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelAddPublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelAddPublisher.class);
private GitHubPRLabel labelProperty;
@DataBoundConstructor
public GitHubPRLabelAddPublisher(GitHubPRLabel labelProperty,
StatusVerifier statusVerifier,
|
PublisherErrorHandler errorHandler) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/category/GitHubTagSCMHeadCategory.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
|
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.util.NonLocalizable;
import org.jvnet.localizer.Localizable;
import edu.umd.cs.findbugs.annotations.NonNull;
|
package com.github.kostyasha.github.integration.multibranch.category;
public class GitHubTagSCMHeadCategory extends GitHubSCMHeadCategory {
public static final GitHubTagSCMHeadCategory TAG = new GitHubTagSCMHeadCategory("tag", new NonLocalizable("Tags"));
public GitHubTagSCMHeadCategory(@NonNull String name, Localizable displayName) {
super(name, displayName);
}
@NonNull
@Override
protected Localizable defaultDisplayName() {
return new NonLocalizable("Tag");
}
@Override
public boolean isMatch(@NonNull SCMHead instance) {
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/category/GitHubTagSCMHeadCategory.java
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.util.NonLocalizable;
import org.jvnet.localizer.Localizable;
import edu.umd.cs.findbugs.annotations.NonNull;
package com.github.kostyasha.github.integration.multibranch.category;
public class GitHubTagSCMHeadCategory extends GitHubSCMHeadCategory {
public static final GitHubTagSCMHeadCategory TAG = new GitHubTagSCMHeadCategory("tag", new NonLocalizable("Tags"));
public GitHubTagSCMHeadCategory(@NonNull String name, Localizable displayName) {
super(name, displayName);
}
@NonNull
@Override
protected Localizable defaultDisplayName() {
return new NonLocalizable("Tag");
}
@Override
public boolean isMatch(@NonNull SCMHead instance) {
|
return instance instanceof GitHubTagSCMHead;
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/hooks/GitHubBranchSCMHeadEvent.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
|
import com.github.kostyasha.github.integration.branch.webhook.BranchInfo;
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Collections;
import java.util.Map;
|
package com.github.kostyasha.github.integration.multibranch.hooks;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubBranchSCMHeadEvent extends GitHubScmHeadEvent<BranchInfo> {
public GitHubBranchSCMHeadEvent(@NonNull Type type, long timestamp, @NonNull BranchInfo payload, @CheckForNull String origin) {
super(type, timestamp, payload, origin);
}
@NonNull
@Override
protected String getSourceRepo() {
return getPayload().getRepo();
}
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
if (!isMatch(source)) {
return Collections.emptyMap();
}
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubBranchSCMHead.java
// public class GitHubBranchSCMHead extends GitHubSCMHead<GitHubBranchCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubBranchSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Branch " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHBranch branch = remoteRepo.getBranch(getName());
// if (branch == null) {
// throw new IOException("No branch " + getName() + " in " + remoteRepo.getFullName());
// }
// return branch.getSHA1();
// }
//
// @Override
// public String getHeadSha(GitHubBranchCause cause) {
// return cause.getCommitSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/hooks/GitHubBranchSCMHeadEvent.java
import com.github.kostyasha.github.integration.branch.webhook.BranchInfo;
import com.github.kostyasha.github.integration.multibranch.head.GitHubBranchSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Collections;
import java.util.Map;
package com.github.kostyasha.github.integration.multibranch.hooks;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubBranchSCMHeadEvent extends GitHubScmHeadEvent<BranchInfo> {
public GitHubBranchSCMHeadEvent(@NonNull Type type, long timestamp, @NonNull BranchInfo payload, @CheckForNull String origin) {
super(type, timestamp, payload, origin);
}
@NonNull
@Override
protected String getSourceRepo() {
return getPayload().getRepo();
}
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
if (!isMatch(source)) {
return Collections.emptyMap();
}
|
return Collections.singletonMap(new GitHubBranchSCMHead(getPayload().getBranchName(), source.getId()), null);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/hooks/GitHubPullRequestScmHeadEvent.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubPRSCMHead.java
// public class GitHubPRSCMHead extends GitHubSCMHead<GitHubPRCause> {
// private static final long serialVersionUID = 1L;
//
// private final int prNumber;
// private final String targetBranch;
//
// public GitHubPRSCMHead(@NonNull GitHubPRCause prCause, String sourceId) {
// this(prCause.getNumber(), prCause.getTargetBranch(), sourceId);
// }
//
// public GitHubPRSCMHead(@NonNull Integer prNumber, @NonNull String targetBranch, String sourceId) {
// super("pr-" + Integer.toString(prNumber), sourceId);
// this.prNumber = prNumber;
// this.targetBranch = targetBranch;
// }
//
// public int getPrNumber() {
// return prNumber;
// }
//
// public String getTargetBranch() {
// return targetBranch;
// }
//
// @Override
// public String getPronoun() {
// return "PR#" + prNumber;
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHPullRequest pullRequest = remoteRepo.getPullRequest(prNumber);
// if (pullRequest == null) {
// throw new IOException("No PR " + prNumber + " in " + remoteRepo.getFullName());
// }
// return pullRequest.getHead().getSha();
// }
//
// @Override
// public String getHeadSha(GitHubPRCause cause) {
// return cause.getHeadSha();
// }
// }
|
import com.github.kostyasha.github.integration.multibranch.head.GitHubPRSCMHead;
import hudson.scm.SCM;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import org.jenkinsci.plugins.github.pullrequest.webhook.PullRequestInfo;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Collections;
import java.util.Map;
|
package com.github.kostyasha.github.integration.multibranch.hooks;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubPullRequestScmHeadEvent extends GitHubScmHeadEvent<PullRequestInfo> {
public GitHubPullRequestScmHeadEvent(@NonNull Type type, long timestamp, @NonNull PullRequestInfo payload,
@CheckForNull String origin) {
super(type, timestamp, payload, origin);
}
@NonNull
@Override
protected String getSourceRepo() {
return getPayload().getRepo();
}
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
if (!isMatch(source)) {
return Collections.emptyMap();
}
return Collections.singletonMap(
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubPRSCMHead.java
// public class GitHubPRSCMHead extends GitHubSCMHead<GitHubPRCause> {
// private static final long serialVersionUID = 1L;
//
// private final int prNumber;
// private final String targetBranch;
//
// public GitHubPRSCMHead(@NonNull GitHubPRCause prCause, String sourceId) {
// this(prCause.getNumber(), prCause.getTargetBranch(), sourceId);
// }
//
// public GitHubPRSCMHead(@NonNull Integer prNumber, @NonNull String targetBranch, String sourceId) {
// super("pr-" + Integer.toString(prNumber), sourceId);
// this.prNumber = prNumber;
// this.targetBranch = targetBranch;
// }
//
// public int getPrNumber() {
// return prNumber;
// }
//
// public String getTargetBranch() {
// return targetBranch;
// }
//
// @Override
// public String getPronoun() {
// return "PR#" + prNumber;
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHPullRequest pullRequest = remoteRepo.getPullRequest(prNumber);
// if (pullRequest == null) {
// throw new IOException("No PR " + prNumber + " in " + remoteRepo.getFullName());
// }
// return pullRequest.getHead().getSha();
// }
//
// @Override
// public String getHeadSha(GitHubPRCause cause) {
// return cause.getHeadSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/hooks/GitHubPullRequestScmHeadEvent.java
import com.github.kostyasha.github.integration.multibranch.head.GitHubPRSCMHead;
import hudson.scm.SCM;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import org.jenkinsci.plugins.github.pullrequest.webhook.PullRequestInfo;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Collections;
import java.util.Map;
package com.github.kostyasha.github.integration.multibranch.hooks;
/**
* @author Kanstantsin Shautsou
*/
public class GitHubPullRequestScmHeadEvent extends GitHubScmHeadEvent<PullRequestInfo> {
public GitHubPullRequestScmHeadEvent(@NonNull Type type, long timestamp, @NonNull PullRequestInfo payload,
@CheckForNull String origin) {
super(type, timestamp, payload, origin);
}
@NonNull
@Override
protected String getSourceRepo() {
return getPayload().getRepo();
}
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
if (!isMatch(source)) {
return Collections.emptyMap();
}
return Collections.singletonMap(
|
new GitHubPRSCMHead(getPayload().getNum(), getPayload().getTarget(), source.getId()), null
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelRemovePublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements removing of labels (one or many) from GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelRemovePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelRemovePublisher.class);
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelRemovePublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements removing of labels (one or many) from GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelRemovePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelRemovePublisher.class);
|
private GitHubPRLabel labelProperty;
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelRemovePublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements removing of labels (one or many) from GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelRemovePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelRemovePublisher.class);
private GitHubPRLabel labelProperty;
@DataBoundConstructor
public GitHubPRLabelRemovePublisher(GitHubPRLabel labelProperty,
StatusVerifier statusVerifier,
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRLabel.java
// public class GitHubPRLabel implements Describable<GitHubPRLabel> {
// private Set<String> labels;
//
// @DataBoundConstructor
// public GitHubPRLabel(String labels) {
// this(new HashSet<>(Arrays.asList(labels.split("\n"))));
// }
//
// public GitHubPRLabel(Set<String> labels) {
// this.labels = labels;
// }
//
// // for UI binding
// public String getLabels() {
// return Joiner.on("\n").skipNulls().join(labels);
// }
//
// @NonNull
// public Set<String> getLabelsSet() {
// return nonNull(labels) ? labels : Collections.<String>emptySet();
// }
//
// public DescriptorImpl getDescriptor() {
// return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);
// }
//
// @Symbol("labels")
// @Extension
// public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Labels";
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelRemovePublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements removing of labels (one or many) from GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelRemovePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelRemovePublisher.class);
private GitHubPRLabel labelProperty;
@DataBoundConstructor
public GitHubPRLabelRemovePublisher(GitHubPRLabel labelProperty,
StatusVerifier statusVerifier,
|
PublisherErrorHandler errorHandler) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/tag/GitHubTagCause.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/AbstractGitHubBranchCause.java
// public abstract class AbstractGitHubBranchCause<T extends AbstractGitHubBranchCause<T>> extends GitHubCause<T> {
//
// /**
// * null for deleted branch/tag
// */
// @CheckForNull
// private final String commitSha;
//
// @CheckForNull
// private final String fullRef;
//
// protected AbstractGitHubBranchCause(String commitSha, String fullRef) {
// this.commitSha = commitSha;
// this.fullRef = fullRef;
// }
//
// /**
// * Copy constructor
// */
// protected AbstractGitHubBranchCause(AbstractGitHubBranchCause<T> cause) {
// this(cause.getCommitSha(), cause.getFullRef());
// withGitUrl(cause.getGitUrl());
// withSshUrl(cause.getSshUrl());
// withHtmlUrl(cause.getHtmlUrl());
// withPollingLog(cause.getPollingLog());
// withReason(cause.getReason());
// withSkip(cause.isSkip());
// withTitle(cause.getTitle());
// }
//
// @CheckForNull
// public String getCommitSha() {
// return commitSha;
// }
//
// @CheckForNull
// public String getFullRef() {
// return fullRef;
// }
//
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
|
import com.github.kostyasha.github.integration.branch.AbstractGitHubBranchCause;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import hudson.model.ParameterValue;
import org.kohsuke.github.GHTag;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.List;
|
}
/**
* Copy constructor
*/
public GitHubTagCause(GitHubTagCause cause) {
super(cause);
this.tagName = cause.getTagName();
}
public String getTagName() {
return tagName;
}
@NonNull
@Override
public String getShortDescription() {
if (getHtmlUrl() != null) {
return "GitHub tag " + getTagName() + ": " + getReason();
} else {
return "Deleted tag";
}
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubTagEnv.getParams(this, params);
}
@Override
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/AbstractGitHubBranchCause.java
// public abstract class AbstractGitHubBranchCause<T extends AbstractGitHubBranchCause<T>> extends GitHubCause<T> {
//
// /**
// * null for deleted branch/tag
// */
// @CheckForNull
// private final String commitSha;
//
// @CheckForNull
// private final String fullRef;
//
// protected AbstractGitHubBranchCause(String commitSha, String fullRef) {
// this.commitSha = commitSha;
// this.fullRef = fullRef;
// }
//
// /**
// * Copy constructor
// */
// protected AbstractGitHubBranchCause(AbstractGitHubBranchCause<T> cause) {
// this(cause.getCommitSha(), cause.getFullRef());
// withGitUrl(cause.getGitUrl());
// withSshUrl(cause.getSshUrl());
// withHtmlUrl(cause.getHtmlUrl());
// withPollingLog(cause.getPollingLog());
// withReason(cause.getReason());
// withSkip(cause.isSkip());
// withTitle(cause.getTitle());
// }
//
// @CheckForNull
// public String getCommitSha() {
// return commitSha;
// }
//
// @CheckForNull
// public String getFullRef() {
// return fullRef;
// }
//
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/tag/GitHubTagCause.java
import com.github.kostyasha.github.integration.branch.AbstractGitHubBranchCause;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import hudson.model.ParameterValue;
import org.kohsuke.github.GHTag;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.List;
}
/**
* Copy constructor
*/
public GitHubTagCause(GitHubTagCause cause) {
super(cause);
this.tagName = cause.getTagName();
}
public String getTagName() {
return tagName;
}
@NonNull
@Override
public String getShortDescription() {
if (getHtmlUrl() != null) {
return "GitHub tag " + getTagName() + ": " + getReason();
} else {
return "Deleted tag";
}
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubTagEnv.getParams(this, params);
}
@Override
|
public GitHubSCMHead<GitHubTagCause> createSCMHead(String sourceId) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/tag/GitHubTagCause.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/AbstractGitHubBranchCause.java
// public abstract class AbstractGitHubBranchCause<T extends AbstractGitHubBranchCause<T>> extends GitHubCause<T> {
//
// /**
// * null for deleted branch/tag
// */
// @CheckForNull
// private final String commitSha;
//
// @CheckForNull
// private final String fullRef;
//
// protected AbstractGitHubBranchCause(String commitSha, String fullRef) {
// this.commitSha = commitSha;
// this.fullRef = fullRef;
// }
//
// /**
// * Copy constructor
// */
// protected AbstractGitHubBranchCause(AbstractGitHubBranchCause<T> cause) {
// this(cause.getCommitSha(), cause.getFullRef());
// withGitUrl(cause.getGitUrl());
// withSshUrl(cause.getSshUrl());
// withHtmlUrl(cause.getHtmlUrl());
// withPollingLog(cause.getPollingLog());
// withReason(cause.getReason());
// withSkip(cause.isSkip());
// withTitle(cause.getTitle());
// }
//
// @CheckForNull
// public String getCommitSha() {
// return commitSha;
// }
//
// @CheckForNull
// public String getFullRef() {
// return fullRef;
// }
//
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
|
import com.github.kostyasha.github.integration.branch.AbstractGitHubBranchCause;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import hudson.model.ParameterValue;
import org.kohsuke.github.GHTag;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.List;
|
/**
* Copy constructor
*/
public GitHubTagCause(GitHubTagCause cause) {
super(cause);
this.tagName = cause.getTagName();
}
public String getTagName() {
return tagName;
}
@NonNull
@Override
public String getShortDescription() {
if (getHtmlUrl() != null) {
return "GitHub tag " + getTagName() + ": " + getReason();
} else {
return "Deleted tag";
}
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubTagEnv.getParams(this, params);
}
@Override
public GitHubSCMHead<GitHubTagCause> createSCMHead(String sourceId) {
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/branch/AbstractGitHubBranchCause.java
// public abstract class AbstractGitHubBranchCause<T extends AbstractGitHubBranchCause<T>> extends GitHubCause<T> {
//
// /**
// * null for deleted branch/tag
// */
// @CheckForNull
// private final String commitSha;
//
// @CheckForNull
// private final String fullRef;
//
// protected AbstractGitHubBranchCause(String commitSha, String fullRef) {
// this.commitSha = commitSha;
// this.fullRef = fullRef;
// }
//
// /**
// * Copy constructor
// */
// protected AbstractGitHubBranchCause(AbstractGitHubBranchCause<T> cause) {
// this(cause.getCommitSha(), cause.getFullRef());
// withGitUrl(cause.getGitUrl());
// withSshUrl(cause.getSshUrl());
// withHtmlUrl(cause.getHtmlUrl());
// withPollingLog(cause.getPollingLog());
// withReason(cause.getReason());
// withSkip(cause.isSkip());
// withTitle(cause.getTitle());
// }
//
// @CheckForNull
// public String getCommitSha() {
// return commitSha;
// }
//
// @CheckForNull
// public String getFullRef() {
// return fullRef;
// }
//
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubTagSCMHead.java
// public class GitHubTagSCMHead extends GitHubSCMHead<GitHubTagCause> {
// private static final long serialVersionUID = 1L;
//
// public GitHubTagSCMHead(@NonNull String name, String sourceId) {
// super(name, sourceId);
// }
//
// @Override
// public String getPronoun() {
// return "Tag " + getName();
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHTag tag = GitHubTag.findRemoteTag(remoteRepo, getName());
// if (tag == null) {
// throw new IOException("No tag " + getName() + " in " + remoteRepo.getFullName());
// }
// return tag.getCommit().getSHA1();
// }
//
// public String getHeadSha(GitHubTagCause cause) {
// return cause.getCommitSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/tag/GitHubTagCause.java
import com.github.kostyasha.github.integration.branch.AbstractGitHubBranchCause;
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.head.GitHubTagSCMHead;
import hudson.model.ParameterValue;
import org.kohsuke.github.GHTag;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.List;
/**
* Copy constructor
*/
public GitHubTagCause(GitHubTagCause cause) {
super(cause);
this.tagName = cause.getTagName();
}
public String getTagName() {
return tagName;
}
@NonNull
@Override
public String getShortDescription() {
if (getHtmlUrl() != null) {
return "GitHub tag " + getTagName() + ": " + getReason();
} else {
return "Deleted tag";
}
}
@Override
public void fillParameters(List<ParameterValue> params) {
GitHubTagEnv.getParams(this, params);
}
@Override
public GitHubSCMHead<GitHubTagCause> createSCMHead(String sourceId) {
|
return new GitHubTagSCMHead(tagName, sourceId);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/generic/GitHubCause.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
|
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.revision.GitHubSCMRevision;
import hudson.model.Cause;
import hudson.model.ParameterValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.apache.commons.lang.StringUtils.abbreviate;
|
return remoteData;
}
public GitHubCause<T> withRemoteData(Object remoteData) {
this.remoteData = remoteData;
return this;
}
/**
* @return the title of the cause, never null.
*/
@NonNull
public String getTitle() {
return nonNull(title) ? title : "";
}
public GitHubCause<T> withTitle(String title) {
this.title = title;
return this;
}
/**
* @return at most the first 30 characters of the title, or
*/
public String getAbbreviatedTitle() {
return abbreviate(getTitle(), 30);
}
public abstract void fillParameters(List<ParameterValue> params);
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubSCMHead.java
// public abstract class GitHubSCMHead<T extends GitHubCause<T>> extends SCMHead {
// private static final long serialVersionUID = 1L;
//
// private final String sourceId;
//
// public GitHubSCMHead(@NonNull String name, String sourceId) {
// super(name);
// this.sourceId = sourceId;
// }
//
// public String getSourceId() {
// return sourceId;
// }
//
// public abstract String fetchHeadSha(GHRepository remoteRepo) throws IOException;
//
// public abstract String getHeadSha(T cause);
//
// public GitHubSCMRevision createSCMRevision(T cause) {
// return new GitHubSCMRevision(this, getHeadSha(cause), cause);
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/generic/GitHubCause.java
import com.github.kostyasha.github.integration.multibranch.head.GitHubSCMHead;
import com.github.kostyasha.github.integration.multibranch.revision.GitHubSCMRevision;
import hudson.model.Cause;
import hudson.model.ParameterValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.apache.commons.lang.StringUtils.abbreviate;
return remoteData;
}
public GitHubCause<T> withRemoteData(Object remoteData) {
this.remoteData = remoteData;
return this;
}
/**
* @return the title of the cause, never null.
*/
@NonNull
public String getTitle() {
return nonNull(title) ? title : "";
}
public GitHubCause<T> withTitle(String title) {
this.title = title;
return this;
}
/**
* @return at most the first 30 characters of the title, or
*/
public String getAbbreviatedTitle() {
return abbreviate(getTitle(), 30);
}
public abstract void fillParameters(List<ParameterValue> params);
|
public abstract GitHubSCMHead<T> createSCMHead(String sourceId);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRRepositoryFactory.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRTrigger ghPRTriggerFromJob(Job<?, ?> job) {
// return triggerFrom(job, GitHubPRTrigger.class);
// }
|
import com.cloudbees.jenkins.GitHubRepositoryName;
import com.coravy.hudson.plugins.github.GithubProjectProperty;
import com.github.kostyasha.github.integration.generic.GitHubRepositoryFactory;
import hudson.Extension;
import hudson.XmlFile;
import hudson.model.Action;
import hudson.model.Job;
import hudson.model.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import static java.util.Collections.singleton;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromJob;
|
package org.jenkinsci.plugins.github.pullrequest;
/**
* Create GitHubPRRepository.
* Don't depend on remote connection because updateTransientActions() called only once and connection may appear later.
*
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRRepositoryFactory extends GitHubRepositoryFactory<GitHubPRRepositoryFactory, GitHubPRTrigger> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRRepositoryFactory.class);
@Override
@NonNull
public Collection<? extends Action> createFor(@NonNull Job job) {
try {
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRTrigger ghPRTriggerFromJob(Job<?, ?> job) {
// return triggerFrom(job, GitHubPRTrigger.class);
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRRepositoryFactory.java
import com.cloudbees.jenkins.GitHubRepositoryName;
import com.coravy.hudson.plugins.github.GithubProjectProperty;
import com.github.kostyasha.github.integration.generic.GitHubRepositoryFactory;
import hudson.Extension;
import hudson.XmlFile;
import hudson.model.Action;
import hudson.model.Job;
import hudson.model.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import static java.util.Collections.singleton;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromJob;
package org.jenkinsci.plugins.github.pullrequest;
/**
* Create GitHubPRRepository.
* Don't depend on remote connection because updateTransientActions() called only once and connection may appear later.
*
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRRepositoryFactory extends GitHubRepositoryFactory<GitHubPRRepositoryFactory, GitHubPRTrigger> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRRepositoryFactory.class);
@Override
@NonNull
public Collection<? extends Action> createFor(@NonNull Job job) {
try {
|
if (nonNull(ghPRTriggerFromJob(job))) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
|
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
String publishedURL = getTriggerDescriptor().getPublishedURL();
if (publishedURL != null && !publishedURL.isEmpty()) {
try {
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
String publishedURL = getTriggerDescriptor().getPublishedURL();
if (publishedURL != null && !publishedURL.isEmpty()) {
try {
|
if (getGhIssue(run).getState().equals(GHIssueState.OPEN)) {
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
String publishedURL = getTriggerDescriptor().getPublishedURL();
if (publishedURL != null && !publishedURL.isEmpty()) {
try {
if (getGhIssue(run).getState().equals(GHIssueState.OPEN)) {
try {
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
String publishedURL = getTriggerDescriptor().getPublishedURL();
if (publishedURL != null && !publishedURL.isEmpty()) {
try {
if (getGhIssue(run).getState().equals(GHIssueState.OPEN)) {
try {
|
getGhPullRequest(run).close();
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
|
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
|
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
String publishedURL = getTriggerDescriptor().getPublishedURL();
if (publishedURL != null && !publishedURL.isEmpty()) {
try {
if (getGhIssue(run).getState().equals(GHIssueState.OPEN)) {
try {
getGhPullRequest(run).close();
} catch (IOException ex) {
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/GitHubPRAbstractPublisher.java
// public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {
//
// @CheckForNull
// private StatusVerifier statusVerifier;
//
// @CheckForNull
// private PublisherErrorHandler errorHandler;
//
// public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
// this.statusVerifier = statusVerifier;
// this.errorHandler = errorHandler;
// }
//
// public StatusVerifier getStatusVerifier() {
// return statusVerifier;
// }
//
// public PublisherErrorHandler getErrorHandler() {
// return errorHandler;
// }
//
// protected void handlePublisherError(Run<?, ?> run) {
// if (errorHandler != null) {
// errorHandler.markBuildAfterError(run);
// }
// }
//
// public final BuildStepMonitor getRequiredMonitorService() {
// return BuildStepMonitor.NONE;
// }
//
// public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {
// return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);
// }
//
// public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
// @Override
// public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {
// return true;
// }
//
// @Override
// public abstract String getDisplayName();
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/PublisherErrorHandler.java
// public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {
//
// private Result buildStatus;
//
// @DataBoundConstructor
// public PublisherErrorHandler(Result buildStatus) {
// this.buildStatus = buildStatus;
// }
//
// public Result getBuildStatus() {
// return buildStatus;
// }
//
// public Result markBuildAfterError(Run<?, ?> run) {
// run.setResult(buildStatus);
// return buildStatus;
// }
//
// @Symbol("statusOnPublisherError")
// @Extension
// public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {
// @NonNull
// @Override
// public String getDisplayName() {
// return "Set build status if publisher failed";
// }
//
// public ListBoxModel doFillBuildStatusItems() {
// ListBoxModel items = new ListBoxModel();
// items.add(Result.UNSTABLE.toString());
// items.add(Result.FAILURE.toString());
// return items;
// }
// }
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static GHIssue getGhPullRequest(final Run<?, ?> run) throws IOException {
// return getGhRepositoryFromPRTrigger(run).getPullRequest(getPRNumberFromPRCause(run));
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {
// GitHubPRCause cause = ghPRCauseFromRun(run);
// if (isNull(cause)) {
// throw new AbortException("Can't get cause from run/build");
// }
// return cause.getNumber();
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRClosePublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhPullRequest;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Closes pull request after build.
*
* @author Alina Karpovich
*/
public class GitHubPRClosePublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRClosePublisher.class);
@DataBoundConstructor
public GitHubPRClosePublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
String publishedURL = getTriggerDescriptor().getPublishedURL();
if (publishedURL != null && !publishedURL.isEmpty()) {
try {
if (getGhIssue(run).getState().equals(GHIssueState.OPEN)) {
try {
getGhPullRequest(run).close();
} catch (IOException ex) {
|
LOGGER.error("Couldn't close the pull request #{}:", getPRNumberFromPRCause(run), ex);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/category/GitHubPRSCMHeadCategory.java
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubPRSCMHead.java
// public class GitHubPRSCMHead extends GitHubSCMHead<GitHubPRCause> {
// private static final long serialVersionUID = 1L;
//
// private final int prNumber;
// private final String targetBranch;
//
// public GitHubPRSCMHead(@NonNull GitHubPRCause prCause, String sourceId) {
// this(prCause.getNumber(), prCause.getTargetBranch(), sourceId);
// }
//
// public GitHubPRSCMHead(@NonNull Integer prNumber, @NonNull String targetBranch, String sourceId) {
// super("pr-" + Integer.toString(prNumber), sourceId);
// this.prNumber = prNumber;
// this.targetBranch = targetBranch;
// }
//
// public int getPrNumber() {
// return prNumber;
// }
//
// public String getTargetBranch() {
// return targetBranch;
// }
//
// @Override
// public String getPronoun() {
// return "PR#" + prNumber;
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHPullRequest pullRequest = remoteRepo.getPullRequest(prNumber);
// if (pullRequest == null) {
// throw new IOException("No PR " + prNumber + " in " + remoteRepo.getFullName());
// }
// return pullRequest.getHead().getSha();
// }
//
// @Override
// public String getHeadSha(GitHubPRCause cause) {
// return cause.getHeadSha();
// }
// }
|
import com.github.kostyasha.github.integration.multibranch.head.GitHubPRSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.util.NonLocalizable;
import org.jvnet.localizer.Localizable;
import edu.umd.cs.findbugs.annotations.NonNull;
|
package com.github.kostyasha.github.integration.multibranch.category;
public class GitHubPRSCMHeadCategory extends GitHubSCMHeadCategory {
public static final GitHubPRSCMHeadCategory PR = new GitHubPRSCMHeadCategory("pr", new NonLocalizable("Pull Requests"));
public GitHubPRSCMHeadCategory(@NonNull String urlName, Localizable pronoun) {
super(urlName, pronoun);
}
@Override
public boolean isMatch(@NonNull SCMHead instance) {
|
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/head/GitHubPRSCMHead.java
// public class GitHubPRSCMHead extends GitHubSCMHead<GitHubPRCause> {
// private static final long serialVersionUID = 1L;
//
// private final int prNumber;
// private final String targetBranch;
//
// public GitHubPRSCMHead(@NonNull GitHubPRCause prCause, String sourceId) {
// this(prCause.getNumber(), prCause.getTargetBranch(), sourceId);
// }
//
// public GitHubPRSCMHead(@NonNull Integer prNumber, @NonNull String targetBranch, String sourceId) {
// super("pr-" + Integer.toString(prNumber), sourceId);
// this.prNumber = prNumber;
// this.targetBranch = targetBranch;
// }
//
// public int getPrNumber() {
// return prNumber;
// }
//
// public String getTargetBranch() {
// return targetBranch;
// }
//
// @Override
// public String getPronoun() {
// return "PR#" + prNumber;
// }
//
// @Override
// public String fetchHeadSha(GHRepository remoteRepo) throws IOException {
// GHPullRequest pullRequest = remoteRepo.getPullRequest(prNumber);
// if (pullRequest == null) {
// throw new IOException("No PR " + prNumber + " in " + remoteRepo.getFullName());
// }
// return pullRequest.getHead().getSha();
// }
//
// @Override
// public String getHeadSha(GitHubPRCause cause) {
// return cause.getHeadSha();
// }
// }
// Path: github-pullrequest-plugin/src/main/java/com/github/kostyasha/github/integration/multibranch/category/GitHubPRSCMHeadCategory.java
import com.github.kostyasha.github.integration.multibranch.head.GitHubPRSCMHead;
import jenkins.scm.api.SCMHead;
import jenkins.util.NonLocalizable;
import org.jvnet.localizer.Localizable;
import edu.umd.cs.findbugs.annotations.NonNull;
package com.github.kostyasha.github.integration.multibranch.category;
public class GitHubPRSCMHeadCategory extends GitHubSCMHeadCategory {
public static final GitHubPRSCMHeadCategory PR = new GitHubPRSCMHeadCategory("pr", new NonLocalizable("Pull Requests"));
public GitHubPRSCMHeadCategory(@NonNull String urlName, Localizable pronoun) {
super(urlName, pronoun);
}
@Override
public boolean isMatch(@NonNull SCMHead instance) {
|
return instance instanceof GitHubPRSCMHead;
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRBuildListener.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRCause ghPRCauseFromRun(Run<?, ?> run) {
// return ghCauseFromRun(run, GitHubPRCause.class);
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRTrigger ghPRTriggerFromRun(Run<?, ?> run) {
// return triggerFrom(run.getParent(), GitHubPRTrigger.class);
// }
|
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.git.util.BuildData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRCauseFromRun;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromRun;
|
package org.jenkinsci.plugins.github.pullrequest;
/**
* Sets Pending build status before build run and manipulates Git's BuildData attached to job Action.
*
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRBuildListener extends RunListener<Run<?, ?>> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRBuildListener.class);
@Override
public void onCompleted(Run<?, ?> run, @NonNull TaskListener listener) {
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRCause ghPRCauseFromRun(Run<?, ?> run) {
// return ghCauseFromRun(run, GitHubPRCause.class);
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRTrigger ghPRTriggerFromRun(Run<?, ?> run) {
// return triggerFrom(run.getParent(), GitHubPRTrigger.class);
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRBuildListener.java
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.git.util.BuildData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRCauseFromRun;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromRun;
package org.jenkinsci.plugins.github.pullrequest;
/**
* Sets Pending build status before build run and manipulates Git's BuildData attached to job Action.
*
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRBuildListener extends RunListener<Run<?, ?>> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRBuildListener.class);
@Override
public void onCompleted(Run<?, ?> run, @NonNull TaskListener listener) {
|
GitHubPRTrigger trigger = ghPRTriggerFromRun(run);
|
KostyaSha/github-integration-plugin
|
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRBuildListener.java
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRCause ghPRCauseFromRun(Run<?, ?> run) {
// return ghCauseFromRun(run, GitHubPRCause.class);
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRTrigger ghPRTriggerFromRun(Run<?, ?> run) {
// return triggerFrom(run.getParent(), GitHubPRTrigger.class);
// }
|
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.git.util.BuildData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRCauseFromRun;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromRun;
|
package org.jenkinsci.plugins.github.pullrequest;
/**
* Sets Pending build status before build run and manipulates Git's BuildData attached to job Action.
*
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRBuildListener extends RunListener<Run<?, ?>> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRBuildListener.class);
@Override
public void onCompleted(Run<?, ?> run, @NonNull TaskListener listener) {
GitHubPRTrigger trigger = ghPRTriggerFromRun(run);
if (isNull(trigger)) {
return;
}
|
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRCause ghPRCauseFromRun(Run<?, ?> run) {
// return ghCauseFromRun(run, GitHubPRCause.class);
// }
//
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/utils/JobHelper.java
// @CheckForNull
// public static GitHubPRTrigger ghPRTriggerFromRun(Run<?, ?> run) {
// return triggerFrom(run.getParent(), GitHubPRTrigger.class);
// }
// Path: github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/GitHubPRBuildListener.java
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.git.util.BuildData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRCauseFromRun;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromRun;
package org.jenkinsci.plugins.github.pullrequest;
/**
* Sets Pending build status before build run and manipulates Git's BuildData attached to job Action.
*
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRBuildListener extends RunListener<Run<?, ?>> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRBuildListener.class);
@Override
public void onCompleted(Run<?, ?> run, @NonNull TaskListener listener) {
GitHubPRTrigger trigger = ghPRTriggerFromRun(run);
if (isNull(trigger)) {
return;
}
|
GitHubPRCause cause = ghPRCauseFromRun(run);
|
in28minutes/SpringMvcStepByStep
|
src/main/java/com/in28minutes/todo/TodoController.java
|
// Path: src/main/java/com/in28minutes/exception/ExceptionController.java
// @ControllerAdvice
// public class ExceptionController {
//
// private Log logger = LogFactory.getLog(ExceptionController.class);
//
// @ExceptionHandler(value = Exception.class)
// public String handleException(HttpServletRequest request, Exception ex) {
// logger.error("Request " + request.getRequestURL()
// + " Threw an Exception", ex);
// return "error";
// }
//
// }
|
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.in28minutes.exception.ExceptionController;
|
package com.in28minutes.todo;
@Controller
@SessionAttributes("name")
public class TodoController {
|
// Path: src/main/java/com/in28minutes/exception/ExceptionController.java
// @ControllerAdvice
// public class ExceptionController {
//
// private Log logger = LogFactory.getLog(ExceptionController.class);
//
// @ExceptionHandler(value = Exception.class)
// public String handleException(HttpServletRequest request, Exception ex) {
// logger.error("Request " + request.getRequestURL()
// + " Threw an Exception", ex);
// return "error";
// }
//
// }
// Path: src/main/java/com/in28minutes/todo/TodoController.java
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.in28minutes.exception.ExceptionController;
package com.in28minutes.todo;
@Controller
@SessionAttributes("name")
public class TodoController {
|
private Log logger = LogFactory.getLog(ExceptionController.class);
|
idega/se.idega.idegaweb.commune.school
|
src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassViewer.java
|
// Path: src/java/se/idega/idegaweb/commune/school/event/SchoolEventListener.java
// public class SchoolEventListener implements IWPageEventListener {
//
// private int _schoolID = -1;
// private int _schoolSeasonID = -1;
// private int _schoolYearID = -1;
// private int _schoolClassID = -1;
// private int _studentID = -1;
//
// /**
// * @see com.idega.business.IWEventListener#actionPerformed(IWContext)
// */
// public boolean actionPerformed(IWContext iwc) {
// try {
// SchoolCommuneSession session = getSchoolCommuneSession(iwc);
// this._schoolID = session.getSchoolID();
//
// if (iwc.isParameterSet(session.getParameterSchoolID())) {
// this._schoolID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolSeasonID())) {
// this._schoolSeasonID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolSeasonID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolYearID())) {
// this._schoolYearID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolYearID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolClassID())) {
// this._schoolClassID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolClassID()));
// }
//
// if (iwc.isParameterSet(session.getParameterStudentID())) {
// this._studentID = Integer.parseInt(iwc.getParameter(session.getParameterStudentID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolGroupIDs())) {
// session.setSchoolGroupIDs(iwc.getParameterValues(session.getParameterSchoolGroupIDs()));
// }
//
// if ( this._schoolClassID != -1 && this._schoolYearID != -1 ) {
// validateSchoolClass(iwc);
// }
//
// session.setSchoolClassID(this._schoolClassID);
// session.setSchoolID(this._schoolID);
// session.setSchoolSeasonID(this._schoolSeasonID);
// session.setSchoolYearID(this._schoolYearID);
// session.setStudentID(this._studentID);
// return true;
// }
// catch (RemoteException re) {
// return false;
// }
// }
//
// private void validateSchoolClass(IWContext iwc) throws RemoteException {
// SchoolClass schoolClass = getSchoolCommuneBusiness(iwc).getSchoolBusiness().findSchoolClass(new Integer(this._schoolClassID));
// SchoolYear schoolYear = getSchoolCommuneBusiness(iwc).getSchoolBusiness().getSchoolYear(new Integer(this._schoolYearID));
// if (!schoolClass.hasRelationToSchoolYear(schoolYear) ) {
// Collection schoolClasses = getSchoolCommuneBusiness(iwc).getSchoolBusiness().findSchoolClassesBySchoolAndSeasonAndYear(this._schoolID, this._schoolSeasonID, this._schoolYearID);
// if ( !schoolClasses.isEmpty() ) {
// Iterator iter = schoolClasses.iterator();
// while (iter.hasNext()) {
// this._schoolClassID = ((Integer)((SchoolClass) iter.next()).getPrimaryKey()).intValue();
// continue;
// }
// }
// }
// }
//
// private SchoolCommuneSession getSchoolCommuneSession(IWContext iwc) throws RemoteException {
// return (SchoolCommuneSession) IBOLookup.getSessionInstance(iwc, SchoolCommuneSession.class);
// }
//
// private SchoolCommuneBusiness getSchoolCommuneBusiness(IWContext iwc) throws RemoteException {
// return (SchoolCommuneBusiness) IBOLookup.getServiceInstance(iwc, SchoolCommuneBusiness.class);
// }
//
// }
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import se.idega.idegaweb.commune.school.event.SchoolEventListener;
import com.idega.block.school.business.SchoolYearComparator;
import com.idega.block.school.data.SchoolYear;
import com.idega.data.IDORelationshipException;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.CheckBox;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.GenericButton;
import com.idega.presentation.ui.SubmitButton;
|
/*
* Created on Dec 11, 2003
*/
package se.idega.idegaweb.commune.school.presentation;
/**
* @author laddi
*/
public class SchoolClassViewer extends SchoolCommuneBlock {
/* (non-Javadoc)
* @see se.idega.idegaweb.commune.school.presentation.SchoolCommuneBlock#init(com.idega.presentation.IWContext)
*/
public void init(IWContext iwc) throws Exception {
Form form = new Form();
|
// Path: src/java/se/idega/idegaweb/commune/school/event/SchoolEventListener.java
// public class SchoolEventListener implements IWPageEventListener {
//
// private int _schoolID = -1;
// private int _schoolSeasonID = -1;
// private int _schoolYearID = -1;
// private int _schoolClassID = -1;
// private int _studentID = -1;
//
// /**
// * @see com.idega.business.IWEventListener#actionPerformed(IWContext)
// */
// public boolean actionPerformed(IWContext iwc) {
// try {
// SchoolCommuneSession session = getSchoolCommuneSession(iwc);
// this._schoolID = session.getSchoolID();
//
// if (iwc.isParameterSet(session.getParameterSchoolID())) {
// this._schoolID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolSeasonID())) {
// this._schoolSeasonID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolSeasonID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolYearID())) {
// this._schoolYearID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolYearID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolClassID())) {
// this._schoolClassID = Integer.parseInt(iwc.getParameter(session.getParameterSchoolClassID()));
// }
//
// if (iwc.isParameterSet(session.getParameterStudentID())) {
// this._studentID = Integer.parseInt(iwc.getParameter(session.getParameterStudentID()));
// }
//
// if (iwc.isParameterSet(session.getParameterSchoolGroupIDs())) {
// session.setSchoolGroupIDs(iwc.getParameterValues(session.getParameterSchoolGroupIDs()));
// }
//
// if ( this._schoolClassID != -1 && this._schoolYearID != -1 ) {
// validateSchoolClass(iwc);
// }
//
// session.setSchoolClassID(this._schoolClassID);
// session.setSchoolID(this._schoolID);
// session.setSchoolSeasonID(this._schoolSeasonID);
// session.setSchoolYearID(this._schoolYearID);
// session.setStudentID(this._studentID);
// return true;
// }
// catch (RemoteException re) {
// return false;
// }
// }
//
// private void validateSchoolClass(IWContext iwc) throws RemoteException {
// SchoolClass schoolClass = getSchoolCommuneBusiness(iwc).getSchoolBusiness().findSchoolClass(new Integer(this._schoolClassID));
// SchoolYear schoolYear = getSchoolCommuneBusiness(iwc).getSchoolBusiness().getSchoolYear(new Integer(this._schoolYearID));
// if (!schoolClass.hasRelationToSchoolYear(schoolYear) ) {
// Collection schoolClasses = getSchoolCommuneBusiness(iwc).getSchoolBusiness().findSchoolClassesBySchoolAndSeasonAndYear(this._schoolID, this._schoolSeasonID, this._schoolYearID);
// if ( !schoolClasses.isEmpty() ) {
// Iterator iter = schoolClasses.iterator();
// while (iter.hasNext()) {
// this._schoolClassID = ((Integer)((SchoolClass) iter.next()).getPrimaryKey()).intValue();
// continue;
// }
// }
// }
// }
//
// private SchoolCommuneSession getSchoolCommuneSession(IWContext iwc) throws RemoteException {
// return (SchoolCommuneSession) IBOLookup.getSessionInstance(iwc, SchoolCommuneSession.class);
// }
//
// private SchoolCommuneBusiness getSchoolCommuneBusiness(IWContext iwc) throws RemoteException {
// return (SchoolCommuneBusiness) IBOLookup.getServiceInstance(iwc, SchoolCommuneBusiness.class);
// }
//
// }
// Path: src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassViewer.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import se.idega.idegaweb.commune.school.event.SchoolEventListener;
import com.idega.block.school.business.SchoolYearComparator;
import com.idega.block.school.data.SchoolYear;
import com.idega.data.IDORelationshipException;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.CheckBox;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.GenericButton;
import com.idega.presentation.ui.SubmitButton;
/*
* Created on Dec 11, 2003
*/
package se.idega.idegaweb.commune.school.presentation;
/**
* @author laddi
*/
public class SchoolClassViewer extends SchoolCommuneBlock {
/* (non-Javadoc)
* @see se.idega.idegaweb.commune.school.presentation.SchoolCommuneBlock#init(com.idega.presentation.IWContext)
*/
public void init(IWContext iwc) throws Exception {
Form form = new Form();
|
form.setEventListener(SchoolEventListener.class);
|
idega/se.idega.idegaweb.commune.school
|
src/java/se/idega/idegaweb/commune/school/business/CentralPlacementBusinessBean.java
|
// Path: src/java/se/idega/idegaweb/commune/school/presentation/CentralPlacementEditorConstants.java
// public class CentralPlacementEditorConstants {
//
// public static final String KP = "central_placement_editor.";
// public static final String FORM_NAME = CommuneCareConstants.CENTRAL_PLACEMENT_EDITOR_FORM_NAME;
// public static final String KEY_PLACEMENT_PARAGRAPH_LABEL = KP + "placement_paragraph_label";
// public static final String KEY_SCHOOL_YEAR = KP + "school_year";
// public static final String KEY_SCHOOL_GROUP = KP + "school_group";
// public static final String KEY_STUDY_PATH = KP + "study_path";
// public static final String KEY_LANGUAGE = KP + "language";
// public static final String KEY_NATIVE_LANGUAGE = KP + "native_language";
//
// }
|
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.FinderException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import se.idega.idegaweb.commune.business.CommuneUserBusiness;
import se.idega.idegaweb.commune.care.business.CareBusiness;
import se.idega.idegaweb.commune.care.resource.data.ResourceClassMember;
import se.idega.idegaweb.commune.care.resource.data.ResourceClassMemberHome;
import se.idega.idegaweb.commune.school.presentation.CentralPlacementEditorConstants;
import com.idega.block.school.business.SchoolBusiness;
import com.idega.block.school.data.SchoolCategory;
import com.idega.block.school.data.SchoolCategoryHome;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.block.school.data.SchoolClassMemberHome;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolStudyPath;
import com.idega.block.school.data.SchoolStudyPathHome;
import com.idega.block.school.data.SchoolYear;
import com.idega.business.IBOLookup;
import com.idega.business.IBOServiceBean;
import com.idega.data.IDOLookup;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.IWContext;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
|
public SchoolSeason getCurrentSeason() {
SchoolSeason season = null;
try {
season = getCareBusiness().getSchoolSeasonHome().findSeasonByDate(getSchoolBusiness().getCategoryElementarySchool(), new IWTimestamp().getDate());
} catch (Exception e) {}
if (season == null) {
try {
season = getCareBusiness().getCurrentSeason();
} catch (Exception e1) {
e1.printStackTrace();
}
}
return season;
}
public String getPlacementString(SchoolClassMember placement, User user, IWResourceBundle iwrb) {
// Placement
StringBuffer buf = new StringBuffer("");
try {
// add school name
buf.append(placement.getSchoolClass().getSchool().getName());
} catch (Exception e) {}
try {
// school year
SchoolYear theYear = placement.getSchoolYear();
if (theYear != null) {
|
// Path: src/java/se/idega/idegaweb/commune/school/presentation/CentralPlacementEditorConstants.java
// public class CentralPlacementEditorConstants {
//
// public static final String KP = "central_placement_editor.";
// public static final String FORM_NAME = CommuneCareConstants.CENTRAL_PLACEMENT_EDITOR_FORM_NAME;
// public static final String KEY_PLACEMENT_PARAGRAPH_LABEL = KP + "placement_paragraph_label";
// public static final String KEY_SCHOOL_YEAR = KP + "school_year";
// public static final String KEY_SCHOOL_GROUP = KP + "school_group";
// public static final String KEY_STUDY_PATH = KP + "study_path";
// public static final String KEY_LANGUAGE = KP + "language";
// public static final String KEY_NATIVE_LANGUAGE = KP + "native_language";
//
// }
// Path: src/java/se/idega/idegaweb/commune/school/business/CentralPlacementBusinessBean.java
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.FinderException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import se.idega.idegaweb.commune.business.CommuneUserBusiness;
import se.idega.idegaweb.commune.care.business.CareBusiness;
import se.idega.idegaweb.commune.care.resource.data.ResourceClassMember;
import se.idega.idegaweb.commune.care.resource.data.ResourceClassMemberHome;
import se.idega.idegaweb.commune.school.presentation.CentralPlacementEditorConstants;
import com.idega.block.school.business.SchoolBusiness;
import com.idega.block.school.data.SchoolCategory;
import com.idega.block.school.data.SchoolCategoryHome;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.block.school.data.SchoolClassMemberHome;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolStudyPath;
import com.idega.block.school.data.SchoolStudyPathHome;
import com.idega.block.school.data.SchoolYear;
import com.idega.business.IBOLookup;
import com.idega.business.IBOServiceBean;
import com.idega.data.IDOLookup;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.IWContext;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
public SchoolSeason getCurrentSeason() {
SchoolSeason season = null;
try {
season = getCareBusiness().getSchoolSeasonHome().findSeasonByDate(getSchoolBusiness().getCategoryElementarySchool(), new IWTimestamp().getDate());
} catch (Exception e) {}
if (season == null) {
try {
season = getCareBusiness().getCurrentSeason();
} catch (Exception e1) {
e1.printStackTrace();
}
}
return season;
}
public String getPlacementString(SchoolClassMember placement, User user, IWResourceBundle iwrb) {
// Placement
StringBuffer buf = new StringBuffer("");
try {
// add school name
buf.append(placement.getSchoolClass().getSchool().getName());
} catch (Exception e) {}
try {
// school year
SchoolYear theYear = placement.getSchoolYear();
if (theYear != null) {
|
buf.append(", " + iwrb.getLocalizedString(CentralPlacementEditorConstants.KEY_SCHOOL_YEAR, "school year") + " "
|
idega/se.idega.idegaweb.commune.school
|
src/java/se/idega/idegaweb/commune/school/data/SchoolChoiceHome.java
|
// Path: src/java/se/idega/idegaweb/commune/school/business/MailReceiver.java
// public class MailReceiver implements Serializable {
// private String studentName;
// private String ssn;
// private String parentName;
// private String streetAddress;
// private String postalAddress;
// private boolean isInDefaultCommune;
//
// public MailReceiver(){
//
// }
//
// MailReceiver(FamilyLogic familyLogic, UserBusiness userBusiness, Integer userId) throws RemoteException, FinderException {
// User student = userBusiness.getUser(userId);
// this.studentName = student.getName();
// this.ssn = student.getPersonalID();
// Address address = userBusiness.getUsersMainAddress(student);
// Collection parents = null;
// try {
// if(familyLogic!=null) {
// parents = familyLogic.getCustodiansFor(student);
// }
// }
// catch (NoCustodianFound e) {
// parents = null;
// }
// if (parents == null || parents.isEmpty()) {
// this.parentName = "?";
// }
// else {
// User parent = (User) parents.iterator().next();
// this.parentName = parent.getName();
// }
// this.streetAddress = address != null ? address.getStreetAddress() : "?";
// this.postalAddress = address != null ? address.getPostalAddress() : "?";
// this.isInDefaultCommune = userBusiness.isInDefaultCommune (student);
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public String getSsn() {
// return this.ssn;
// }
//
// public String getParentName() {
// return this.parentName;
// }
//
// public String getStreetAddress() {
// return this.streetAddress;
// }
//
// public String getPostalAddress() {
// return this.postalAddress;
// }
//
// public boolean isInDefaultCommune () {
// return this.isInDefaultCommune;
// }
//
// public void setInDefaultCommune(boolean isInDefaultCommune) {
// this.isInDefaultCommune = isInDefaultCommune;
// }
// public void setParentName(String parentName) {
// this.parentName = parentName;
// }
// public void setPostalAddress(String postalAddress) {
// this.postalAddress = postalAddress;
// }
// public void setSsn(String ssn) {
// this.ssn = ssn;
// }
// public void setStreetAddress(String streetAddress) {
// this.streetAddress = streetAddress;
// }
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
// }
|
import java.sql.Date;
import java.sql.SQLException;
import java.util.Collection;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.school.business.MailReceiver;
import com.idega.block.process.data.Case;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolYear;
import com.idega.data.IDOException;
import com.idega.data.IDOHome;
import com.idega.user.data.User;
|
public int getNumberOfChoices(int userID, int seasonID, String[] notInStatuses) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetMoveChoices
*/
public int getMoveChoices(int userID, int schoolID, int seasonID) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetChoices
*/
public int getChoices(int userID, int seasonID, String[] notInStatus) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetChoices
*/
public int getChoices(int userID, int schoolID, int seasonID, String[] notInStatus) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbFindByParent
*/
public Collection findByParent(Case parent) throws FinderException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeCountChildrenWithoutSchoolChoice
*/
public int countChildrenWithoutSchoolChoice(SchoolSeason season, SchoolYear year, boolean onlyInCommune, boolean onlyLastGrade, int maxAge) throws SQLException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetChildrenWithoutSchoolChoice
*/
|
// Path: src/java/se/idega/idegaweb/commune/school/business/MailReceiver.java
// public class MailReceiver implements Serializable {
// private String studentName;
// private String ssn;
// private String parentName;
// private String streetAddress;
// private String postalAddress;
// private boolean isInDefaultCommune;
//
// public MailReceiver(){
//
// }
//
// MailReceiver(FamilyLogic familyLogic, UserBusiness userBusiness, Integer userId) throws RemoteException, FinderException {
// User student = userBusiness.getUser(userId);
// this.studentName = student.getName();
// this.ssn = student.getPersonalID();
// Address address = userBusiness.getUsersMainAddress(student);
// Collection parents = null;
// try {
// if(familyLogic!=null) {
// parents = familyLogic.getCustodiansFor(student);
// }
// }
// catch (NoCustodianFound e) {
// parents = null;
// }
// if (parents == null || parents.isEmpty()) {
// this.parentName = "?";
// }
// else {
// User parent = (User) parents.iterator().next();
// this.parentName = parent.getName();
// }
// this.streetAddress = address != null ? address.getStreetAddress() : "?";
// this.postalAddress = address != null ? address.getPostalAddress() : "?";
// this.isInDefaultCommune = userBusiness.isInDefaultCommune (student);
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public String getSsn() {
// return this.ssn;
// }
//
// public String getParentName() {
// return this.parentName;
// }
//
// public String getStreetAddress() {
// return this.streetAddress;
// }
//
// public String getPostalAddress() {
// return this.postalAddress;
// }
//
// public boolean isInDefaultCommune () {
// return this.isInDefaultCommune;
// }
//
// public void setInDefaultCommune(boolean isInDefaultCommune) {
// this.isInDefaultCommune = isInDefaultCommune;
// }
// public void setParentName(String parentName) {
// this.parentName = parentName;
// }
// public void setPostalAddress(String postalAddress) {
// this.postalAddress = postalAddress;
// }
// public void setSsn(String ssn) {
// this.ssn = ssn;
// }
// public void setStreetAddress(String streetAddress) {
// this.streetAddress = streetAddress;
// }
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
// }
// Path: src/java/se/idega/idegaweb/commune/school/data/SchoolChoiceHome.java
import java.sql.Date;
import java.sql.SQLException;
import java.util.Collection;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.school.business.MailReceiver;
import com.idega.block.process.data.Case;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolYear;
import com.idega.data.IDOException;
import com.idega.data.IDOHome;
import com.idega.user.data.User;
public int getNumberOfChoices(int userID, int seasonID, String[] notInStatuses) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetMoveChoices
*/
public int getMoveChoices(int userID, int schoolID, int seasonID) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetChoices
*/
public int getChoices(int userID, int seasonID, String[] notInStatus) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetChoices
*/
public int getChoices(int userID, int schoolID, int seasonID, String[] notInStatus) throws IDOException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbFindByParent
*/
public Collection findByParent(Case parent) throws FinderException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeCountChildrenWithoutSchoolChoice
*/
public int countChildrenWithoutSchoolChoice(SchoolSeason season, SchoolYear year, boolean onlyInCommune, boolean onlyLastGrade, int maxAge) throws SQLException;
/**
* @see se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean#ejbHomeGetChildrenWithoutSchoolChoice
*/
|
public MailReceiver[] getChildrenWithoutSchoolChoice(SchoolSeason season, SchoolYear year, boolean onlyInCommune, boolean onlyLastGrade, int maxAge) throws FinderException;
|
idega/se.idega.idegaweb.commune.school
|
src/java/se/idega/idegaweb/commune/school/data/SchoolChoiceHomeImpl.java
|
// Path: src/java/se/idega/idegaweb/commune/school/business/MailReceiver.java
// public class MailReceiver implements Serializable {
// private String studentName;
// private String ssn;
// private String parentName;
// private String streetAddress;
// private String postalAddress;
// private boolean isInDefaultCommune;
//
// public MailReceiver(){
//
// }
//
// MailReceiver(FamilyLogic familyLogic, UserBusiness userBusiness, Integer userId) throws RemoteException, FinderException {
// User student = userBusiness.getUser(userId);
// this.studentName = student.getName();
// this.ssn = student.getPersonalID();
// Address address = userBusiness.getUsersMainAddress(student);
// Collection parents = null;
// try {
// if(familyLogic!=null) {
// parents = familyLogic.getCustodiansFor(student);
// }
// }
// catch (NoCustodianFound e) {
// parents = null;
// }
// if (parents == null || parents.isEmpty()) {
// this.parentName = "?";
// }
// else {
// User parent = (User) parents.iterator().next();
// this.parentName = parent.getName();
// }
// this.streetAddress = address != null ? address.getStreetAddress() : "?";
// this.postalAddress = address != null ? address.getPostalAddress() : "?";
// this.isInDefaultCommune = userBusiness.isInDefaultCommune (student);
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public String getSsn() {
// return this.ssn;
// }
//
// public String getParentName() {
// return this.parentName;
// }
//
// public String getStreetAddress() {
// return this.streetAddress;
// }
//
// public String getPostalAddress() {
// return this.postalAddress;
// }
//
// public boolean isInDefaultCommune () {
// return this.isInDefaultCommune;
// }
//
// public void setInDefaultCommune(boolean isInDefaultCommune) {
// this.isInDefaultCommune = isInDefaultCommune;
// }
// public void setParentName(String parentName) {
// this.parentName = parentName;
// }
// public void setPostalAddress(String postalAddress) {
// this.postalAddress = postalAddress;
// }
// public void setSsn(String ssn) {
// this.ssn = ssn;
// }
// public void setStreetAddress(String streetAddress) {
// this.streetAddress = streetAddress;
// }
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
// }
|
import java.sql.Date;
import java.sql.SQLException;
import java.util.Collection;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.school.business.MailReceiver;
import com.idega.block.process.data.Case;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolYear;
import com.idega.data.IDOException;
import com.idega.data.IDOFactory;
import com.idega.user.data.User;
|
}
public int getChoices(int userID, int seasonID, String[] notInStatus) throws IDOException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((SchoolChoiceBMPBean) entity).ejbHomeGetChoices(userID, seasonID, notInStatus);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
public int getChoices(int userID, int schoolID, int seasonID, String[] notInStatus) throws IDOException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((SchoolChoiceBMPBean) entity).ejbHomeGetChoices(userID, schoolID, seasonID, notInStatus);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
public Collection findByParent(Case parent) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((SchoolChoiceBMPBean) entity).ejbFindByParent(parent);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public int countChildrenWithoutSchoolChoice(SchoolSeason season, SchoolYear year, boolean onlyInCommune, boolean onlyLastGrade, int maxAge) throws SQLException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((SchoolChoiceBMPBean) entity).ejbHomeCountChildrenWithoutSchoolChoice(season, year, onlyInCommune, onlyLastGrade, maxAge);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
|
// Path: src/java/se/idega/idegaweb/commune/school/business/MailReceiver.java
// public class MailReceiver implements Serializable {
// private String studentName;
// private String ssn;
// private String parentName;
// private String streetAddress;
// private String postalAddress;
// private boolean isInDefaultCommune;
//
// public MailReceiver(){
//
// }
//
// MailReceiver(FamilyLogic familyLogic, UserBusiness userBusiness, Integer userId) throws RemoteException, FinderException {
// User student = userBusiness.getUser(userId);
// this.studentName = student.getName();
// this.ssn = student.getPersonalID();
// Address address = userBusiness.getUsersMainAddress(student);
// Collection parents = null;
// try {
// if(familyLogic!=null) {
// parents = familyLogic.getCustodiansFor(student);
// }
// }
// catch (NoCustodianFound e) {
// parents = null;
// }
// if (parents == null || parents.isEmpty()) {
// this.parentName = "?";
// }
// else {
// User parent = (User) parents.iterator().next();
// this.parentName = parent.getName();
// }
// this.streetAddress = address != null ? address.getStreetAddress() : "?";
// this.postalAddress = address != null ? address.getPostalAddress() : "?";
// this.isInDefaultCommune = userBusiness.isInDefaultCommune (student);
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public String getSsn() {
// return this.ssn;
// }
//
// public String getParentName() {
// return this.parentName;
// }
//
// public String getStreetAddress() {
// return this.streetAddress;
// }
//
// public String getPostalAddress() {
// return this.postalAddress;
// }
//
// public boolean isInDefaultCommune () {
// return this.isInDefaultCommune;
// }
//
// public void setInDefaultCommune(boolean isInDefaultCommune) {
// this.isInDefaultCommune = isInDefaultCommune;
// }
// public void setParentName(String parentName) {
// this.parentName = parentName;
// }
// public void setPostalAddress(String postalAddress) {
// this.postalAddress = postalAddress;
// }
// public void setSsn(String ssn) {
// this.ssn = ssn;
// }
// public void setStreetAddress(String streetAddress) {
// this.streetAddress = streetAddress;
// }
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
// }
// Path: src/java/se/idega/idegaweb/commune/school/data/SchoolChoiceHomeImpl.java
import java.sql.Date;
import java.sql.SQLException;
import java.util.Collection;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.school.business.MailReceiver;
import com.idega.block.process.data.Case;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolYear;
import com.idega.data.IDOException;
import com.idega.data.IDOFactory;
import com.idega.user.data.User;
}
public int getChoices(int userID, int seasonID, String[] notInStatus) throws IDOException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((SchoolChoiceBMPBean) entity).ejbHomeGetChoices(userID, seasonID, notInStatus);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
public int getChoices(int userID, int schoolID, int seasonID, String[] notInStatus) throws IDOException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((SchoolChoiceBMPBean) entity).ejbHomeGetChoices(userID, schoolID, seasonID, notInStatus);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
public Collection findByParent(Case parent) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((SchoolChoiceBMPBean) entity).ejbFindByParent(parent);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public int countChildrenWithoutSchoolChoice(SchoolSeason season, SchoolYear year, boolean onlyInCommune, boolean onlyLastGrade, int maxAge) throws SQLException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((SchoolChoiceBMPBean) entity).ejbHomeCountChildrenWithoutSchoolChoice(season, year, onlyInCommune, onlyLastGrade, maxAge);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
|
public MailReceiver[] getChildrenWithoutSchoolChoice(SchoolSeason season, SchoolYear year, boolean onlyInCommune, boolean onlyLastGrade, int maxAge) throws FinderException {
|
idega/se.idega.idegaweb.commune.school
|
src/java/se/idega/idegaweb/commune/school/importer/NackaStudentTimeImportFileHandlerBean.java
|
// Path: src/java/se/idega/idegaweb/commune/school/data/SchoolTime.java
// public interface SchoolTime extends IDOEntity {
// public void setUser (User user) throws RemoteException;
// public void setSchool (School school) throws RemoteException;
// public void setHours (int hours) throws RemoteException;
// public void setSeason (SchoolSeason season) throws RemoteException;
// public void setRegistrationTime (Date date) throws RemoteException;
// }
|
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.ejb.FinderException;
import javax.ejb.SessionContext;
import javax.transaction.UserTransaction;
import se.idega.idegaweb.commune.business.CommuneUserBusiness;
import se.idega.idegaweb.commune.school.business.SchoolCommuneBusiness;
import se.idega.idegaweb.commune.school.data.SchoolTime;
import se.idega.idegaweb.commune.school.data.SchoolTimeHome;
import se.idega.util.PIDChecker;
import com.idega.block.importer.data.ImportFile;
import com.idega.block.school.business.SchoolBusiness;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolHome;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolSeasonHome;
import com.idega.business.IBOServiceBean;
import com.idega.data.IDOLookup;
import com.idega.user.data.Group;
import com.idega.user.data.User;
import com.idega.user.data.UserHome;
|
@Override
public void setRootGroup (final Group rootGroup) {
this.rootGroup = rootGroup;
}
/**
* Reads records in a format specified in {@link se.idega.idegaweb.commune.school.importer.NackaStudentTimeImportFileHandler}.
* Relies on the fact that {@link #setImportFile} has been invoked correctly
* prior to invocation of this method.
*/
@Override
public boolean handleRecords () {
log ("Importing records: " + getClass ().getName ());
boolean readSuccess = true;
failedRecords.clear ();
final SessionContext sessionContext = getSessionContext();
final UserTransaction transaction = sessionContext.getUserTransaction();
final Set unknownSchools = new HashSet ();
try {
transaction.begin();
// get all home and business objects needed in traversal below
final CommuneUserBusiness communeUserBusiness
= (CommuneUserBusiness) getServiceInstance
(CommuneUserBusiness.class);
final UserHome userHome = communeUserBusiness.getUserHome ();
final SchoolBusiness schoolBusiness = (SchoolBusiness)
getServiceInstance (SchoolBusiness.class);
final SchoolHome schoolHome = schoolBusiness.getSchoolHome ();
final PIDChecker pidChecker = PIDChecker.getInstance ();
final SchoolTimeHome schoolTimeHome
|
// Path: src/java/se/idega/idegaweb/commune/school/data/SchoolTime.java
// public interface SchoolTime extends IDOEntity {
// public void setUser (User user) throws RemoteException;
// public void setSchool (School school) throws RemoteException;
// public void setHours (int hours) throws RemoteException;
// public void setSeason (SchoolSeason season) throws RemoteException;
// public void setRegistrationTime (Date date) throws RemoteException;
// }
// Path: src/java/se/idega/idegaweb/commune/school/importer/NackaStudentTimeImportFileHandlerBean.java
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.ejb.FinderException;
import javax.ejb.SessionContext;
import javax.transaction.UserTransaction;
import se.idega.idegaweb.commune.business.CommuneUserBusiness;
import se.idega.idegaweb.commune.school.business.SchoolCommuneBusiness;
import se.idega.idegaweb.commune.school.data.SchoolTime;
import se.idega.idegaweb.commune.school.data.SchoolTimeHome;
import se.idega.util.PIDChecker;
import com.idega.block.importer.data.ImportFile;
import com.idega.block.school.business.SchoolBusiness;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolHome;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolSeasonHome;
import com.idega.business.IBOServiceBean;
import com.idega.data.IDOLookup;
import com.idega.user.data.Group;
import com.idega.user.data.User;
import com.idega.user.data.UserHome;
@Override
public void setRootGroup (final Group rootGroup) {
this.rootGroup = rootGroup;
}
/**
* Reads records in a format specified in {@link se.idega.idegaweb.commune.school.importer.NackaStudentTimeImportFileHandler}.
* Relies on the fact that {@link #setImportFile} has been invoked correctly
* prior to invocation of this method.
*/
@Override
public boolean handleRecords () {
log ("Importing records: " + getClass ().getName ());
boolean readSuccess = true;
failedRecords.clear ();
final SessionContext sessionContext = getSessionContext();
final UserTransaction transaction = sessionContext.getUserTransaction();
final Set unknownSchools = new HashSet ();
try {
transaction.begin();
// get all home and business objects needed in traversal below
final CommuneUserBusiness communeUserBusiness
= (CommuneUserBusiness) getServiceInstance
(CommuneUserBusiness.class);
final UserHome userHome = communeUserBusiness.getUserHome ();
final SchoolBusiness schoolBusiness = (SchoolBusiness)
getServiceInstance (SchoolBusiness.class);
final SchoolHome schoolHome = schoolBusiness.getSchoolHome ();
final PIDChecker pidChecker = PIDChecker.getInstance ();
final SchoolTimeHome schoolTimeHome
|
= (SchoolTimeHome) IDOLookup.getHome (SchoolTime.class);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/LiquibaseCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.liquibase.LiquibaseEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(LiquibaseEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.liquibase.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "liquibase", description = "Liquibase database migration details (if applicable)")
public final class LiquibaseCommand extends AbstractSystemCommand {
private final LiquibaseEndpoint liquibaseEndpoint;
LiquibaseCommand(@Value("${sshd.system.command.roles.liquibase}") String[] systemRoles,
LiquibaseEndpoint liquibaseEndpoint) {
super(systemRoles);
this.liquibaseEndpoint = liquibaseEndpoint;
}
public String liquibase(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/LiquibaseCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.liquibase.LiquibaseEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(LiquibaseEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.liquibase.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "liquibase", description = "Liquibase database migration details (if applicable)")
public final class LiquibaseCommand extends AbstractSystemCommand {
private final LiquibaseEndpoint liquibaseEndpoint;
LiquibaseCommand(@Value("${sshd.system.command.roles.liquibase}") String[] systemRoles,
LiquibaseEndpoint liquibaseEndpoint) {
super(systemRoles);
this.liquibaseEndpoint = liquibaseEndpoint;
}
public String liquibase(String arg) {
|
return JsonUtils.asJson(liquibaseEndpoint.liquibaseBeans());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ColorType.java
// @lombok.AllArgsConstructor
// public enum ColorType {
//
// BLACK(AttributedStyle.BLACK),
// RED(AttributedStyle.RED),
// GREEN(AttributedStyle.GREEN),
// YELLOW(AttributedStyle.YELLOW),
// BLUE(AttributedStyle.BLUE),
// MAGENTA(AttributedStyle.MAGENTA),
// CYAN(AttributedStyle.CYAN),
// WHITE(AttributedStyle.WHITE);
//
// public int value;
// }
|
import org.springframework.boot.context.properties.ConfigurationProperties;
import sshd.shell.springboot.console.ColorType;
|
@lombok.Data
public static class Filesystem {
private final Base base = new Base();
@lombok.Data
public static class Base {
private String dir = System.getProperty("user.home");
}
}
@lombok.Data
public static class Shell {
private int port = 8022;
private boolean enabled = false;
private String username = "admin";
private String password;
private String publicKeyFile;
private String host = "127.0.0.1";
private String hostKeyFile = "hostKey.ser";
private final Prompt prompt = new Prompt();
private final Text text = new Text();
private final Auth auth = new Auth();
@lombok.Data
public static class Prompt {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ColorType.java
// @lombok.AllArgsConstructor
// public enum ColorType {
//
// BLACK(AttributedStyle.BLACK),
// RED(AttributedStyle.RED),
// GREEN(AttributedStyle.GREEN),
// YELLOW(AttributedStyle.YELLOW),
// BLUE(AttributedStyle.BLUE),
// MAGENTA(AttributedStyle.MAGENTA),
// CYAN(AttributedStyle.CYAN),
// WHITE(AttributedStyle.WHITE);
//
// public int value;
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import sshd.shell.springboot.console.ColorType;
@lombok.Data
public static class Filesystem {
private final Base base = new Base();
@lombok.Data
public static class Base {
private String dir = System.getProperty("user.home");
}
}
@lombok.Data
public static class Shell {
private int port = 8022;
private boolean enabled = false;
private String username = "admin";
private String password;
private String publicKeyFile;
private String host = "127.0.0.1";
private String hostKeyFile = "hostKey.ser";
private final Prompt prompt = new Prompt();
private final Text text = new Text();
private final Auth auth = new Auth();
@lombok.Data
public static class Prompt {
|
private ColorType color = ColorType.BLACK;
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/MappingsCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.web.mappings.MappingsEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(MappingsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.mappings.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "mappings", description = "List http request mappings")
public final class MappingsCommand extends AbstractSystemCommand {
private final MappingsEndpoint mappingsEndpoint;
MappingsCommand(@Value("${sshd.system.command.roles.mappings}") String[] systemRoles,
MappingsEndpoint mappingsEndpoint) {
super(systemRoles);
this.mappingsEndpoint = mappingsEndpoint;
}
public String mappings(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/MappingsCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.web.mappings.MappingsEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(MappingsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.mappings.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "mappings", description = "List http request mappings")
public final class MappingsCommand extends AbstractSystemCommand {
private final MappingsEndpoint mappingsEndpoint;
MappingsCommand(@Value("${sshd.system.command.roles.mappings}") String[] systemRoles,
MappingsEndpoint mappingsEndpoint) {
super(systemRoles);
this.mappingsEndpoint = mappingsEndpoint;
}
public String mappings(String arg) {
|
return JsonUtils.asJson(mappingsEndpoint.mappings());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/CommandUtils.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/ZipUtils.java
// public enum ZipUtils {
// ;
//
// public static Path zipFiles(Path dirToStoreZipFile, boolean isDeleteOriginalFiles, Path... filesToZip) throws
// IOException {
// validate(dirToStoreZipFile, filesToZip);
// String zipFileName = getZipFileName(filesToZip);
// Path zipFilePath = dirToStoreZipFile.resolve(zipFileName);
// runZipOperation(zipFilePath, filesToZip);
// cleanUp(isDeleteOriginalFiles, filesToZip);
// return zipFilePath;
// }
//
// private static void validate(Path dirToStoreZipFile, Path[] filesToZip) {
// File dir = dirToStoreZipFile.toFile();
// Assert.isTrue(dir.exists() && dir.isDirectory(), "File is does not exist or it's not a directory");
// Assert.notEmpty(filesToZip, "Require at least one file for zip");
// }
//
// private static String getZipFileName(Path[] filesToZip) {
// return (filesToZip.length == 1
// ? filesToZip[0].getFileName().toString()
// : "Files " + LocalDateTime.now().toString()) + ".zip";
// }
//
// private static void runZipOperation(Path zipFilePath, Path[] filesToZip) throws IOException {
// try (FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
// ZipOutputStream zipOut = new ZipOutputStream(fos)) {
// for (Path fileToZip : filesToZip) {
// addZipEntriesIntoZipFile(fileToZip, zipOut);
// }
// }
// }
//
// private static void addZipEntriesIntoZipFile(Path fileToZip, final ZipOutputStream zipOut) throws IOException {
// try (FileInputStream fis = new FileInputStream(fileToZip.toFile())) {
// ZipEntry zipEntry = new ZipEntry(fileToZip.toFile().getName());
// zipOut.putNextEntry(zipEntry);
// byte[] bytes = new byte[1024];
// int length;
// while ((length = fis.read(bytes)) >= 0) {
// zipOut.write(bytes, 0, length);
// }
// }
// }
//
// private static void cleanUp(boolean isDeleteOriginalFiles, Path[] filesToZip) throws IOException {
// if (isDeleteOriginalFiles) {
// for (Path fileToZip : filesToZip) {
// Files.deleteIfExists(fileToZip);
// }
// }
// }
// }
|
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.ZipUtils;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public enum CommandUtils {
;
public static Path sessionUserPathContainingZippedResource(Resource resource) throws IOException {
Path heapDumpFilePath = Paths.get(resource.getURI());
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/ZipUtils.java
// public enum ZipUtils {
// ;
//
// public static Path zipFiles(Path dirToStoreZipFile, boolean isDeleteOriginalFiles, Path... filesToZip) throws
// IOException {
// validate(dirToStoreZipFile, filesToZip);
// String zipFileName = getZipFileName(filesToZip);
// Path zipFilePath = dirToStoreZipFile.resolve(zipFileName);
// runZipOperation(zipFilePath, filesToZip);
// cleanUp(isDeleteOriginalFiles, filesToZip);
// return zipFilePath;
// }
//
// private static void validate(Path dirToStoreZipFile, Path[] filesToZip) {
// File dir = dirToStoreZipFile.toFile();
// Assert.isTrue(dir.exists() && dir.isDirectory(), "File is does not exist or it's not a directory");
// Assert.notEmpty(filesToZip, "Require at least one file for zip");
// }
//
// private static String getZipFileName(Path[] filesToZip) {
// return (filesToZip.length == 1
// ? filesToZip[0].getFileName().toString()
// : "Files " + LocalDateTime.now().toString()) + ".zip";
// }
//
// private static void runZipOperation(Path zipFilePath, Path[] filesToZip) throws IOException {
// try (FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
// ZipOutputStream zipOut = new ZipOutputStream(fos)) {
// for (Path fileToZip : filesToZip) {
// addZipEntriesIntoZipFile(fileToZip, zipOut);
// }
// }
// }
//
// private static void addZipEntriesIntoZipFile(Path fileToZip, final ZipOutputStream zipOut) throws IOException {
// try (FileInputStream fis = new FileInputStream(fileToZip.toFile())) {
// ZipEntry zipEntry = new ZipEntry(fileToZip.toFile().getName());
// zipOut.putNextEntry(zipEntry);
// byte[] bytes = new byte[1024];
// int length;
// while ((length = fis.read(bytes)) >= 0) {
// zipOut.write(bytes, 0, length);
// }
// }
// }
//
// private static void cleanUp(boolean isDeleteOriginalFiles, Path[] filesToZip) throws IOException {
// if (isDeleteOriginalFiles) {
// for (Path fileToZip : filesToZip) {
// Files.deleteIfExists(fileToZip);
// }
// }
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/CommandUtils.java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.ZipUtils;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public enum CommandUtils {
;
public static Path sessionUserPathContainingZippedResource(Resource resource) throws IOException {
Path heapDumpFilePath = Paths.get(resource.getURI());
|
return ZipUtils.zipFiles(sessionUserDir(), true, heapDumpFilePath);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/CommandUtils.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/ZipUtils.java
// public enum ZipUtils {
// ;
//
// public static Path zipFiles(Path dirToStoreZipFile, boolean isDeleteOriginalFiles, Path... filesToZip) throws
// IOException {
// validate(dirToStoreZipFile, filesToZip);
// String zipFileName = getZipFileName(filesToZip);
// Path zipFilePath = dirToStoreZipFile.resolve(zipFileName);
// runZipOperation(zipFilePath, filesToZip);
// cleanUp(isDeleteOriginalFiles, filesToZip);
// return zipFilePath;
// }
//
// private static void validate(Path dirToStoreZipFile, Path[] filesToZip) {
// File dir = dirToStoreZipFile.toFile();
// Assert.isTrue(dir.exists() && dir.isDirectory(), "File is does not exist or it's not a directory");
// Assert.notEmpty(filesToZip, "Require at least one file for zip");
// }
//
// private static String getZipFileName(Path[] filesToZip) {
// return (filesToZip.length == 1
// ? filesToZip[0].getFileName().toString()
// : "Files " + LocalDateTime.now().toString()) + ".zip";
// }
//
// private static void runZipOperation(Path zipFilePath, Path[] filesToZip) throws IOException {
// try (FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
// ZipOutputStream zipOut = new ZipOutputStream(fos)) {
// for (Path fileToZip : filesToZip) {
// addZipEntriesIntoZipFile(fileToZip, zipOut);
// }
// }
// }
//
// private static void addZipEntriesIntoZipFile(Path fileToZip, final ZipOutputStream zipOut) throws IOException {
// try (FileInputStream fis = new FileInputStream(fileToZip.toFile())) {
// ZipEntry zipEntry = new ZipEntry(fileToZip.toFile().getName());
// zipOut.putNextEntry(zipEntry);
// byte[] bytes = new byte[1024];
// int length;
// while ((length = fis.read(bytes)) >= 0) {
// zipOut.write(bytes, 0, length);
// }
// }
// }
//
// private static void cleanUp(boolean isDeleteOriginalFiles, Path[] filesToZip) throws IOException {
// if (isDeleteOriginalFiles) {
// for (Path fileToZip : filesToZip) {
// Files.deleteIfExists(fileToZip);
// }
// }
// }
// }
|
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.ZipUtils;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public enum CommandUtils {
;
public static Path sessionUserPathContainingZippedResource(Resource resource) throws IOException {
Path heapDumpFilePath = Paths.get(resource.getURI());
return ZipUtils.zipFiles(sessionUserDir(), true, heapDumpFilePath);
}
private static Path sessionUserDir() throws IOException {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/ZipUtils.java
// public enum ZipUtils {
// ;
//
// public static Path zipFiles(Path dirToStoreZipFile, boolean isDeleteOriginalFiles, Path... filesToZip) throws
// IOException {
// validate(dirToStoreZipFile, filesToZip);
// String zipFileName = getZipFileName(filesToZip);
// Path zipFilePath = dirToStoreZipFile.resolve(zipFileName);
// runZipOperation(zipFilePath, filesToZip);
// cleanUp(isDeleteOriginalFiles, filesToZip);
// return zipFilePath;
// }
//
// private static void validate(Path dirToStoreZipFile, Path[] filesToZip) {
// File dir = dirToStoreZipFile.toFile();
// Assert.isTrue(dir.exists() && dir.isDirectory(), "File is does not exist or it's not a directory");
// Assert.notEmpty(filesToZip, "Require at least one file for zip");
// }
//
// private static String getZipFileName(Path[] filesToZip) {
// return (filesToZip.length == 1
// ? filesToZip[0].getFileName().toString()
// : "Files " + LocalDateTime.now().toString()) + ".zip";
// }
//
// private static void runZipOperation(Path zipFilePath, Path[] filesToZip) throws IOException {
// try (FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
// ZipOutputStream zipOut = new ZipOutputStream(fos)) {
// for (Path fileToZip : filesToZip) {
// addZipEntriesIntoZipFile(fileToZip, zipOut);
// }
// }
// }
//
// private static void addZipEntriesIntoZipFile(Path fileToZip, final ZipOutputStream zipOut) throws IOException {
// try (FileInputStream fis = new FileInputStream(fileToZip.toFile())) {
// ZipEntry zipEntry = new ZipEntry(fileToZip.toFile().getName());
// zipOut.putNextEntry(zipEntry);
// byte[] bytes = new byte[1024];
// int length;
// while ((length = fis.read(bytes)) >= 0) {
// zipOut.write(bytes, 0, length);
// }
// }
// }
//
// private static void cleanUp(boolean isDeleteOriginalFiles, Path[] filesToZip) throws IOException {
// if (isDeleteOriginalFiles) {
// for (Path fileToZip : filesToZip) {
// Files.deleteIfExists(fileToZip);
// }
// }
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/CommandUtils.java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.ZipUtils;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public enum CommandUtils {
;
public static Path sessionUserPathContainingZippedResource(Resource resource) throws IOException {
Path heapDumpFilePath = Paths.get(resource.getURI());
return ZipUtils.zipFiles(sessionUserDir(), true, heapDumpFilePath);
}
private static Path sessionUserDir() throws IOException {
|
File sessionUserDir = SshSessionContext.getUserDir();
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import java.io.IOException;
import java.util.Objects;
import org.jline.reader.LineReader;
import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public enum ConsoleIO {
;
static final String LINE_READER = "__lineReader";
static final String TEXT_STYLE = "__textStyle";
static final String TERMINAL = "__terminal";
static final String HIGHLIGHT_COLOR = "__highlightColor";
/**
* Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
* characters that get echoed with input
*
* @param text Text to show
* @param mask mask
* @return input from user
* @throws IOException if any
*/
public static String readInput(String text, Character mask) throws IOException {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
import java.io.IOException;
import java.util.Objects;
import org.jline.reader.LineReader;
import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public enum ConsoleIO {
;
static final String LINE_READER = "__lineReader";
static final String TEXT_STYLE = "__textStyle";
static final String TERMINAL = "__terminal";
static final String HIGHLIGHT_COLOR = "__highlightColor";
/**
* Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
* characters that get echoed with input
*
* @param text Text to show
* @param mask mask
* @return input from user
* @throws IOException if any
*/
public static String readInput(String text, Character mask) throws IOException {
|
LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import java.io.IOException;
import java.util.Objects;
import org.jline.reader.LineReader;
import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.JsonUtils;
|
public static void writeOutput(String output, String textToHighlight) {
Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
AttributedStringBuilder builder = new AttributedStringBuilder()
.style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
if (Objects.isNull(textToHighlight)) {
builder.append(output);
} else {
addHighlightedTextToBuilder(output, textToHighlight, builder);
}
terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
terminal.flush();
}
private static void addHighlightedTextToBuilder(String output, String textToHighlight,
AttributedStringBuilder builder) {
String[] split = output.split(textToHighlight);
for (int i = 0; i < split.length - 1; i++) {
builder.append(split[i])
.style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
.append(textToHighlight)
.style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
}
builder.append(split[split.length - 1]);
}
public static void writeJsonOutput(Object object) {
writeJsonOutput(object, null);
}
public static void writeJsonOutput(Object object, String textToHighlight) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
import java.io.IOException;
import java.util.Objects;
import org.jline.reader.LineReader;
import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.JsonUtils;
public static void writeOutput(String output, String textToHighlight) {
Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
AttributedStringBuilder builder = new AttributedStringBuilder()
.style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
if (Objects.isNull(textToHighlight)) {
builder.append(output);
} else {
addHighlightedTextToBuilder(output, textToHighlight, builder);
}
terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
terminal.flush();
}
private static void addHighlightedTextToBuilder(String output, String textToHighlight,
AttributedStringBuilder builder) {
String[] split = output.split(textToHighlight);
for (int i = 0; i < split.length - 1; i++) {
builder.append(split[i])
.style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
.append(textToHighlight)
.style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
}
builder.append(split[split.length - 1]);
}
public static void writeJsonOutput(Object object) {
writeJsonOutput(object, null);
}
public static void writeJsonOutput(Object object, String textToHighlight) {
|
writeOutput(JsonUtils.asJson(object), textToHighlight);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/BeansCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.beans.BeansEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(BeansEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.beans.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "beans", description = "List beans")
public final class BeansCommand extends AbstractSystemCommand {
private final BeansEndpoint beansEndpoint;
BeansCommand(@Value("${sshd.system.command.roles.beans}") String[] systemRoles, BeansEndpoint beansEndpoint) {
super(systemRoles);
this.beansEndpoint = beansEndpoint;
}
public String beans(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/BeansCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.beans.BeansEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(BeansEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.beans.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "beans", description = "List beans")
public final class BeansCommand extends AbstractSystemCommand {
private final BeansEndpoint beansEndpoint;
BeansCommand(@Value("${sshd.system.command.roles.beans}") String[] systemRoles, BeansEndpoint beansEndpoint) {
super(systemRoles);
this.beansEndpoint = beansEndpoint;
}
public String beans(String arg) {
|
return JsonUtils.asJson(beansEndpoint.beans());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/IntegrationGraphCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.integration.IntegrationGraphEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(IntegrationGraphEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.integrationgraph.enabled", havingValue = "true",
matchIfMissing = true)
@SshdShellCommand(value = "integrationGraph", description = "Information about Spring Integration graph")
public final class IntegrationGraphCommand extends AbstractSystemCommand {
private final IntegrationGraphEndpoint integrationGraphEndpoint;
IntegrationGraphCommand(@Value("${sshd.system.command.roles.integrationGraph}") String[] systemRoles,
IntegrationGraphEndpoint integrationGraphEndpoint) {
super(systemRoles);
this.integrationGraphEndpoint = integrationGraphEndpoint;
}
public String integrationGraph(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/IntegrationGraphCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.integration.IntegrationGraphEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(IntegrationGraphEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.integrationgraph.enabled", havingValue = "true",
matchIfMissing = true)
@SshdShellCommand(value = "integrationGraph", description = "Information about Spring Integration graph")
public final class IntegrationGraphCommand extends AbstractSystemCommand {
private final IntegrationGraphEndpoint integrationGraphEndpoint;
IntegrationGraphCommand(@Value("${sshd.system.command.roles.integrationGraph}") String[] systemRoles,
IntegrationGraphEndpoint integrationGraphEndpoint) {
super(systemRoles);
this.integrationGraphEndpoint = integrationGraphEndpoint;
}
public String integrationGraph(String arg) {
|
return JsonUtils.asJson(integrationGraphEndpoint.graph());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/DefaultUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import java.util.Optional;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.util.Assert;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component("__defaultUserInputProcessor")
@Order(Integer.MAX_VALUE)
class DefaultUserInputProcessor extends BaseUserInputProcessor {
private final String[] bannedSymbols = {"|"};
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.<UsageInfo>empty();
}
@Override
public Pattern getPattern() {
return Pattern.compile("[\\w\\W]+");
}
@Override
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/DefaultUserInputProcessor.java
import java.util.Optional;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.util.Assert;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component("__defaultUserInputProcessor")
@Order(Integer.MAX_VALUE)
class DefaultUserInputProcessor extends BaseUserInputProcessor {
private final String[] bannedSymbols = {"|"};
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.<UsageInfo>empty();
}
@Override
public Pattern getPattern() {
return Pattern.compile("[\\w\\W]+");
}
@Override
|
public void processUserInput(String userInput) throws InterruptedException, ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/DefaultUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import java.util.Optional;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.util.Assert;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component("__defaultUserInputProcessor")
@Order(Integer.MAX_VALUE)
class DefaultUserInputProcessor extends BaseUserInputProcessor {
private final String[] bannedSymbols = {"|"};
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.<UsageInfo>empty();
}
@Override
public Pattern getPattern() {
return Pattern.compile("[\\w\\W]+");
}
@Override
public void processUserInput(String userInput) throws InterruptedException, ShellException {
for (String bannedSymbol : bannedSymbols) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/DefaultUserInputProcessor.java
import java.util.Optional;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.util.Assert;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component("__defaultUserInputProcessor")
@Order(Integer.MAX_VALUE)
class DefaultUserInputProcessor extends BaseUserInputProcessor {
private final String[] bannedSymbols = {"|"};
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.<UsageInfo>empty();
}
@Override
public Pattern getPattern() {
return Pattern.compile("[\\w\\W]+");
}
@Override
public void processUserInput(String userInput) throws InterruptedException, ShellException {
for (String bannedSymbol : bannedSymbols) {
|
Assert.isTrue(!userInput.contains(bannedSymbol), "Invalid command");
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-test-app/src/main/java/demo/AdminCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
|
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
|
/*
* Copyright 2017 anand.
*
* 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 demo;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "admin", description = "Admin functionality. Type 'admin' for supported subcommands",
roles = "ADMIN")
public class AdminCommand {
@SshdShellCommand(value = "manage", description = "Manage task. Usage: admin manage <arg>", roles = "ADMIN")
public String manage(String arg) {
return arg + " has been managed by admin";
}
@SshdShellCommand(value = "testShellException", description = "Test throwing ShellException")
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: sshd-shell-spring-boot-test-app/src/main/java/demo/AdminCommand.java
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
/*
* Copyright 2017 anand.
*
* 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 demo;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "admin", description = "Admin functionality. Type 'admin' for supported subcommands",
roles = "ADMIN")
public class AdminCommand {
@SshdShellCommand(value = "manage", description = "Manage task. Usage: admin manage <arg>", roles = "ADMIN")
public String manage(String arg) {
return arg + " has been managed by admin";
}
@SshdShellCommand(value = "testShellException", description = "Test throwing ShellException")
|
public String testShellException(String arg) throws ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
|
import java.util.Objects;
import sshd.shell.springboot.ShellException;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.util;
/**
*
* @author anand
*/
public enum Assert {
;
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
import java.util.Objects;
import sshd.shell.springboot.ShellException;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.util;
/**
*
* @author anand
*/
public enum Assert {
;
|
public static void isTrue(boolean statement, String errorMessage) throws ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleConfiguration.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
// @lombok.extern.slf4j.Slf4j
// public class CommandExecutableDetails {
//
// private final Set<String> roles;
// private final String command;
// @lombok.Getter
// private final String description;
// @lombok.Getter
// private final CommandExecutor commandExecutor;
//
// CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
// this.roles = Collections.unmodifiableSet(roles);
// this.command = command.value();
// this.description = command.description();
// this.commandExecutor = commandExecutor;
// }
//
// public boolean matchesRole(Collection<String> userRoles) {
// if (roles.contains("*") || userRoles.contains("*")) {
// return true;
// }
// return CollectionUtils.containsAny(roles, userRoles);
// }
//
// public String executeWithArg(String arg) throws InterruptedException, ShellException {
// return commandExecutor.get(arg);
// }
//
// @Override
// public String toString() {
// return new StringBuilder("Command: ").append(command).append(", description: ").append(description)
// .append(", roles: ").append(roles).toString();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @ConfigurationProperties(prefix = "sshd")
// @lombok.Data
// public class SshdShellProperties {
//
// private final FileTransfer filetransfer = new FileTransfer();
// private final Filesystem filesystem = new Filesystem();
// private final Shell shell = new Shell();
//
// @lombok.Data
// public static class FileTransfer {
//
// private boolean enabled = false;
// }
//
// @lombok.Data
// public static class Filesystem {
//
// private final Base base = new Base();
//
// @lombok.Data
// public static class Base {
//
// private String dir = System.getProperty("user.home");
// }
// }
//
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// }
|
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jline.builtins.Completers;
import org.jline.builtins.Completers.TreeCompleter.Node;
import static org.jline.builtins.Completers.TreeCompleter.node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sshd.shell.springboot.autoconfiguration.CommandExecutableDetails;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Configuration
@ConditionalOnProperty(name = "sshd.shell.enabled", havingValue = "true")
class ConsoleConfiguration {
@Autowired
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
// @lombok.extern.slf4j.Slf4j
// public class CommandExecutableDetails {
//
// private final Set<String> roles;
// private final String command;
// @lombok.Getter
// private final String description;
// @lombok.Getter
// private final CommandExecutor commandExecutor;
//
// CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
// this.roles = Collections.unmodifiableSet(roles);
// this.command = command.value();
// this.description = command.description();
// this.commandExecutor = commandExecutor;
// }
//
// public boolean matchesRole(Collection<String> userRoles) {
// if (roles.contains("*") || userRoles.contains("*")) {
// return true;
// }
// return CollectionUtils.containsAny(roles, userRoles);
// }
//
// public String executeWithArg(String arg) throws InterruptedException, ShellException {
// return commandExecutor.get(arg);
// }
//
// @Override
// public String toString() {
// return new StringBuilder("Command: ").append(command).append(", description: ").append(description)
// .append(", roles: ").append(roles).toString();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @ConfigurationProperties(prefix = "sshd")
// @lombok.Data
// public class SshdShellProperties {
//
// private final FileTransfer filetransfer = new FileTransfer();
// private final Filesystem filesystem = new Filesystem();
// private final Shell shell = new Shell();
//
// @lombok.Data
// public static class FileTransfer {
//
// private boolean enabled = false;
// }
//
// @lombok.Data
// public static class Filesystem {
//
// private final Base base = new Base();
//
// @lombok.Data
// public static class Base {
//
// private String dir = System.getProperty("user.home");
// }
// }
//
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleConfiguration.java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jline.builtins.Completers;
import org.jline.builtins.Completers.TreeCompleter.Node;
import static org.jline.builtins.Completers.TreeCompleter.node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sshd.shell.springboot.autoconfiguration.CommandExecutableDetails;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Configuration
@ConditionalOnProperty(name = "sshd.shell.enabled", havingValue = "true")
class ConsoleConfiguration {
@Autowired
|
private SshdShellProperties properties;
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleConfiguration.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
// @lombok.extern.slf4j.Slf4j
// public class CommandExecutableDetails {
//
// private final Set<String> roles;
// private final String command;
// @lombok.Getter
// private final String description;
// @lombok.Getter
// private final CommandExecutor commandExecutor;
//
// CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
// this.roles = Collections.unmodifiableSet(roles);
// this.command = command.value();
// this.description = command.description();
// this.commandExecutor = commandExecutor;
// }
//
// public boolean matchesRole(Collection<String> userRoles) {
// if (roles.contains("*") || userRoles.contains("*")) {
// return true;
// }
// return CollectionUtils.containsAny(roles, userRoles);
// }
//
// public String executeWithArg(String arg) throws InterruptedException, ShellException {
// return commandExecutor.get(arg);
// }
//
// @Override
// public String toString() {
// return new StringBuilder("Command: ").append(command).append(", description: ").append(description)
// .append(", roles: ").append(roles).toString();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @ConfigurationProperties(prefix = "sshd")
// @lombok.Data
// public class SshdShellProperties {
//
// private final FileTransfer filetransfer = new FileTransfer();
// private final Filesystem filesystem = new Filesystem();
// private final Shell shell = new Shell();
//
// @lombok.Data
// public static class FileTransfer {
//
// private boolean enabled = false;
// }
//
// @lombok.Data
// public static class Filesystem {
//
// private final Base base = new Base();
//
// @lombok.Data
// public static class Base {
//
// private String dir = System.getProperty("user.home");
// }
// }
//
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// }
|
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jline.builtins.Completers;
import org.jline.builtins.Completers.TreeCompleter.Node;
import static org.jline.builtins.Completers.TreeCompleter.node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sshd.shell.springboot.autoconfiguration.CommandExecutableDetails;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Configuration
@ConditionalOnProperty(name = "sshd.shell.enabled", havingValue = "true")
class ConsoleConfiguration {
@Autowired
private SshdShellProperties properties;
@Autowired
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
// @lombok.extern.slf4j.Slf4j
// public class CommandExecutableDetails {
//
// private final Set<String> roles;
// private final String command;
// @lombok.Getter
// private final String description;
// @lombok.Getter
// private final CommandExecutor commandExecutor;
//
// CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
// this.roles = Collections.unmodifiableSet(roles);
// this.command = command.value();
// this.description = command.description();
// this.commandExecutor = commandExecutor;
// }
//
// public boolean matchesRole(Collection<String> userRoles) {
// if (roles.contains("*") || userRoles.contains("*")) {
// return true;
// }
// return CollectionUtils.containsAny(roles, userRoles);
// }
//
// public String executeWithArg(String arg) throws InterruptedException, ShellException {
// return commandExecutor.get(arg);
// }
//
// @Override
// public String toString() {
// return new StringBuilder("Command: ").append(command).append(", description: ").append(description)
// .append(", roles: ").append(roles).toString();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @ConfigurationProperties(prefix = "sshd")
// @lombok.Data
// public class SshdShellProperties {
//
// private final FileTransfer filetransfer = new FileTransfer();
// private final Filesystem filesystem = new Filesystem();
// private final Shell shell = new Shell();
//
// @lombok.Data
// public static class FileTransfer {
//
// private boolean enabled = false;
// }
//
// @lombok.Data
// public static class Filesystem {
//
// private final Base base = new Base();
//
// @lombok.Data
// public static class Base {
//
// private String dir = System.getProperty("user.home");
// }
// }
//
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleConfiguration.java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jline.builtins.Completers;
import org.jline.builtins.Completers.TreeCompleter.Node;
import static org.jline.builtins.Completers.TreeCompleter.node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sshd.shell.springboot.autoconfiguration.CommandExecutableDetails;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Configuration
@ConditionalOnProperty(name = "sshd.shell.enabled", havingValue = "true")
class ConsoleConfiguration {
@Autowired
private SshdShellProperties properties;
@Autowired
|
private Map<String, Map<String, CommandExecutableDetails>> sshdShellCommands;
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleConfiguration.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
// @lombok.extern.slf4j.Slf4j
// public class CommandExecutableDetails {
//
// private final Set<String> roles;
// private final String command;
// @lombok.Getter
// private final String description;
// @lombok.Getter
// private final CommandExecutor commandExecutor;
//
// CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
// this.roles = Collections.unmodifiableSet(roles);
// this.command = command.value();
// this.description = command.description();
// this.commandExecutor = commandExecutor;
// }
//
// public boolean matchesRole(Collection<String> userRoles) {
// if (roles.contains("*") || userRoles.contains("*")) {
// return true;
// }
// return CollectionUtils.containsAny(roles, userRoles);
// }
//
// public String executeWithArg(String arg) throws InterruptedException, ShellException {
// return commandExecutor.get(arg);
// }
//
// @Override
// public String toString() {
// return new StringBuilder("Command: ").append(command).append(", description: ").append(description)
// .append(", roles: ").append(roles).toString();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @ConfigurationProperties(prefix = "sshd")
// @lombok.Data
// public class SshdShellProperties {
//
// private final FileTransfer filetransfer = new FileTransfer();
// private final Filesystem filesystem = new Filesystem();
// private final Shell shell = new Shell();
//
// @lombok.Data
// public static class FileTransfer {
//
// private boolean enabled = false;
// }
//
// @lombok.Data
// public static class Filesystem {
//
// private final Base base = new Base();
//
// @lombok.Data
// public static class Base {
//
// private String dir = System.getProperty("user.home");
// }
// }
//
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// }
|
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jline.builtins.Completers;
import org.jline.builtins.Completers.TreeCompleter.Node;
import static org.jline.builtins.Completers.TreeCompleter.node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sshd.shell.springboot.autoconfiguration.CommandExecutableDetails;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Configuration
@ConditionalOnProperty(name = "sshd.shell.enabled", havingValue = "true")
class ConsoleConfiguration {
@Autowired
private SshdShellProperties properties;
@Autowired
private Map<String, Map<String, CommandExecutableDetails>> sshdShellCommands;
@Autowired
private List<BaseUserInputProcessor> userInputProcessors;
@Bean
TerminalProcessor terminalProcessor() {
return new TerminalProcessor(properties.getShell(), new Completers.TreeCompleter(buildTextCompleters()),
userInputProcessors);
}
private List<Node> buildTextCompleters() {
return sshdShellCommands.entrySet().stream().map(entry -> buildTextCompleterNode(entry))
.collect(Collectors.toList());
}
private Node buildTextCompleterNode(Map.Entry<String, Map<String, CommandExecutableDetails>> entry) {
Object[] subCommands = entry.getValue().keySet().stream()
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
// @lombok.extern.slf4j.Slf4j
// public class CommandExecutableDetails {
//
// private final Set<String> roles;
// private final String command;
// @lombok.Getter
// private final String description;
// @lombok.Getter
// private final CommandExecutor commandExecutor;
//
// CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
// this.roles = Collections.unmodifiableSet(roles);
// this.command = command.value();
// this.description = command.description();
// this.commandExecutor = commandExecutor;
// }
//
// public boolean matchesRole(Collection<String> userRoles) {
// if (roles.contains("*") || userRoles.contains("*")) {
// return true;
// }
// return CollectionUtils.containsAny(roles, userRoles);
// }
//
// public String executeWithArg(String arg) throws InterruptedException, ShellException {
// return commandExecutor.get(arg);
// }
//
// @Override
// public String toString() {
// return new StringBuilder("Command: ").append(command).append(", description: ").append(description)
// .append(", roles: ").append(roles).toString();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @ConfigurationProperties(prefix = "sshd")
// @lombok.Data
// public class SshdShellProperties {
//
// private final FileTransfer filetransfer = new FileTransfer();
// private final Filesystem filesystem = new Filesystem();
// private final Shell shell = new Shell();
//
// @lombok.Data
// public static class FileTransfer {
//
// private boolean enabled = false;
// }
//
// @lombok.Data
// public static class Filesystem {
//
// private final Base base = new Base();
//
// @lombok.Data
// public static class Base {
//
// private String dir = System.getProperty("user.home");
// }
// }
//
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleConfiguration.java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jline.builtins.Completers;
import org.jline.builtins.Completers.TreeCompleter.Node;
import static org.jline.builtins.Completers.TreeCompleter.node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sshd.shell.springboot.autoconfiguration.CommandExecutableDetails;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Configuration
@ConditionalOnProperty(name = "sshd.shell.enabled", havingValue = "true")
class ConsoleConfiguration {
@Autowired
private SshdShellProperties properties;
@Autowired
private Map<String, Map<String, CommandExecutableDetails>> sshdShellCommands;
@Autowired
private List<BaseUserInputProcessor> userInputProcessors;
@Bean
TerminalProcessor terminalProcessor() {
return new TerminalProcessor(properties.getShell(), new Completers.TreeCompleter(buildTextCompleters()),
userInputProcessors);
}
private List<Node> buildTextCompleters() {
return sshdShellCommands.entrySet().stream().map(entry -> buildTextCompleterNode(entry))
.collect(Collectors.toList());
}
private Node buildTextCompleterNode(Map.Entry<String, Map<String, CommandExecutableDetails>> entry) {
Object[] subCommands = entry.getValue().keySet().stream()
|
.filter(s -> !s.equals(Constants.EXECUTE))
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/console/ConsoleIOTest.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
public class ConsoleIOTest {
@Test
public void testConsoleIOAsJsonException() {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/console/ConsoleIOTest.java
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
public class ConsoleIOTest {
@Test
public void testConsoleIOAsJsonException() {
|
assertTrue(JsonUtils.asJson(new X("x")).startsWith("Error processing json output"));
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-test-app/src/main/java/demo/EchoCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
// @lombok.extern.slf4j.Slf4j
// public enum ConsoleIO {
// ;
//
// static final String LINE_READER = "__lineReader";
// static final String TEXT_STYLE = "__textStyle";
// static final String TERMINAL = "__terminal";
// static final String HIGHLIGHT_COLOR = "__highlightColor";
//
// /**
// * Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
// * characters that get echoed with input
// *
// * @param text Text to show
// * @param mask mask
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text, Character mask) throws IOException {
// LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
// AttributedStyle textStyle = SshSessionContext.<AttributedStyle>get(TEXT_STYLE);
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// String prompt = new AttributedStringBuilder()
// .style(textStyle)
// .append(text)
// .append(' ')
// .style(AttributedStyle.DEFAULT)
// .toAnsi(terminal);
// return reader.readLine(prompt, mask);
// }
//
// /**
// * Read input from line with input echoed.
// *
// * @param text Text to show
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text) throws IOException {
// return readInput(text, null);
// }
//
// /**
// * Write output.
// *
// * @param output Text output
// */
// public static void writeOutput(String output) {
// writeOutput(output, null);
// }
//
// /**
// * Write highlighted output.
// *
// * @param output Text output
// * @param textToHighlight text to highlight
// */
// public static void writeOutput(String output, String textToHighlight) {
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// AttributedStringBuilder builder = new AttributedStringBuilder()
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// if (Objects.isNull(textToHighlight)) {
// builder.append(output);
// } else {
// addHighlightedTextToBuilder(output, textToHighlight, builder);
// }
// terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
// terminal.flush();
// }
//
// private static void addHighlightedTextToBuilder(String output, String textToHighlight,
// AttributedStringBuilder builder) {
// String[] split = output.split(textToHighlight);
// for (int i = 0; i < split.length - 1; i++) {
// builder.append(split[i])
// .style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
// .append(textToHighlight)
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// }
// builder.append(split[split.length - 1]);
// }
//
// public static void writeJsonOutput(Object object) {
// writeJsonOutput(object, null);
// }
//
// public static void writeJsonOutput(Object object, String textToHighlight) {
// writeOutput(JsonUtils.asJson(object), textToHighlight);
// }
// }
|
import java.io.IOException;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.console.ConsoleIO;
|
package demo;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "echo", description = "Echo by users. Type 'echo' for supported subcommands")
public class EchoCommand {
@SshdShellCommand(value = "bob", description = "Bob's echo. Usage: echo bob <arg>")
public String bobSays(String arg) throws IOException {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
// @lombok.extern.slf4j.Slf4j
// public enum ConsoleIO {
// ;
//
// static final String LINE_READER = "__lineReader";
// static final String TEXT_STYLE = "__textStyle";
// static final String TERMINAL = "__terminal";
// static final String HIGHLIGHT_COLOR = "__highlightColor";
//
// /**
// * Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
// * characters that get echoed with input
// *
// * @param text Text to show
// * @param mask mask
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text, Character mask) throws IOException {
// LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
// AttributedStyle textStyle = SshSessionContext.<AttributedStyle>get(TEXT_STYLE);
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// String prompt = new AttributedStringBuilder()
// .style(textStyle)
// .append(text)
// .append(' ')
// .style(AttributedStyle.DEFAULT)
// .toAnsi(terminal);
// return reader.readLine(prompt, mask);
// }
//
// /**
// * Read input from line with input echoed.
// *
// * @param text Text to show
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text) throws IOException {
// return readInput(text, null);
// }
//
// /**
// * Write output.
// *
// * @param output Text output
// */
// public static void writeOutput(String output) {
// writeOutput(output, null);
// }
//
// /**
// * Write highlighted output.
// *
// * @param output Text output
// * @param textToHighlight text to highlight
// */
// public static void writeOutput(String output, String textToHighlight) {
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// AttributedStringBuilder builder = new AttributedStringBuilder()
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// if (Objects.isNull(textToHighlight)) {
// builder.append(output);
// } else {
// addHighlightedTextToBuilder(output, textToHighlight, builder);
// }
// terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
// terminal.flush();
// }
//
// private static void addHighlightedTextToBuilder(String output, String textToHighlight,
// AttributedStringBuilder builder) {
// String[] split = output.split(textToHighlight);
// for (int i = 0; i < split.length - 1; i++) {
// builder.append(split[i])
// .style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
// .append(textToHighlight)
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// }
// builder.append(split[split.length - 1]);
// }
//
// public static void writeJsonOutput(Object object) {
// writeJsonOutput(object, null);
// }
//
// public static void writeJsonOutput(Object object, String textToHighlight) {
// writeOutput(JsonUtils.asJson(object), textToHighlight);
// }
// }
// Path: sshd-shell-spring-boot-test-app/src/main/java/demo/EchoCommand.java
import java.io.IOException;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.console.ConsoleIO;
package demo;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "echo", description = "Echo by users. Type 'echo' for supported subcommands")
public class EchoCommand {
@SshdShellCommand(value = "bob", description = "Bob's echo. Usage: echo bob <arg>")
public String bobSays(String arg) throws IOException {
|
String name = ConsoleIO.readInput("What's your name?");
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-test-app/src/main/java/demo/EchoCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
// @lombok.extern.slf4j.Slf4j
// public enum ConsoleIO {
// ;
//
// static final String LINE_READER = "__lineReader";
// static final String TEXT_STYLE = "__textStyle";
// static final String TERMINAL = "__terminal";
// static final String HIGHLIGHT_COLOR = "__highlightColor";
//
// /**
// * Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
// * characters that get echoed with input
// *
// * @param text Text to show
// * @param mask mask
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text, Character mask) throws IOException {
// LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
// AttributedStyle textStyle = SshSessionContext.<AttributedStyle>get(TEXT_STYLE);
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// String prompt = new AttributedStringBuilder()
// .style(textStyle)
// .append(text)
// .append(' ')
// .style(AttributedStyle.DEFAULT)
// .toAnsi(terminal);
// return reader.readLine(prompt, mask);
// }
//
// /**
// * Read input from line with input echoed.
// *
// * @param text Text to show
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text) throws IOException {
// return readInput(text, null);
// }
//
// /**
// * Write output.
// *
// * @param output Text output
// */
// public static void writeOutput(String output) {
// writeOutput(output, null);
// }
//
// /**
// * Write highlighted output.
// *
// * @param output Text output
// * @param textToHighlight text to highlight
// */
// public static void writeOutput(String output, String textToHighlight) {
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// AttributedStringBuilder builder = new AttributedStringBuilder()
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// if (Objects.isNull(textToHighlight)) {
// builder.append(output);
// } else {
// addHighlightedTextToBuilder(output, textToHighlight, builder);
// }
// terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
// terminal.flush();
// }
//
// private static void addHighlightedTextToBuilder(String output, String textToHighlight,
// AttributedStringBuilder builder) {
// String[] split = output.split(textToHighlight);
// for (int i = 0; i < split.length - 1; i++) {
// builder.append(split[i])
// .style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
// .append(textToHighlight)
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// }
// builder.append(split[split.length - 1]);
// }
//
// public static void writeJsonOutput(Object object) {
// writeJsonOutput(object, null);
// }
//
// public static void writeJsonOutput(Object object, String textToHighlight) {
// writeOutput(JsonUtils.asJson(object), textToHighlight);
// }
// }
|
import java.io.IOException;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.console.ConsoleIO;
|
package demo;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "echo", description = "Echo by users. Type 'echo' for supported subcommands")
public class EchoCommand {
@SshdShellCommand(value = "bob", description = "Bob's echo. Usage: echo bob <arg>")
public String bobSays(String arg) throws IOException {
String name = ConsoleIO.readInput("What's your name?");
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
// @lombok.extern.slf4j.Slf4j
// public enum ConsoleIO {
// ;
//
// static final String LINE_READER = "__lineReader";
// static final String TEXT_STYLE = "__textStyle";
// static final String TERMINAL = "__terminal";
// static final String HIGHLIGHT_COLOR = "__highlightColor";
//
// /**
// * Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
// * characters that get echoed with input
// *
// * @param text Text to show
// * @param mask mask
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text, Character mask) throws IOException {
// LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
// AttributedStyle textStyle = SshSessionContext.<AttributedStyle>get(TEXT_STYLE);
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// String prompt = new AttributedStringBuilder()
// .style(textStyle)
// .append(text)
// .append(' ')
// .style(AttributedStyle.DEFAULT)
// .toAnsi(terminal);
// return reader.readLine(prompt, mask);
// }
//
// /**
// * Read input from line with input echoed.
// *
// * @param text Text to show
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text) throws IOException {
// return readInput(text, null);
// }
//
// /**
// * Write output.
// *
// * @param output Text output
// */
// public static void writeOutput(String output) {
// writeOutput(output, null);
// }
//
// /**
// * Write highlighted output.
// *
// * @param output Text output
// * @param textToHighlight text to highlight
// */
// public static void writeOutput(String output, String textToHighlight) {
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// AttributedStringBuilder builder = new AttributedStringBuilder()
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// if (Objects.isNull(textToHighlight)) {
// builder.append(output);
// } else {
// addHighlightedTextToBuilder(output, textToHighlight, builder);
// }
// terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
// terminal.flush();
// }
//
// private static void addHighlightedTextToBuilder(String output, String textToHighlight,
// AttributedStringBuilder builder) {
// String[] split = output.split(textToHighlight);
// for (int i = 0; i < split.length - 1; i++) {
// builder.append(split[i])
// .style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
// .append(textToHighlight)
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// }
// builder.append(split[split.length - 1]);
// }
//
// public static void writeJsonOutput(Object object) {
// writeJsonOutput(object, null);
// }
//
// public static void writeJsonOutput(Object object, String textToHighlight) {
// writeOutput(JsonUtils.asJson(object), textToHighlight);
// }
// }
// Path: sshd-shell-spring-boot-test-app/src/main/java/demo/EchoCommand.java
import java.io.IOException;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.console.ConsoleIO;
package demo;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "echo", description = "Echo by users. Type 'echo' for supported subcommands")
public class EchoCommand {
@SshdShellCommand(value = "bob", description = "Bob's echo. Usage: echo bob <arg>")
public String bobSays(String arg) throws IOException {
String name = ConsoleIO.readInput("What's your name?");
|
SshSessionContext.put("name", name);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/MetricsCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(MetricsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.metrics.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "metrics", description = "Metrics operations")
public final class MetricsCommand extends AbstractSystemCommand {
private final MetricsEndpoint metricsEndpoint;
MetricsCommand(@Value("${sshd.system.command.roles.metrics}") String[] systemRoles,
MetricsEndpoint metricsEndpoint) {
super(systemRoles);
this.metricsEndpoint = metricsEndpoint;
}
@SshdShellCommand(value = "listNames", description = "List names of all metrics")
public String listNames(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/MetricsCommand.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(MetricsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.metrics.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "metrics", description = "Metrics operations")
public final class MetricsCommand extends AbstractSystemCommand {
private final MetricsEndpoint metricsEndpoint;
MetricsCommand(@Value("${sshd.system.command.roles.metrics}") String[] systemRoles,
MetricsEndpoint metricsEndpoint) {
super(systemRoles);
this.metricsEndpoint = metricsEndpoint;
}
@SshdShellCommand(value = "listNames", description = "List names of all metrics")
public String listNames(String arg) {
|
return JsonUtils.asJson(metricsEndpoint.listNames());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/InfoCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(InfoEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.info.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "info", description = "System status")
public final class InfoCommand extends AbstractSystemCommand {
private final InfoEndpoint infoEndpoint;
InfoCommand(@Value("${sshd.system.command.roles.info}") String[] systemRoles, InfoEndpoint infoEndpoint) {
super(systemRoles);
this.infoEndpoint = infoEndpoint;
}
public String info(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/InfoCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(InfoEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.info.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "info", description = "System status")
public final class InfoCommand extends AbstractSystemCommand {
private final InfoEndpoint infoEndpoint;
InfoCommand(@Value("${sshd.system.command.roles.info}") String[] systemRoles, InfoEndpoint infoEndpoint) {
super(systemRoles);
this.infoEndpoint = infoEndpoint;
}
public String info(String arg) {
|
return JsonUtils.asJson(infoEndpoint.info());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/HealthCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(HealthEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.health.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "health", description = "System health info")
public final class HealthCommand extends AbstractSystemCommand {
private final HealthEndpoint healthEndpoint;
HealthCommand(@Value("${sshd.system.command.roles.health}") String[] systemRoles, HealthEndpoint healthEndpoint) {
super(systemRoles);
this.healthEndpoint = healthEndpoint;
}
@SshdShellCommand(value = "info", description = "Health info for all components")
public String healthInfo(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/HealthCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(HealthEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.health.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "health", description = "System health info")
public final class HealthCommand extends AbstractSystemCommand {
private final HealthEndpoint healthEndpoint;
HealthCommand(@Value("${sshd.system.command.roles.health}") String[] systemRoles, HealthEndpoint healthEndpoint) {
super(systemRoles);
this.healthEndpoint = healthEndpoint;
}
@SshdShellCommand(value = "info", description = "Health info for all components")
public String healthInfo(String arg) {
|
return JsonUtils.asJson(healthEndpoint.health());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
|
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public class TerminalProcessor {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public class TerminalProcessor {
|
private static final String SUPPORTED_COMMANDS_MESSAGE = "Enter '" + Constants.HELP
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
|
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public class TerminalProcessor {
private static final String SUPPORTED_COMMANDS_MESSAGE = "Enter '" + Constants.HELP
+ "' for a list of supported commands";
static final String UNSUPPORTED_COMMANDS_MESSAGE = "Unknown command. " + SUPPORTED_COMMANDS_MESSAGE;
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public class TerminalProcessor {
private static final String SUPPORTED_COMMANDS_MESSAGE = "Enter '" + Constants.HELP
+ "' for a list of supported commands";
static final String UNSUPPORTED_COMMANDS_MESSAGE = "Unknown command. " + SUPPORTED_COMMANDS_MESSAGE;
|
private final Shell properties;
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
|
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
|
.toAnsi();
}
public void processInputs(InputStream is, OutputStream os, String terminalType, IntConsumer exitCallback) {
try (Terminal terminal = newTerminalInstance(terminalType, is, os)) {
LineReader reader = newLineReaderInstance(terminal);
createDefaultSessionContext(reader, terminal);
ConsoleIO.writeOutput(SUPPORTED_COMMANDS_MESSAGE);
processInputs(reader, exitCallback);
} catch (IOException ex) {
log.error("Error building terminal instance", ex);
}
}
private Terminal newTerminalInstance(String terminalType, InputStream is, OutputStream os) throws IOException {
return TerminalBuilder.builder()
.system(false)
.type(terminalType)
.streams(is, os)
.build();
}
private LineReader newLineReaderInstance(final Terminal terminal) {
return LineReaderBuilder.builder()
.terminal(terminal)
.completer(completer)
.build();
}
private void createDefaultSessionContext(LineReader reader, Terminal terminal) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
.toAnsi();
}
public void processInputs(InputStream is, OutputStream os, String terminalType, IntConsumer exitCallback) {
try (Terminal terminal = newTerminalInstance(terminalType, is, os)) {
LineReader reader = newLineReaderInstance(terminal);
createDefaultSessionContext(reader, terminal);
ConsoleIO.writeOutput(SUPPORTED_COMMANDS_MESSAGE);
processInputs(reader, exitCallback);
} catch (IOException ex) {
log.error("Error building terminal instance", ex);
}
}
private Terminal newTerminalInstance(String terminalType, InputStream is, OutputStream os) throws IOException {
return TerminalBuilder.builder()
.system(false)
.type(terminalType)
.streams(is, os)
.build();
}
private LineReader newLineReaderInstance(final Terminal terminal) {
return LineReaderBuilder.builder()
.terminal(terminal)
.completer(completer)
.build();
}
private void createDefaultSessionContext(LineReader reader, Terminal terminal) {
|
SshSessionContext.put(ConsoleIO.LINE_READER, reader);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
|
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
|
AttributedStyle.DEFAULT.background(properties.getText().getHighlightColor().value));
SshSessionContext.put(ConsoleIO.TERMINAL, terminal);
}
private AttributedStyle getStyle(ColorType color) {
// This check is done to allow for default contrasting color texts to be shown on black or white screens
return color == ColorType.BLACK || color == ColorType.WHITE
? AttributedStyle.DEFAULT
: AttributedStyle.DEFAULT.foreground(color.value);
}
private void processInputs(LineReader reader, IntConsumer exitCallback) {
try {
processUserInput(reader, exitCallback);
} catch (UserInterruptException ex) {
// Need not concern with this exception
log.warn("[{}] Ctrl-C interrupt", SshSessionContext.<String>get(Constants.USER));
exitCallback.accept(1);
}
}
private void processUserInput(LineReader reader, IntConsumer exitCallback) {
while (true) {
try {
handleUserInput(reader.readLine(prompt).trim());
} catch (InterruptedException ex) {
Thread.interrupted();
ConsoleIO.writeOutput(ex.getMessage());
exitCallback.accept(0);
break;
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshSessionContext.java
// public enum SshSessionContext {
//
// ;
//
// private static final ThreadLocal<Supplier<File>> USER_DIR_CONTEXT = new ThreadLocal<Supplier<File>>();
// private static final ThreadLocal<Map<String, Object>> THREAD_CONTEXT = new ThreadLocal<Map<String, Object>>() {
// @Override
// protected Map<String, Object> initialValue() {
// return new HashMap<>();
// }
// };
//
// public static void put(String key, Object value) {
// THREAD_CONTEXT.get().put(key, value);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E get(String key) {
// return (E) THREAD_CONTEXT.get().get(key);
// }
//
// @SuppressWarnings("unchecked")
// public static <E> E remove(String key) {
// return (E) THREAD_CONTEXT.get().remove(key);
// }
//
// public static boolean containsKey(String key) {
// return THREAD_CONTEXT.get().containsKey(key);
// }
//
// public static boolean isEmpty() {
// return THREAD_CONTEXT.get().isEmpty();
// }
//
// public static void clear() {
// THREAD_CONTEXT.remove();
// USER_DIR_CONTEXT.remove();
// }
//
// public static void setUserDir(Supplier<File> userDirSupplier) {
// USER_DIR_CONTEXT.set(userDirSupplier);
// }
//
// public static File getUserDir() {
// return USER_DIR_CONTEXT.get().get();
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/TerminalProcessor.java
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.regex.Matcher;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import sshd.shell.springboot.ShellException;
AttributedStyle.DEFAULT.background(properties.getText().getHighlightColor().value));
SshSessionContext.put(ConsoleIO.TERMINAL, terminal);
}
private AttributedStyle getStyle(ColorType color) {
// This check is done to allow for default contrasting color texts to be shown on black or white screens
return color == ColorType.BLACK || color == ColorType.WHITE
? AttributedStyle.DEFAULT
: AttributedStyle.DEFAULT.foreground(color.value);
}
private void processInputs(LineReader reader, IntConsumer exitCallback) {
try {
processUserInput(reader, exitCallback);
} catch (UserInterruptException ex) {
// Need not concern with this exception
log.warn("[{}] Ctrl-C interrupt", SshSessionContext.<String>get(Constants.USER));
exitCallback.accept(1);
}
}
private void processUserInput(LineReader reader, IntConsumer exitCallback) {
while (true) {
try {
handleUserInput(reader.readLine(prompt).trim());
} catch (InterruptedException ex) {
Thread.interrupted();
ConsoleIO.writeOutput(ex.getMessage());
exitCallback.accept(0);
break;
|
} catch (ShellException | IllegalArgumentException ex) {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
|
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.springframework.util.CollectionUtils;
import sshd.shell.springboot.ShellException;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.autoconfiguration;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public class CommandExecutableDetails {
private final Set<String> roles;
private final String command;
@lombok.Getter
private final String description;
@lombok.Getter
private final CommandExecutor commandExecutor;
CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
this.roles = Collections.unmodifiableSet(roles);
this.command = command.value();
this.description = command.description();
this.commandExecutor = commandExecutor;
}
public boolean matchesRole(Collection<String> userRoles) {
if (roles.contains("*") || userRoles.contains("*")) {
return true;
}
return CollectionUtils.containsAny(roles, userRoles);
}
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutableDetails.java
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.springframework.util.CollectionUtils;
import sshd.shell.springboot.ShellException;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.autoconfiguration;
/**
*
* @author anand
*/
@lombok.extern.slf4j.Slf4j
public class CommandExecutableDetails {
private final Set<String> roles;
private final String command;
@lombok.Getter
private final String description;
@lombok.Getter
private final CommandExecutor commandExecutor;
CommandExecutableDetails(SshdShellCommand command, Set<String> roles, CommandExecutor commandExecutor) {
this.roles = Collections.unmodifiableSet(roles);
this.command = command.value();
this.description = command.description();
this.commandExecutor = commandExecutor;
}
public boolean matchesRole(Collection<String> userRoles) {
if (roles.contains("*") || userRoles.contains("*")) {
return true;
}
return CollectionUtils.containsAny(roles, userRoles);
}
|
public String executeWithArg(String arg) throws InterruptedException, ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/SshdAuthorizedKeysAuthenticator.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
|
import java.nio.file.Path;
import java.security.PublicKey;
import java.util.Collections;
import org.apache.sshd.server.config.keys.AuthorizedKeysAuthenticator;
import org.apache.sshd.server.session.ServerSession;
import sshd.shell.springboot.autoconfiguration.Constants;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
class SshdAuthorizedKeysAuthenticator extends AuthorizedKeysAuthenticator {
SshdAuthorizedKeysAuthenticator(Path path) {
super(path);
}
@Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
if (super.authenticate(username, key, session)) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/SshdAuthorizedKeysAuthenticator.java
import java.nio.file.Path;
import java.security.PublicKey;
import java.util.Collections;
import org.apache.sshd.server.config.keys.AuthorizedKeysAuthenticator;
import org.apache.sshd.server.session.ServerSession;
import sshd.shell.springboot.autoconfiguration.Constants;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
class SshdAuthorizedKeysAuthenticator extends AuthorizedKeysAuthenticator {
SshdAuthorizedKeysAuthenticator(Path path) {
super(path);
}
@Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
if (super.authenticate(username, key, session)) {
|
session.getIoSession().setAttribute(Constants.USER_ROLES, Collections.<String>singleton("*"));
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
|
import sshd.shell.springboot.ShellException;
|
/**
* 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 sshd.shell.springboot.autoconfiguration;
/**
*
* @author anand
*/
@FunctionalInterface
interface CommandExecutor {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/CommandExecutor.java
import sshd.shell.springboot.ShellException;
/**
* 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 sshd.shell.springboot.autoconfiguration;
/**
*
* @author anand
*/
@FunctionalInterface
interface CommandExecutor {
|
String get(String arg) throws InterruptedException, ShellException;
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/SessionsCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import java.util.Objects;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.session.SessionsEndpoint;
import org.springframework.boot.actuate.session.SessionsEndpoint.SessionDescriptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(SessionsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.sessions.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "sessions", description = "Sessions management")
public final class SessionsCommand extends AbstractSystemCommand {
private final SessionsEndpoint sessionsEndpoint;
SessionsCommand(@Value("${sshd.system.command.roles.sessions}") String[] systemRoles,
SessionsEndpoint sessionsEndpoint) {
super(systemRoles);
this.sessionsEndpoint = sessionsEndpoint;
}
@SshdShellCommand(value = "username", description = "Find sessions given username")
public String findSessionsByUsername(String arg) {
if (!StringUtils.hasText(arg)) {
return "Usage: sessions username <username>";
}
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/SessionsCommand.java
import java.util.Objects;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.session.SessionsEndpoint;
import org.springframework.boot.actuate.session.SessionsEndpoint.SessionDescriptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(SessionsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.sessions.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "sessions", description = "Sessions management")
public final class SessionsCommand extends AbstractSystemCommand {
private final SessionsEndpoint sessionsEndpoint;
SessionsCommand(@Value("${sshd.system.command.roles.sessions}") String[] systemRoles,
SessionsEndpoint sessionsEndpoint) {
super(systemRoles);
this.sessionsEndpoint = sessionsEndpoint;
}
@SshdShellCommand(value = "username", description = "Find sessions given username")
public String findSessionsByUsername(String arg) {
if (!StringUtils.hasText(arg)) {
return "Usage: sessions username <username>";
}
|
return JsonUtils.asJson(sessionsEndpoint.sessionsForUsername(arg));
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/HttpTraceCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.trace.http.HttpTraceEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(HttpTraceEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.httptrace.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "httpTrace", description = "Http trace information")
public final class HttpTraceCommand extends AbstractSystemCommand {
private final HttpTraceEndpoint httpTraceEndpoint;
HttpTraceCommand(@Value("${sshd.system.command.roles.httpTrace}") String[] systemRoles,
HttpTraceEndpoint httpTraceEndpoint) {
super(systemRoles);
this.httpTraceEndpoint = httpTraceEndpoint;
}
public String httpTrace(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/HttpTraceCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.trace.http.HttpTraceEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(HttpTraceEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.httptrace.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "httpTrace", description = "Http trace information")
public final class HttpTraceCommand extends AbstractSystemCommand {
private final HttpTraceEndpoint httpTraceEndpoint;
HttpTraceCommand(@Value("${sshd.system.command.roles.httpTrace}") String[] systemRoles,
HttpTraceEndpoint httpTraceEndpoint) {
super(systemRoles);
this.httpTraceEndpoint = httpTraceEndpoint;
}
public String httpTrace(String arg) {
|
return JsonUtils.asJson(httpTraceEndpoint.traces());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ConditionsReportCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.condition.ConditionsReportEndpoint;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnAvailableEndpoint(endpoint = ConditionsReportEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.conditions.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "conditionsReport", description = "Conditions report")
public final class ConditionsReportCommand extends AbstractSystemCommand {
private final ConditionsReportEndpoint conditionsReportEndpoint;
ConditionsReportCommand(@Value("${sshd.system.command.roles.conditionsReport}") String[] systemRoles,
ConditionsReportEndpoint conditionsReportEndpoint) {
super(systemRoles);
this.conditionsReportEndpoint = conditionsReportEndpoint;
}
public String conditionsReport(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ConditionsReportCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.condition.ConditionsReportEndpoint;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnAvailableEndpoint(endpoint = ConditionsReportEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.conditions.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "conditionsReport", description = "Conditions report")
public final class ConditionsReportCommand extends AbstractSystemCommand {
private final ConditionsReportEndpoint conditionsReportEndpoint;
ConditionsReportCommand(@Value("${sshd.system.command.roles.conditionsReport}") String[] systemRoles,
ConditionsReportEndpoint conditionsReportEndpoint) {
super(systemRoles);
this.conditionsReportEndpoint = conditionsReportEndpoint;
}
public String conditionsReport(String arg) {
|
return JsonUtils.asJson(conditionsReportEndpoint.applicationConditionEvaluation());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/SimpleSshdPasswordAuthenticator.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
|
import java.util.Set;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
@lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE)
class SimpleSshdPasswordAuthenticator implements PasswordAuthenticator {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/SimpleSshdPasswordAuthenticator.java
import java.util.Set;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
@lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE)
class SimpleSshdPasswordAuthenticator implements PasswordAuthenticator {
|
private final Shell props;
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/SimpleSshdPasswordAuthenticator.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
|
import java.util.Set;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
@lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE)
class SimpleSshdPasswordAuthenticator implements PasswordAuthenticator {
private final Shell props;
private final Set<String> systemCommandRoles;
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
PasswordChangeRequiredException {
if (username.equals(props.getUsername()) && password.equals(props.getPassword())) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellProperties.java
// @lombok.Data
// public static class Shell {
//
// private int port = 8022;
// private boolean enabled = false;
// private String username = "admin";
// private String password;
// private String publicKeyFile;
// private String host = "127.0.0.1";
// private String hostKeyFile = "hostKey.ser";
// private final Prompt prompt = new Prompt();
// private final Text text = new Text();
// private final Auth auth = new Auth();
//
// @lombok.Data
// public static class Prompt {
//
// private ColorType color = ColorType.BLACK;
// private String title = "app";
// }
//
// @lombok.Data
// public static class Text {
//
// private ColorType color = ColorType.BLACK;
// private ColorType highlightColor = ColorType.YELLOW;
// private String usageInfoFormat = "%n%-35s%s";
// }
//
// @lombok.Data
// public static class Auth {
//
// public enum AuthType {
// SIMPLE,
// AUTH_PROVIDER
// }
//
// private AuthType authType = AuthType.SIMPLE;
// private String authProviderBeanName;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/SimpleSshdPasswordAuthenticator.java
import java.util.Set;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;
import sshd.shell.springboot.autoconfiguration.Constants;
import sshd.shell.springboot.autoconfiguration.SshdShellProperties.Shell;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
@lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE)
class SimpleSshdPasswordAuthenticator implements PasswordAuthenticator {
private final Shell props;
private final Set<String> systemCommandRoles;
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
PasswordChangeRequiredException {
if (username.equals(props.getUsername()) && password.equals(props.getPassword())) {
|
session.getIoSession().setAttribute(Constants.USER_ROLES, systemCommandRoles);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/AuthProviderSshdPasswordAuthenticator.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
|
import java.util.stream.Collectors;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import sshd.shell.springboot.autoconfiguration.Constants;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
@lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE)
@lombok.extern.slf4j.Slf4j
class AuthProviderSshdPasswordAuthenticator implements PasswordAuthenticator {
private final AuthenticationProvider authProvider;
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
PasswordChangeRequiredException {
try {
Authentication auth = authProvider.authenticate(
new UsernamePasswordAuthenticationToken(username, password));
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/Constants.java
// public enum Constants {
//
// ;
// public static final String USER = "__user";
// public static final String HELP = "help";
// public static final String USER_ROLES = "__userRoles";
// public static final String EXECUTE = "__execute";
// public static final String SHELL_BANNER = "__shellBanner";
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/server/AuthProviderSshdPasswordAuthenticator.java
import java.util.stream.Collectors;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import sshd.shell.springboot.autoconfiguration.Constants;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.server;
/**
*
* @author anand
*/
@lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE)
@lombok.extern.slf4j.Slf4j
class AuthProviderSshdPasswordAuthenticator implements PasswordAuthenticator {
private final AuthenticationProvider authProvider;
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
PasswordChangeRequiredException {
try {
Authentication auth = authProvider.authenticate(
new UsernamePasswordAuthenticationToken(username, password));
|
session.getIoSession().setAttribute(Constants.USER, username);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ScheduledTasksCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.scheduling.ScheduledTasksEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(ScheduledTasksEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.scheduledtasks.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "scheduledTasks", description = "Scheduled tasks")
public final class ScheduledTasksCommand extends AbstractSystemCommand {
private final ScheduledTasksEndpoint scheduledTasksEndpoint;
ScheduledTasksCommand(@Value("${sshd.system.command.roles.scheduledTasks}") String[] systemRoles,
ScheduledTasksEndpoint scheduledTasksEndpoint) {
super(systemRoles);
this.scheduledTasksEndpoint = scheduledTasksEndpoint;
}
public String scheduledTasks(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ScheduledTasksCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.scheduling.ScheduledTasksEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(ScheduledTasksEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.scheduledtasks.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "scheduledTasks", description = "Scheduled tasks")
public final class ScheduledTasksCommand extends AbstractSystemCommand {
private final ScheduledTasksEndpoint scheduledTasksEndpoint;
ScheduledTasksCommand(@Value("${sshd.system.command.roles.scheduledTasks}") String[] systemRoles,
ScheduledTasksEndpoint scheduledTasksEndpoint) {
super(systemRoles);
this.scheduledTasksEndpoint = scheduledTasksEndpoint;
}
public String scheduledTasks(String arg) {
|
return JsonUtils.asJson(scheduledTasksEndpoint.scheduledTasks());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ThreadDumpCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.management.ThreadDumpEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(ThreadDumpEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.threaddump.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "threadDump", description = "Print thread dump")
public final class ThreadDumpCommand extends AbstractSystemCommand {
private final ThreadDumpEndpoint threadDumpEndpoint;
ThreadDumpCommand(@Value("${sshd.system.command.roles.threadDump}") String[] systemRoles,
ThreadDumpEndpoint threadDumpEndpoint) {
super(systemRoles);
this.threadDumpEndpoint = threadDumpEndpoint;
}
public String threadDump(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ThreadDumpCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.management.ThreadDumpEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(ThreadDumpEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.threaddump.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "threadDump", description = "Print thread dump")
public final class ThreadDumpCommand extends AbstractSystemCommand {
private final ThreadDumpEndpoint threadDumpEndpoint;
ThreadDumpCommand(@Value("${sshd.system.command.roles.threadDump}") String[] systemRoles,
ThreadDumpEndpoint threadDumpEndpoint) {
super(systemRoles);
this.threadDumpEndpoint = threadDumpEndpoint;
}
public String threadDump(String arg) {
|
return JsonUtils.asJson(threadDumpEndpoint.threadDump());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/FlywayCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.flyway.FlywayEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(FlywayEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.flyway.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "flyway", description = "Flyway database migration details (if applicable)")
public final class FlywayCommand extends AbstractSystemCommand {
private final FlywayEndpoint flywayEndpoint;
FlywayCommand(@Value("${sshd.system.command.roles.flyway}") String[] systemRoles, FlywayEndpoint flywayEndpoint) {
super(systemRoles);
this.flywayEndpoint = flywayEndpoint;
}
public String flyway(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/FlywayCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.flyway.FlywayEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2019 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(FlywayEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.flyway.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "flyway", description = "Flyway database migration details (if applicable)")
public final class FlywayCommand extends AbstractSystemCommand {
private final FlywayEndpoint flywayEndpoint;
FlywayCommand(@Value("${sshd.system.command.roles.flyway}") String[] systemRoles, FlywayEndpoint flywayEndpoint) {
super(systemRoles);
this.flywayEndpoint = flywayEndpoint;
}
public String flyway(String arg) {
|
return JsonUtils.asJson(flywayEndpoint.flywayBeans());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/command/ExceptionCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
|
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
|
/**
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "exception", description = "throws Exceptions")
public class ExceptionCommand {
@SshdShellCommand(value = "iae", description = "throws IAE")
public String iae(String arg) {
throw new IllegalArgumentException("illegalargumentexception");
}
@SshdShellCommand(value = "se", description = "throws ShellException")
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/command/ExceptionCommand.java
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
/**
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "exception", description = "throws Exceptions")
public class ExceptionCommand {
@SshdShellCommand(value = "iae", description = "throws IAE")
public String iae(String arg) {
throw new IllegalArgumentException("illegalargumentexception");
}
@SshdShellCommand(value = "se", description = "throws ShellException")
|
public String se(String arg) throws ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ConfigurationPropertiesReportCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.context.properties.ConfigurationPropertiesReportEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(ConfigurationPropertiesReportEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.configprops.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "configurationPropertiesReport", description = "Configuration properties report")
public final class ConfigurationPropertiesReportCommand extends AbstractSystemCommand {
private final ConfigurationPropertiesReportEndpoint confPropsReportEndpoint;
ConfigurationPropertiesReportCommand(ConfigurationPropertiesReportEndpoint confPropsReportEndpoint,
@Value("${sshd.system.command.roles.configurationPropertiesReport}") String[] systemRoles) {
super(systemRoles);
this.confPropsReportEndpoint = confPropsReportEndpoint;
}
public String configurationPropertiesReport(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ConfigurationPropertiesReportCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.context.properties.ConfigurationPropertiesReportEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(ConfigurationPropertiesReportEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.configprops.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "configurationPropertiesReport", description = "Configuration properties report")
public final class ConfigurationPropertiesReportCommand extends AbstractSystemCommand {
private final ConfigurationPropertiesReportEndpoint confPropsReportEndpoint;
ConfigurationPropertiesReportCommand(ConfigurationPropertiesReportEndpoint confPropsReportEndpoint,
@Value("${sshd.system.command.roles.configurationPropertiesReport}") String[] systemRoles) {
super(systemRoles);
this.confPropsReportEndpoint = confPropsReportEndpoint;
}
public String configurationPropertiesReport(String arg) {
|
return JsonUtils.asJson(confPropsReportEndpoint.configurationProperties());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/command/TestCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
// @lombok.extern.slf4j.Slf4j
// public enum ConsoleIO {
// ;
//
// static final String LINE_READER = "__lineReader";
// static final String TEXT_STYLE = "__textStyle";
// static final String TERMINAL = "__terminal";
// static final String HIGHLIGHT_COLOR = "__highlightColor";
//
// /**
// * Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
// * characters that get echoed with input
// *
// * @param text Text to show
// * @param mask mask
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text, Character mask) throws IOException {
// LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
// AttributedStyle textStyle = SshSessionContext.<AttributedStyle>get(TEXT_STYLE);
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// String prompt = new AttributedStringBuilder()
// .style(textStyle)
// .append(text)
// .append(' ')
// .style(AttributedStyle.DEFAULT)
// .toAnsi(terminal);
// return reader.readLine(prompt, mask);
// }
//
// /**
// * Read input from line with input echoed.
// *
// * @param text Text to show
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text) throws IOException {
// return readInput(text, null);
// }
//
// /**
// * Write output.
// *
// * @param output Text output
// */
// public static void writeOutput(String output) {
// writeOutput(output, null);
// }
//
// /**
// * Write highlighted output.
// *
// * @param output Text output
// * @param textToHighlight text to highlight
// */
// public static void writeOutput(String output, String textToHighlight) {
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// AttributedStringBuilder builder = new AttributedStringBuilder()
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// if (Objects.isNull(textToHighlight)) {
// builder.append(output);
// } else {
// addHighlightedTextToBuilder(output, textToHighlight, builder);
// }
// terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
// terminal.flush();
// }
//
// private static void addHighlightedTextToBuilder(String output, String textToHighlight,
// AttributedStringBuilder builder) {
// String[] split = output.split(textToHighlight);
// for (int i = 0; i < split.length - 1; i++) {
// builder.append(split[i])
// .style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
// .append(textToHighlight)
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// }
// builder.append(split[split.length - 1]);
// }
//
// public static void writeJsonOutput(Object object) {
// writeJsonOutput(object, null);
// }
//
// public static void writeJsonOutput(Object object, String textToHighlight) {
// writeOutput(JsonUtils.asJson(object), textToHighlight);
// }
// }
|
import java.io.IOException;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.console.ConsoleIO;
|
/**
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "test", description = "test description", roles = {"USER", "ADMIN"})
public class TestCommand {
@SshdShellCommand(value = "run", description = "test run", roles = "USER")
public String run(String arg) {
return "test run " + arg;
}
@SshdShellCommand(value = "execute", description = "test execute", roles = "ADMIN")
public String execute(String arg) {
return "test execute successful";
}
@SshdShellCommand(value = "interactive", description = "test interactive")
public String interactive(String arg) throws IOException {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/ConsoleIO.java
// @lombok.extern.slf4j.Slf4j
// public enum ConsoleIO {
// ;
//
// static final String LINE_READER = "__lineReader";
// static final String TEXT_STYLE = "__textStyle";
// static final String TERMINAL = "__terminal";
// static final String HIGHLIGHT_COLOR = "__highlightColor";
//
// /**
// * Read input from line with mask. Use null if input is to be echoed. Use 0 if nothing is to be echoed and other
// * characters that get echoed with input
// *
// * @param text Text to show
// * @param mask mask
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text, Character mask) throws IOException {
// LineReader reader = SshSessionContext.<LineReader>get(LINE_READER);
// AttributedStyle textStyle = SshSessionContext.<AttributedStyle>get(TEXT_STYLE);
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// String prompt = new AttributedStringBuilder()
// .style(textStyle)
// .append(text)
// .append(' ')
// .style(AttributedStyle.DEFAULT)
// .toAnsi(terminal);
// return reader.readLine(prompt, mask);
// }
//
// /**
// * Read input from line with input echoed.
// *
// * @param text Text to show
// * @return input from user
// * @throws IOException if any
// */
// public static String readInput(String text) throws IOException {
// return readInput(text, null);
// }
//
// /**
// * Write output.
// *
// * @param output Text output
// */
// public static void writeOutput(String output) {
// writeOutput(output, null);
// }
//
// /**
// * Write highlighted output.
// *
// * @param output Text output
// * @param textToHighlight text to highlight
// */
// public static void writeOutput(String output, String textToHighlight) {
// Terminal terminal = SshSessionContext.<Terminal>get(TERMINAL);
// AttributedStringBuilder builder = new AttributedStringBuilder()
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// if (Objects.isNull(textToHighlight)) {
// builder.append(output);
// } else {
// addHighlightedTextToBuilder(output, textToHighlight, builder);
// }
// terminal.writer().println(builder.style(AttributedStyle.DEFAULT).toAnsi(terminal));
// terminal.flush();
// }
//
// private static void addHighlightedTextToBuilder(String output, String textToHighlight,
// AttributedStringBuilder builder) {
// String[] split = output.split(textToHighlight);
// for (int i = 0; i < split.length - 1; i++) {
// builder.append(split[i])
// .style(SshSessionContext.<AttributedStyle>get(HIGHLIGHT_COLOR))
// .append(textToHighlight)
// .style(SshSessionContext.<AttributedStyle>get(TEXT_STYLE));
// }
// builder.append(split[split.length - 1]);
// }
//
// public static void writeJsonOutput(Object object) {
// writeJsonOutput(object, null);
// }
//
// public static void writeJsonOutput(Object object, String textToHighlight) {
// writeOutput(JsonUtils.asJson(object), textToHighlight);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/command/TestCommand.java
import java.io.IOException;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.console.ConsoleIO;
/**
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@SshdShellCommand(value = "test", description = "test description", roles = {"USER", "ADMIN"})
public class TestCommand {
@SshdShellCommand(value = "run", description = "test run", roles = "USER")
public String run(String arg) {
return "test run " + arg;
}
@SshdShellCommand(value = "execute", description = "test execute", roles = "ADMIN")
public String execute(String arg) {
return "test execute successful";
}
@SshdShellCommand(value = "interactive", description = "test interactive")
public String interactive(String arg) throws IOException {
|
String name = ConsoleIO.readInput("Name:");
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/LoggersCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.logging.LoggersEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.logging.LogLevel;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(LoggersEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.loggers.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "loggers", description = "Logging configuration")
public final class LoggersCommand extends AbstractSystemCommand {
private final LoggersEndpoint loggersEndpoint;
LoggersCommand(@Value("${sshd.system.command.roles.loggers}") String[] systemRoles,
LoggersEndpoint loggersEndpoint) {
super(systemRoles);
this.loggersEndpoint = loggersEndpoint;
}
@SshdShellCommand(value = "info", description = "Show logging info")
public String info(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/LoggersCommand.java
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.logging.LoggersEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.logging.LogLevel;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(LoggersEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.loggers.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "loggers", description = "Logging configuration")
public final class LoggersCommand extends AbstractSystemCommand {
private final LoggersEndpoint loggersEndpoint;
LoggersCommand(@Value("${sshd.system.command.roles.loggers}") String[] systemRoles,
LoggersEndpoint loggersEndpoint) {
super(systemRoles);
this.loggersEndpoint = loggersEndpoint;
}
@SshdShellCommand(value = "info", description = "Show logging info")
public String info(String arg) {
|
return JsonUtils.asJson(loggersEndpoint.loggers());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/HighlightUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/UsageInfo.java
// @lombok.AllArgsConstructor
// @lombok.Getter
// public static class Row {
//
// private final String usage;
// private final String description;
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.console.UsageInfo.Row;
import sshd.shell.springboot.util.Assert;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(1)
class HighlightUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?h (.+)");
@Override
public Optional<UsageInfo> getUsageInfo() {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/UsageInfo.java
// @lombok.AllArgsConstructor
// @lombok.Getter
// public static class Row {
//
// private final String usage;
// private final String description;
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/HighlightUserInputProcessor.java
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.console.UsageInfo.Row;
import sshd.shell.springboot.util.Assert;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(1)
class HighlightUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?h (.+)");
@Override
public Optional<UsageInfo> getUsageInfo() {
|
return Optional.of(new UsageInfo(Arrays.<Row>asList(
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/HighlightUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/UsageInfo.java
// @lombok.AllArgsConstructor
// @lombok.Getter
// public static class Row {
//
// private final String usage;
// private final String description;
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.console.UsageInfo.Row;
import sshd.shell.springboot.util.Assert;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(1)
class HighlightUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?h (.+)");
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<Row>asList(
new Row("h <arg>", "Highlights <arg> in response output of command execution"),
new Row("", "Example usage: help | h exit"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/UsageInfo.java
// @lombok.AllArgsConstructor
// @lombok.Getter
// public static class Row {
//
// private final String usage;
// private final String description;
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/HighlightUserInputProcessor.java
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.console.UsageInfo.Row;
import sshd.shell.springboot.util.Assert;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(1)
class HighlightUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?h (.+)");
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<Row>asList(
new Row("h <arg>", "Highlights <arg> in response output of command execution"),
new Row("", "Example usage: help | h exit"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
|
public void processUserInput(String userInput) throws InterruptedException, ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/HighlightUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/UsageInfo.java
// @lombok.AllArgsConstructor
// @lombok.Getter
// public static class Row {
//
// private final String usage;
// private final String description;
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.console.UsageInfo.Row;
import sshd.shell.springboot.util.Assert;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(1)
class HighlightUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?h (.+)");
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<Row>asList(
new Row("h <arg>", "Highlights <arg> in response output of command execution"),
new Row("", "Example usage: help | h exit"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
public void processUserInput(String userInput) throws InterruptedException, ShellException {
String textToHighlight = getHighlightedText(userInput);
String[] tokens = splitAndValidateCommand(userInput, "\\|", 2);
String commandExecution = tokens[0];
String output = processCommands(commandExecution);
ConsoleIO.writeOutput(output, textToHighlight);
}
private String getHighlightedText(String userInput) throws ShellException {
Matcher matcher = pattern.matcher(userInput);
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/UsageInfo.java
// @lombok.AllArgsConstructor
// @lombok.Getter
// public static class Row {
//
// private final String usage;
// private final String description;
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/HighlightUserInputProcessor.java
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.console.UsageInfo.Row;
import sshd.shell.springboot.util.Assert;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(1)
class HighlightUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?h (.+)");
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<Row>asList(
new Row("h <arg>", "Highlights <arg> in response output of command execution"),
new Row("", "Example usage: help | h exit"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
public void processUserInput(String userInput) throws InterruptedException, ShellException {
String textToHighlight = getHighlightedText(userInput);
String[] tokens = splitAndValidateCommand(userInput, "\\|", 2);
String commandExecution = tokens[0];
String output = processCommands(commandExecution);
ConsoleIO.writeOutput(output, textToHighlight);
}
private String getHighlightedText(String userInput) throws ShellException {
Matcher matcher = pattern.matcher(userInput);
|
Assert.isTrue(matcher.find(), "Unexpected error");
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ShutdownCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnAvailableEndpoint(endpoint = ShutdownEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.shutdown.enabled", havingValue = "true", matchIfMissing = false)
@SshdShellCommand(value = "shutdown", description = "Shutdown application")
public final class ShutdownCommand extends AbstractSystemCommand {
private final ShutdownEndpoint shutdownEndpoint;
ShutdownCommand(@Value("${sshd.system.command.roles.shutdown}") String[] systemRoles,
ShutdownEndpoint shutdownEndpoint) {
super(systemRoles);
this.shutdownEndpoint = shutdownEndpoint;
}
public String shutdown(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/ShutdownCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnAvailableEndpoint(endpoint = ShutdownEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.shutdown.enabled", havingValue = "true", matchIfMissing = false)
@SshdShellCommand(value = "shutdown", description = "Shutdown application")
public final class ShutdownCommand extends AbstractSystemCommand {
private final ShutdownEndpoint shutdownEndpoint;
ShutdownCommand(@Value("${sshd.system.command.roles.shutdown}") String[] systemRoles,
ShutdownEndpoint shutdownEndpoint) {
super(systemRoles);
this.shutdownEndpoint = shutdownEndpoint;
}
public String shutdown(String arg) {
|
return JsonUtils.asJson(shutdownEndpoint.shutdown());
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/EnvironmentCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.env.EnvironmentEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(EnvironmentEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.env.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "environment", description = "Environment details")
public final class EnvironmentCommand extends AbstractSystemCommand {
private final EnvironmentEndpoint envEndpoint;
EnvironmentCommand(@Value("${sshd.system.command.roles.environment}") String[] systemRoles,
EnvironmentEndpoint envEndpoint) {
super(systemRoles);
this.envEndpoint = envEndpoint;
}
@SshdShellCommand(value = "pattern", description = "Get environment details with given pattern")
public String withPattern(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/EnvironmentCommand.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.env.EnvironmentEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(EnvironmentEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.env.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "environment", description = "Environment details")
public final class EnvironmentCommand extends AbstractSystemCommand {
private final EnvironmentEndpoint envEndpoint;
EnvironmentCommand(@Value("${sshd.system.command.roles.environment}") String[] systemRoles,
EnvironmentEndpoint envEndpoint) {
super(systemRoles);
this.envEndpoint = envEndpoint;
}
@SshdShellCommand(value = "pattern", description = "Get environment details with given pattern")
public String withPattern(String arg) {
|
return JsonUtils.asJson(envEndpoint.environment(arg));
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/AuditEventsCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.time.OffsetDateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.audit.AuditEventsEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(AuditEventsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.auditevents.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "auditEvents", description = "Event auditing")
public final class AuditEventsCommand extends AbstractSystemCommand {
private final AuditEventsEndpoint auditEventsEndpoint;
AuditEventsCommand(@Value("${sshd.system.command.roles.auditEvents}") String[] systemRoles,
AuditEventsEndpoint auditEventsEndpoint) {
super(systemRoles);
this.auditEventsEndpoint = auditEventsEndpoint;
}
@SshdShellCommand(value = "list", description = "List events")
public String auditEvents(String arg) {
if (!StringUtils.hasText(arg)) {
return "Usage: auditEvents list {\"principal\":\"<user>\",\"after\":\"<yyyy-MM-dd HH:mm>\","
+ "\"type\":\"<type>\"}";
}
return CommandUtils.process(() -> {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/AuditEventsCommand.java
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.time.OffsetDateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.audit.AuditEventsEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(AuditEventsEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.auditevents.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "auditEvents", description = "Event auditing")
public final class AuditEventsCommand extends AbstractSystemCommand {
private final AuditEventsEndpoint auditEventsEndpoint;
AuditEventsCommand(@Value("${sshd.system.command.roles.auditEvents}") String[] systemRoles,
AuditEventsEndpoint auditEventsEndpoint) {
super(systemRoles);
this.auditEventsEndpoint = auditEventsEndpoint;
}
@SshdShellCommand(value = "list", description = "List events")
public String auditEvents(String arg) {
if (!StringUtils.hasText(arg)) {
return "Usage: auditEvents list {\"principal\":\"<user>\",\"after\":\"<yyyy-MM-dd HH:mm>\","
+ "\"type\":\"<type>\"}";
}
return CommandUtils.process(() -> {
|
Event event = JsonUtils.stringToObject(arg, Event.class);
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellAutoConfiguration.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/AbstractSystemCommand.java
// public abstract class AbstractSystemCommand {
//
// private final Set<String> systemRoles;
//
// public AbstractSystemCommand(String[] systemRoles) {
// this.systemRoles = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(systemRoles)));
// }
//
// public final Set<String> getSystemRoles() {
// return systemRoles;
// }
// }
|
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.command.AbstractSystemCommand;
|
}
private Map<String, CommandExecutableDetails> getSupplierMap(SshdShellCommand annotation,
Map<String, Map<String, CommandExecutableDetails>> sshdShellCommandsMap) {
Map<String, CommandExecutableDetails> map = sshdShellCommandsMap.get(annotation.value());
Assert.isTrue(Objects.isNull(map), "Duplicate commands in different classes are not allowed");
sshdShellCommandsMap.put(annotation.value(), map = new TreeMap<>());
return map;
}
private void loadSshdShellCommandSuppliers(Class<?> clazz, SshdShellCommand annotation,
Map<String, CommandExecutableDetails> map, Object obj) {
loadClassLevelCommandSupplier(clazz, annotation, map, obj);
loadMethodLevelCommandSupplier(clazz, map, obj);
}
private void loadClassLevelCommandSupplier(Class<?> clazz, SshdShellCommand annotation,
Map<String, CommandExecutableDetails> map, Object obj) {
log.debug("Loading class level command supplier for {}", clazz.getName());
try {
Method method = clazz.getDeclaredMethod(annotation.value(), String.class);
map.put(Constants.EXECUTE, getMethodSupplier(annotation, obj, buildCommandExecutable(method, obj)));
} catch (NoSuchMethodException ex) {
map.put(Constants.EXECUTE, getMethodSupplier(annotation, obj, null));
}
}
private CommandExecutableDetails getMethodSupplier(SshdShellCommand annotation, Object obj,
CommandExecutor commandExecutor) {
CommandExecutableDetails ced = new CommandExecutableDetails(annotation,
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/AbstractSystemCommand.java
// public abstract class AbstractSystemCommand {
//
// private final Set<String> systemRoles;
//
// public AbstractSystemCommand(String[] systemRoles) {
// this.systemRoles = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(systemRoles)));
// }
//
// public final Set<String> getSystemRoles() {
// return systemRoles;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellAutoConfiguration.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.command.AbstractSystemCommand;
}
private Map<String, CommandExecutableDetails> getSupplierMap(SshdShellCommand annotation,
Map<String, Map<String, CommandExecutableDetails>> sshdShellCommandsMap) {
Map<String, CommandExecutableDetails> map = sshdShellCommandsMap.get(annotation.value());
Assert.isTrue(Objects.isNull(map), "Duplicate commands in different classes are not allowed");
sshdShellCommandsMap.put(annotation.value(), map = new TreeMap<>());
return map;
}
private void loadSshdShellCommandSuppliers(Class<?> clazz, SshdShellCommand annotation,
Map<String, CommandExecutableDetails> map, Object obj) {
loadClassLevelCommandSupplier(clazz, annotation, map, obj);
loadMethodLevelCommandSupplier(clazz, map, obj);
}
private void loadClassLevelCommandSupplier(Class<?> clazz, SshdShellCommand annotation,
Map<String, CommandExecutableDetails> map, Object obj) {
log.debug("Loading class level command supplier for {}", clazz.getName());
try {
Method method = clazz.getDeclaredMethod(annotation.value(), String.class);
map.put(Constants.EXECUTE, getMethodSupplier(annotation, obj, buildCommandExecutable(method, obj)));
} catch (NoSuchMethodException ex) {
map.put(Constants.EXECUTE, getMethodSupplier(annotation, obj, null));
}
}
private CommandExecutableDetails getMethodSupplier(SshdShellCommand annotation, Object obj,
CommandExecutor commandExecutor) {
CommandExecutableDetails ced = new CommandExecutableDetails(annotation,
|
obj instanceof AbstractSystemCommand
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellAutoConfiguration.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/AbstractSystemCommand.java
// public abstract class AbstractSystemCommand {
//
// private final Set<String> systemRoles;
//
// public AbstractSystemCommand(String[] systemRoles) {
// this.systemRoles = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(systemRoles)));
// }
//
// public final Set<String> getSystemRoles() {
// return systemRoles;
// }
// }
|
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.command.AbstractSystemCommand;
|
} catch (NoSuchMethodException ex) {
map.put(Constants.EXECUTE, getMethodSupplier(annotation, obj, null));
}
}
private CommandExecutableDetails getMethodSupplier(SshdShellCommand annotation, Object obj,
CommandExecutor commandExecutor) {
CommandExecutableDetails ced = new CommandExecutableDetails(annotation,
obj instanceof AbstractSystemCommand
? ((AbstractSystemCommand) obj).getSystemRoles()
: new HashSet<>(Arrays.asList(annotation.roles())),
commandExecutor);
log.debug("Command Execution details summary: {}", ced);
return ced;
}
private CommandExecutor buildCommandExecutable(Method method, Object obj) {
return arg -> {
try {
return (String) method.invoke(obj, arg);
} catch (InvocationTargetException ex) {
rethrowSupportedExceptionsOnCommandExecutor(ex.getCause());
return printAndGetErrorInfo(ex.getCause());
} catch (IllegalAccessException ex) {
return printAndGetErrorInfo(ex);
}
};
}
private void rethrowSupportedExceptionsOnCommandExecutor(Throwable ex) throws IllegalArgumentException,
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/AbstractSystemCommand.java
// public abstract class AbstractSystemCommand {
//
// private final Set<String> systemRoles;
//
// public AbstractSystemCommand(String[] systemRoles) {
// this.systemRoles = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(systemRoles)));
// }
//
// public final Set<String> getSystemRoles() {
// return systemRoles;
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/autoconfiguration/SshdShellAutoConfiguration.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import sshd.shell.springboot.ShellException;
import sshd.shell.springboot.command.AbstractSystemCommand;
} catch (NoSuchMethodException ex) {
map.put(Constants.EXECUTE, getMethodSupplier(annotation, obj, null));
}
}
private CommandExecutableDetails getMethodSupplier(SshdShellCommand annotation, Object obj,
CommandExecutor commandExecutor) {
CommandExecutableDetails ced = new CommandExecutableDetails(annotation,
obj instanceof AbstractSystemCommand
? ((AbstractSystemCommand) obj).getSystemRoles()
: new HashSet<>(Arrays.asList(annotation.roles())),
commandExecutor);
log.debug("Command Execution details summary: {}", ced);
return ced;
}
private CommandExecutor buildCommandExecutable(Method method, Object obj) {
return arg -> {
try {
return (String) method.invoke(obj, arg);
} catch (InvocationTargetException ex) {
rethrowSupportedExceptionsOnCommandExecutor(ex.getCause());
return printAndGetErrorInfo(ex.getCause());
} catch (IllegalAccessException ex) {
return printAndGetErrorInfo(ex);
}
};
}
private void rethrowSupportedExceptionsOnCommandExecutor(Throwable ex) throws IllegalArgumentException,
|
InterruptedException, ShellException {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.