conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
public static class USCensusPopMinAlpha implements Preset {
=======
public static class WikipediaAdj implements Preset {
public Aggregator<?,?> aggregator() {return new Numbers.Count<Object>();}
public Renderer renderer() {return new ParallelRenderer(RENDER_POOL);}
public Glyphset<?,?> glyphset() {return WIKIPEDIA;}
public Transfer<?,?> transfer() {return new WrappedTransfer.RedWhiteLog().op();}
public String name() {return "Wikipedia Adjacency (BFS Error layout): HDAlpha";}
public String toString() {return fullName(this);}
public boolean init(Presets panel) {
return glyphset() != null;
}
}
public static class USPopMinAlpha implements Preset {
>>>>>>>
public static class WikipediaAdj implements Preset {
public Aggregator<?,?> aggregator() {return new Numbers.Count<Object>();}
public Renderer renderer() {return new ParallelRenderer(RENDER_POOL);}
public Glyphset<?,?> glyphset() {return WIKIPEDIA;}
public Transfer<?,?> transfer() {return new WrappedTransfer.RedWhiteLog().op();}
public String name() {return "Wikipedia Adjacency (BFS Error layout): HDAlpha";}
public String toString() {return fullName(this);}
public boolean init(Presets panel) {
return glyphset() != null;
}
}
public static class USPopMinAlpha implements Preset {
<<<<<<<
private static final Glyphset<Point2D, Character> CENSUS_SYN_PEOPLE;
=======
private static final Glyphset<Point2D, Color> WIKIPEDIA;
>>>>>>>
private static final Glyphset<Point2D, Character> CENSUS_SYN_PEOPLE;
private static final Glyphset<Point2D, Color> WIKIPEDIA;
<<<<<<<
private static String CENSUS_TRACTS = "../data/2010Census_RaceTract.hbin";
private static String CENSUS_SYN_PEOPLE_BIN = "../data/2010Census_RacePersonPoints.hbin";
=======
private static String CENSUS = "../data/2010Census_RaceTract.hbin";
private static String WIKIPEDIA_BFS= "../data/wiki-adj.hbin";
>>>>>>>
private static String CENSUS_TRACTS = "../data/2010Census_RaceTract.hbin";
private static String CENSUS_SYN_PEOPLE_BIN = "../data/2010Census_RacePersonPoints.hbin";
private static String CENSUS = "../data/2010Census_RaceTract.hbin";
private static String WIKIPEDIA_BFS= "../data/wiki-adj.hbin";
<<<<<<<
System.err.printf("Error loading data from %s. Related presets are unavailable.\n", CENSUS_TRACTS);
=======
System.err.printf("## Error loading data from %s. Related presets are unavailable.\n", CENSUS);
>>>>>>>
System.err.printf("## Error loading data from %s. Related presets are unavailable.\n", CENSUS);
<<<<<<<
KIVA_ADJ = kiva_temp;
=======
KIVA_ADJ = kiva_temp;
Glyphset<Rectangle2D, Color> kiva_temp2 = null;
try {kiva_temp2 = GlyphsetUtils.memMap(
"Kiva", KIVA_BIN,
new Indexed.ToRect(Double.MIN_VALUE, Double.MIN_VALUE, false, 0, 1),
new Valuer.Constant<Indexed, Color>(Color.RED),
1, null);
} catch (Exception e) {
System.err.printf("## Error loading data from %s. Related presets are unavailable.\n", KIVA_BIN);
}
KIVA_ADJ_RECTS = kiva_temp2;
Glyphset<Point2D, Color> wiki_temp = null;
try {wiki_temp = GlyphsetUtils.memMap(
"Wikipedia BFS adjacnecy", WIKIPEDIA_BFS,
new Indexed.ToPoint(false, 0, 1),
new Valuer.Constant<Indexed, Color>(Color.RED),
1, null);
} catch (Exception e) {
System.err.printf("## Error loading data from %s. Related presets are unavailable.\n", KIVA_BIN);
}
WIKIPEDIA = wiki_temp;
>>>>>>>
KIVA_ADJ = kiva_temp;
Glyphset<Point2D, Color> wiki_temp = null;
try {wiki_temp = GlyphsetUtils.memMap(
"Wikipedia BFS adjacnecy", WIKIPEDIA_BFS,
new Indexed.ToPoint(false, 0, 1),
new Valuer.Constant<Indexed, Color>(Color.RED),
1, null);
} catch (Exception e) {
System.err.printf("## Error loading data from %s. Related presets are unavailable.\n", KIVA_BIN);
}
WIKIPEDIA = wiki_temp; |
<<<<<<<
@Override
public OUT at(int x, int y, Aggregates<? extends IN> aggregates) {
=======
@Override public OUT emptyValue() {return empty;}
@Override public ar.Transfer.Specialized<IN, OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
@Override public OUT at(int x, int y, Aggregates<? extends IN> aggregates) {
>>>>>>>
@Override
public OUT at(int x, int y, Aggregates<? extends IN> aggregates) {
<<<<<<<
@Override public boolean localOnly() {return true;}
@Override public OUT emptyValue() {return empty;}
@Override public ar.Transfer.Specialized<IN, OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
}
public static final class Last<IN> implements Aggregator<IN,IN> {
private final IN id;
public <V extends IN> Last(V id) {this.id = id;}
public IN combine(IN current, IN update) {return update;}
public IN rollup(IN left, IN right) {return right;}
public IN identity() {return id;}
=======
@Override
public Aggregates<OUT> process(Aggregates<? extends IN> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
>>>>>>>
@Override public OUT emptyValue() {return empty;}
@Override public ar.Transfer.Specialized<IN, OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
@Override public Aggregates<OUT> process(Aggregates<? extends IN> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
<<<<<<<
=======
@Override public T emptyValue() {return empty;}
@Override public Specialized<T,T> specialize(Aggregates<? extends T> aggregates) {return this;}
@Override
public Aggregates<T> process(Aggregates<? extends T> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
@Override
>>>>>>>
@Override public T emptyValue() {return empty;}
@Override public Specialized<T,T> specialize(Aggregates<? extends T> aggregates) {return this;}
@Override
public Aggregates<T> process(Aggregates<? extends T> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
@Override
<<<<<<<
@Override public boolean localOnly() {return false;}
@Override public V emptyValue() {return empty;}
@Override public Specialized<V, V> specialize(Aggregates<? extends V> aggregates) {return this;}
=======
@Override
public Aggregates<V> process(Aggregates<? extends V> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
>>>>>>>
@Override public V emptyValue() {return empty;}
@Override public Specialized<V, V> specialize(Aggregates<? extends V> aggregates) {return this;}
@Override
public Aggregates<V> process(Aggregates<? extends V> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
<<<<<<<
return cachedAggs.get(x, y);
}
@Override public boolean localOnly() {return false;}
=======
return cachedAggs.get(x, y);
}
>>>>>>>
return cachedAggs.get(x, y);
}
<<<<<<<
@Override public OUT combine(OUT left, A update) {return val;}
@Override public OUT rollup(OUT left, OUT right) {return val;}
@Override public OUT identity() {return val;}
@Override public OUT emptyValue() {return val;}
@Override public Specialized<A, OUT> specialize(Aggregates<? extends A> aggregates) {return this;}
@Override public OUT at(int x, int y, Aggregates<? extends A> aggregates) {return val;}
@Override public boolean localOnly() {return true;}
=======
@Override public OUT combine(OUT left, A update) {return val;}
@Override public OUT rollup(OUT left, OUT right) {return val;}
@Override public OUT identity() {return val;}
@Override public OUT emptyValue() {return val;}
@Override public ar.Transfer.Specialized<A, OUT> specialize(Aggregates<? extends A> aggregates) {return this;}
@Override public OUT at(int x, int y, Aggregates<? extends A> aggregates) {return val;}
@Override
public Aggregates<OUT> process(Aggregates<? extends A> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
>>>>>>>
@Override public OUT combine(OUT left, A update) {return val;}
@Override public OUT rollup(OUT left, OUT right) {return val;}
@Override public OUT identity() {return val;}
@Override public OUT emptyValue() {return val;}
@Override public ar.Transfer.Specialized<A, OUT> specialize(Aggregates<? extends A> aggregates) {return this;}
@Override public OUT at(int x, int y, Aggregates<? extends A> aggregates) {return val;}
@Override
public Aggregates<OUT> process(Aggregates<? extends A> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
<<<<<<<
@Override public T rollup(T left, T right) {
=======
@Override public T at(int x, int y, Aggregates<? extends T> aggregates) {return aggregates.get(x, y);}
@Override public T emptyValue() {return empty;}
@Override public T identity() {return emptyValue();}
@Override public Echo<T> specialize(Aggregates<? extends T> aggregates) {return this;}
@Override public T combine(T left, T update) {return update;}
@Override public T rollup(T left, T right) {
>>>>>>>
@Override public T at(int x, int y, Aggregates<? extends T> aggregates) {return aggregates.get(x, y);}
@Override public T emptyValue() {return empty;}
@Override public T identity() {return emptyValue();}
@Override public Echo<T> specialize(Aggregates<? extends T> aggregates) {return this;}
@Override public T combine(T left, T update) {return update;}
@Override public T rollup(T left, T right) {
<<<<<<<
@Override public T at(int x, int y, Aggregates<? extends T> aggregates) {return aggregates.get(x, y);}
@Override public T emptyValue() {return empty;}
@Override public T combine(T left, T update) {return update;}
@Override public T identity() {return emptyValue();}
@Override public Echo<T> specialize(Aggregates<? extends T> aggregates) {return this;}
@Override public boolean localOnly() {return true;}
=======
@Override
public Aggregates<T> process(Aggregates<? extends T> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
>>>>>>>
@Override
public Aggregates<T> process(Aggregates<? extends T> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
<<<<<<<
@Override public Present<IN, OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
@Override public OUT emptyValue() {return absent;}
@Override public boolean localOnly() {return true;}
=======
@Override
public Aggregates<OUT> process(Aggregates<? extends IN> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
>>>>>>>
@Override
public Aggregates<OUT> process(Aggregates<? extends IN> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
<<<<<<<
@Override public boolean localOnly() {return true;}
@Override public OUT emptyValue() {return other;}
@Override public MapWrapper<IN,OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
=======
@Override public OUT emptyValue() {return other;}
@Override public MapWrapper<IN,OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
@Override
public Aggregates<OUT> process(Aggregates<? extends IN> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
>>>>>>>
@Override public OUT emptyValue() {return other;}
@Override public MapWrapper<IN,OUT> specialize(Aggregates<? extends IN> aggregates) {return this;}
@Override
public Aggregates<OUT> process(Aggregates<? extends IN> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
} |
<<<<<<<
IClass iClass = resolved.getTheClass();
ITypeParameter[] typeVariables;
IType concrete;
=======
final IClass iClass = resolved.getTheClass();
final ITypeVariable[] typeVariables;
final IType concrete;
>>>>>>>
final IClass iClass = resolved.getTheClass();
final ITypeParameter[] typeVariables;
final IType concrete;
<<<<<<<
resolved = iClass.getType();
typeVariables = iClass.getTypeParameters();
=======
typeVariables = iClass.getTypeVariables();
>>>>>>>
typeVariables = iClass.getTypeParameters();
<<<<<<<
ITypeParameter typeVariable = typeVariables[i];
IType type = this.typeArguments[i];
=======
final ITypeVariable typeVariable = typeVariables[i];
final IType type = this.typeArguments[i];
>>>>>>>
final ITypeParameter typeVariable = typeVariables[i];
final IType type = this.typeArguments[i]; |
<<<<<<<
Aggregates<A> rslt;
if ((high-low) > taskSize) {rslt=split();}
else {rslt=local();}
recorder.update((high-low)/2);
return rslt;
=======
if (viewport.isEmpty()) {return new ConstantAggregates<>(op.identity());}
if ((high-low) > taskSize) {return split();}
else {return local();}
>>>>>>>
if (viewport.isEmpty()) {return new ConstantAggregates<>(op.identity());}
Aggregates<A> rslt;
if ((high-low) > taskSize) {rslt=split();}
else {rslt=local();}
recorder.update((high-low)/2);
return rslt; |
<<<<<<<
import ar.renderers.ParallelSpatial;
import ar.rules.Aggregators;
=======
import ar.app.util.CharityNetLoader;
import ar.rules.Reductions;
>>>>>>>
import ar.renderers.ParallelSpatial;
import ar.rules.Aggregators;
import ar.app.util.CharityNetLoader; |
<<<<<<<
import ar.app.util.GlyphsetUtils;
import ar.ext.textfile.*;
import ar.glyphsets.DynamicQuadTree;
=======
>>>>>>>
import ar.ext.textfile.*;
<<<<<<<
public OptionAggregator<? super I,?> defaultAggregator() {return defaultAggregator;}
public List<OptionTransfer<?>> defaultTransfers() {return defaultTransfers;}
public static final OptionDataset<Point2D, Integer> WIKIPEDIA_TXT;
static {
OptionDataset<Point2D, Integer> temp;
try {
temp = new OptionDataset<>(
"Wikipedia BFS adjacnecy (Commons txt)",
new DelimitedFile<>(
new File("../data/wiki.full.txt"), ',', new Converter.TYPE[]{Converter.TYPE.LONG,Converter.TYPE.LONG, Converter.TYPE.COLOR},
new Indexed.ToPoint(false, 0,1), new Valuer.Constant<Indexed,Integer>(1)),
OptionAggregator.COUNT,
new OptionTransfer.MathTransfer(),
new OptionTransfer.Interpolate());
} catch (Exception e) {temp = null;}
WIKIPEDIA_TXT = temp;
}
=======
>>>>>>>
public OptionAggregator<? super I,?> defaultAggregator() {return defaultAggregator;}
public List<OptionTransfer<?>> defaultTransfers() {return defaultTransfers;}
public static final OptionDataset<Point2D, Integer> WIKIPEDIA_TXT;
static {
OptionDataset<Point2D, Integer> temp;
try {
temp = new OptionDataset<>(
"Wikipedia BFS adjacnecy (Commons txt)",
new DelimitedFile<>(
new File("../data/wiki.full.txt"), ',', new Converter.TYPE[]{Converter.TYPE.LONG,Converter.TYPE.LONG, Converter.TYPE.COLOR},
new Indexed.ToPoint(false, 0,1), new Valuer.Constant<Indexed,Integer>(1)),
OptionAggregator.COUNT,
new OptionTransfer.MathTransfer(),
new OptionTransfer.Interpolate());
} catch (Exception e) {temp = null;}
WIKIPEDIA_TXT = temp;
} |
<<<<<<<
@Override public GlyphList<Shape, N> contours() {return contours;}
@Override public boolean localOnly() {return true;}
@Override public N at(int x, int y, Aggregates<? extends N> aggregates) {return cached.get(x,y);}
=======
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Single<N>[] ts = LocalUtils.stepTransfers(contourLevels, fill);
Transfer.Specialized<N,N> t = new Fan.Specialized<>(
new MergeContours<N>(aggregates.defaultValue()),
ts,
aggregates);
return (ContourAggregates<N>) rend.transfer(aggregates, t);
}
>>>>>>>
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Single<N>[] ts = LocalUtils.stepTransfers(contourLevels, fill);
Transfer.Specialized<N,N> t = new Fan.Specialized<>(
new MergeContours<N>(aggregates.defaultValue()),
ts,
aggregates);
return (ContourAggregates<N>) rend.transfer(aggregates, t);
}
<<<<<<<
@Override public boolean localOnly() {return true;}
@Override public GlyphList<Shape, N> contours() {return contours;}
@Override public N at(int x, int y, Aggregates<? extends N> aggregates) {return cached.get(x,y);}
=======
>>>>>>>
<<<<<<<
public N emptyValue() {return null;}
public Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {
return new Specialized<>(renderer, threshold, fill, aggregates);
}
public static final class Specialized<N extends Number> extends Single<N> implements Transfer.Specialized<N,N>, ISOContours<N> {
private final GlyphList<Shape, N> contours;
protected final Aggregates<N> cached;
public Specialized(Renderer renderer, N threshold, boolean fill, Aggregates<? extends N> aggregates) {
super(renderer, threshold, fill);
Aggregates<? extends N> padAggs = new PadAggregates<>(aggregates, null);
Aggregates<Boolean> isoDivided = renderer.transfer(padAggs, new ISOBelow<>(threshold));
Aggregates<MC_TYPE> classified = renderer.transfer(isoDivided, new MCClassifier());
Shape s = Assembler.assembleContours(classified, isoDivided);
contours = new GlyphList<>();
contours.add(new SimpleGlyph<>(s, threshold));
if (!fill) {isoDivided = renderer.transfer(isoDivided, new General.Simplify<>(isoDivided.defaultValue()));}
cached = renderer.transfer(isoDivided, new General.MapWrapper<>(true, threshold, null));
}
@Override public boolean localOnly() {return true;}
@Override public GlyphList<Shape, N> contours() {return contours;}
@Override public N at(int x, int y, Aggregates<? extends N> aggregates) {return cached.get(x,y);}
=======
@Override public N emptyValue() {return null;}
@Override public Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {return this;}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Aggregates<? extends N> padAggs = new PadAggregates<>(aggregates, null);
Aggregates<Boolean> isoDivided = rend.transfer(padAggs, new ISOBelow<>(threshold));
Aggregates<MC_TYPE> classified = rend.transfer(isoDivided, new MCClassifier());
Shape s = Assembler.assembleContours(classified, isoDivided);
GlyphList<Shape, N> contours = new GlyphList<>();
contours.add(new SimpleGlyph<>(s, threshold));
if (!fill) {isoDivided = rend.transfer(isoDivided, new General.Simplify<>(isoDivided.defaultValue()));}
Aggregates<N> base = rend.transfer(isoDivided, new General.MapWrapper<>(true, threshold, null));
return new ContourAggregates<>(base, contours);
>>>>>>>
@Override public N emptyValue() {return null;}
@Override public Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {return this;}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Aggregates<? extends N> padAggs = new PadAggregates<>(aggregates, null);
Aggregates<Boolean> isoDivided = rend.transfer(padAggs, new ISOBelow<>(threshold));
Aggregates<MC_TYPE> classified = rend.transfer(isoDivided, new MCClassifier());
Shape s = Assembler.assembleContours(classified, isoDivided);
GlyphList<Shape, N> contours = new GlyphList<>();
contours.add(new SimpleGlyph<>(s, threshold));
if (!fill) {isoDivided = rend.transfer(isoDivided, new General.Simplify<>(isoDivided.defaultValue()));}
Aggregates<N> base = rend.transfer(isoDivided, new General.MapWrapper<>(true, threshold, null));
return new ContourAggregates<>(base, contours); |
<<<<<<<
@Provides @IntoSet
public ProjectActionHandler providesSetEntityFormDataActionHandler(SetEntityFormDataActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesGetEntityFormActionHandler(GetEntityFormActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesGetProjectFormDescriptorsActionHandler(GetProjectFormDescriptorsActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesSetProjectFormDescriptorsActionHandler(SetProjectFormDescriptorsActionHandler handler) {
return handler;
}
=======
@Provides @IntoSet
public ProjectActionHandler providesGetUserProjectEntityGraphCriteriaActionHandler(
GetUserProjectEntityGraphCriteriaActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesSetUserProjectEntityGraphCriteriaActionHandler(
SetUserProjectEntityGraphCriteriaActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler provideSetEntityGraphActiveFiltersActionHandler(SetEntityGraphActiveFiltersActionHandler handler) {
return handler;
}
>>>>>>>
@Provides @IntoSet
public ProjectActionHandler providesSetEntityFormDataActionHandler(SetEntityFormDataActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesGetUserProjectEntityGraphCriteriaActionHandler(
GetUserProjectEntityGraphCriteriaActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesGetEntityFormActionHandler(GetEntityFormActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesSetUserProjectEntityGraphCriteriaActionHandler(
SetUserProjectEntityGraphCriteriaActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesGetProjectFormDescriptorsActionHandler(GetProjectFormDescriptorsActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler providesSetProjectFormDescriptorsActionHandler(SetProjectFormDescriptorsActionHandler handler) {
return handler;
}
@Provides @IntoSet
public ProjectActionHandler provideSetEntityGraphActiveFiltersActionHandler(SetEntityGraphActiveFiltersActionHandler handler) {
return handler;
} |
<<<<<<<
module.addDeserializer(FormDataValue.class, new FormDataValueDeserializer(dataFactory));
=======
module.addSerializer(OWLLiteral.class, new OWLLiteralSerializer());
module.addDeserializer(OWLLiteral.class, new OWLLiteralDeserializer(dataFactory));
>>>>>>>
module.addDeserializer(FormDataValue.class, new FormDataValueDeserializer(dataFactory));
module.addSerializer(OWLLiteral.class, new OWLLiteralSerializer());
module.addDeserializer(OWLLiteral.class, new OWLLiteralDeserializer(dataFactory)); |
<<<<<<<
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
protected void onResume() {
super.onResume();
bindService();
updateStatus("");
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
Log.d("lala", ""+mService.getStatus());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateStatus("");
handleIntents();
}
=======
>>>>>>> |
<<<<<<<
import uk.chromis.pos.printer.DeviceTicket;
import uk.chromis.pos.ticket.TicketType;
=======
import uk.chromis.pos.promotion.DataLogicPromotions;
import uk.chromis.pos.promotion.PromotionSupport;
>>>>>>>
import uk.chromis.pos.printer.DeviceTicket;
import uk.chromis.pos.ticket.TicketType;
import uk.chromis.pos.promotion.DataLogicPromotions;
import uk.chromis.pos.promotion.PromotionSupport;
<<<<<<<
=======
private AppConfig m_config;
private PromotionSupport m_promotionSupport = null;
>>>>>>>
private AppConfig m_config;
private PromotionSupport m_promotionSupport = null;
<<<<<<<
visorTicketLine(null);
printPartialTotals();
stateToZero();
=======
updatePromotions( "promotion.removeline", i );
visorTicketLine(null); // borro el visor
printPartialTotals(); // pinto los totales parciales...
stateToZero(); // Pongo a cero
>>>>>>>
updatePromotions("promotion.removeline", i);
visorTicketLine(null);
printPartialTotals();
stateToZero(); |
<<<<<<<
// Switch Instructions
public void writeTableSwitch(Label defaultHandler, int start, int end, Label[] handlers);
public void writeLookupSwitch(Label defaultHandler, int[] keys, Label[] handlers);
=======
// Inlining
public void startInline(int varOffset, int stackOffset, Label end);
public void endInline(int varOffset, int stackOffset, Label end);
>>>>>>>
// Switch Instructions
public void writeTableSwitch(Label defaultHandler, int start, int end, Label[] handlers);
public void writeLookupSwitch(Label defaultHandler, int[] keys, Label[] handlers);
// Inlining
public void startInline(int varOffset, int stackOffset, Label end);
public void endInline(int varOffset, int stackOffset, Label end); |
<<<<<<<
// if (!paymentdialog.isPrintSelected()) {
// ticket.setTicketType(TicketType.INVOICE);
// }
=======
>>>>>>>
if (!paymentdialog.isPrintSelected()) {
ticket.setTicketType(TicketType.INVOICE);
}
<<<<<<<
// Reset the customer display here
if (!AppConfig.getInstance().getBoolean("machine.customerdisplay")) {
String sresource = dlSystem.getResourceAsXML("Display.Message");
DeviceTicket m_TP = new DeviceTicket(this, AppConfig.getInstance());
if (sresource == null) {
=======
/* Commented out due to not functioning as expected.
// Reset the customer display here
String sresource = dlSystem.getResourceAsXML("Display.Message");
DeviceTicket m_TP = new DeviceTicket(this, AppConfig.getInstance());
if (sresource == null) {
m_TP.getDeviceDisplay().writeVisor(AppLocal.APP_NAME, AppLocal.APP_VERSION);
} else {
try {
m_TTP.printTicket(sresource);
} catch (TicketPrinterException eTP) {
>>>>>>>
// Reset the customer display here
String sresource = dlSystem.getResourceAsXML("Display.Message");
DeviceTicket m_TP = new DeviceTicket(this, AppConfig.getInstance());
if (sresource == null) {
m_TP.getDeviceDisplay().writeVisor(AppLocal.APP_NAME, AppLocal.APP_VERSION);
} else {
try {
m_TTP.printTicket(sresource);
} catch (TicketPrinterException eTP) { |
<<<<<<<
GenericController<T, ID> {
protected S service;
@PersistenceContext
private EntityManager em;
public GenericControllerImpl() {
}
public void setService(S service) {
this.service = service;
}
public S getService() {
return this.service;
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#create(T)
*/
@Override
@POST
public T create(T entity) {
return this.service.create(entity);
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#update(ID, T)
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
@PUT
@Path("/{id}")
public T update(@PathParam("id") ID id, T entity) {
Assert.notNull(id, "id cannot be null");
T retreivedEntity = this.service.findById(id);
if (retreivedEntity == null) {
throw new NotFoundException();
}
MetamodelUtils utils = new MetamodelUtils<T, ID>((Class<T>) ClassUtils.getGenericTypeFromBean(this.service),
em.getMetamodel());
Serializable entityId = utils.getIdFromEntity(entity);
if ((entityId != null) && !id.equals(this.getIdFromEntity(retreivedEntity))) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
if (null == entityId) {
utils.setIdForEntity(entity, id);
}
return this.service.update(entity);
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#getEntities()
*/
@Override
@GET
@Path("/all")
public List<T> findAll() {
return this.service.findAll();
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#findAll(java.lang.Integer, java.lang.Integer)
*/
@Override
@GET
public PageResponse<T> findAll(@QueryParam("page") @DefaultValue("0") Integer page,
@QueryParam("size") @DefaultValue("5") Integer size) {
return new PageResponse<T>(this.service.findAll(new PageRequest(page, size)));
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#getResource(ID)
*/
@Override
@GET
@Path("/{id}")
public T findById(@PathParam("id") ID id) {
T entity = this.service.findById(id);
if (entity == null) {
throw new NotFoundException();
}
return entity;
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#delete()
*/
@Override
@DELETE
@Path("/all")
public void delete() {
this.service.deleteAllWithCascade();
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#delete(ID)
*/
@Override
@DELETE
@Path("/{id}")
public void delete(@PathParam("id") ID id) {
this.service.delete(id);
}
/**
* Automatically retrieve ID from entity instance.
*
* @param obj
* The object from whom we need primary key
* @return The corresponding primary key.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected ID getIdFromEntity(T obj) {
MetamodelUtils utils = new MetamodelUtils<T, ID>((Class<T>) ClassUtils.getGenericTypeFromBean(this.service),
em.getMetamodel());
return (ID) utils.getIdFromEntity(obj);
}
=======
GenericController<T, ID> {
protected S service;
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
public GenericControllerImpl() {
}
public void setService(S service) {
this.service = service;
}
public S getService() {
return this.service;
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#create(T)
*/
@Override
@POST
public T create(T entity) {
return this.service.create(entity);
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#update(ID, T)
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
@PUT
@Path("/{id}")
public T update(@PathParam("id") ID id, T entity) {
Assert.notNull(id, "id cannot be null");
T retreivedEntity = this.service.findById(id);
if (retreivedEntity == null) {
throw new NotFoundException();
}
MetamodelUtils utils = new MetamodelUtils<T, ID>((Class<T>) ClassUtils.getGenericTypeFromBean(this.service),
em.getMetamodel());
Serializable entityId = utils.getIdFromEntity(entity);
if ((entityId != null) && !id.equals(this.getIdFromEntity(retreivedEntity))) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
if (null == entityId) {
utils.setIdForEntity(entity, id);
}
return this.service.update(entity);
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#getEntities()
*/
@Override
@GET
@Path("/all")
public List<T> findAll() {
return this.service.findAll();
}
/*
* (non-Javadoc)
*
* @see
* org.resthub.web.controller.GenericController#getEntities(java.lang.Integer
* , java.lang.Integer)
*/
@Override
@GET
public PageResponse<T> findAll(@QueryParam("page") @DefaultValue("0") Integer page,
@QueryParam("size") @DefaultValue("5") Integer size) {
return new PageResponse<T>(this.service.findAll(new PageRequest(page, size)));
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#getResource(ID)
*/
@Override
@GET
@Path("/{id}")
public T findById(@PathParam("id") ID id) {
T entity = this.service.findById(id);
if (entity == null) {
throw new NotFoundException();
}
return entity;
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#delete()
*/
@Override
@DELETE
@Path("/all")
public void delete() {
this.service.deleteAllWithCascade();
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#delete(ID)
*/
@Override
@DELETE
@Path("/{id}")
public void delete(@PathParam("id") ID id) {
this.service.delete(id);
}
/**
* Automatically retrieve ID from entity instance.
*
* @param obj
* The object from whom we need primary key
* @return The corresponding primary key.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected ID getIdFromEntity(T obj) {
MetamodelUtils utils = new MetamodelUtils<T, ID>((Class<T>) ClassUtils.getGenericTypeFromBean(this.service),
em.getMetamodel());
return (ID) utils.getIdFromEntity(obj);
}
>>>>>>>
GenericController<T, ID> {
protected S service;
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
public GenericControllerImpl() {
}
public void setService(S service) {
this.service = service;
}
public S getService() {
return this.service;
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#create(T)
*/
@Override
@POST
public T create(T entity) {
return this.service.create(entity);
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#update(ID, T)
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
@PUT
@Path("/{id}")
public T update(@PathParam("id") ID id, T entity) {
Assert.notNull(id, "id cannot be null");
T retreivedEntity = this.service.findById(id);
if (retreivedEntity == null) {
throw new NotFoundException();
}
MetamodelUtils utils = new MetamodelUtils<T, ID>((Class<T>) ClassUtils.getGenericTypeFromBean(this.service),
em.getMetamodel());
Serializable entityId = utils.getIdFromEntity(entity);
if ((entityId != null) && !id.equals(this.getIdFromEntity(retreivedEntity))) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
if (null == entityId) {
utils.setIdForEntity(entity, id);
}
return this.service.update(entity);
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#getEntities()
*/
@Override
@GET
@Path("/all")
public List<T> findAll() {
return this.service.findAll();
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#findAll(java.lang.Integer, java.lang.Integer)
*/
@Override
@GET
public PageResponse<T> findAll(@QueryParam("page") @DefaultValue("0") Integer page,
@QueryParam("size") @DefaultValue("5") Integer size) {
return new PageResponse<T>(this.service.findAll(new PageRequest(page, size)));
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#getResource(ID)
*/
@Override
@GET
@Path("/{id}")
public T findById(@PathParam("id") ID id) {
T entity = this.service.findById(id);
if (entity == null) {
throw new NotFoundException();
}
return entity;
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#delete()
*/
@Override
@DELETE
@Path("/all")
public void delete() {
this.service.deleteAllWithCascade();
}
/*
* (non-Javadoc)
*
* @see org.resthub.web.controller.GenericController#delete(ID)
*/
@Override
@DELETE
@Path("/{id}")
public void delete(@PathParam("id") ID id) {
this.service.delete(id);
}
/**
* Automatically retrieve ID from entity instance.
*
* @param obj
* The object from whom we need primary key
* @return The corresponding primary key.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected ID getIdFromEntity(T obj) {
MetamodelUtils utils = new MetamodelUtils<T, ID>((Class<T>) ClassUtils.getGenericTypeFromBean(this.service),
em.getMetamodel());
return (ID) utils.getIdFromEntity(obj);
} |
<<<<<<<
/**
* Kind of changes notified by this service
*/
enum GroupServiceChange {
/**
* Group creation. Arguments :
* 1- created group.
*/
GROUP_CREATION,
/**
* Group deletion. Arguments :
* 1- deleted group.
*/
GROUP_DELETION,
/**
* Group addition to a group. Arguments :
* 1- added group.
* 2- concerned parent group.
*/
GROUP_ADDED_TO_GROUP,
/**
* Group removal from a group. Arguments :
* 1- removed group.
* 2- concerned parent group.
*/
GROUP_REMOVED_FROM_GROUP
};
/**
* Finds group by name.
* @param name
* the group's Name
* @return the group or null if no group with this name is found
*/
public Group findByName( String name );
=======
/**
* Finds group by name.
* @param name
* the group's Name
* @return the group or null if no group with this name is found
*/
public Group findByName(String name);
>>>>>>>
/**
* Kind of changes notified by this service
*/
enum GroupServiceChange {
/**
* Group creation. Arguments :
* 1- created group.
*/
GROUP_CREATION,
/**
* Group deletion. Arguments :
* 1- deleted group.
*/
GROUP_DELETION,
/**
* Group addition to a group. Arguments :
* 1- added group.
* 2- concerned parent group.
*/
GROUP_ADDED_TO_GROUP,
/**
* Group removal from a group. Arguments :
* 1- removed group.
* 2- concerned parent group.
*/
GROUP_REMOVED_FROM_GROUP
};
/**
* Finds group by name.
* @param name
* the group's Name
* @return the group or null if no group with this name is found
*/
public Group findByName(String name); |
<<<<<<<
Race race = (Race) getDesc().get(FilterArg.RACE);
if (race != null && race != card.getAttribute(Attribute.RACE)) {
=======
Race race = (Race) desc.get(FilterArg.RACE);
if (race != null && !card.getRace().hasRace(race)) {
>>>>>>>
Race race = (Race) getDesc().get(FilterArg.RACE);
if (race != null && !card.getRace().hasRace(race)) { |
<<<<<<<
runGym(((context, player, opponent) -> {
context.setDeckFormat(new FixedCardsDeckFormat("minion_legendary_test"));
=======
runGym((context, player, opponent) -> {
>>>>>>>
runGym((context, player, opponent) -> {
context.setDeckFormat(new FixedCardsDeckFormat("minion_legendary_test"));
<<<<<<<
runGym(((context, player, opponent) -> {
context.setDeckFormat(new FixedCardsDeckFormat("minion_legendary_test"));
=======
runGym((context, player, opponent) -> {
>>>>>>>
runGym((context, player, opponent) -> {
context.setDeckFormat(new FixedCardsDeckFormat("minion_legendary_test"));
<<<<<<<
runGym(((context, player, opponent) -> {
context.setDeckFormat(new FixedCardsDeckFormat("minion_legendary_test"));
=======
runGym((context, player, opponent) -> {
>>>>>>>
runGym((context, player, opponent) -> {
context.setDeckFormat(new FixedCardsDeckFormat("minion_legendary_test")); |
<<<<<<<
public void testSpellbender() {
runGym((context, player, opponent) -> {
playCard(context, player, "secret_spellbender");
context.endTurn();
playCardWithTarget(context, opponent, "spell_fireball", player.getHero());
Assert.assertEquals(player.getSecrets().size(), 1);
});
runGym((context, player, opponent) -> {
playCard(context, player, "secret_spellbender");
Minion bloodfen = playMinionCard(context, player, "minion_bloodfen_raptor");
context.endTurn();
playCardWithTarget(context, opponent, "spell_fireball", bloodfen);
Assert.assertEquals(player.getSecrets().size(), 0);
Assert.assertEquals(player.getMinions().size(), 1);
Assert.assertFalse(bloodfen.isDestroyed());
Assert.assertTrue(player.getGraveyard().stream().anyMatch(e -> e.getSourceCard().getCardId().equals("token_spellbender")));
});
}
@Test
public void testYsera() {
runGym((context, player, opponent) -> {
playCard(context, player, "minion_ysera");
overrideRandomCard(context, "spell_dream");
context.endTurn();
Assert.assertEquals(player.getHand().get(0).getCardId(), "spell_dream");
Assert.assertEquals(player.getHand().size(), 1);
});
runGym((context, player, opponent) -> {
playCard(context, player, "minion_ysera");
Stream<String> yseraCards = Arrays.stream((String[]) ((MinionCardDesc) CardCatalogue.getRecords().get("minion_ysera")
.getDesc()).trigger.spell.get(SpellArg.CARDS));
context.endTurn();
Assert.assertTrue(yseraCards.anyMatch(c -> c.equals(player.getHand().get(0).getCardId())));
Assert.assertEquals(player.getHand().size(), 1);
});
}
@Test
=======
public void testAIWillNeverPlayCursed() {
runGym((context, player, opponent) -> {
context.endTurn();
opponent.setMana(2);
opponent.setMaxMana(2);
receiveCard(context, opponent, "spell_cursed");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.SPELL);
});
runGym((context, player, opponent) -> {
context.endTurn();
opponent.setMana(4);
opponent.setMaxMana(4);
Card cursed = receiveCard(context, opponent, "spell_cursed");
receiveCard(context, opponent, "spell_fireball");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
context.getLogic().performGameAction(opponent.getId(), action);
action = behaviour.requestAction(context, opponent, context.getValidActions());
context.getLogic().performGameAction(opponent.getId(), action);
Assert.assertFalse(opponent.getHand().contains(cursed));
});
}
@Test
public void testAIWillPlayIntoDoomsayer() {
runGym((context, player, opponent) -> {
playCard(context, player, "minion_doomsayer");
context.endTurn();
receiveCard(context, opponent, "minion_snowflipper_penguin");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.END_TURN);
});
runGym((context, player, opponent) -> {
Minion doomsayer = playMinionCard(context, player, "minion_doomsayer");
context.endTurn();
for (int i = 0; i < 3; i++) {
playMinionCard(context, opponent, "minion_wolfrider");
}
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.PHYSICAL_ATTACK);
Assert.assertEquals(action.getTargetReference(), doomsayer.getReference());
});
runGym((context, player, opponent) -> {
Minion doomsayer = playMinionCard(context, player, "minion_doomsayer");
context.endTurn();
playMinionCard(context, opponent, "minion_kobold_geomancer");
receiveCard(context, opponent, "spell_fireball");
opponent.setMaxMana(4);
opponent.setMana(4);
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.SPELL);
Assert.assertEquals(action.getTargetReference(), doomsayer.getReference());
});
}
@Test
public void testAIWillPlayIntoSnakeTrap() {
runGym((context, player, opponent) -> {
playCard(context, player, "secret_snake_trap");
Minion targetDummy = playMinionCard(context, player, "minion_target_dummy");
context.endTurn();
Minion wolfrider = playMinionCard(context, opponent, "minion_wolfrider");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.PHYSICAL_ATTACK);
Assert.assertEquals(action.getTargetReference(), targetDummy.getReference());
Assert.assertEquals(action.getSourceReference(), wolfrider.getReference());
});
}
@Test
>>>>>>>
public void testSpellbender() {
runGym((context, player, opponent) -> {
playCard(context, player, "secret_spellbender");
context.endTurn();
playCardWithTarget(context, opponent, "spell_fireball", player.getHero());
Assert.assertEquals(player.getSecrets().size(), 1);
});
runGym((context, player, opponent) -> {
playCard(context, player, "secret_spellbender");
Minion bloodfen = playMinionCard(context, player, "minion_bloodfen_raptor");
context.endTurn();
playCardWithTarget(context, opponent, "spell_fireball", bloodfen);
Assert.assertEquals(player.getSecrets().size(), 0);
Assert.assertEquals(player.getMinions().size(), 1);
Assert.assertFalse(bloodfen.isDestroyed());
Assert.assertTrue(player.getGraveyard().stream().anyMatch(e -> e.getSourceCard().getCardId().equals("token_spellbender")));
});
}
@Test
public void testYsera() {
runGym((context, player, opponent) -> {
playCard(context, player, "minion_ysera");
overrideRandomCard(context, "spell_dream");
context.endTurn();
Assert.assertEquals(player.getHand().get(0).getCardId(), "spell_dream");
Assert.assertEquals(player.getHand().size(), 1);
});
runGym((context, player, opponent) -> {
playCard(context, player, "minion_ysera");
Stream<String> yseraCards = Arrays.stream((String[]) ((MinionCardDesc) CardCatalogue.getRecords().get("minion_ysera")
.getDesc()).trigger.spell.get(SpellArg.CARDS));
context.endTurn();
Assert.assertTrue(yseraCards.anyMatch(c -> c.equals(player.getHand().get(0).getCardId())));
Assert.assertEquals(player.getHand().size(), 1);
});
}
@Test
public void testAIWillNeverPlayCursed() {
runGym((context, player, opponent) -> {
context.endTurn();
opponent.setMana(2);
opponent.setMaxMana(2);
receiveCard(context, opponent, "spell_cursed");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.SPELL);
});
runGym((context, player, opponent) -> {
context.endTurn();
opponent.setMana(4);
opponent.setMaxMana(4);
Card cursed = receiveCard(context, opponent, "spell_cursed");
receiveCard(context, opponent, "spell_fireball");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
context.getLogic().performGameAction(opponent.getId(), action);
action = behaviour.requestAction(context, opponent, context.getValidActions());
context.getLogic().performGameAction(opponent.getId(), action);
Assert.assertFalse(opponent.getHand().contains(cursed));
});
}
@Test
public void testAIWillPlayIntoDoomsayer() {
runGym((context, player, opponent) -> {
playCard(context, player, "minion_doomsayer");
context.endTurn();
receiveCard(context, opponent, "minion_snowflipper_penguin");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.END_TURN);
});
runGym((context, player, opponent) -> {
Minion doomsayer = playMinionCard(context, player, "minion_doomsayer");
context.endTurn();
for (int i = 0; i < 3; i++) {
playMinionCard(context, opponent, "minion_wolfrider");
}
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.PHYSICAL_ATTACK);
Assert.assertEquals(action.getTargetReference(), doomsayer.getReference());
});
runGym((context, player, opponent) -> {
Minion doomsayer = playMinionCard(context, player, "minion_doomsayer");
context.endTurn();
playMinionCard(context, opponent, "minion_kobold_geomancer");
receiveCard(context, opponent, "spell_fireball");
opponent.setMaxMana(4);
opponent.setMana(4);
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.SPELL);
Assert.assertEquals(action.getTargetReference(), doomsayer.getReference());
});
}
@Test
public void testAIWillPlayIntoSnakeTrap() {
runGym((context, player, opponent) -> {
playCard(context, player, "secret_snake_trap");
Minion targetDummy = playMinionCard(context, player, "minion_target_dummy");
context.endTurn();
Minion wolfrider = playMinionCard(context, opponent, "minion_wolfrider");
GameStateValueBehaviour behaviour = new GameStateValueBehaviour();
GameAction action = behaviour.requestAction(context, opponent, context.getValidActions());
Assert.assertEquals(action.getActionType(), ActionType.PHYSICAL_ATTACK);
Assert.assertEquals(action.getTargetReference(), targetDummy.getReference());
Assert.assertEquals(action.getSourceReference(), wolfrider.getReference());
});
}
@Test |
<<<<<<<
* @see #replayContext(boolean, Optional<Consumer<GameContext>>) to replay a context after loading it from a string.
* Provide {@code skipLastAction: true} as the argument if the last action throws an exception (useful for debugging).
* Provide {@code recorder} is useful if you'd like to process each {@link GameContext} (useful for recording
* replays).
=======
* @see #replayContext(boolean, Optional<Consumer<GameContext>>) to replay a context after loading it from a string.
* Provide {@code skipLastAction: true} as the argument if the last action throws an exception (useful for
* debugging). Provide {@code recorder} is useful if you'd like to process each {@link GameContext} (useful for
* recording replays).
>>>>>>>
* @see #replayContext(boolean, Optional<Consumer<GameContext>>) to replay a context after loading it from a string.
* Provide {@code skipLastAction: true} as the argument if the last action throws an exception (useful for debugging).
* Provide {@code recorder} is useful if you'd like to process each {@link GameContext} (useful for recording
* replays).
<<<<<<<
public GameContext replayContext() {
return replayContext(false, null);
}
public GameContext replayContext(boolean skipLastAction) {
return replayContext(skipLastAction, null);
}
/**
* Creates a game context and replays it using data from this trace. A {@link Consumer} can be optionally specified
* that receives the game context before every action taken by either player.
*
* @param skipLastAction
* @param beforeRequestActionHandler
* @return
*/
public GameContext replayContext(boolean skipLastAction, @Nullable Consumer<GameContext> beforeRequestActionHandler) {
=======
public GameContext replayContext(boolean skipLastAction, Optional<Consumer<GameContext>> recorder) {
>>>>>>>
public GameContext replayContext() {
return replayContext(false, null);
}
public GameContext replayContext(boolean skipLastAction) {
return replayContext(skipLastAction, null);
}
/**
* Creates a game context and replays it using data from this trace. A {@link Consumer} can be optionally specified
* that receives the game context before every action taken by either player.
*
* @param skipLastAction
* @param beforeRequestActionHandler
* @return
*/
public GameContext replayContext(boolean skipLastAction, @Nullable Consumer<GameContext> beforeRequestActionHandler) {
<<<<<<<
int[][] mulligans1 = new int[2][];
int[][] mulligans2 = new int[2][];
mulligans1[0] = Arrays.copyOf(mulligans[0], mulligans[0].length);
mulligans1[1] = Arrays.copyOf(mulligans[1], mulligans[1].length);
mulligans2[0] = Arrays.copyOf(mulligans[0], mulligans[0].length);
mulligans2[1] = Arrays.copyOf(mulligans[1], mulligans[1].length);
stateRestored.setBehaviour(
0, new TraceBehaviour(0, mulligans1, nextAction, behaviourActions, beforeRequestActionHandler));
stateRestored.setBehaviour(
1, new TraceBehaviour(1, mulligans2, nextAction, behaviourActions, beforeRequestActionHandler));
=======
stateRestored.setBehaviour(
0, new TraceBehaviour(0, mulligans, nextAction, behaviourActions, recorder));
stateRestored.setBehaviour(
1, new TraceBehaviour(1, mulligans, nextAction, behaviourActions, recorder));
>>>>>>>
stateRestored.setBehaviour(
0, new TraceBehaviour(0, mulligans, nextAction, behaviourActions, beforeRequestActionHandler));
stateRestored.setBehaviour(
1, new TraceBehaviour(1, mulligans, nextAction, behaviourActions, beforeRequestActionHandler)); |
<<<<<<<
import net.demilich.metastone.game.spells.desc.filter.ComparisonOperation;
=======
import net.demilich.metastone.game.entities.minions.BoardPositionRelative;
>>>>>>>
import net.demilich.metastone.game.spells.desc.filter.ComparisonOperation;
import net.demilich.metastone.game.entities.minions.BoardPositionRelative; |
<<<<<<<
.add(new MigrationRequest()
.withVersion(31)
.withUp(thisVertex -> {
changeCardId("minion_student_of_the_tiger", "minion_lungrath_hunter");
changeCardId("hero_chen_stormstout", "hero_mienzhou");
changeCardId("hero_power_meditation", "hero_power_effuse");
changeCardId("minion_blessed_koi_statue", "minion_jade_serpent_statue");
changeCardId("minion_skunky_brew_alemental", "minion_deepwoods_elemental");
changeCardId("minion_crane_school_instructor", "minion_desciple_of_shitakiri");
changeCardId("minion_black_ox_statue", "minion_enchanted_tapestry");
changeCardId("minion_emperor_shaohao", "minion_master_jigen");
changeCardId("minion_monastery_guard", "minion_monastery_warden");
changeCardId("minion_windwalk_master", "minion_shigaraki_elder");
changeCardId("minion_elusive_brawler", "minion_sly_brawler");
changeCardId("spell_leg_sweep", "spell_axe_kick");
changeCardId("spell_chi_torpedo", "spell_chi_restoration");
changeCardId("spell_gift_of_the_mists", "spell_enlightenment");
changeCardId("spell_flying_serpent_kick", "spell_fiery_kitsune_punch");
changeCardId("spell_fortifying_brew", "spell_fortifying_prayer");
changeCardId("spell_storm_earth_and_fire", "spell_fury_of_the_elements");
changeCardId("spell_staggering_brew", "spell_honed_potion");
changeCardId("spell_keg_smash", "spell_mark_of_despair");
changeCardId("spell_tiger_palm_strike", "spell_palm_strike");
changeCardId("spell_effuse", "spell_springs_of_ebisu");
changeCardId("spell_dampen_harm", "spell_steadfast_defense");
changeCardId("spell_breath_of_fire", "spell_windswept_strike");
changeCardId("spell_storm_spirit", "spell_bellowing_spirit");
changeCardId("spell_fire_spirit", "spell_burning_spirit");
changeCardId("token_xuen_the_white_tiger", "token_kumiho_nine_tailed_kitsune");
changeCardId("token_chi_ji_the_red_crane", "token_shitakiri_slit_tongue_suzume");
changeCardId("token_tiny_alemental", "token_stony_elemental");
changeCardId("token_earth_spirit", "token_unearthed_spirit");
changeCardId("token_niuzao_the_black_ox", "token_yashima_cheerful_tanuki");
}))
.migrateTo(31, then2 ->
=======
.add(new MigrationRequest()
.withVersion(31)
.withUp(thisVertx -> {
// Rerun the earlier changes since something definitely glitched out
changeCardId("minion_anub'rekhan", "minion_anobii");
changeCardId("minion_azjol_visionary", "minion_visionary");
changeCardId("minion_nerubian_vizier", "minion_vizier");
changeCardId("weapon_maexxnas_femur", "weapon_scepter_of_bees");
changeCardId("minion_qiraji_guardian", "minion_grand_guardian");
changeCardId("minion_prophet_skeram", "minion_vermancer_prophet");
changeCardId("minion_silithid_wasp", "minion_servant_wasp");
changeCardId("spell_elementium_shell", "spell_reinforced_shell");
changeCardId("spell_ahnqiraj_portal", "spell_ancient_waygate");
}))
.migrateTo(31, then2 ->
>>>>>>>
.add(new MigrationRequest()
.withVersion(31)
.withUp(thisVertex -> {
changeCardId("minion_student_of_the_tiger", "minion_lungrath_hunter");
changeCardId("hero_chen_stormstout", "hero_mienzhou");
changeCardId("hero_power_meditation", "hero_power_effuse");
changeCardId("minion_blessed_koi_statue", "minion_jade_serpent_statue");
changeCardId("minion_skunky_brew_alemental", "minion_deepwoods_elemental");
changeCardId("minion_crane_school_instructor", "minion_desciple_of_shitakiri");
changeCardId("minion_black_ox_statue", "minion_enchanted_tapestry");
changeCardId("minion_emperor_shaohao", "minion_master_jigen");
changeCardId("minion_monastery_guard", "minion_monastery_warden");
changeCardId("minion_windwalk_master", "minion_shigaraki_elder");
changeCardId("minion_elusive_brawler", "minion_sly_brawler");
changeCardId("spell_leg_sweep", "spell_axe_kick");
changeCardId("spell_chi_torpedo", "spell_chi_restoration");
changeCardId("spell_gift_of_the_mists", "spell_enlightenment");
changeCardId("spell_flying_serpent_kick", "spell_fiery_kitsune_punch");
changeCardId("spell_fortifying_brew", "spell_fortifying_prayer");
changeCardId("spell_storm_earth_and_fire", "spell_fury_of_the_elements");
changeCardId("spell_staggering_brew", "spell_honed_potion");
changeCardId("spell_keg_smash", "spell_mark_of_despair");
changeCardId("spell_tiger_palm_strike", "spell_palm_strike");
changeCardId("spell_effuse", "spell_springs_of_ebisu");
changeCardId("spell_dampen_harm", "spell_steadfast_defense");
changeCardId("spell_breath_of_fire", "spell_windswept_strike");
changeCardId("spell_storm_spirit", "spell_bellowing_spirit");
changeCardId("spell_fire_spirit", "spell_burning_spirit");
changeCardId("token_xuen_the_white_tiger", "token_kumiho_nine_tailed_kitsune");
changeCardId("token_chi_ji_the_red_crane", "token_shitakiri_slit_tongue_suzume");
changeCardId("token_tiny_alemental", "token_stony_elemental");
changeCardId("token_earth_spirit", "token_unearthed_spirit");
changeCardId("token_niuzao_the_black_ox", "token_yashima_cheerful_tanuki");
// Rerun the earlier changes since something definitely glitched out
changeCardId("minion_anub'rekhan", "minion_anobii");
changeCardId("minion_azjol_visionary", "minion_visionary");
changeCardId("minion_nerubian_vizier", "minion_vizier");
changeCardId("weapon_maexxnas_femur", "weapon_scepter_of_bees");
changeCardId("minion_qiraji_guardian", "minion_grand_guardian");
changeCardId("minion_prophet_skeram", "minion_vermancer_prophet");
changeCardId("minion_silithid_wasp", "minion_servant_wasp");
changeCardId("spell_elementium_shell", "spell_reinforced_shell");
changeCardId("spell_ahnqiraj_portal", "spell_ancient_waygate");
}))
.migrateTo(31, then2 -> |
<<<<<<<
@Suspendable
public void equipWeapon(int playerId, Weapon weapon, boolean resolveBattlecry) {
PreEquipWeapon preEquipWeapon = new PreEquipWeapon(playerId, weapon).invoke();
Weapon currentWeapon = preEquipWeapon.getCurrentWeapon();
Player player = preEquipWeapon.getPlayer();
=======
public void equipWeapon(int playerId, Weapon weapon) {
equipWeapon(playerId, weapon, false);
}
public void equipWeapon(int playerId, Weapon weapon, boolean battlecry) {
Player player = context.getPlayer(playerId);
>>>>>>>
public void equipWeapon(int playerId, Weapon weapon) {
equipWeapon(playerId, weapon, false);
}
@Suspendable
public void equipWeapon(int playerId, Weapon weapon, boolean resolveBattlecry) {
PreEquipWeapon preEquipWeapon = new PreEquipWeapon(playerId, weapon).invoke();
Weapon currentWeapon = preEquipWeapon.getCurrentWeapon();
Player player = preEquipWeapon.getPlayer();
<<<<<<<
protected void postEquipWeapon(int playerId, Weapon newWeapon, Weapon currentWeapon, Player player) {
=======
if (battlecry && weapon.getBattlecry() != null) {
resolveBattlecry(playerId, weapon);
}
>>>>>>>
protected void postEquipWeapon(int playerId, Weapon newWeapon, Weapon currentWeapon, Player player) {
<<<<<<<
player.getStatistics().equipWeapon(newWeapon);
newWeapon.onEquip(context, player);
newWeapon.setActive(context.getActivePlayerId() == playerId);
if (newWeapon.hasSpellTrigger()) {
SpellTrigger spellTrigger = newWeapon.getSpellTrigger();
addGameEventListener(player, spellTrigger, newWeapon);
=======
player.getStatistics().equipWeapon(weapon);
weapon.onEquip(context, player);
weapon.setActive(context.getActivePlayerId() == playerId);
if (weapon.hasSpellTrigger()) {
for (SpellTrigger spellTrigger : weapon.getSpellTriggers()) {
addGameEventListener(player, spellTrigger, weapon);
}
>>>>>>>
player.getStatistics().equipWeapon(newWeapon);
newWeapon.onEquip(context, player);
newWeapon.setActive(context.getActivePlayerId() == playerId);
if (newWeapon.hasSpellTrigger()) {
List<SpellTrigger> spellTriggers = newWeapon.getSpellTriggers();
spellTriggers.forEach(s -> {
addGameEventListener(player, s, newWeapon);
});
<<<<<<<
GameAction targetedBattlecry = player.getBehaviour().requestAction(context, player, battlecryActions);
performBattlecryAction(playerId, actor, player, targetedBattlecry);
=======
if (attributeExists(Attribute.ALL_RANDOM_FINAL_DESTINATION)) {
battlecryAction = battlecryActions.get(random(battlecryActions.size()));
} else {
battlecryAction = player.getBehaviour().requestAction(context, player, battlecryActions);
}
>>>>>>>
GameAction targetedBattlecry = player.getBehaviour().requestAction(context, player, battlecryActions);
performBattlecryAction(playerId, actor, player, targetedBattlecry); |
<<<<<<<
=======
public static void loadCardsFromPackage() throws IOException, URISyntaxException, CardParseException {
synchronized (cards) {
if (cards.getCount() == 0) {
Collection<ResourceInputStream> inputStreams = ResourceLoader.loadJsonInputStreams(CARDS_FOLDER, false);
loadCards(inputStreams);
}
}
}
public static void loadCardsFromFilesystem() throws IOException, URISyntaxException, CardParseException {
// load cards from ~/metastone/cards on the file system
Collection<ResourceInputStream> inputStreams = ResourceLoader.loadJsonInputStreams(CARDS_FOLDER_PATH, true);
loadCards(inputStreams);
}
private static void loadCards(Collection<ResourceInputStream> inputStreams) throws IOException, URISyntaxException, CardParseException {
Map<String, CardDesc> cardDesc = new HashMap<String, CardDesc>();
ArrayList<String> badCards = new ArrayList<>();
CardParser cardParser = new CardParser();
for (ResourceInputStream resourceInputStream : inputStreams) {
try {
CardDesc desc = cardParser.parseCard(resourceInputStream);
if (cardDesc.containsKey(desc.id)) {
logger.error("Card id {} is duplicated!", desc.id);
}
cardDesc.put(desc.id, desc);
} catch (Exception e) {
//logger.error("Error parsing card '{}'", resourceInputStream.fileName);
System.out.println(e.toString());
logger.error(e.toString());
badCards.add(resourceInputStream.fileName);
}
}
for (CardDesc desc : cardDesc.values()) {
Card instance = desc.createInstance();
CardCatalogue.add(instance);
logger.debug("Adding {} to CardCatalogue", instance);
}
if (!badCards.isEmpty()) {
throw new CardParseException(badCards);
}
}
>>>>>>> |
<<<<<<<
public float getTypeMatch(IType type)
{
if (this.field == null)
{
return 0;
}
IType type1 = this.getType();
if (type.equals(type1))
{
return 3;
}
if (type.isSuperTypeOf(type1))
{
return 2;
}
return 0;
}
@Override
public IReference toReference()
{
if (this.field.isField())
{
if (this.field.hasModifier(Modifiers.STATIC))
{
return new StaticFieldReference((IField) this.field);
}
}
return null;
}
@Override
=======
public float getTypeMatch(IType type)
{
if (this.field == null)
{
return 0;
}
return type.getSubTypeDistance(this.getType());
}
@Override
>>>>>>>
public float getTypeMatch(IType type)
{
if (this.field == null)
{
return 0;
}
return type.getSubTypeDistance(this.getType());
}
@Override
public IReference toReference()
{
if (this.field.isField())
{
if (this.field.hasModifier(Modifiers.STATIC))
{
return new StaticFieldReference((IField) this.field);
}
}
return null;
}
@Override |
<<<<<<<
import com.hiddenswitch.proto3.net.models.CreateGameSessionRequest;
import com.hiddenswitch.proto3.net.models.CurrentMatchRequest;
import com.hiddenswitch.proto3.net.util.RPC;
=======
import com.hiddenswitch.proto3.net.client.models.CreateAccountRequest;
import com.hiddenswitch.proto3.net.client.models.CreateAccountResponse;
import com.hiddenswitch.proto3.net.models.*;
>>>>>>>
import com.hiddenswitch.proto3.net.models.CreateGameSessionRequest;
import com.hiddenswitch.proto3.net.models.CurrentMatchRequest;
import com.hiddenswitch.proto3.net.models.DeckCreateRequest;
import com.hiddenswitch.proto3.net.models.DeckCreateResponse;
import com.hiddenswitch.proto3.net.util.RPC;
<<<<<<<
import net.demilich.metastone.game.events.GameEventType;
import net.demilich.metastone.game.targeting.EntityReference;
=======
import net.demilich.metastone.game.entities.heroes.HeroClass;
>>>>>>>
import net.demilich.metastone.game.entities.heroes.HeroClass;
import net.demilich.metastone.game.events.GameEventType;
import net.demilich.metastone.game.targeting.EntityReference;
<<<<<<<
@Test
public void testMinionatePersistenceApi(TestContext context) {
setLoggingLevel(Level.ERROR);
wrap(context);
ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<Long>();
// Use all random yogg as a test attribute
vertx.runOnContext(ignored -> {
Minionate.minionate().persistAttribute("yogg-only-1", GameEventType.TURN_END, Attribute.ALL_RANDOM_YOGG_ONLY_FINAL_DESTINATION, persistenceContext -> {
// Save the turn number to this yogg attribute
long updated = persistenceContext.update(EntityReference.ALL_MINIONS, persistenceContext.event().getGameContext().getTurn());
queue.add(updated);
});
});
// Start a game and assert that there are entities with all random yogg
vertx.executeBlocking(done -> {
UnityClient client = new UnityClient(context);
client.createUserAccount();
client.matchmakeAndPlayAgainstAI();
client.waitUntilDone();
getContext().assertTrue(client.isGameOver());
done.complete();
}, context.asyncAssertSuccess(also -> {
context.assertTrue(queue.stream().anyMatch(l -> l > 0L), "Any number of the entities updated was greater than zero.");
service.inventory.getMongo().count(Inventory.INVENTORY,
json("facts." + Attribute.ALL_RANDOM_YOGG_ONLY_FINAL_DESTINATION.toKeyCase(), json("$exists", true)),
context.asyncAssertSuccess(count -> {
context.assertTrue(count > 0L, "There is at least one inventory item that has the attribute that we configured to listen for.");
}));
}));
}
@Test
@Ignore
public void testTotalDamageDealt(TestContext context) {
}
=======
@Test
public void testWeaponActionReceived(TestContext context) {
setLoggingLevel(Level.ERROR);
wrap(context);
Async async = context.async();
vertx.runOnContext(ignored -> {
AtomicBoolean didGetPlayWeaponAction = new AtomicBoolean(false);
UnityClient client = new UnityClient(context) {
@Override
protected void assertValidActions(ServerToClientMessage message) {
super.assertValidActions(message);
if (message.getMessageType() == MessageType.ON_REQUEST_ACTION
&& message.getActions().getWeapons() != null
&& message.getActions().getWeapons().size() > 0) {
didGetPlayWeaponAction.set(true);
}
}
};
final String[] deckId = new String[1];
vertx.executeBlocking(done -> {
client.createUserAccount(null);
Fiber<Void> fiber = new Fiber<Void>(Sync.getContextScheduler(), () -> {
DeckCreateResponse res = service.decks.createDeck(new DeckCreateRequest()
.withUserId(client.getAccount().getId())
.withHeroClass(HeroClass.ROGUE)
.withName("Test Weapon Deck")
.withCardIds(Collections.nCopies(30, "weapon_clandestine_laser")));
deckId[0] = res.getDeckId();
}).start();
while (deckId[0] == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
done.handle(Future.succeededFuture());
}, true, context.asyncAssertSuccess(then -> {
vertx.executeBlocking(done2 -> {
client.matchmakeAndPlayAgainstAI(deckId[0]);
client.waitUntilDone();
getContext().assertTrue(client.isGameOver());
getContext().assertTrue(didGetPlayWeaponAction.get());
done2.handle(Future.succeededFuture());
}, true, context.asyncAssertSuccess(finallyy -> {
async.complete();
}));
}));
});
}
>>>>>>>
@Test
public void testMinionatePersistenceApi(TestContext context) {
setLoggingLevel(Level.ERROR);
wrap(context);
ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<Long>();
// Use all random yogg as a test attribute
vertx.runOnContext(ignored -> {
Minionate.minionate().persistAttribute("yogg-only-1", GameEventType.TURN_END, Attribute.ALL_RANDOM_YOGG_ONLY_FINAL_DESTINATION, persistenceContext -> {
// Save the turn number to this yogg attribute
long updated = persistenceContext.update(EntityReference.ALL_MINIONS, persistenceContext.event().getGameContext().getTurn());
queue.add(updated);
});
});
// Start a game and assert that there are entities with all random yogg
vertx.executeBlocking(done -> {
UnityClient client = new UnityClient(context);
client.createUserAccount();
client.matchmakeAndPlayAgainstAI();
client.waitUntilDone();
getContext().assertTrue(client.isGameOver());
done.complete();
}, context.asyncAssertSuccess(also -> {
context.assertTrue(queue.stream().anyMatch(l -> l > 0L), "Any number of the entities updated was greater than zero.");
service.inventory.getMongo().count(Inventory.INVENTORY,
json("facts." + Attribute.ALL_RANDOM_YOGG_ONLY_FINAL_DESTINATION.toKeyCase(), json("$exists", true)),
context.asyncAssertSuccess(count -> {
context.assertTrue(count > 0L, "There is at least one inventory item that has the attribute that we configured to listen for.");
}));
}));
}
@Test
public void testWeaponActionReceived(TestContext context) {
setLoggingLevel(Level.ERROR);
wrap(context);
Async async = context.async();
vertx.runOnContext(ignored -> {
AtomicBoolean didGetPlayWeaponAction = new AtomicBoolean(false);
UnityClient client = new UnityClient(context) {
@Override
protected void assertValidActions(ServerToClientMessage message) {
super.assertValidActions(message);
if (message.getMessageType() == MessageType.ON_REQUEST_ACTION
&& message.getActions().getWeapons() != null
&& message.getActions().getWeapons().size() > 0) {
didGetPlayWeaponAction.set(true);
}
}
};
final String[] deckId = new String[1];
vertx.executeBlocking(done -> {
client.createUserAccount(null);
Fiber<Void> fiber = new Fiber<Void>(Sync.getContextScheduler(), () -> {
DeckCreateResponse res = service.decks.createDeck(new DeckCreateRequest()
.withUserId(client.getAccount().getId())
.withHeroClass(HeroClass.ROGUE)
.withName("Test Weapon Deck")
.withCardIds(Collections.nCopies(30, "weapon_clandestine_laser")));
deckId[0] = res.getDeckId();
}).start();
while (deckId[0] == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
done.handle(Future.succeededFuture());
}, true, context.asyncAssertSuccess(then -> {
vertx.executeBlocking(done2 -> {
client.matchmakeAndPlayAgainstAI(deckId[0]);
client.waitUntilDone();
getContext().assertTrue(client.isGameOver());
getContext().assertTrue(didGetPlayWeaponAction.get());
done2.handle(Future.succeededFuture());
}, true, context.asyncAssertSuccess(finallyy -> {
async.complete();
}));
}));
});
} |
<<<<<<<
import java.util.Map;
import java.util.stream.Stream;
import co.paralleluniverse.fibers.Suspendable;
=======
import com.github.fromage.quasi.fibers.Suspendable;
>>>>>>>
import java.util.Map;
import java.util.stream.Stream;
import com.github.fromage.quasi.fibers.Suspendable; |
<<<<<<<
import java.util.concurrent.ConcurrentLinkedDeque;
=======
import java.util.concurrent.atomic.AtomicReference;
>>>>>>>
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference;
<<<<<<<
/**
* Generates a client-readable {@link Replay} object (for use with the client replay functionality).
*
* @param originalCtx The context for which to generate a replay.
* @return
*/
static Replay replayFromGameContext(GameContext originalCtx) {
Replay replay = new Replay();
Deque<GameStatePair> items = new ConcurrentLinkedDeque<>();
// Replay the game from a trace while capturing the {@link Replay} object.
GameContext replayCtx = originalCtx.getTrace().replayContext(
false,
(GameContext ctx) -> {
// We record each game state by dumping the {@link GameState} objects from each player's point of
// view into the replay.
try {
GameStatePair gameStatePair = new GameStatePair();
gameStatePair.first(getGameState(ctx, ctx.getPlayer1(), ctx.getPlayer2()));
gameStatePair.second(getGameState(ctx, ctx.getPlayer2(), ctx.getPlayer1()));
items.push(gameStatePair);
} catch (Throwable any) {
LOGGER.error("replayFromGameContext: {}", any);
}
}
);
// Append the final game state (from each player's point of view).
GameStatePair gameStatePair = new GameStatePair();
gameStatePair.first(getGameState(replayCtx, replayCtx.getPlayer1(), replayCtx.getPlayer2()));
gameStatePair.second(getGameState(replayCtx, replayCtx.getPlayer2(), replayCtx.getPlayer1()));
items.push(gameStatePair);
replay.setGameStates(new ArrayList<>(items));
return replay;
}
=======
/**
* Compute the {@link EntityChangeSet} between two {@link GameState}s.
*
* @param gameStateOld
* @param gameStateNew
* @return
*/
static EntityChangeSet computeChangeSet(
com.hiddenswitch.spellsource.common.GameState gameStateOld,
com.hiddenswitch.spellsource.common.GameState gameStateNew) {
final MapDifference<Integer, EntityLocation> difference = gameStateOld.to(gameStateNew);
EntityChangeSet changes = new EntityChangeSet();
difference.entriesDiffering().entrySet().stream().map(i -> new EntityChangeSetInner()
.id(i.getKey())
.op(EntityChangeSetInner.OpEnum.C)
.p1(new EntityState()
.location(Games.toClientLocation(i.getValue().rightValue())))
.p0(new EntityState()
.location(Games.toClientLocation(i.getValue().leftValue()))))
.forEach(changes::add);
difference.entriesOnlyOnRight().entrySet().stream().map(i -> new EntityChangeSetInner().id(i.getKey())
.op(EntityChangeSetInner.OpEnum.A)
.p1(new EntityState()
.location(Games.toClientLocation(i.getValue()))))
.forEach(changes::add);
difference.entriesOnlyOnLeft().entrySet().stream().map(i -> new EntityChangeSetInner().id(i.getKey())
.op(EntityChangeSetInner.OpEnum.R)
.p1(new EntityState()
.location(Games.toClientLocation(i.getValue()))))
.forEach(changes::add);
return changes;
}
/**
* Generates a client-readable {@link Replay} object (for use with the client replay functionality).
*
* @param originalCtx The context for which to generate a replay.
* @return
*/
static Replay replayFromGameContext(GameContext originalCtx) {
Replay replay = new Replay();
AtomicReference<com.hiddenswitch.spellsource.common.GameState> gameStateOld = new AtomicReference<>();
Consumer<GameContext> augmentReplayWithCtx = (GameContext ctx) -> {
// We record each game state by dumping the {@link GameState} objects from each player's point of
// view and any state transitions into the replay.
ReplayGameStates gameStates = new ReplayGameStates();
gameStates.first(getGameState(ctx, ctx.getPlayer1(), ctx.getPlayer2()));
gameStates.second(getGameState(ctx, ctx.getPlayer2(), ctx.getPlayer1()));
replay.addGameStatesItem(gameStates);
if (gameStateOld.get() != null) {
com.hiddenswitch.spellsource.common.GameState gameStateNew = ctx.getGameState();
ReplayDelta delta = new ReplayDelta();
delta.forward(computeChangeSet(gameStateOld.get(), gameStateNew));
delta.backward(computeChangeSet(gameStateNew, gameStateOld.get()));
replay.addDeltasItem(delta);
}
gameStateOld.set(ctx.getGameStateCopy());
};
// Replay the game from a trace while capturing the {@link Replay} object.
GameContext replayCtx = originalCtx.getTrace().replayContext(
false,
Optional.of(augmentReplayWithCtx)
);
// Append the final game states / deltas.
augmentReplayWithCtx.accept(replayCtx);
return replay;
}
>>>>>>>
/**
* Compute the {@link EntityChangeSet} between two {@link GameState}s.
*
* @param gameStateOld
* @param gameStateNew
* @return
*/
static EntityChangeSet computeChangeSet(
com.hiddenswitch.spellsource.common.GameState gameStateOld,
com.hiddenswitch.spellsource.common.GameState gameStateNew) {
final MapDifference<Integer, EntityLocation> difference = gameStateOld.to(gameStateNew);
EntityChangeSet changes = new EntityChangeSet();
difference.entriesDiffering().entrySet().stream().map(i -> new EntityChangeSetInner()
.id(i.getKey())
.op(EntityChangeSetInner.OpEnum.C)
.p1(new EntityState()
.location(Games.toClientLocation(i.getValue().rightValue())))
.p0(new EntityState()
.location(Games.toClientLocation(i.getValue().leftValue()))))
.forEach(changes::add);
difference.entriesOnlyOnRight().entrySet().stream().map(i -> new EntityChangeSetInner().id(i.getKey())
.op(EntityChangeSetInner.OpEnum.A)
.p1(new EntityState()
.location(Games.toClientLocation(i.getValue()))))
.forEach(changes::add);
difference.entriesOnlyOnLeft().entrySet().stream().map(i -> new EntityChangeSetInner().id(i.getKey())
.op(EntityChangeSetInner.OpEnum.R)
.p1(new EntityState()
.location(Games.toClientLocation(i.getValue()))))
.forEach(changes::add);
return changes;
}
/**
* Generates a client-readable {@link Replay} object (for use with the client replay functionality).
*
* @param originalCtx The context for which to generate a replay.
* @return
*/
static Replay replayFromGameContext(GameContext originalCtx) {
Replay replay = new Replay();
AtomicReference<com.hiddenswitch.spellsource.common.GameState> gameStateOld = new AtomicReference<>();
Consumer<GameContext> augmentReplayWithCtx = (GameContext ctx) -> {
// We record each game state by dumping the {@link GameState} objects from each player's point of
// view and any state transitions into the replay.
ReplayGameStates gameStates = new ReplayGameStates();
gameStates.first(getGameState(ctx, ctx.getPlayer1(), ctx.getPlayer2()));
gameStates.second(getGameState(ctx, ctx.getPlayer2(), ctx.getPlayer1()));
replay.addGameStatesItem(gameStates);
if (gameStateOld.get() != null) {
com.hiddenswitch.spellsource.common.GameState gameStateNew = ctx.getGameState();
ReplayDelta delta = new ReplayDelta();
delta.forward(computeChangeSet(gameStateOld.get(), gameStateNew));
delta.backward(computeChangeSet(gameStateNew, gameStateOld.get()));
replay.addDeltasItem(delta);
}
gameStateOld.set(ctx.getGameStateCopy());
};
// Replay the game from a trace while capturing the {@link Replay} object.
GameContext replayCtx = originalCtx.getTrace().replayContext(
false,
augmentReplayWithCtx
);
// Append the final game states / deltas.
augmentReplayWithCtx.accept(replayCtx);
return replay;
} |
<<<<<<<
=======
//Implement SpellOverrideAura
Class<? extends Spell> spellClass = spellDesc.getDescClass();
Entity finalSource = source;
List<Aura> overrideAuras = context.getTriggerManager().getTriggers().stream()
.filter(t -> t instanceof SpellOverrideAura)
.map(t -> (Aura) t)
.filter(((Predicate<Aura>) Aura::isExpired).negate())
.filter(aura -> aura.getDesc().getRemoveEffect().get(SpellArg.CLASS).equals(spellClass))
.filter(aura -> aura.getAffectedEntities().contains(playerId))
.collect(Collectors.toList());
if (!overrideAuras.isEmpty()) {
spellDesc = spellDesc.clone();
for (Aura aura : overrideAuras) {
for (Map.Entry<SpellArg, Object> spellArgObjectEntry : aura.getDesc().getApplyEffect().entrySet()) {
spellDesc.put(spellArgObjectEntry.getKey(), spellArgObjectEntry.getValue());
}
}
}
>>>>>>>
//Implement SpellOverrideAura
Class<? extends Spell> spellClass = spellDesc.getDescClass();
Entity finalSource = source;
List<Aura> overrideAuras = context.getTriggerManager().getTriggers().stream()
.filter(t -> t instanceof SpellOverrideAura)
.map(t -> (Aura) t)
.filter(((Predicate<Aura>) Aura::isExpired).negate())
.filter(aura -> aura.getDesc().getRemoveEffect().get(SpellArg.CLASS).equals(spellClass))
.filter(aura -> aura.getAffectedEntities().contains(playerId))
.collect(Collectors.toList());
if (!overrideAuras.isEmpty()) {
spellDesc = spellDesc.clone();
for (Aura aura : overrideAuras) {
for (Map.Entry<SpellArg, Object> spellArgObjectEntry : aura.getDesc().getApplyEffect().entrySet()) {
spellDesc.put(spellArgObjectEntry.getKey(), spellArgObjectEntry.getValue());
}
}
}
<<<<<<<
if (!player.hasAttribute(Attribute.LAST_SHUFFLED)) {
player.setAttribute(Attribute.LAST_SHUFFLED, new CardArrayList(Arrays.asList(context.getCardById(card.getCardId()))));
} else {
final CardList shuffledCards = (CardList) player.getAttribute(Attribute.LAST_SHUFFLED);
shuffledCards.add(context.getCardById(card.getCardId()));
}
=======
return true;
>>>>>>>
if (!player.hasAttribute(Attribute.LAST_SHUFFLED)) {
player.setAttribute(Attribute.LAST_SHUFFLED, new CardArrayList(Arrays.asList(context.getCardById(card.getCardId()))));
} else {
final CardList shuffledCards = (CardList) player.getAttribute(Attribute.LAST_SHUFFLED);
shuffledCards.add(context.getCardById(card.getCardId()));
}
return true; |
<<<<<<<
WITHERED,
/**
* Counter for each time a "XXXXX's Scheme" card has upgraded
*/
SCHEME,
/**
* Indicates a minion is part of the "___ Lackey" subset of cards for the Year of the Dragon
*/
LACKEY,
/**
* Indicates a minion is an official Treant, considered for Treant-related synergies
*/
TREANT,
DRAINED_THIS_TURN, TOTAL_DRAINED, DRAINED_LAST_TURN, DYNAMIC_DESCRIPTION;
=======
WITHERED,
/**
* Indicates the amount of health drained by the {@link net.demilich.metastone.game.spells.DrainSpell} effect this
* turn.
*/
DRAINED_THIS_TURN,
TOTAL_DRAINED,
DRAINED_LAST_TURN,
/**
* The keyword for cards with Surge (a bonus gained when the card is drawn that turn).
*/
SURGE,
DYNAMIC_DESCRIPTION;
>>>>>>>
WITHERED,
/**
* Counter for each time a "XXXXX's Scheme" card has upgraded
*/
SCHEME,
/**
* Indicates a minion is part of the "___ Lackey" subset of cards for the Year of the Dragon
*/
LACKEY,
/**
* Indicates a minion is an official Treant, considered for Treant-related synergies
*/
TREANT,
DRAINED_THIS_TURN,
TOTAL_DRAINED,
DRAINED_LAST_TURN,
/**
* The keyword for cards with Surge (a bonus gained when the card is drawn that turn).
*/
SURGE,
DYNAMIC_DESCRIPTION; |
<<<<<<<
@Test
public void testStringShot() {
runGym(((context, player, opponent) -> {
Minion target = playMinionCard(context, opponent, "minion_test_3_2");
Card stringShotCard = receiveCard(context, player, "spell_string_shot");
playCard(context, player, "minion_lil_wormy");
player.setMana(1);
assertEquals(context.getValidActions().stream().filter(action ->
Objects.equals(action.getSourceReference(), stringShotCard.getReference()) &&
Objects.equals(action.getTargetReference(), target.getReference())).count(), 1L);
}));
}
@Test
public void testTheGlutton() {
runGym(((context, player, opponent) -> {
Minion glutton = playMinionCard(context, player, "minion_the_glutton");
Minion toBeEaten = playMinionCard(context, player, "minion_black_test");
assertEquals(glutton.getAttack(), glutton.getBaseAttack());
context.endTurn();
assertTrue(toBeEaten.isDestroyed());
assertEquals(glutton.getAttack(), glutton.getBaseAttack() + 1);
context.endTurn();
context.endTurn();
assertEquals(glutton.getAttack(), glutton.getBaseAttack() + 1);
}));
}
=======
@Test
public void testOmegaRune() {
runGym(((context, player, opponent) -> {
playCard(context, player, "spell_the_omega_rune");
player.getHero().setHp(20);
opponent.getHero().setHp(20);
playCard(context, player, "spell_test_deal_5_to_enemy_hero");
assertEquals(opponent.getHero().getHp(), 15);
assertEquals(player.getHero().getHp(), 25);
playCard(context, opponent, "spell_test_deal_5_to_enemy_hero");
assertEquals(opponent.getHero().getHp(), 15);
assertEquals(player.getHero().getHp(), 20);
}));
}
@Test
public void testMatriarchAiiranDescription() {
runGym((context, player, opponent) -> {
Minion aiiranOnBoard = playMinionCard(context, player, "minion_matriarch_aiiran");
Card aiiranInHand = receiveCard(context, player, "minion_matriarch_aiiran");
assertEquals(aiiranOnBoard.getDescription(context, player), "Opener: Deal X damage. (Increases by 2 for each other Dragon in your hand)");
assertEquals(aiiranInHand.getDescription(context, player), "Opener: Deal 0 damage. (Increases by 2 for each other Dragon in your hand)");
});
}
@Test
public void testMonolithOfDoomDescription() {
runGym((context, player, opponent) -> {
Minion monolithOnBoard = playMinionCard(context, player, "minion_monolith_of_doom");
Card monolithInHand = receiveCard(context, player, "minion_monolith_of_doom");
assertEquals(monolithOnBoard.getDescription(context, player), "Opener: Deal X damage. (Doubles for each Monolith of Doom you played this turn)");
assertEquals(monolithInHand.getDescription(context, player), "Opener: Deal 2 damage. (Doubles for each Monolith of Doom you played this turn)");
});
}
@Test
public void testBerryHoarder() {
runGym(((context, player, opponent) -> {
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "weapon_stick");
putOnTopOfDeck(context, player, "weapon_stick");
playCard(context, player, "minion_berry_hoarder");
assertEquals(player.getDeck().size(), 0);
assertEquals(player.getHand().size(), 0);
}));
runGym(((context, player, opponent) -> {
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "weapon_stick");
putOnTopOfDeck(context, player, "weapon_stick");
player.setMana(5);
playCard(context, player, "minion_berry_hoarder");
assertEquals(player.getDeck().size(), 0);
assertEquals(player.getHand().size(), 4);
}));
}
>>>>>>>
@Test
public void testStringShot() {
runGym(((context, player, opponent) -> {
Minion target = playMinionCard(context, opponent, "minion_test_3_2");
Card stringShotCard = receiveCard(context, player, "spell_string_shot");
playCard(context, player, "minion_lil_wormy");
player.setMana(1);
assertEquals(context.getValidActions().stream().filter(action ->
Objects.equals(action.getSourceReference(), stringShotCard.getReference()) &&
Objects.equals(action.getTargetReference(), target.getReference())).count(), 1L);
}));
}
@Test
public void testOmegaRune() {
runGym(((context, player, opponent) -> {
playCard(context, player, "spell_the_omega_rune");
player.getHero().setHp(20);
opponent.getHero().setHp(20);
playCard(context, player, "spell_test_deal_5_to_enemy_hero");
assertEquals(opponent.getHero().getHp(), 15);
assertEquals(player.getHero().getHp(), 25);
playCard(context, opponent, "spell_test_deal_5_to_enemy_hero");
assertEquals(opponent.getHero().getHp(), 15);
assertEquals(player.getHero().getHp(), 20);
}));
}
@Test
public void testTheGlutton() {
runGym(((context, player, opponent) -> {
Minion glutton = playMinionCard(context, player, "minion_the_glutton");
Minion toBeEaten = playMinionCard(context, player, "minion_black_test");
assertEquals(glutton.getAttack(), glutton.getBaseAttack());
context.endTurn();
assertTrue(toBeEaten.isDestroyed());
assertEquals(glutton.getAttack(), glutton.getBaseAttack() + 1);
context.endTurn();
context.endTurn();
assertEquals(glutton.getAttack(), glutton.getBaseAttack() + 1);
}));
}
@Test
public void testMatriarchAiiranDescription() {
runGym((context, player, opponent) -> {
Minion aiiranOnBoard = playMinionCard(context, player, "minion_matriarch_aiiran");
Card aiiranInHand = receiveCard(context, player, "minion_matriarch_aiiran");
assertEquals(aiiranOnBoard.getDescription(context, player), "Opener: Deal X damage. (Increases by 2 for each other Dragon in your hand)");
assertEquals(aiiranInHand.getDescription(context, player), "Opener: Deal 0 damage. (Increases by 2 for each other Dragon in your hand)");
});
}
@Test
public void testMonolithOfDoomDescription() {
runGym((context, player, opponent) -> {
Minion monolithOnBoard = playMinionCard(context, player, "minion_monolith_of_doom");
Card monolithInHand = receiveCard(context, player, "minion_monolith_of_doom");
assertEquals(monolithOnBoard.getDescription(context, player), "Opener: Deal X damage. (Doubles for each Monolith of Doom you played this turn)");
assertEquals(monolithInHand.getDescription(context, player), "Opener: Deal 2 damage. (Doubles for each Monolith of Doom you played this turn)");
});
}
@Test
public void testBerryHoarder() {
runGym(((context, player, opponent) -> {
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "weapon_stick");
putOnTopOfDeck(context, player, "weapon_stick");
playCard(context, player, "minion_berry_hoarder");
assertEquals(player.getDeck().size(), 0);
assertEquals(player.getHand().size(), 0);
}));
runGym(((context, player, opponent) -> {
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "minion_knight_eternal");
putOnTopOfDeck(context, player, "weapon_stick");
putOnTopOfDeck(context, player, "weapon_stick");
player.setMana(5);
playCard(context, player, "minion_berry_hoarder");
assertEquals(player.getDeck().size(), 0);
assertEquals(player.getHand().size(), 4);
}));
} |
<<<<<<<
private CardType cardType;
private CardSet cardSet;
private Rarity rarity;
private HeroClass classRestriction;
=======
private final CardType cardType;
private final CardSet cardSet;
private final Rarity rarity;
private HeroClass heroClass;
private HeroClass[] heroClasses;
>>>>>>>
private CardType cardType;
private CardSet cardSet;
private Rarity rarity;
private HeroClass heroClass;
private HeroClass[] heroClasses;
<<<<<<<
=======
public boolean hasBattlecry() {
return this.battlecry != null;
}
public boolean hasHeroClass(HeroClass heroClass) {
if (getHeroClasses() != null) {
for (HeroClass h : getHeroClasses()) {
if (heroClass.equals(h)) {
return true;
}
}
} else if (heroClass == getHeroClass()) {
return true;
}
return false;
}
>>>>>>>
public boolean hasHeroClass(HeroClass heroClass) {
if (getHeroClasses() != null) {
for (HeroClass h : getHeroClasses()) {
if (heroClass.equals(h)) {
return true;
}
}
} else if (heroClass == getHeroClass()) {
return true;
}
return false;
} |
<<<<<<<
import dyvilx.tools.compiler.ast.generic.TypeParameterList;
import dyvilx.tools.compiler.ast.header.IClassCompilable;
=======
import dyvilx.tools.compiler.ast.header.ClassCompilable;
>>>>>>>
import dyvilx.tools.compiler.ast.generic.TypeParameterList;
import dyvilx.tools.compiler.ast.header.ClassCompilable; |
<<<<<<<
import com.pmease.gitop.web.page.project.CreateProjectPage;
import com.pmease.gitop.web.page.project.ProjectHomePage;
import com.pmease.gitop.web.page.test.MergeRequestsPage;
import com.pmease.gitop.web.page.test.ProjectPage;
=======
import com.pmease.gitop.web.page.project.issue.ProjectMergeRequestsPage;
import com.pmease.gitop.web.page.project.settings.CreateProjectPage;
import com.pmease.gitop.web.page.project.settings.MergeRequestSettingsPage;
import com.pmease.gitop.web.page.project.settings.ProjectAuditLogPage;
import com.pmease.gitop.web.page.project.settings.ProjectHooksPage;
import com.pmease.gitop.web.page.project.settings.ProjectOptionsPage;
import com.pmease.gitop.web.page.project.settings.ProjectPermissionsPage;
import com.pmease.gitop.web.page.project.source.ProjectHomePage;
import com.pmease.gitop.web.page.project.source.RepositoryBlobPage;
import com.pmease.gitop.web.page.project.source.RepositoryBranchesPage;
import com.pmease.gitop.web.page.project.source.RepositoryCommitsPage;
import com.pmease.gitop.web.page.project.source.RepositoryContributorsPage;
import com.pmease.gitop.web.page.project.source.RepositoryTagsPage;
import com.pmease.gitop.web.page.project.source.RepositoryTreePage;
import com.pmease.gitop.web.page.project.stats.ProjectForksPage;
import com.pmease.gitop.web.page.project.stats.ProjectGraphsPage;
import com.pmease.gitop.web.page.project.wiki.ProjectWikiPage;
import com.pmease.gitop.web.page.test.TestPage;
import com.pmease.gitop.web.page.test.TestPage2;
>>>>>>>
import com.pmease.gitop.web.page.project.issue.ProjectMergeRequestsPage;
import com.pmease.gitop.web.page.project.settings.CreateProjectPage;
import com.pmease.gitop.web.page.project.settings.MergeRequestSettingsPage;
import com.pmease.gitop.web.page.project.settings.ProjectAuditLogPage;
import com.pmease.gitop.web.page.project.settings.ProjectHooksPage;
import com.pmease.gitop.web.page.project.settings.ProjectOptionsPage;
import com.pmease.gitop.web.page.project.settings.ProjectPermissionsPage;
import com.pmease.gitop.web.page.project.source.ProjectHomePage;
import com.pmease.gitop.web.page.project.source.RepositoryBlobPage;
import com.pmease.gitop.web.page.project.source.RepositoryBranchesPage;
import com.pmease.gitop.web.page.project.source.RepositoryCommitsPage;
import com.pmease.gitop.web.page.project.source.RepositoryContributorsPage;
import com.pmease.gitop.web.page.project.source.RepositoryTagsPage;
import com.pmease.gitop.web.page.project.source.RepositoryTreePage;
import com.pmease.gitop.web.page.project.stats.ProjectForksPage;
import com.pmease.gitop.web.page.project.stats.ProjectGraphsPage;
import com.pmease.gitop.web.page.project.wiki.ProjectWikiPage;
import com.pmease.gitop.web.page.test.MergeRequestsPage;
import com.pmease.gitop.web.page.test.ProjectPage; |
<<<<<<<
tabs.add(new UserTab("Build Setting", "fa fa-fw fa-play-circle", UserJobSecretsPage.class, UserBuildSettingPage.class));
=======
if (isSshEnabled()) {
tabs.add(new UserTab("Ssh Keys", "fa fa-fw fa-shield", UserSshKeysPage.class));
}
tabs.add(new UserTab("Build Setting", "fa fa-fw fa-cubes", UserJobSecretsPage.class, UserBuildSettingPage.class));
>>>>>>>
if (isSshEnabled()) {
tabs.add(new UserTab("Ssh Keys", "fa fa-fw fa-shield", UserSshKeysPage.class));
}
tabs.add(new UserTab("Build Setting", "fa fa-fw fa-play-circle", UserJobSecretsPage.class, UserBuildSettingPage.class)); |
<<<<<<<
private static final String PIPELINE_IDLE_STATE_HANLDER = "idleStateHandler";
private static final String PIPELINE_GRACEFUL_SHUTDOWN_TIMEOUT_HANDLER = "gracefulShutdownTimeoutHandler";
=======
private static final String PIPELINE_IDLE_STATE_HANDLER = "idleStateHandler";
>>>>>>>
private static final String PIPELINE_IDLE_STATE_HANDLER = "idleStateHandler";
private static final String PIPELINE_GRACEFUL_SHUTDOWN_TIMEOUT_HANDLER = "gracefulShutdownTimeoutHandler";
<<<<<<<
if (this.apnsConnection.shutdownNotification == null) {
log.debug("{} will shut down gracefully due to inactivity.", this.apnsConnection.name);
this.apnsConnection.shutdownGracefully();
} else {
log.debug("Graceful shutdown attempt for {} timed out; shutting down immediately.", this.apnsConnection.name);
this.apnsConnection.shutdownImmediately();
}
=======
log.debug("{} will shut down due to inactivity.", this.apnsConnection.name);
context.pipeline().remove(ApnsConnection.PIPELINE_IDLE_STATE_HANDLER);
this.apnsConnection.shutdownGracefully();
>>>>>>>
if (this.apnsConnection.shutdownNotification == null) {
log.debug("{} will shut down gracefully due to inactivity.", this.apnsConnection.name);
this.apnsConnection.shutdownGracefully();
} else {
log.debug("Graceful shutdown attempt for {} timed out; shutting down immediately.", this.apnsConnection.name);
this.apnsConnection.shutdownImmediately();
} |
<<<<<<<
private Integer sendAttemptLimit = null;
=======
private Integer closeAfterInactivityTime = null;
>>>>>>>
private Integer closeAfterInactivityTime = null;
private Integer sendAttemptLimit = null;
<<<<<<<
/**
* Returns the number of notifications a connection may attempt to send before shutting down.
*
* @return the number of notifications a connection may attempt to send before shutting down, or {@code null} if no
* limit has been set
*/
public Integer getSendAttemptLimit() {
return this.sendAttemptLimit;
}
/**
* <p>Sets the number of notifications a connection may attempt to send before shutting down. If not {@code null},
* connections will attempt to shut down gracefully after the given number of send attempts regardless of whether
* those attempts were actually successful. By default, no limit is set.</p>
*
* <p>If the a send attempt limit is set and is less than the sent notification buffer size, it is guaranteed that
* notifications will never be lost due to buffer overruns (though they may be lost by other means, such as non-
* graceful shutdowns).</p>
*
* @param sendAttemptLimit the number of notifications the connection may attempt to send before shutting down
* gracefully; if {@code null}, no limit is set
*
* @see ApnsConnectionConfiguration#setSentNotificationBufferCapacity(int)
*/
public void setSendAttemptLimit(final Integer sendAttemptLimit) {
this.sendAttemptLimit = sendAttemptLimit;
}
=======
/**
* Returns the time, in seconds, since the last push notification was sent after which connections created with this
* configuration will be closed. If {@code null}, connections created with this configuration will never be closed
* due to inactivity.
*
* @return the time, in seconds, since the last push notification was sent after which connections created with this
* configuration will be closed
*/
public Integer getCloseAfterInactivityTime() {
return this.closeAfterInactivityTime;
}
/**
* Sets the time, in seconds, since the last push notification was sent after which connections created with this
* configuration will be closed. If {@code null} (the default), connections will never be closed due to inactivity.
*
* @param closeAfterInactivityTime the time, in seconds since the last push notification was sent, after which
* connections will be closed
*/
public void setCloseAfterInactivityTime(final Integer closeAfterInactivityTime) {
this.closeAfterInactivityTime = closeAfterInactivityTime;
}
>>>>>>>
/**
* Returns the time, in seconds, since the last push notification was sent after which connections created with this
* configuration will be closed. If {@code null}, connections created with this configuration will never be closed
* due to inactivity.
*
* @return the time, in seconds, since the last push notification was sent after which connections created with this
* configuration will be closed
*/
public Integer getCloseAfterInactivityTime() {
return this.closeAfterInactivityTime;
}
/**
* Sets the time, in seconds, since the last push notification was sent after which connections created with this
* configuration will be closed. If {@code null} (the default), connections will never be closed due to inactivity.
*
* @param closeAfterInactivityTime the time, in seconds since the last push notification was sent, after which
* connections will be closed
*/
public void setCloseAfterInactivityTime(final Integer closeAfterInactivityTime) {
this.closeAfterInactivityTime = closeAfterInactivityTime;
}
/**
* Returns the number of notifications a connection may attempt to send before shutting down.
*
* @return the number of notifications a connection may attempt to send before shutting down, or {@code null} if no
* limit has been set
*/
public Integer getSendAttemptLimit() {
return this.sendAttemptLimit;
}
/**
* <p>Sets the number of notifications a connection may attempt to send before shutting down. If not {@code null},
* connections will attempt to shut down gracefully after the given number of send attempts regardless of whether
* those attempts were actually successful. By default, no limit is set.</p>
*
* <p>If the a send attempt limit is set and is less than the sent notification buffer size, it is guaranteed that
* notifications will never be lost due to buffer overruns (though they may be lost by other means, such as non-
* graceful shutdowns).</p>
*
* @param sendAttemptLimit the number of notifications the connection may attempt to send before shutting down
* gracefully; if {@code null}, no limit is set
*
* @see ApnsConnectionConfiguration#setSentNotificationBufferCapacity(int)
*/
public void setSendAttemptLimit(final Integer sendAttemptLimit) {
this.sendAttemptLimit = sendAttemptLimit;
} |
<<<<<<<
import com.relayrides.pushy.apns.metrics.ApnsClientMetricsListener;
=======
import com.relayrides.pushy.apns.proxy.ProxyHandlerFactory;
>>>>>>>
import com.relayrides.pushy.apns.metrics.ApnsClientMetricsListener;
import com.relayrides.pushy.apns.proxy.ProxyHandlerFactory; |
<<<<<<<
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.ref.WeakReference;
=======
>>>>>>>
import java.lang.Thread.UncaughtExceptionHandler;
<<<<<<<
private final int concurrentConnections;
=======
private final int concurrentConnectionCount;
>>>>>>>
private final int concurrentConnectionCount;
<<<<<<<
private final ThreadExceptionHandler threadExceptionHandler;
private final ArrayList<WeakReference<RejectedNotificationListener<T>>> rejectedNotificationListeners;
=======
private final Vector<RejectedNotificationListener<? super T>> rejectedNotificationListeners;
>>>>>>>
private final ThreadExceptionHandler threadExceptionHandler;
private final Vector<RejectedNotificationListener<? super T>> rejectedNotificationListeners;
<<<<<<<
public PushManager(final ApnsEnvironment environment, final KeyStore keyStore, final char[] keyStorePassword, final int concurrentConnections, final NioEventLoopGroup workerGroup) {
=======
protected PushManager(final ApnsEnvironment environment, final KeyStore keyStore, final char[] keyStorePassword,
final int concurrentConnectionCount, final NioEventLoopGroup workerGroup, final BlockingQueue<T> queue) {
>>>>>>>
protected PushManager(final ApnsEnvironment environment, final KeyStore keyStore, final char[] keyStorePassword,
final int concurrentConnectionCount, final NioEventLoopGroup workerGroup, final BlockingQueue<T> queue) {
<<<<<<<
this.concurrentConnections = concurrentConnections;
this.clientThreads = new ArrayList<ApnsClientThread<T>>(this.concurrentConnections);
this.threadExceptionHandler = new ThreadExceptionHandler(this);
=======
this.concurrentConnectionCount = concurrentConnectionCount;
this.clientThreads = new ArrayList<ApnsClientThread<T>>(this.concurrentConnectionCount);
>>>>>>>
this.concurrentConnectionCount = concurrentConnectionCount;
this.clientThreads = new ArrayList<ApnsClientThread<T>>(this.concurrentConnectionCount);
this.threadExceptionHandler = new ThreadExceptionHandler(this);
<<<<<<<
for (int i = 0; i < this.concurrentConnections; i++) {
final ApnsClientThread<T> clientThread = getNewClientThread();
this.clientThreads.add(clientThread);
clientThread.start();
=======
for (int i = 0; i < this.concurrentConnectionCount; i++) {
final ApnsClientThread<T> clientThread = new ApnsClientThread<T>(this);
this.clientThreads.add(clientThread);
clientThread.start();
>>>>>>>
for (int i = 0; i < this.concurrentConnectionCount; i++) {
final ApnsClientThread<T> clientThread = getNewClientThread();
this.clientThreads.add(clientThread);
clientThread.start();
<<<<<<<
public synchronized void registerRejectedNotificationListener(final RejectedNotificationListener<T> listener) {
this.rejectedNotificationListeners.add(new WeakReference<RejectedNotificationListener<T>>(listener));
}
protected synchronized void replaceThread(Thread t) {
if(this.shutDown) {
return;
}
if(!clientThreads.remove(t)) {
log.warn(String.format("Did not find thread %s in list of client threads.", t.getName()));
}
ApnsClientThread<T> newThread = getNewClientThread();
clientThreads.add(newThread);
newThread.start();
}
protected synchronized void notifyListenersOfRejectedNotification(final T notification, final RejectedNotificationReason reason) {
final ArrayList<RejectedNotificationListener<T>> listeners = new ArrayList<RejectedNotificationListener<T>>();
final ArrayList<Integer> expiredListenerIndices = new ArrayList<Integer>();
=======
public void registerRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) {
if (this.shutDown) {
throw new IllegalStateException("Rejected notification listeners may not be registered after a push manager has been shut down.");
}
>>>>>>>
public void registerRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) {
if (this.shutDown) {
throw new IllegalStateException("Rejected notification listeners may not be registered after a push manager has been shut down.");
} |
<<<<<<<
private Integer sendAttemptLimit = null;
=======
private Integer gracefulShutdownTimeout = null;
>>>>>>>
private Integer gracefulShutdownTimeout = null;
private Integer sendAttemptLimit = null;
<<<<<<<
/**
* Returns the number of notifications a connection may attempt to send before shutting down.
*
* @return the number of notifications a connection may attempt to send before shutting down, or {@code null} if no
* limit has been set
*/
public Integer getSendAttemptLimit() {
return this.sendAttemptLimit;
}
/**
* <p>Sets the number of notifications a connection may attempt to send before shutting down. If not {@code null},
* connections will attempt to shut down gracefully after the given number of send attempts regardless of whether
* those attempts were actually successful. By default, no limit is set.</p>
*
* <p>If the a send attempt limit is set and is less than the sent notification buffer size, it is guaranteed that
* notifications will never be lost due to buffer overruns (though they may be lost by other means, such as non-
* graceful shutdowns).</p>
*
* @param sendAttemptLimit the number of notifications the connection may attempt to send before shutting down
* gracefully; if {@code null}, no limit is set
*
* @see ApnsConnectionConfiguration#setSentNotificationBufferCapacity(int)
*/
public void setSendAttemptLimit(final Integer sendAttemptLimit) {
this.sendAttemptLimit = sendAttemptLimit;
}
=======
/**
* Returns the time, in seconds, after which a graceful shutdown attempt should be abandoned and the connection
* should be closed immediately.
*
* @return the time, in seconds, after which a graceful shutdown attempt should be abandoned and the connection
* should be closed immediately
*/
public Integer getGracefulShutdownTimeout() {
return this.gracefulShutdownTimeout;
}
/**
* Sets the time, in seconds, after which a graceful shutdown attempt should be abandoned and the connection should
* be closed immediately. If {@code null} (the default) graceful shutdown attempts will never time out. Note that,
* if a graceful shutdown attempt times out, no guarantees are made as to the state of notifications sent by the
* connection.
*
* @param gracefulShutdownTimeout the time, in seconds, after which a graceful shutdown attempt should be abandoned
*/
public void setGracefulShutdownTimeout(final Integer gracefulShutdownTimeout) {
this.gracefulShutdownTimeout = gracefulShutdownTimeout;
}
>>>>>>>
/**
* Returns the time, in seconds, after which a graceful shutdown attempt should be abandoned and the connection
* should be closed immediately.
*
* @return the time, in seconds, after which a graceful shutdown attempt should be abandoned and the connection
* should be closed immediately
*/
public Integer getGracefulShutdownTimeout() {
return this.gracefulShutdownTimeout;
}
/**
* Sets the time, in seconds, after which a graceful shutdown attempt should be abandoned and the connection should
* be closed immediately. If {@code null} (the default) graceful shutdown attempts will never time out. Note that,
* if a graceful shutdown attempt times out, no guarantees are made as to the state of notifications sent by the
* connection.
*
* @param gracefulShutdownTimeout the time, in seconds, after which a graceful shutdown attempt should be abandoned
*/
public void setGracefulShutdownTimeout(final Integer gracefulShutdownTimeout) {
this.gracefulShutdownTimeout = gracefulShutdownTimeout;
}
/**
* Returns the number of notifications a connection may attempt to send before shutting down.
*
* @return the number of notifications a connection may attempt to send before shutting down, or {@code null} if no
* limit has been set
*/
public Integer getSendAttemptLimit() {
return this.sendAttemptLimit;
}
/**
* <p>Sets the number of notifications a connection may attempt to send before shutting down. If not {@code null},
* connections will attempt to shut down gracefully after the given number of send attempts regardless of whether
* those attempts were actually successful. By default, no limit is set.</p>
*
* <p>If the a send attempt limit is set and is less than the sent notification buffer size, it is guaranteed that
* notifications will never be lost due to buffer overruns (though they may be lost by other means, such as non-
* graceful shutdowns).</p>
*
* @param sendAttemptLimit the number of notifications the connection may attempt to send before shutting down
* gracefully; if {@code null}, no limit is set
*
* @see ApnsConnectionConfiguration#setSentNotificationBufferCapacity(int)
*/
public void setSendAttemptLimit(final Integer sendAttemptLimit) {
this.sendAttemptLimit = sendAttemptLimit;
} |
<<<<<<<
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.expr.ClosureExpression;
=======
>>>>>>>
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.expr.ClosureExpression;
<<<<<<<
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.classgen.Verifier;
=======
import org.codehaus.groovy.ast.tools.GenericsUtils;
>>>>>>>
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.ast.tools.GenericsUtils;
<<<<<<<
public static MethodNode correctToGenericsSpec(Map genericsSpec, MethodNode mn) {
ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, mn.getReturnType());
Parameter[] origParameters = mn.getParameters();
Parameter[] newParameters = new Parameter[origParameters.length];
for (int i = 0; i < origParameters.length; i++) {
Parameter origParameter = origParameters[i];
newParameters[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, origParameter.getType()), origParameter.getName(), origParameter.getInitialExpression());
}
return new MethodNode(mn.getName(), mn.getModifiers(), correctedType, newParameters, mn.getExceptions(), mn.getCode());
}
public static ClassNode correctToGenericsSpecRecurse(Map genericsSpec, ClassNode type) {
if (type.isGenericsPlaceHolder()) {
String name = type.getGenericsTypes()[0].getName();
type = (ClassNode) genericsSpec.get(name);
}
if (type == null) type = ClassHelper.OBJECT_TYPE;
GenericsType[] oldgTypes = type.getGenericsTypes();
GenericsType[] newgTypes = new GenericsType[0];
if (oldgTypes != null) {
newgTypes = new GenericsType[oldgTypes.length];
for (int i = 0; i < newgTypes.length; i++) {
GenericsType oldgType = oldgTypes[i];
if (oldgType.isPlaceholder() ) {
if (genericsSpec.get(oldgType.getName())!=null) {
newgTypes[i] = new GenericsType((ClassNode) genericsSpec.get(oldgType.getName()));
} else {
newgTypes[i] = new GenericsType(ClassHelper.OBJECT_TYPE);
}
} else if (oldgType.isWildcard()) {
ClassNode oldLower = oldgType.getLowerBound();
ClassNode lower = oldLower!=null?correctToGenericsSpecRecurse(genericsSpec, oldLower):null;
ClassNode[] oldUpper = oldgType.getUpperBounds();
ClassNode[] upper = null;
if (oldUpper!=null) {
upper = new ClassNode[oldUpper.length];
for (int j = 0; j < oldUpper.length; j++) {
upper[j] = correctToGenericsSpecRecurse(genericsSpec,oldUpper[j]);
}
}
GenericsType fixed = new GenericsType(oldgType.getType(), upper, lower);
fixed.setWildcard(true);
newgTypes[i] = fixed;
} else {
newgTypes[i] = new GenericsType(Verifier.correctToGenericsSpec(genericsSpec, oldgType));
}
}
}
return makeClassSafeWithGenerics(type, newgTypes);
}
/**
* Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
* and {@link java.lang.annotation.RetentionPolicy#CLASS}.
* <p>
* Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported by now.
*/
public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, List<AnnotationNode> notCopied) {
List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
for (AnnotationNode annotation : annotationList) {
List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(RETENTION_CLASSNODE);
if (annotations.isEmpty()) continue;
if (hasClosureMember(annotation)) {
notCopied.add(annotation);
continue;
}
AnnotationNode retentionPolicyAnnotation = annotations.get(0);
Expression valueExpression = retentionPolicyAnnotation.getMember("value");
if (!(valueExpression instanceof PropertyExpression)) continue;
PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
boolean processAnnotation =
propertyExpression.getProperty() instanceof ConstantExpression &&
(
"RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()) ||
"CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
);
if (processAnnotation) {
AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet()) {
newAnnotation.addMember(member.getKey(), member.getValue());
}
newAnnotation.setSourcePosition(annotatedNode);
copied.add(newAnnotation);
}
}
}
private static boolean hasClosureMember(AnnotationNode annotation) {
Map<String, Expression> members = annotation.getMembers();
for (Map.Entry<String, Expression> member : members.entrySet()) {
if (member.getValue() instanceof ClosureExpression) return true;
if (member.getValue() instanceof ClassExpression) {
ClassExpression classExpression = (ClassExpression) member.getValue();
Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null;
if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true;
}
}
return false;
}
=======
>>>>>>>
public static ClassNode newClass(ClassNode type) {
return type.getPlainNodeReference();
}
public static ClassNode makeClassSafe0(ClassNode type, GenericsType... genericTypes) {
ClassNode plainNodeReference = newClass(type);
if (genericTypes != null && genericTypes.length > 0) plainNodeReference.setGenericsTypes(genericTypes);
return plainNodeReference;
}
public static ClassNode makeClassSafeWithGenerics(ClassNode type, GenericsType... genericTypes) {
if (type.isArray()) {
return makeClassSafeWithGenerics(type.getComponentType(), genericTypes).makeArray();
}
GenericsType[] gtypes = new GenericsType[0];
if (genericTypes != null) {
gtypes = new GenericsType[genericTypes.length];
System.arraycopy(genericTypes, 0, gtypes, 0, gtypes.length);
}
return makeClassSafe0(type, gtypes);
}
public static MethodNode correctToGenericsSpec(Map genericsSpec, MethodNode mn) {
ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, mn.getReturnType());
Parameter[] origParameters = mn.getParameters();
Parameter[] newParameters = new Parameter[origParameters.length];
for (int i = 0; i < origParameters.length; i++) {
Parameter origParameter = origParameters[i];
newParameters[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, origParameter.getType()), origParameter.getName(), origParameter.getInitialExpression());
}
return new MethodNode(mn.getName(), mn.getModifiers(), correctedType, newParameters, mn.getExceptions(), mn.getCode());
}
public static ClassNode correctToGenericsSpecRecurse(Map genericsSpec, ClassNode type) {
if (type.isGenericsPlaceHolder()) {
String name = type.getGenericsTypes()[0].getName();
type = (ClassNode) genericsSpec.get(name);
}
if (type == null) type = ClassHelper.OBJECT_TYPE;
GenericsType[] oldgTypes = type.getGenericsTypes();
GenericsType[] newgTypes = new GenericsType[0];
if (oldgTypes != null) {
newgTypes = new GenericsType[oldgTypes.length];
for (int i = 0; i < newgTypes.length; i++) {
GenericsType oldgType = oldgTypes[i];
if (oldgType.isPlaceholder() ) {
if (genericsSpec.get(oldgType.getName())!=null) {
newgTypes[i] = new GenericsType((ClassNode) genericsSpec.get(oldgType.getName()));
} else {
newgTypes[i] = new GenericsType(ClassHelper.OBJECT_TYPE);
}
} else if (oldgType.isWildcard()) {
ClassNode oldLower = oldgType.getLowerBound();
ClassNode lower = oldLower!=null?correctToGenericsSpecRecurse(genericsSpec, oldLower):null;
ClassNode[] oldUpper = oldgType.getUpperBounds();
ClassNode[] upper = null;
if (oldUpper!=null) {
upper = new ClassNode[oldUpper.length];
for (int j = 0; j < oldUpper.length; j++) {
upper[j] = correctToGenericsSpecRecurse(genericsSpec,oldUpper[j]);
}
}
GenericsType fixed = new GenericsType(oldgType.getType(), upper, lower);
fixed.setWildcard(true);
newgTypes[i] = fixed;
} else {
newgTypes[i] = new GenericsType(GenericsUtils.correctToGenericsSpec(genericsSpec, oldgType));
}
}
}
return makeClassSafeWithGenerics(type, newgTypes);
}
/**
* Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
* and {@link java.lang.annotation.RetentionPolicy#CLASS}.
* <p>
* Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported by now.
*/
public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, List<AnnotationNode> notCopied) {
List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
for (AnnotationNode annotation : annotationList) {
List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(RETENTION_CLASSNODE);
if (annotations.isEmpty()) continue;
if (hasClosureMember(annotation)) {
notCopied.add(annotation);
continue;
}
AnnotationNode retentionPolicyAnnotation = annotations.get(0);
Expression valueExpression = retentionPolicyAnnotation.getMember("value");
if (!(valueExpression instanceof PropertyExpression)) continue;
PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
boolean processAnnotation =
propertyExpression.getProperty() instanceof ConstantExpression &&
(
"RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()) ||
"CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
);
if (processAnnotation) {
AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet()) {
newAnnotation.addMember(member.getKey(), member.getValue());
}
newAnnotation.setSourcePosition(annotatedNode);
copied.add(newAnnotation);
}
}
}
private static boolean hasClosureMember(AnnotationNode annotation) {
Map<String, Expression> members = annotation.getMembers();
for (Map.Entry<String, Expression> member : members.entrySet()) {
if (member.getValue() instanceof ClosureExpression) return true;
if (member.getValue() instanceof ClassExpression) {
ClassExpression classExpression = (ClassExpression) member.getValue();
Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null;
if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true;
}
}
return false;
} |
<<<<<<<
NUODB
=======
MONETDB,
>>>>>>>
MONETDB,
NUODB |
<<<<<<<
import dyvil.tools.compiler.ast.member.Name;
import dyvil.tools.compiler.ast.method.intrinsic.IntrinsicData;
import dyvil.tools.compiler.ast.method.intrinsic.Intrinsics;
=======
>>>>>>>
import dyvil.tools.compiler.ast.method.intrinsic.IntrinsicData;
import dyvil.tools.compiler.ast.method.intrinsic.Intrinsics;
<<<<<<<
this.intrinsicData = Intrinsics.readAnnotation(this, annotation);
return false;
=======
this.readIntrinsicAnnotation(annotation);
return this.getClass() != ExternalMethod.class;
>>>>>>>
this.intrinsicData = Intrinsics.readAnnotation(this, annotation);
return this.getClass() != ExternalMethod.class;
<<<<<<<
else if (this.intrinsicData == null && instance.isPrimitive())
=======
else if (this.intrinsicOpcodes == null || !instance.isPrimitive())
>>>>>>>
else if (this.intrinsicData == null || !instance.isPrimitive())
<<<<<<<
=======
private void writeIntrinsic(MethodWriter writer, IValue instance, IArguments arguments, int lineNumber) throws BytecodeException
{
if (this.type.getTheClass() == Types.BOOLEAN_CLASS)
{
int len = this.intrinsicOpcodes.length - 1;
if (this.intrinsicOpcodes[len] == IFNE)
{
for (int i = 0; i < len; i++)
{
int insn = this.intrinsicOpcodes[i];
if (insn == INSTANCE)
{
this.writeInstance(writer, instance);
}
else if (insn == ARGUMENTS)
{
this.writeArguments(writer, instance, arguments);
}
else
{
writer.writeInsn(insn, lineNumber);
}
}
return;
}
Label ifEnd = new Label();
Label elseEnd = new Label();
this.writeIntrinsic(writer, ifEnd, instance, arguments, lineNumber);
// If Block
writer.writeLDC(0);
writer.writeJumpInsn(Opcodes.GOTO, elseEnd);
writer.writeLabel(ifEnd);
// Else Block
writer.writeLDC(1);
writer.writeLabel(elseEnd);
return;
}
for (int i : this.intrinsicOpcodes)
{
if (i == INSTANCE)
{
this.writeInstance(writer, instance);
}
else if (i == ARGUMENTS)
{
this.writeArguments(writer, instance, arguments);
}
else
{
writer.writeInsn(i, lineNumber);
}
}
}
private void writeIntrinsic(MethodWriter writer, Label dest, IValue instance, IArguments arguments, int lineNumber) throws BytecodeException
{
for (int i : this.intrinsicOpcodes)
{
if (i == INSTANCE)
{
this.writeInstance(writer, instance);
}
else if (i == ARGUMENTS)
{
this.writeArguments(writer, instance, arguments);
}
else if (Opcodes.isJumpOpcode(i))
{
writer.writeJumpInsn(i, dest);
}
else
{
writer.writeInsn(i, lineNumber);
}
}
}
private void writeInvIntrinsic(MethodWriter writer, Label dest, IValue instance, IArguments arguments, int lineNumber) throws BytecodeException
{
for (int i : this.intrinsicOpcodes)
{
if (i == INSTANCE)
{
this.writeInstance(writer, instance);
}
else if (i == ARGUMENTS)
{
this.writeArguments(writer, instance, arguments);
}
else if (Opcodes.isJumpOpcode(i))
{
writer.writeJumpInsn(Opcodes.getInverseOpcode(i), dest);
}
else
{
writer.writeInsn(i, lineNumber);
}
}
}
>>>>>>> |
<<<<<<<
@Option(name = "--oauth2_client_id")
private String oauth2ClientId;
@Option(name = "--oauth2_client_secret")
private String oauth2ClientSecret;
@Option(name = "--oauth2_refresh_token_path", metaVar = "<path>")
private String oauth2RefreshTokenPath;
=======
@Option(name = "--use_tls", metaVar = "true|false")
private String useTls;
>>>>>>>
@Option(name = "--oauth2_client_id")
private String oauth2ClientId;
@Option(name = "--oauth2_client_secret")
private String oauth2ClientSecret;
@Option(name = "--oauth2_refresh_token_path", metaVar = "<path>")
private String oauth2RefreshTokenPath;
@Option(name = "--use_tls", metaVar = "true|false")
private String useTls; |
<<<<<<<
import io.cloudslang.lang.entities.bindings.values.Value;
=======
import io.cloudslang.runtime.api.python.PythonRuntimeService;
import io.cloudslang.runtime.impl.python.PythonExecutionCachedEngine;
import io.cloudslang.runtime.impl.python.PythonExecutionEngine;
import io.cloudslang.runtime.impl.python.PythonExecutor;
import io.cloudslang.runtime.impl.python.PythonRuntimeServiceImpl;
>>>>>>>
import io.cloudslang.lang.entities.bindings.values.Value;
import io.cloudslang.runtime.api.python.PythonRuntimeService;
import io.cloudslang.runtime.impl.python.PythonExecutionCachedEngine;
import io.cloudslang.runtime.impl.python.PythonExecutionEngine;
import io.cloudslang.runtime.impl.python.PythonExecutor;
import io.cloudslang.runtime.impl.python.PythonRuntimeServiceImpl;
<<<<<<<
scriptEvaluator.evalExpr("", new HashMap<String, Value>(), new HashSet<SystemProperty>());
=======
reset(pythonInterpreter);
scriptEvaluator.evalExpr("", new HashMap<String, Serializable>(), new HashSet<SystemProperty>());
>>>>>>>
reset(pythonInterpreter);
scriptEvaluator.evalExpr("", new HashMap<String, Value>(), new HashSet<SystemProperty>()); |
<<<<<<<
import java.util.*;
=======
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
>>>>>>>
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
<<<<<<<
verifyStepPublishValues(stepData);
}
@Test
public void testInputMissing() throws Exception {
URL resource = getClass().getResource("/yaml/check_weather_missing_input.sl");
CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource.toURI()), new HashSet<SlangSource>());
Map<String, Value> userInputs = Collections.emptyMap();
Set<SystemProperty> systemProperties = Collections.emptySet();
exception.expect(RuntimeException.class);
exception.expectMessage("Error running: 'check_weather_missing_input'.\n" +
"\t Error binding input: 'input_get_missing_input', \n" +
"\tError is: Error in running script expression: 'missing_input',\n" +
"\tException is: name 'missing_input' is not defined");
triggerWithData(compilationArtifact, userInputs, systemProperties);
}
private void verifyStepPublishValues(StepData stepData) {
Map<String, Serializable> expectedPublishValues = new LinkedHashMap<>();
expectedPublishValues.put("step1_publish_1", "op_output_1_value op_input_1_step step_arg_1_value");
expectedPublishValues.put("step1_publish_2_conflict", "op_output_2_value");
Map<String, Serializable> actualPublishValues = stepData.getOutputs();
Assert.assertEquals("step publish values not as expected", expectedPublishValues, actualPublishValues);
=======
>>>>>>>
verifyStepPublishValues(stepData);
}
@Test
public void testInputMissing() throws Exception {
URL resource = getClass().getResource("/yaml/check_weather_missing_input.sl");
CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource.toURI()), new HashSet<SlangSource>());
Map<String, Value> userInputs = Collections.emptyMap();
Set<SystemProperty> systemProperties = Collections.emptySet();
exception.expect(RuntimeException.class);
exception.expectMessage("Error running: 'check_weather_missing_input'.\n" +
"\t Error binding input: 'input_get_missing_input', \n" +
"\tError is: Error in running script expression: 'missing_input',\n" +
"\tException is: name 'missing_input' is not defined");
triggerWithData(compilationArtifact, userInputs, systemProperties);
}
private void verifyStepPublishValues(StepData stepData) {
Map<String, Serializable> expectedPublishValues = new LinkedHashMap<>();
expectedPublishValues.put("step1_publish_1", "op_output_1_value op_input_1_step step_arg_1_value");
expectedPublishValues.put("step1_publish_2_conflict", "op_output_2_value");
Map<String, Serializable> actualPublishValues = stepData.getOutputs();
Assert.assertEquals("step publish values not as expected", expectedPublishValues, actualPublishValues); |
<<<<<<<
import org.junit.Ignore;
=======
import org.junit.Rule;
>>>>>>>
import org.junit.Ignore;
import org.junit.Rule;
<<<<<<<
@Test
public void testCompileLoopFlowWithSystemProperty() throws Exception {
URI flow = getClass().getResource("/loops/loop_from_property_with_custom_navigation.sl").toURI();
URI operation = getClass().getResource("/loops/print.sl").toURI();
Set<SlangSource> path = new HashSet<>();
path.add(SlangSource.fromFile(operation));
CompilationArtifact artifact = compiler.compile(SlangSource.fromFile(flow), path);
assertNotNull("artifact is null", artifact);
Assert.assertEquals(1, artifact.getSystemProperties().size());
Assert.assertEquals("loops.list", artifact.getSystemProperties().iterator().next());
}
=======
@Test
public void testCompileLoopFlowWithBreakOnNonExistingResult() throws Exception {
URI flow = getClass().getResource("/loops/loop_with_break_on_non_existing_result.sl").toURI();
URI operation = getClass().getResource("/loops/print.sl").toURI();
Set<SlangSource> path = new HashSet<>();
path.add(SlangSource.fromFile(operation));
exception.expect(IllegalArgumentException.class);
exception.expectMessage(
"Cannot compile flow 'loops.loop_with_break_on_non_existing_result' since in step" +
" 'print_values' the results [CUSTOM_1, CUSTOM_2] declared in 'break' section " +
"are not declared in the dependency 'loops.print' result section."
);
compiler.compile(SlangSource.fromFile(flow), path);
}
>>>>>>>
@Test
public void testCompileLoopFlowWithSystemProperty() throws Exception {
URI flow = getClass().getResource("/loops/loop_from_property_with_custom_navigation.sl").toURI();
URI operation = getClass().getResource("/loops/print.sl").toURI();
Set<SlangSource> path = new HashSet<>();
path.add(SlangSource.fromFile(operation));
CompilationArtifact artifact = compiler.compile(SlangSource.fromFile(flow), path);
assertNotNull("artifact is null", artifact);
Assert.assertEquals(1, artifact.getSystemProperties().size());
Assert.assertEquals("loops.list", artifact.getSystemProperties().iterator().next());
}
@Test
public void testCompileLoopFlowWithBreakOnNonExistingResult() throws Exception {
URI flow = getClass().getResource("/loops/loop_with_break_on_non_existing_result.sl").toURI();
URI operation = getClass().getResource("/loops/print.sl").toURI();
Set<SlangSource> path = new HashSet<>();
path.add(SlangSource.fromFile(operation));
exception.expect(IllegalArgumentException.class);
exception.expectMessage(
"Cannot compile flow 'loops.loop_with_break_on_non_existing_result' since in step" +
" 'print_values' the results [CUSTOM_1, CUSTOM_2] declared in 'break' section " +
"are not declared in the dependency 'loops.print' result section."
);
compiler.compile(SlangSource.fromFile(flow), path);
} |
<<<<<<<
if(isQuiet){
handlerTypes.add(EVENT_EXECUTION_FINISHED);
}
else {
handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT);
handlerTypes.add(EventConstants.SCORE_ERROR_EVENT);
handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT);
handlerTypes.add(SLANG_EXECUTION_EXCEPTION);
handlerTypes.add(EVENT_EXECUTION_FINISHED);
handlerTypes.add(EVENT_INPUT_END);
}
=======
handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT);
handlerTypes.add(EventConstants.SCORE_ERROR_EVENT);
handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT);
handlerTypes.add(SLANG_EXECUTION_EXCEPTION);
handlerTypes.add(EVENT_EXECUTION_FINISHED);
handlerTypes.add(EVENT_INPUT_END);
handlerTypes.add(EVENT_OUTPUT_END);
>>>>>>>
if(isQuiet){
handlerTypes.add(EVENT_EXECUTION_FINISHED);
}
else {
handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT);
handlerTypes.add(EventConstants.SCORE_ERROR_EVENT);
handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT);
handlerTypes.add(SLANG_EXECUTION_EXCEPTION);
handlerTypes.add(EVENT_EXECUTION_FINISHED);
handlerTypes.add(EVENT_INPUT_END);
handlerTypes.add(EVENT_OUTPUT_END);
}
<<<<<<<
private class SyncTriggerEventListener implements ScoreEventListener {
private AtomicBoolean flowFinished = new AtomicBoolean(false);
private AtomicReference<String> errorMessage = new AtomicReference<>("");
public boolean isFlowFinished() {
return flowFinished.get();
}
public String getErrorMessage() {
return errorMessage.get();
}
@Override
public synchronized void onEvent(ScoreEvent scoreEvent) throws InterruptedException {
@SuppressWarnings("unchecked") Map<String, Serializable> data = (Map<String, Serializable>) scoreEvent.getData();
switch (scoreEvent.getEventType()) {
case EventConstants.SCORE_FINISHED_EVENT:
flowFinished.set(true);
break;
case EventConstants.SCORE_ERROR_EVENT :
errorMessage.set(SCORE_ERROR_EVENT_MSG + data.get(EventConstants.SCORE_ERROR_LOG_MSG) + " , " +
data.get(EventConstants.SCORE_ERROR_MSG));
break;
case EventConstants.SCORE_FAILURE_EVENT:
printWithColor(Ansi.Color.RED, FLOW_FINISHED_WITH_FAILURE_MSG);
flowFinished.set(true);
break;
case ScoreLangConstants.SLANG_EXECUTION_EXCEPTION:
errorMessage.set(SLANG_STEP_ERROR_MSG + data.get(EXCEPTION));
break;
case ScoreLangConstants.EVENT_INPUT_END:
String taskName = (String)data.get(LanguageEventData.levelName.TASK_NAME.name());
if(StringUtils.isNotEmpty(taskName)){
String path = (String) data.get(LanguageEventData.PATH);
int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
String prefix = StringUtils.repeat(TASK_PATH_PREFIX, matches);
printWithColor(Ansi.Color.YELLOW, prefix + taskName);
}
break;
case EVENT_EXECUTION_FINISHED:
if (!flowFinished.get()) {
flowFinished.set(true);
}
printFinishEvent(data);
break;
}
}
private void printFinishEvent(Map<String, Serializable> data) {
String flowResult = (String)data.get(RESULT);
String flowName = (String)data.get(LanguageEventData.levelName.EXECUTABLE_NAME.toString());
printWithColor(Ansi.Color.CYAN,"Flow : " + flowName + " finished with result : " + flowResult);
}
private void printWithColor(Ansi.Color color, String msg){
AnsiConsole.out().print(ansi().fg(color).a(msg).newline());
AnsiConsole.out().print(ansi().fg(Ansi.Color.WHITE));
}
}
=======
>>>>>>>
private class SyncTriggerEventListener implements ScoreEventListener{
private AtomicBoolean flowFinished = new AtomicBoolean(false);
private AtomicReference<String> errorMessage = new AtomicReference<>("");
public boolean isFlowFinished() {
return flowFinished.get();
}
public String getErrorMessage() {
return errorMessage.get();
}
@Override
public synchronized void onEvent(ScoreEvent scoreEvent) throws InterruptedException {
@SuppressWarnings("unchecked") Map<String,Serializable> data = (Map<String,Serializable>)scoreEvent.getData();
switch (scoreEvent.getEventType()){
case EventConstants.SCORE_FINISHED_EVENT :
flowFinished.set(true);
break;
case EventConstants.SCORE_ERROR_EVENT :
errorMessage.set(SCORE_ERROR_EVENT_MSG + data.get(EventConstants.SCORE_ERROR_LOG_MSG) + " , " +
data.get(EventConstants.SCORE_ERROR_MSG));
break;
case EventConstants.SCORE_FAILURE_EVENT :
printWithColor(Ansi.Color.RED,FLOW_FINISHED_WITH_FAILURE_MSG);
flowFinished.set(true);
break;
case ScoreLangConstants.SLANG_EXECUTION_EXCEPTION:
errorMessage.set(SLANG_STEP_ERROR_MSG + data.get(EXCEPTION));
break;
case ScoreLangConstants.EVENT_INPUT_END:
String taskName = (String)data.get(LanguageEventData.levelName.TASK_NAME.name());
if(StringUtils.isNotEmpty(taskName)){
String path = (String) data.get(LanguageEventData.PATH);
int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
String prefix = StringUtils.repeat(TASK_PATH_PREFIX, matches);
printWithColor(Ansi.Color.YELLOW, prefix + taskName);
}
break;
case EVENT_EXECUTION_FINISHED :
printFinishEvent(data);
break;
}
}
private void printFinishEvent(Map<String, Serializable> data) {
String flowResult = (String)data.get(RESULT);
String flowName = (String)data.get(LanguageEventData.levelName.EXECUTABLE_NAME.toString());
printWithColor(Ansi.Color.CYAN,"Flow : " + flowName + " finished with result : " + flowResult);
}
private void printWithColor(Ansi.Color color, String msg){
AnsiConsole.out().print(ansi().fg(color).a(msg).newline());
AnsiConsole.out().print(ansi().fg(Ansi.Color.WHITE));
}
} |
<<<<<<<
resolveVariables(inputs, imports);
=======
Map<String, SlangFileType> dependencies;
>>>>>>>
resolveVariables(inputs, imports);
Map<String, SlangFileType> dependencies;
<<<<<<<
private static void resolveVariables(List<Input> inputs, Map<String, String> imports) {
if(inputs == null) return;
for(Input input : inputs) {
String variableName = input.getVariableName();
if(variableName != null) {
variableName = resolveRefId(variableName, imports);
input.setVariableName(variableName);
}
}
}
private static String resolveRefId(String refIdString, Map<String, String> imports) {
String alias = StringUtils.substringBefore(refIdString, ".");
Validate.notNull(imports, "No imports specified");
if(!imports.containsKey(alias)) throw new RuntimeException("Unresovled alias: " + alias);
String refName = StringUtils.substringAfter(refIdString, ".");
return imports.get(alias) + "." + refName;
}
=======
private String resolveRefId(String refIdString, Map<String, String> imports) {
String importAlias = StringUtils.substringBefore(refIdString, ".");
String refName = StringUtils.substringAfter(refIdString, ".");
return imports.get(importAlias) + "." + refName;
}
/**
* Fetch the first level of the dependencies of the executable (non recursively)
* @param workflow the workflow of the flow
* @return a map of dependencies. Key - dependency full name, value - type
*/
private Map<String, SlangFileType> fetchDirectTasksDependencies(Workflow workflow){
Map<String, SlangFileType> dependencies = new HashMap<>();
Deque<Task> tasks = workflow.getTasks();
for (Task task : tasks) {
String refId = task.getRefId();
dependencies.put(refId, SlangFileType.EXECUTABLE);
}
return dependencies;
}
>>>>>>>
private static void resolveVariables(List<Input> inputs, Map<String, String> imports) {
if(inputs == null) return;
for(Input input : inputs) {
String variableName = input.getVariableName();
if(variableName != null) {
variableName = resolveRefId(variableName, imports);
input.setVariableName(variableName);
}
}
}
private static String resolveRefId(String refIdString, Map<String, String> imports) {
String alias = StringUtils.substringBefore(refIdString, ".");
Validate.notNull(imports, "No imports specified");
if(!imports.containsKey(alias)) throw new RuntimeException("Unresovled alias: " + alias);
String refName = StringUtils.substringAfter(refIdString, ".");
return imports.get(alias) + "." + refName;
}
/**
* Fetch the first level of the dependencies of the executable (non recursively)
* @param workflow the workflow of the flow
* @return a map of dependencies. Key - dependency full name, value - type
*/
private Map<String, SlangFileType> fetchDirectTasksDependencies(Workflow workflow){
Map<String, SlangFileType> dependencies = new HashMap<>();
Deque<Task> tasks = workflow.getTasks();
for (Task task : tasks) {
String refId = task.getRefId();
dependencies.put(refId, SlangFileType.EXECUTABLE);
}
return dependencies;
} |
<<<<<<<
=======
import io.cloudslang.score.events.ScoreEvent;
import io.cloudslang.score.lang.ExecutionRuntimeServices;
import io.cloudslang.lang.entities.LoopStatement;
import io.cloudslang.lang.entities.ResultNavigation;
import io.cloudslang.lang.entities.bindings.Input;
import io.cloudslang.lang.runtime.bindings.InputsBinding;
import io.cloudslang.lang.runtime.bindings.ScriptEvaluator;
import io.cloudslang.lang.runtime.env.Context;
import io.cloudslang.lang.runtime.env.ParentFlowData;
import io.cloudslang.lang.runtime.env.RunEnvironment;
import org.python.google.common.collect.Lists;
>>>>>>>
import org.python.google.common.collect.Lists;
<<<<<<<
import java.util.*;
=======
import java.util.*;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyMap;
>>>>>>>
import java.util.*;
<<<<<<<
@SuppressWarnings("unchecked")
List<String> inputsToBind = (List<String>)startBindingEventData.get(LanguageEventData.ARGUMENTS);
Assert.assertTrue(inputsToBind.contains("input1"));
Assert.assertTrue(inputsToBind.contains("input2"));
=======
@SuppressWarnings("unchecked")
List<String> inputsToBind = (List<String>)startBindingEventData.get(LanguageEventData.INPUTS);
Assert.assertEquals(
"Inputs are not in defined order in start binding event",
Lists.newArrayList("input1", "input2"),
inputsToBind
);
>>>>>>>
@SuppressWarnings("unchecked")
List<String> inputsToBind = (List<String>)startBindingEventData.get(LanguageEventData.ARGUMENTS);
Assert.assertEquals(
"Inputs are not in defined order in start binding event",
Lists.newArrayList("input1", "input2"),
inputsToBind
);
<<<<<<<
@SuppressWarnings("unchecked")
Map<String,Serializable> boundInputs = (Map<String,Serializable>)eventData.get(LanguageEventData.BOUND_ARGUMENTS);
Assert.assertEquals(5,boundInputs.get("input1"));
Assert.assertEquals(3,boundInputs.get("input2"));
=======
@SuppressWarnings("unchecked")
Map<String, Serializable> boundInputs = (Map<String,Serializable>)eventData.get(LanguageEventData.BOUND_INPUTS);
Assert.assertEquals(2, boundInputs.size());
// verify input names are in defined order and have the expected value
Set<Map.Entry<String, Serializable>> inputEntries = boundInputs.entrySet();
Iterator<Map.Entry<String, Serializable>> inputNamesIterator = inputEntries.iterator();
Map.Entry<String, Serializable> firstInput = inputNamesIterator.next();
Assert.assertEquals("Inputs are not in defined order in end inputs binding event", "input1", firstInput.getKey());
Assert.assertEquals(5,firstInput.getValue());
Map.Entry<String, Serializable> secondInput = inputNamesIterator.next();
Assert.assertEquals("Inputs are not in defined order in end inputs binding event", "input2", secondInput.getKey());
Assert.assertEquals(3,secondInput.getValue());
>>>>>>>
@SuppressWarnings("unchecked")
Map<String, Serializable> boundInputs = (Map<String,Serializable>)eventData.get(LanguageEventData.BOUND_ARGUMENTS);
Assert.assertEquals(2, boundInputs.size());
// verify input names are in defined order and have the expected value
Set<Map.Entry<String, Serializable>> inputEntries = boundInputs.entrySet();
Iterator<Map.Entry<String, Serializable>> inputNamesIterator = inputEntries.iterator();
Map.Entry<String, Serializable> firstInput = inputNamesIterator.next();
Assert.assertEquals("Inputs are not in defined order in end inputs binding event", "input1", firstInput.getKey());
Assert.assertEquals(5,firstInput.getValue());
Map.Entry<String, Serializable> secondInput = inputNamesIterator.next();
Assert.assertEquals("Inputs are not in defined order in end inputs binding event", "input2", secondInput.getKey());
Assert.assertEquals(3,secondInput.getValue()); |
<<<<<<<
void validateResultsSection(Map<String, Object> executableRawData, String artifact, List<RuntimeException> errors);
=======
Map<String, Map<String, Object>> validateOnFailurePosition(
List<Map<String, Map<String, Object>>> workFlowRawData,
String execName,
List<RuntimeException> errors);
>>>>>>>
Map<String, Map<String, Object>> validateOnFailurePosition(
List<Map<String, Map<String, Object>>> workFlowRawData,
String execName,
List<RuntimeException> errors);
void validateResultsSection(Map<String, Object> executableRawData, String artifact, List<RuntimeException> errors); |
<<<<<<<
import static io.cloudslang.lang.compiler.SlangTextualKeys.OVERRIDABLE_KEY;
=======
import static io.cloudslang.lang.compiler.SlangTextualKeys.ENCRYPTED_KEY;
import static io.cloudslang.lang.compiler.SlangTextualKeys.PRIVATE_INPUT_KEY;
>>>>>>>
import static io.cloudslang.lang.compiler.SlangTextualKeys.PRIVATE_INPUT_KEY;
<<<<<<<
List<String> knownKeys = Arrays.asList(REQUIRED_KEY, SENSITIVE_KEY, OVERRIDABLE_KEY, DEFAULT_KEY);
=======
List<String> knownKeys = Arrays.asList(REQUIRED_KEY, ENCRYPTED_KEY, PRIVATE_INPUT_KEY, DEFAULT_KEY);
>>>>>>>
List<String> knownKeys = Arrays.asList(REQUIRED_KEY, SENSITIVE_KEY, PRIVATE_INPUT_KEY, DEFAULT_KEY);
<<<<<<<
// default is sensitive=false
boolean sensitive = props.containsKey(SENSITIVE_KEY) &&
(boolean) props.get(SENSITIVE_KEY);
// default is overridable=true
boolean overridable = !props.containsKey(OVERRIDABLE_KEY) ||
(boolean) props.get(OVERRIDABLE_KEY);
=======
// default is encrypted=false
boolean encrypted = props.containsKey(ENCRYPTED_KEY) &&
(boolean) props.get(ENCRYPTED_KEY);
// default is private=false
boolean privateInput = props.containsKey(PRIVATE_INPUT_KEY) &&
(boolean) props.get(PRIVATE_INPUT_KEY);
>>>>>>>
// default is sensitive=false
boolean sensitive = props.containsKey(SENSITIVE_KEY) &&
(boolean) props.get(SENSITIVE_KEY);
// default is overridable=true
boolean privateInput = props.containsKey(PRIVATE_INPUT_KEY) &&
(boolean) props.get(PRIVATE_INPUT_KEY);
<<<<<<<
return createInput(inputName, value, sensitive, required, overridable);
=======
return createInput(inputName, value, encrypted, required, privateInput);
>>>>>>>
return createInput(inputName, value, sensitive, required, privateInput); |
<<<<<<<
workFlowRawData = (List) executableRawData.get(SlangTextualKeys.WORKFLOW_KEY);
=======
workFlowRawData = (LinkedHashMap) executableRawData.get(WORKFLOW_KEY);
>>>>>>>
workFlowRawData = (List) executableRawData.get(WORKFLOW_KEY);
<<<<<<<
List<Map<String, Map<String, Object>>> onFailureData;
Iterator<Map<String, Map<String, Object>>> tasksIterator = workFlowRawData.iterator();
while(tasksIterator.hasNext()){
Map<String, Map<String, Object>> taskData = tasksIterator.next();
String taskName = taskData.keySet().iterator().next();
if(taskName.equals(SlangTextualKeys.ON_FAILURE_KEY)){
try{
onFailureData = (List<Map<String, Map<String, Object>>>)taskData.values().iterator().next();
} catch (ClassCastException ex){
throw new RuntimeException("Flow: '" + execName + "' syntax is illegal.\nBelow 'on_failure' property there should be a list of tasks and not a map");
}
if (CollectionUtils.isNotEmpty(onFailureData)) {
onFailureWorkFlow = compileWorkFlow(onFailureData, imports, null, true);
}
tasksIterator.remove();
break;
}
=======
LinkedHashMap<String, Map<String, Object>> onFailureData;
try{
onFailureData = (LinkedHashMap) workFlowRawData.remove(ON_FAILURE_KEY);
} catch (ClassCastException ex){
throw new RuntimeException("Flow: '" + execName + "' syntax is illegal.\nBelow 'on_failure' property there should be a map of tasks and not a list");
}
if (MapUtils.isNotEmpty(onFailureData)) {
onFailureWorkFlow = compileWorkFlow(onFailureData, imports, null, true);
>>>>>>>
List<Map<String, Map<String, Object>>> onFailureData;
Iterator<Map<String, Map<String, Object>>> tasksIterator = workFlowRawData.iterator();
while(tasksIterator.hasNext()){
Map<String, Map<String, Object>> taskData = tasksIterator.next();
String taskName = taskData.keySet().iterator().next();
if(taskName.equals(ON_FAILURE_KEY)){
try{
onFailureData = (List<Map<String, Map<String, Object>>>)taskData.values().iterator().next();
} catch (ClassCastException ex){
throw new RuntimeException("Flow: '" + execName + "' syntax is illegal.\nBelow 'on_failure' property there should be a list of tasks and not a map");
}
if (CollectionUtils.isNotEmpty(onFailureData)) {
onFailureWorkFlow = compileWorkFlow(onFailureData, imports, null, true);
}
tasksIterator.remove();
break;
}
<<<<<<<
taskRawDataValue = taskRawData.values().iterator().next();
=======
taskRawDataValue = taskRawData.getValue();
if (MapUtils.isNotEmpty(taskRawDataValue) && taskRawDataValue.containsKey(LOOP_KEY)) {
message = "Task: " + taskName + " syntax is illegal.\nBelow the 'loop' keyword, there should be a map of values in the format:\nfor:\ndo:\n\top_name:";
taskRawDataValue.putAll((Map<String, Object>) taskRawDataValue.remove(LOOP_KEY));
}
>>>>>>>
taskRawDataValue = taskRawData.values().iterator().next();
if (MapUtils.isNotEmpty(taskRawDataValue) && taskRawDataValue.containsKey(LOOP_KEY)) {
message = "Task: " + taskName + " syntax is illegal.\nBelow the 'loop' keyword, there should be a map of values in the format:\nfor:\ndo:\n\top_name:";
taskRawDataValue.putAll((Map<String, Object>) taskRawDataValue.remove(LOOP_KEY));
} |
<<<<<<<
private final boolean encrypted;
private final boolean required;
private final boolean overridable;
private final String systemPropertyName;
=======
private boolean encrypted;
private boolean required;
private boolean overridable;
private String systemPropertyName;
>>>>>>>
private boolean encrypted;
private boolean required;
private boolean overridable;
private String systemPropertyName;
<<<<<<<
=======
public void setSystemPropertyName(String systemPropertyName) {
this.systemPropertyName = systemPropertyName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Input that = (Input) o;
return new EqualsBuilder()
.appendSuper(super.equals(that))
.append(this.encrypted, that.encrypted)
.append(this.required, that.required)
.append(this.overridable, that.overridable)
.append(this.systemPropertyName, that.systemPropertyName)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.appendSuper(super.hashCode())
.append(encrypted)
.append(required)
.append(overridable)
.append(systemPropertyName)
.toHashCode();
}
>>>>>>> |
<<<<<<<
@Override
public void validateNoDuplicateInputs(List<Input> inputs, Input element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(inputs);
String message = "Duplicate input found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
@Override
public void validateNoDuplicateStepInputs(List<Argument> inputs, Argument element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(inputs);
String message = "Duplicate step input found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
@Override
public void validateNoDuplicateOutputs(List<Output> outputs, Output element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(outputs);
String message = "Duplicate output / publish value found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
@Override
public void validateNoDuplicateResults(List<Result> results, Result element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(results);
String message = "Duplicate result found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
public String getExecutableName(Map<String, Object> executableRawData) {
=======
private String getExecutableName(Map<String, Object> executableRawData) {
>>>>>>>
@Override
public void validateNoDuplicateInputs(List<Input> inputs, Input element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(inputs);
String message = "Duplicate input found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
@Override
public void validateNoDuplicateStepInputs(List<Argument> inputs, Argument element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(inputs);
String message = "Duplicate step input found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
@Override
public void validateNoDuplicateOutputs(List<Output> outputs, Output element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(outputs);
String message = "Duplicate output / publish value found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
@Override
public void validateNoDuplicateResults(List<Result> results, Result element) {
Collection<InOutParam> inOutParams = new ArrayList<>();
inOutParams.addAll(results);
String message = "Duplicate result found: " + element.getName();
validateNotDuplicateInOutParam(inOutParams, element, message);
}
private String getExecutableName(Map<String, Object> executableRawData) { |
<<<<<<<
import org.apache.commons.lang.StringUtils;
=======
import org.apache.commons.collections4.MapUtils;
>>>>>>>
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
<<<<<<<
@CliOption(key = {"i", "inputs"}, mandatory = false, help = "inputs in a key=value comma separated list") final Map<String, Serializable> inputs,
@CliOption(key = {"", "q", "quiet"}, mandatory = false, help = "quiet", specifiedDefaultValue = "true",unspecifiedDefaultValue = "false") final Boolean quiet,
=======
@CliOption(key = {"i", "inputs"}, mandatory = false, help = "inputs in a key=value comma separated list") final Map<String,? extends Serializable> inputs,
@CliOption(key = {"if", "input-file"}, mandatory = false, help = "comma separated list of input file locations") final List<String> inputFiles,
>>>>>>>
@CliOption(key = {"i", "inputs"}, mandatory = false, help = "inputs in a key=value comma separated list") final Map<String,? extends Serializable> inputs,
@CliOption(key = {"if", "input-file"}, mandatory = false, help = "comma separated list of input file locations") final List<String> inputFiles,
@CliOption(key = {"", "q", "quiet"}, mandatory = false, help = "quiet", specifiedDefaultValue = "true",unspecifiedDefaultValue = "false") final Boolean quiet,
<<<<<<<
id = scoreServices.triggerSync(compilationArtifact, inputs, systemProperties, quiet);
=======
id = scoreServices.triggerSync(compilationArtifact, mergedInputs, systemProperties);
>>>>>>>
id = scoreServices.triggerSync(compilationArtifact, mergedInputs, systemProperties, quiet);
<<<<<<<
id = scoreServices.trigger(compilationArtifact, inputs, systemProperties);
return quiet ? StringUtils.EMPTY : triggerAsyncMsg(id, compilationArtifact.getExecutionPlan().getName());
=======
id = scoreServices.trigger(compilationArtifact, mergedInputs, systemProperties);
return triggerAsyncMsg(id, compilationArtifact.getExecutionPlan().getName());
>>>>>>>
id = scoreServices.trigger(compilationArtifact, inputs, systemProperties);
return quiet ? StringUtils.EMPTY : triggerAsyncMsg(id, compilationArtifact.getExecutionPlan().getName()); |
<<<<<<<
=======
import io.cloudslang.utils.ValidationUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
>>>>>>>
import io.cloudslang.utils.ValidationUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; |
<<<<<<<
public void testAsyncLoopBoundExpression() {
List<Value> asyncLoopBoundExpression = new ArrayList<>(Arrays.asList(ValueFactory.create("a"), ValueFactory.create("b"), ValueFactory.create("c")));
eventData.setAsyncLoopBoundExpression(asyncLoopBoundExpression);
assertEquals(asyncLoopBoundExpression, eventData.getAsyncLoopBoundExpression());
assertEquals(asyncLoopBoundExpression, eventData.get(LanguageEventData.BOUND_ASYNC_LOOP_EXPRESSION));
=======
public void testParallelLoopBoundExpression() {
List<Serializable> parallelLoopBoundExpression = new ArrayList<Serializable>(Arrays.asList("a", "b", "c"));
eventData.setParallelLoopBoundExpression(parallelLoopBoundExpression);
assertEquals(parallelLoopBoundExpression, eventData.getParallelLoopBoundExpression());
assertEquals(parallelLoopBoundExpression, eventData.get(LanguageEventData.BOUND_PARALLEL_LOOP_EXPRESSION));
>>>>>>>
public void testParallelLoopBoundExpression() {
List<Serializable> parallelLoopBoundExpression = new ArrayList<>(Arrays.asList(ValueFactory.create("a"), ValueFactory.create("b"), ValueFactory.create("c")));
eventData.setParallelLoopBoundExpression(parallelLoopBoundExpression);
assertEquals(parallelLoopBoundExpression, eventData.getParallelLoopBoundExpression());
assertEquals(parallelLoopBoundExpression, eventData.get(LanguageEventData.BOUND_PARALLEL_LOOP_EXPRESSION)); |
<<<<<<<
private final static Logger logger = Logger.getLogger(SlangCLI.class);
=======
private final static Logger logger = Logger.getLogger(SlangCLI.class);
>>>>>>>
private final static Logger logger = Logger.getLogger(SlangCLI.class);
<<<<<<<
public static final String RUN_HELP = "triggers a CloudSlang flow";
public static final String FILE_HELP = "Path to filename. e.g. cslang>run --f c:/.../your_flow.sl";
public static final String CLASSPATH_HELP = "Classpath, a directory comma separated list to flow dependencies, by default it will take flow file dir. " +
"e.g. cslang>run --f c:/.../your_flow.sl --i input1=root,input2=25 --cp c:/.../yaml";
public static final String INPUTS_HELP = "inputs in a key=value comma separated list. " +
"e.g. cslang>run --f c:/.../your_flow.sl --i input1=root,input2=25";
public static final String INPUT_FILE_HELP = "comma separated list of input file locations. " +
"e.g. cslang>run --f C:/.../your_flow.sl --if C:/.../inputs.yaml";
public static final String QUIET_HELP = "quiet. e.g. cslang>run --f c:/.../your_flow.sl --q";
public static final String DEBUG_HELP = "print each task outputs. e.g. cslang>run --f c:/.../your_flow.sl --d";
public static final String SYSTEM_PROPERTY_FILE_HELP = "comma separated list of system property file locations. " +
"e.g. cslang>run --f c:/.../your_flow.sl --spf c:/.../yaml";
public static final String ENV_HELP = "Set environment var relevant to the CLI";
public static final String SET_ASYNC_HELP = "set the async. e.g. cslang> env --setAsync true";
public static final String CSLANG_VERSION_HELP = "Prints the CloudSlang version used";
public static final String INPUTS_COMMAND_HELP = "Get flow inputs";
=======
public static final String QUIET = "quiet";
public static final String DEBUG = "debug";
public static final String DEFAULT = "default";
>>>>>>>
public static final String RUN_HELP = "triggers a CloudSlang flow";
public static final String FILE_HELP = "Path to filename. e.g. cslang>run --f c:/.../your_flow.sl";
public static final String CLASSPATH_HELP = "Classpath, a directory comma separated list to flow dependencies, by default it will take flow file dir. " +
"e.g. cslang>run --f c:/.../your_flow.sl --i input1=root,input2=25 --cp c:/.../yaml";
public static final String INPUTS_HELP = "inputs in a key=value comma separated list. " +
"e.g. cslang>run --f c:/.../your_flow.sl --i input1=root,input2=25";
public static final String INPUT_FILE_HELP = "comma separated list of input file locations. " +
"e.g. cslang>run --f C:/.../your_flow.sl --if C:/.../inputs.yaml";
public static final String QUIET_HELP = "quiet. e.g. cslang>run --f c:/.../your_flow.sl --q";
public static final String DEBUG_HELP = "print each task outputs. e.g. cslang>run --f c:/.../your_flow.sl --d";
public static final String SYSTEM_PROPERTY_FILE_HELP = "comma separated list of system property file locations. " +
"e.g. cslang>run --f c:/.../your_flow.sl --spf c:/.../yaml";
public static final String ENV_HELP = "Set environment var relevant to the CLI";
public static final String SET_ASYNC_HELP = "set the async. e.g. cslang> env --setAsync true";
public static final String CSLANG_VERSION_HELP = "Prints the CloudSlang version used";
public static final String INPUTS_COMMAND_HELP = "Get flow inputs";
public static final String QUIET = "quiet";
public static final String DEBUG = "debug";
public static final String DEFAULT = "default";
<<<<<<<
@CliOption(key = {"", "f", "file"}, mandatory = true, help = FILE_HELP) final File file,
@CliOption(key = {"cp", "classpath"}, mandatory = false, help = CLASSPATH_HELP) final List<String> classPath,
@CliOption(key = {"i", "inputs"}, mandatory = false, help = INPUTS_HELP) final Map<String,? extends Serializable> inputs,
@CliOption(key = {"if", "input-file"}, mandatory = false, help = INPUT_FILE_HELP) final List<String> inputFiles,
@CliOption(key = {"", "q", "quiet"}, mandatory = false, help = QUIET_HELP, specifiedDefaultValue = "true",unspecifiedDefaultValue = "false") final Boolean quiet,
@CliOption(key = {"", "d", "debug"}, mandatory = false, help = DEBUG_HELP, specifiedDefaultValue = "true",unspecifiedDefaultValue = "false") final Boolean debug,
@CliOption(key = {"spf", "system-property-file"}, mandatory = false, help = SYSTEM_PROPERTY_FILE_HELP) final List<String> systemPropertyFiles) throws IOException {
=======
@CliOption(key = {"", "f", "file"}, mandatory = true, help = "Path to filename. e.g. cslang run --f C:\\CloudSlang\\flow.yaml") final File file,
@CliOption(key = {"cp", "classpath"}, mandatory = false, help = "Classpath , a directory comma separated list to flow dependencies, by default it will take flow file dir") final List<String> classPath,
@CliOption(key = {"i", "inputs"}, mandatory = false, help = "inputs in a key=value comma separated list") final Map<String,? extends Serializable> inputs,
@CliOption(key = {"if", "input-file"}, mandatory = false, help = "comma separated list of input file locations") final List<String> inputFiles,
@CliOption(key = {"v", "verbose"}, mandatory = false, help = "default, quiet, debug(print each task outputs). e.g. cslang>run --f c:/.../your_flow.sl --v quiet", specifiedDefaultValue = "debug", unspecifiedDefaultValue = "default") final String verbose,
@CliOption(key = {"spf", "system-property-file"}, mandatory = false, help = "comma separated list of system property file locations") final List<String> systemPropertyFiles) throws IOException {
>>>>>>>
@CliOption(key = {"", "f", "file"}, mandatory = true, help = FILE_HELP) final File file,
@CliOption(key = {"cp", "classpath"}, mandatory = false, help = CLASSPATH_HELP) final List<String> classPath,
@CliOption(key = {"i", "inputs"}, mandatory = false, help = INPUTS_HELP) final Map<String,? extends Serializable> inputs,
@CliOption(key = {"if", "input-file"}, mandatory = false, help = INPUT_FILE_HELP) final List<String> inputFiles,
@CliOption(key = {"v", "verbose"}, mandatory = false, help = "default, quiet, debug(print each task outputs). e.g. cslang>run --f c:/.../your_flow.sl --v quiet", specifiedDefaultValue = "debug", unspecifiedDefaultValue = "default") final String verbose,
@CliOption(key = {"spf", "system-property-file"}, mandatory = false, help = SYSTEM_PROPERTY_FILE_HELP) final List<String> systemPropertyFiles) throws IOException {
<<<<<<<
@CliCommand(value = "env", help = ENV_HELP)
=======
private boolean invalidVerboseInput(String verbose) {
String[] validArguments = {DEFAULT, QUIET, DEBUG};
return !Arrays.asList(validArguments).contains(verbose.toLowerCase());
}
@CliCommand(value = "env", help = "Set environment var relevant to the CLI")
>>>>>>>
private boolean invalidVerboseInput(String verbose) {
String[] validArguments = {DEFAULT, QUIET, DEBUG};
return !Arrays.asList(validArguments).contains(verbose.toLowerCase());
}
@CliCommand(value = "env", help = ENV_HELP) |
<<<<<<<
=======
import java.util.stream.Collectors;
import java.util.Set;
>>>>>>>
<<<<<<<
private WorkerGroupMetadata computeWorkerGroup(WorkerGroupStatement workerGroup,
Context flowContext,
RunEnvironment runEnv,
String expression) {
Value workerGroupValue;
if (workerGroup.getFunctionDependencies() == null && workerGroup.getSystemPropertyDependencies() == null) {
workerGroupValue = ValueFactory.create(expression);
=======
private void handleRobotGroup(RobotGroupStatement robotGroup,
Context flowContext,
RunEnvironment runEnv,
ExecutionRuntimeServices execRuntimeServices) {
String robotGroupValue = DEFAULT_ROBOT_GROUP;
if (robotGroup != null) {
robotGroupValue = computeWorkerValue(robotGroup.getFunctionDependencies(),
robotGroup.getSystemPropertyDependencies(),
flowContext, runEnv, robotGroup.getExpression());
} else if (isNotEmpty(execRuntimeServices.getRobotGroupName())) {
robotGroupValue = execRuntimeServices.getRobotGroupName();
}
execRuntimeServices.setRobotGroupName(robotGroupValue);
}
private String computeWorkerValue(Set<ScriptFunction> scriptFunctionSet,
Set<String> systemProperties,
Context flowContext,
RunEnvironment runEnv,
String expression) {
Value resolvedValue;
if (isEmpty(scriptFunctionSet) && isEmpty(systemProperties)) {
resolvedValue = ValueFactory.create(expression);
>>>>>>>
private void handleRobotGroup(RobotGroupStatement robotGroup,
Context flowContext,
RunEnvironment runEnv,
ExecutionRuntimeServices execRuntimeServices) {
String robotGroupValue = DEFAULT_ROBOT_GROUP;
if (robotGroup != null) {
robotGroupValue = computeWorkerValue(robotGroup.getFunctionDependencies(),
robotGroup.getSystemPropertyDependencies(),
flowContext, runEnv, robotGroup.getExpression());
} else if (isNotEmpty(execRuntimeServices.getRobotGroupName())) {
robotGroupValue = execRuntimeServices.getRobotGroupName();
}
execRuntimeServices.setRobotGroupName(robotGroupValue);
}
private String computeWorkerValue(Set<ScriptFunction> scriptFunctionSet,
Set<String> systemProperties,
Context flowContext,
RunEnvironment runEnv,
String expression) {
Value resolvedValue;
if (isEmpty(scriptFunctionSet) && isEmpty(systemProperties)) {
resolvedValue = ValueFactory.create(expression); |
<<<<<<<
import dyvil.tools.compiler.ast.reference.ReferenceType;
import dyvil.tools.compiler.ast.structure.IClassCompilableList;
=======
>>>>>>>
import dyvil.tools.compiler.ast.reference.ReferenceType; |
<<<<<<<
=======
import io.cloudslang.runtime.api.java.JavaRuntimeService;
import io.cloudslang.runtime.api.python.PythonRuntimeService;
import io.cloudslang.runtime.impl.java.JavaExecutionCachedEngine;
import io.cloudslang.runtime.impl.java.JavaRuntimeServiceImpl;
import io.cloudslang.runtime.impl.python.PythonExecutionCachedEngine;
import io.cloudslang.runtime.impl.python.PythonExecutionEngine;
import io.cloudslang.runtime.impl.python.PythonRuntimeServiceImpl;
>>>>>>>
import io.cloudslang.runtime.api.java.JavaRuntimeService;
import io.cloudslang.runtime.api.python.PythonRuntimeService;
import io.cloudslang.runtime.impl.java.JavaExecutionCachedEngine;
import io.cloudslang.runtime.impl.java.JavaRuntimeServiceImpl;
import io.cloudslang.runtime.impl.python.PythonExecutionCachedEngine;
import io.cloudslang.runtime.impl.python.PythonExecutionEngine;
import io.cloudslang.runtime.impl.python.PythonRuntimeServiceImpl;
<<<<<<<
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
=======
import java.util.*;
>>>>>>>
import java.util.*; |
<<<<<<<
void validateNoDuplicateInputs(List<Input> inputs, Input element);
void validateNoDuplicateStepInputs(List<Argument> inputs, Argument element);
void validateNoDuplicateOutputs(List<Output> outputs, Output element);
void validateNoDuplicateResults(List<Result> results, Result element);
=======
void validateResultsSection(Map<String, Object> executableRawData, String artifact, List<RuntimeException> errors);
>>>>>>>
void validateResultsSection(Map<String, Object> executableRawData, String artifact, List<RuntimeException> errors);
void validateNoDuplicateInputs(List<Input> inputs, Input element);
void validateNoDuplicateStepInputs(List<Argument> inputs, Argument element);
void validateNoDuplicateOutputs(List<Output> outputs, Output element);
void validateNoDuplicateResults(List<Result> results, Result element); |
<<<<<<<
=======
import java.util.ArrayList;
import org.junit.Assert;
>>>>>>>
import java.util.ArrayList;
import org.junit.Assert;
<<<<<<<
import org.junit.Assert;
=======
import org.junit.Before;
>>>>>>>
import org.junit.Before;
<<<<<<<
runEnv.putCallArguments(new HashMap<String, Value>());
Map<String, Object> nonSerializableExecutionData = new HashMap<>();
=======
runEnv.putCallArguments(new HashMap<String, Serializable>());
>>>>>>>
runEnv.putCallArguments(new HashMap<String, Value>()); |
<<<<<<<
@Override
public Type getType() {
return Type.INTERNAL;
}
private Argument transformListArgument(Object rawArgument) {
=======
private Argument transformListArgument(Object rawArgument, SensitivityLevel sensitivityLevel) {
>>>>>>>
@Override
public Type getType() {
return Type.INTERNAL;
}
private Argument transformListArgument(Object rawArgument, SensitivityLevel sensitivityLevel) { |
<<<<<<<
cl.register("/heal", "heal", "heal yourself or other players");
cl.register("/suicide", "suicide", "kill yourself... you loser");
=======
cl.register("/modify", "modifySplit");
>>>>>>>
cl.register("/heal", "heal", "heal yourself or other players");
cl.register("/suicide", "suicide", "kill yourself... you loser");
cl.register("/modify", "modifySplit"); |
<<<<<<<
String[] myLocale = Config.getLocale().split("[-_ ]");
=======
>>>>>>> |
<<<<<<<
boolean fish = false;
boolean herb = false;
=======
int FoodRank1 = advancedConfig.getFarmerDietRankChange();
int FoodRank2 = advancedConfig.getFarmerDietRankChange() * 2;
int FoodRankMax = advancedConfig.getFarmerDietRankChange() * 5;
>>>>>>>
boolean fish = false;
boolean herb = false;
int FoodRank1 = advancedConfig.getFarmerDietRankChange();
int FoodRank2 = advancedConfig.getFarmerDietRankChange() * 2;
int FoodRankMax = advancedConfig.getFarmerDietRankChange() * 5;
<<<<<<<
rankChange = 200;
herb = true;
=======
rankChange = FoodRank1;
>>>>>>>
herb = true;
rankChange = FoodRank1;
<<<<<<<
rankChange = 400;
herb = true;
=======
rankChange = FoodRank2;
>>>>>>>
herb = true;
rankChange = FoodRank2;
<<<<<<<
rankChange = 400;
herb = true;
=======
rankChange = FoodRank2;
>>>>>>>
herb = true;
rankChange = FoodRank2;
<<<<<<<
rankChange = 200;
herb = true;
=======
rankChange = FoodRank1;
>>>>>>>
herb = true;
rankChange = FoodRank1;
<<<<<<<
rankChange = 200;
herb = true;
=======
rankChange = FoodRank1;
>>>>>>>
herb = true;
rankChange = FoodRank1;
<<<<<<<
rankChange = 400;
herb = true;
=======
rankChange = FoodRank2;
>>>>>>>
herb = true;
rankChange = FoodRank2;
<<<<<<<
rankChange = 200;
herb = true;
=======
rankChange = FoodRank1;
>>>>>>>
herb = true;
rankChange = FoodRank1;
<<<<<<<
rankChange = 400;
herb = true;
=======
rankChange = FoodRank2;
>>>>>>>
herb = true;
rankChange = FoodRank2;
<<<<<<<
rankChange = 200;
herb = true;
=======
rankChange = FoodRank1;
>>>>>>>
herb = true;
rankChange = FoodRank1;
<<<<<<<
rankChange = 200;
herb = true;
break;
case RAW_FISH:
/* RAW FISH RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
rankChange = 400;
fish = true;
break;
case COOKED_FISH:
/* COOKED FISH RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
rankChange = 200;
fish = true;
=======
rankChange = FoodRank1;
>>>>>>>
herb = true;
rankChange = FoodRank1;
break;
case RAW_FISH:
/* RAW FISH RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
rankChange = 400;
fish = true;
break;
case COOKED_FISH:
/* COOKED FISH RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
rankChange = 200;
fish = true;
<<<<<<<
if (herb && !Permissions.getInstance().farmersDiet(player)) {
return;
}
else if (fish && !Permissions.getInstance().fishermansDiet(player)) {
return;
}
for (int i = 200; i <= 1000; i += rankChange) {
if ((herb && herbLevel >= i) || (fish && fishLevel >= i)) {
=======
for (int i = FoodRank1; i <= FoodRankMax; i += rankChange) {
if (herbLevel >= i) {
>>>>>>>
if (herb && !Permissions.getInstance().farmersDiet(player)) {
return;
}
else if (fish && !Permissions.getInstance().fishermansDiet(player)) {
return;
}
for (int i = FoodRank1; i <= FoodRankMax; i += rankChange) {
if ((herb && herbLevel >= i) || (fish && fishLevel >= i)) { |
<<<<<<<
import phylonet.tree.model.TMutableNode;
=======
import javafx.util.Pair;
>>>>>>>
import phylonet.tree.model.TMutableNode;
<<<<<<<
private WeightCalculatorAlgorithm algorithm;
private int polytomies;
public WQWeightCalculator(AbstractInference<Tripartition> inference,
int polytomies) {
=======
private WeightCalculatorAlgorithm algorithm, tmpalgorithm;
public WQWeightCalculator(AbstractInference<Tripartition> inference) {
>>>>>>>
private WeightCalculatorAlgorithm algorithm, tmpalgorithm;
private int polytomies;
public WQWeightCalculator(AbstractInference<Tripartition> inference,
int polytomie) {
<<<<<<<
this.setPolytomies(polytomies);
=======
//this.algorithm = new CondensedTraversalWeightCalculator();
tmpalgorithm = new TraversalWeightCalculator();
//tmpalgorithm.setupGeneTrees((WQInference) inference);
>>>>>>>
this.setPolytomies(polytomies);
this.algorithm = new CondensedTraversalWeightCalculator();
tmpalgorithm = new TraversalWeightCalculator();
//tmpalgorithm.setupGeneTrees((WQInference) inference);
<<<<<<<
=======
long F(int[] x, int[] y, int[] z){
long a = x[0], b = x[1], c = x[2], d = y[0], e = y[1], f = y[2], g = z[0], h = z[1], i = z[2];
return (a + e + i - 3) * a * e * i + (a + f + h - 3) * a * f * h
+ (b + d + i - 3) * b * d * i + (b + f + g - 3) * b * f * g
+ (c + d + h - 3) * c * d * h + (c + e + g - 3) * c * e * g;
}
>>>>>>>
long F(int[] x, int[] y, int[] z){
long a = x[0], b = x[1], c = x[2], d = y[0], e = y[1], f = y[2], g = z[0], h = z[1], i = z[2];
return (a + e + i - 3) * a * e * i + (a + f + h - 3) * a * f * h
+ (b + d + i - 3) * b * d * i + (b + f + g - 3) * b * f * g
+ (c + d + h - 3) * c * d * h + (c + e + g - 3) * c * e * g;
}
<<<<<<<
* ASTRAL-II way of calculating weights
*
=======
* one of ASTRAL-IV way of calculating weights
* Should be memory efficient
* @author chaoszhang
*
*/
class CondensedTraversalWeightCalculator extends WeightCalculatorAlgorithm {
Polytree polytree;
Long calculateWeight(Tripartition trip) {
return polytree.WQWeightByTraversal(trip, this);
}
/***
* Each gene tree is represented as a list of integers, using positive numbers
* for leaves, where the number gives the index of the leaf.
* We use negative numbers for internal nodes, where the value gives the number of children.
* Minus infinity is used for separating different genes.
*/
@Override
void setupGeneTrees(WQInference inference) {
polytree = new Polytree(inference.trees);
}
}
/**
* ASTRAL-II way of calculating weights
>>>>>>>
* one of ASTRAL-IV way of calculating weights
* Should be memory efficient
* @author chaoszhang
*
*/
class CondensedTraversalWeightCalculator extends WeightCalculatorAlgorithm {
Polytree polytree;
Long calculateWeight(Tripartition trip) {
return polytree.WQWeightByTraversal(trip, this);
}
/***
* Each gene tree is represented as a list of integers, using positive numbers
* for leaves, where the number gives the index of the leaf.
* We use negative numbers for internal nodes, where the value gives the number of children.
* Minus infinity is used for separating different genes.
*/
@Override
void setupGeneTrees(WQInference inference, boolean randomResolve) {
polytree = new Polytree(inference.trees, polytomies, randomResolve);
}
}
/**
* ASTRAL-II way of calculating weights
<<<<<<<
=======
/***
* Each gene tree is represented as a list of integers, using positive numbers
* for leaves, where the number gives the index of the leaf.
* We use negative numbers for internal nodes, where the value gives the number of children.
* Minus infinity is used for separating different genes.
*/
>>>>>>>
/***
* Each gene tree is represented as a list of integers, using positive numbers
* for leaves, where the number gives the index of the leaf.
* We use negative numbers for internal nodes, where the value gives the number of children.
* Minus infinity is used for separating different genes.
*/
<<<<<<<
public void setupGeneTrees(WQInference wqInference, boolean randomResolve) {
this.algorithm.setupGeneTrees(wqInference,randomResolve);
=======
public void setupGeneTrees(WQInference wqInference) {
this.algorithm.setupGeneTrees(wqInference);
tmpalgorithm.setupGeneTrees(wqInference);
>>>>>>>
public void setupGeneTrees(WQInference wqInference, boolean randomResolve) {
this.algorithm.setupGeneTrees(wqInference,randomResolve);
tmpalgorithm.setupGeneTrees(wqInference,randomResolve);
<<<<<<<
return ((TraversalWeightCalculator) algorithm).geneTreesAsInts;
=======
return ((TraversalWeightCalculator)tmpalgorithm).geneTreesAsInts;
>>>>>>>
return ((TraversalWeightCalculator)tmpalgorithm).geneTreesAsInts; |
<<<<<<<
import phylonet.tree.model.TMutableNode;
=======
import phylonet.tree.model.TMutableNode;
>>>>>>>
import phylonet.tree.model.TMutableNode;
<<<<<<<
private WeightCalculatorAlgorithm algorithm, tmpalgorithm;
private int polytomies;
=======
WeightCalculatorAlgorithm algorithm;
private WeightCalculatorAlgorithm tmpalgorithm;
>>>>>>>
WeightCalculatorAlgorithm algorithm;
private WeightCalculatorAlgorithm tmpalgorithm;
<<<<<<<
this.setPolytomies(polytomies);
//this.algorithm = new TraversalWeightCalculator();
this.algorithm = new CondensedTraversalWeightCalculator();
=======
//this.algorithm = new TraversalWeightCalculator();
this.algorithm = new CondensedTraversalWeightCalculator();
>>>>>>>
//this.algorithm = new TraversalWeightCalculator();
this.algorithm = new CondensedTraversalWeightCalculator();
<<<<<<<
void setupGeneTrees(WQInference inference, boolean randomResolve) {
System.err.println("Using polytree-based weight calculation and please ignore any debug message saying it is tree-based.");
polytree = new Polytree(inference.trees, polytomies, randomResolve, dataCollection);
=======
void setupGeneTrees(WQInference inference) {
polytree = new Polytree(inference.trees, dataCollection);
>>>>>>>
void setupGeneTrees(WQInference inference) {
polytree = new Polytree(inference.trees, dataCollection);
<<<<<<<
=======
for (Tree tr : inference.trees) {
List<STINode> children = new ArrayList<STINode>();
int n = tr.getLeafCount()/2;
int dist = n;
TNode newroot = tr.getRoot();
for (TNode node : tr.postTraverse()) {
if (!node.isLeaf()) {
for (TNode child : node.getChildren()) {
if (child.isLeaf()) {
children.add((STINode) child);
break;
}
}
if (Math.abs(n - node.getLeafCount()) < dist) {
newroot = node;
dist = n - node.getLeafCount();
}
}
}
for (STINode child: children) {
STINode snode = child.getParent();
snode.removeChild((TMutableNode) child, false);
TMutableNode newChild = snode.createChild(child);
if (child == newroot) {
newroot = newChild;
}
}
if (newroot != tr.getRoot())
((STITree)(tr)).rerootTreeAtEdge(newroot);
>>>>>>>
<<<<<<<
// System.err.println(tr);
=======
//System.err.println(tr);
>>>>>>> |
<<<<<<<
TradeMessage tradeMessage = GsonUtil.GSON.fromJson(eventMessageJsonElement, TradeMessage.class);
tradeMessage.setSym(tradeMessage.getTicker());
=======
TradeMessage tradeMessage = GsonUtil.GSON.fromJson(eventMessageJsonElement,
TradeMessage.class);
>>>>>>>
TradeMessage tradeMessage = GsonUtil.GSON.fromJson(eventMessageJsonElement,
TradeMessage.class);
tradeMessage.setSym(tradeMessage.getTicker());
<<<<<<<
AggregateMinuteMessage aggregateMinuteMessage = GsonUtil.GSON.fromJson(eventMessageJsonElement,
AggregateMinuteMessage.class);
aggregateMinuteMessage.setSym(aggregateMinuteMessage.getTicker());
=======
AggregateMinuteMessage aggregateMinuteMessage = GsonUtil.GSON.fromJson(
eventMessageJsonElement, AggregateMinuteMessage.class);
>>>>>>>
AggregateMinuteMessage aggregateMinuteMessage = GsonUtil.GSON.fromJson(
eventMessageJsonElement, AggregateMinuteMessage.class);
aggregateMinuteMessage.setSym(aggregateMinuteMessage.getTicker()); |
<<<<<<<
", messageCharacterLimit" + messageCharacterLimit +
=======
", toolbarTitleColor=" + toolbarTitleColor +
", toolbarSubtitleColor=" + toolbarSubtitleColor +
>>>>>>>
", messageCharacterLimit" + messageCharacterLimit +
", toolbarTitleColor=" + toolbarTitleColor +
", toolbarSubtitleColor=" + toolbarSubtitleColor + |
<<<<<<<
import com.applozic.mobicomkit.uiwidgets.kommunicate.KmAttachmentsController;
import com.applozic.mobicomkit.uiwidgets.kommunicate.KommunicateUI;
import com.applozic.mobicomkit.uiwidgets.kommunicate.asyncs.KmAutoSuggestionsAsyncTask;
import com.applozic.mobicomkit.uiwidgets.kommunicate.callbacks.PrePostUIMethods;
import com.applozic.mobicomkit.uiwidgets.kommunicate.utils.KmUtils;
=======
import io.kommunicate.async.KmAutoSuggestionsAsyncTask;
import io.kommunicate.utils.KmConstants;
import io.kommunicate.utils.KmUtils;
import com.applozic.mobicomkit.uiwidgets.kommunicate.utils.KmHelper;
>>>>>>>
import com.applozic.mobicomkit.uiwidgets.kommunicate.KmAttachmentsController;
import com.applozic.mobicomkit.uiwidgets.kommunicate.KommunicateUI;
import com.applozic.mobicomkit.uiwidgets.kommunicate.asyncs.KmAutoSuggestionsAsyncTask;
import com.applozic.mobicomkit.uiwidgets.kommunicate.callbacks.PrePostUIMethods;
import com.applozic.mobicomkit.uiwidgets.kommunicate.utils.KmUtils;
import io.kommunicate.async.KmAutoSuggestionsAsyncTask;
import io.kommunicate.utils.KmConstants;
import io.kommunicate.utils.KmUtils;
import com.applozic.mobicomkit.uiwidgets.kommunicate.utils.KmHelper; |
<<<<<<<
import io.kommunicate.models.KmAppSettingModel;
=======
import io.kommunicate.models.KmAgentModel;
import io.kommunicate.models.KmPrechatInputModel;
>>>>>>>
import io.kommunicate.models.KmAppSettingModel;
import io.kommunicate.models.KmAgentModel;
import io.kommunicate.models.KmPrechatInputModel; |
<<<<<<<
final String portName = this.deviceConfig.getPortName();
final int baudrate = this.deviceConfig.getBaudrate();
final boolean dtrValue = this.deviceConfig.isOpenPortDtr();
final int openDelay = this.deviceConfig.getOpenPortDelay();
=======
if ( this.connection == null )
{
final String portName = this.deviceConfig.getPortName();
final int baudrate = this.deviceConfig.getBaudrate();
final boolean dtrValue = this.deviceConfig.isOpenPortDtr();
>>>>>>>
if ( this.connection == null )
{
final String portName = this.deviceConfig.getPortName();
final int baudrate = this.deviceConfig.getBaudrate();
final boolean dtrValue = this.deviceConfig.isOpenPortDtr();
final int openDelay = this.deviceConfig.getOpenPortDelay();
<<<<<<<
return this.streamConnectionFactory.getConnection( portName, baudrate, dtrValue, openDelay );
=======
this.connection = this.streamConnectionFactory.getConnection( portName, baudrate, dtrValue );
}
return this.connection;
>>>>>>>
this.connection = this.streamConnectionFactory.getConnection( portName, baudrate, dtrValue, openDelay );
}
return this.connection; |
<<<<<<<
* Copyright 2009-2016 Eucalyptus Systems, Inc.
=======
* Copyright 2008 Regents of the University of California
* Copyright 2009-2015 Ent. Services Development Corporation LP
>>>>>>>
* Copyright 2008 Regents of the University of California
* Copyright 2009-2016 Ent. Services Development Corporation LP |
<<<<<<<
import com.eucalyptus.reporting.*;
import com.eucalyptus.reporting.event.StorageEvent;
=======
import com.eucalyptus.event.EventListener;
import com.eucalyptus.reporting.GroupByCriterion;
import com.eucalyptus.reporting.Period;
import com.eucalyptus.reporting.event.*;
import com.eucalyptus.event.EventListener;
>>>>>>>
import com.eucalyptus.reporting.*;
import com.eucalyptus.reporting.event.*; |
<<<<<<<
import com.eucalyptus.util.async.AsyncRequests;
=======
>>>>>>>
import com.eucalyptus.util.async.AsyncRequests;
<<<<<<<
LOG.info("Component: "+component+"@"+host);
ServiceConfiguration service = this.lookupService(component,host,name);
try {
BaseMessage reply = null;
if(service.isVmLocal()) {//send direct to local component using mule registry directly
reply = ServiceContext.send(service.getComponentId().getLocalEndpointName(),request);
} else {//send remote
reply = AsyncRequests.sendSync(service,request);
}
return reply;
} catch (Throwable e) {
LOG.error(e);
throw new EucalyptusCloudException("Unable to dispatch message to: "+service.getName());
}
=======
ServiceConfiguration service = this.lookupService(component,host,name);
LOG.info("Component: "+service);
try {
BaseMessage reply = null;
if(service.isVmLocal()) {//send direct to local component using mule registry directly
reply = ServiceContext.send(service.getComponentId().getLocalEndpointName(),request);
} else {//send remote
reply = service.lookupService().getDispatcher().send(request);
}
return reply;
} catch (Exception e) {
LOG.error(e);
throw new EucalyptusCloudException("Unable to dispatch message to: "+service.getName());
}
>>>>>>>
ServiceConfiguration service = this.lookupService(component,host,name);
LOG.info("Component: "+service);
try {
BaseMessage reply = null;
if(service.isVmLocal()) {//send direct to local component using mule registry directly
reply = ServiceContext.send(service.getComponentId().getLocalEndpointName(),request);
} else {//send remote
reply = AsyncRequests.sendSync(service,request);
}
return reply;
} catch (Throwable e) {
LOG.error(e);
throw new EucalyptusCloudException("Unable to dispatch message to: "+service.getName());
}
<<<<<<<
private ServiceConfiguration lookupService(String component,String name,String host) throws EucalyptusCloudException {
ComponentId destCompId = ComponentIds.lookup(component);
if(name != null) {
return ServiceConfigurations.lookupByName(destCompId.getClass(),name);
} else if (host != null) {
return ServiceConfigurations.lookupByHost(destCompId.getClass(),name);
} else {
throw new EucalyptusCloudException("Unable to dispatch message to: "+component+"@"+host);
}
}
=======
private ServiceConfiguration lookupService(String component,String name,String host) throws EucalyptusCloudException {
ComponentId destCompId = ComponentIds.lookup(component);
if(name != null) {
return ServiceConfigurations.lookupByName(destCompId.getClass(),name);
} else if (host != null) {
return ServiceConfigurations.lookupByHost(destCompId.getClass(),name);
} else {
throw new EucalyptusCloudException("Unable to dispatch message to: "+component+"@"+host);
}
}
>>>>>>>
private ServiceConfiguration lookupService(String component,String name,String host) throws EucalyptusCloudException {
ComponentId destCompId = ComponentIds.lookup(component);
if(name != null) {
return ServiceConfigurations.lookupByName(destCompId.getClass(),name);
} else if (host != null) {
return ServiceConfigurations.lookupByHost(destCompId.getClass(),name);
} else {
throw new EucalyptusCloudException("Unable to dispatch message to: "+component+"@"+host);
}
} |
<<<<<<<
import com.eucalyptus.blockstorage.Volume;
import com.eucalyptus.blockstorage.Volumes;
import com.eucalyptus.cloud.util.InvalidMetadataException;
import com.eucalyptus.cloud.util.NoSuchMetadataException;
import com.eucalyptus.images.KernelImageInfo;
import com.eucalyptus.images.RamdiskImageInfo;
import com.eucalyptus.images.Images;
import com.eucalyptus.network.NetworkGroup;
import com.eucalyptus.vmtypes.VmType;
import com.eucalyptus.vmtypes.VmTypes;
=======
import com.google.common.base.Joiner;
>>>>>>>
import com.eucalyptus.blockstorage.Volume;
import com.eucalyptus.blockstorage.Volumes;
import com.eucalyptus.cloud.util.InvalidMetadataException;
import com.eucalyptus.cloud.util.NoSuchMetadataException;
import com.eucalyptus.images.KernelImageInfo;
import com.eucalyptus.images.RamdiskImageInfo;
import com.eucalyptus.images.Images;
import com.eucalyptus.network.NetworkGroup;
import com.eucalyptus.vmtypes.VmType;
import com.eucalyptus.vmtypes.VmTypes;
import com.google.common.base.Joiner; |
<<<<<<<
import com.eucalyptus.compute.common.CloudMetadata.VmInstanceMetadata;
import com.eucalyptus.compute.common.CloudMetadatas;
import com.eucalyptus.compute.common.ImageMetadata;
=======
import com.eucalyptus.cloud.CloudMetadata.VmInstanceMetadata;
import com.eucalyptus.cloud.CloudMetadatas;
import com.eucalyptus.cloud.ImageMetadata;
import com.eucalyptus.cloud.VmInstanceLifecycleHelpers;
>>>>>>>
import com.eucalyptus.compute.common.CloudMetadata.VmInstanceMetadata;
import com.eucalyptus.compute.common.CloudMetadatas;
import com.eucalyptus.compute.common.ImageMetadata;
import com.eucalyptus.cloud.VmInstanceLifecycleHelpers; |
<<<<<<<
import com.eucalyptus.auth.Accounts;
import com.eucalyptus.auth.SystemCredentialProvider;
=======
import com.eucalyptus.auth.Users;
>>>>>>>
import com.eucalyptus.auth.Accounts; |
<<<<<<<
import java.util.concurrent.atomic.AtomicLong;
=======
>>>>>>>
import java.util.concurrent.atomic.AtomicLong;
<<<<<<<
import com.eucalyptus.keys.KeyPairs;
=======
>>>>>>>
import com.eucalyptus.keys.KeyPairs;
<<<<<<<
import com.eucalyptus.network.NetworkGroup;
import com.eucalyptus.network.PrivateNetworkIndex;
=======
>>>>>>>
import com.eucalyptus.network.NetworkGroup;
import com.eucalyptus.network.PrivateNetworkIndex;
<<<<<<<
import com.eucalyptus.util.FullName;
import com.eucalyptus.util.OwnerFullName;
import com.eucalyptus.vm.BundleTask;
=======
import com.eucalyptus.util.HasName;
import com.eucalyptus.util.Transactions;
import com.eucalyptus.util.async.Callback;
import com.eucalyptus.vm.BundleTask;
import com.eucalyptus.vm.SystemState;
import com.eucalyptus.vm.SystemState.Reason;
>>>>>>>
import com.eucalyptus.util.FullName;
import com.eucalyptus.util.OwnerFullName;
import com.eucalyptus.vm.BundleTask;
<<<<<<<
import com.google.common.collect.Sets;
=======
import edu.ucsb.eucalyptus.cloud.Network;
>>>>>>>
import com.google.common.collect.Sets;
<<<<<<<
@Column( name = "metadata_vm_partition_name" )
=======
@Column( name = "vm_instance_uuid" )
private final String instanceUuid;
@Column( name = "vm_cluster_name" )
private final String clusterName;
@Column( name = "vm_partition_name" )
>>>>>>>
@Column( name = "vm_cluster_name" )
private final String clusterName;
@Column( name = "metadata_vm_partition_name" )
<<<<<<<
@ManyToOne
@Cache( usage = CacheConcurrencyStrategy.TRANSACTIONAL )
private final SshKeyPair sshKeyPair;
@ManyToOne
@Cache( usage = CacheConcurrencyStrategy.TRANSACTIONAL )
=======
@Transient
// @Column( name = "vm_ssh_key_pair" )
private SshKeyPair sshKeyPair;
@Transient
// @Column( name = "vm_type" )
>>>>>>>
@ManyToOne
@Cache( usage = CacheConcurrencyStrategy.TRANSACTIONAL )
private final SshKeyPair sshKeyPair;
@ManyToOne
@Cache( usage = CacheConcurrencyStrategy.TRANSACTIONAL )
<<<<<<<
//TODO:GRZE:NOW
private final ConcurrentMap<String, AttachedVolume> persistentVolumes = new ConcurrentSkipListMap<String, AttachedVolume>( );
=======
private final List<Network> networks = Lists.newArrayList( );
@Transient
private final NetworkConfigType networkConfig = new NetworkConfigType( );
@Transient
private final AtomicMarkableReference<VmState> runtimeState = new AtomicMarkableReference<VmState>( VmState.PENDING, false );
>>>>>>>
//TODO:GRZE:NOW
private final ConcurrentMap<String, AttachedVolume> persistentVolumes = new ConcurrentSkipListMap<String, AttachedVolume>( );
<<<<<<<
this.privateNetwork = Boolean.FALSE;
=======
this.stopWatch.start( );
this.updateWatch.start( );
>>>>>>>
this.privateNetwork = Boolean.FALSE;
<<<<<<<
this.networkConfig.setPrivateDnsName( DEFAULT_IP );
this.networkConfig.setPublicDnsName( DEFAULT_IP );
this.networkConfig.setNetworkIndex( networkIndex.getIndex( ) );
=======
this.networkConfig.setNetworkIndex( Integer.parseInt( networkIndex ) );
>>>>>>>
this.networkConfig.setPrivateDnsName( DEFAULT_IP );
this.networkConfig.setPublicDnsName( DEFAULT_IP );
this.networkConfig.setNetworkIndex( networkIndex.getIndex( ) );
<<<<<<<
public void updateNetworkIndex( final Long newIndex ) {
if ( ( this.getNetworkConfig( ).getNetworkIndex( ) > 0 ) && ( newIndex > 0 )
&& ( VmState.RUNNING.equals( this.getState( ) ) || VmState.PENDING.equals( this.getState( ) ) ) ) {
=======
public void updateNetworkIndex( Integer newIndex ) {
if ( this.getNetworkConfig( ).getNetworkIndex( ) > 0 && newIndex > 0
&& ( VmState.RUNNING.equals( this.getRuntimeState( ) ) || VmState.PENDING.equals( this.getRuntimeState( ) ) ) ) {
>>>>>>>
public void updateNetworkIndex( final Long newIndex ) {
if ( ( this.getNetworkConfig( ).getNetworkIndex( ) > 0 ) && ( newIndex > 0 )
&& ( VmState.RUNNING.equals( this.getRuntimeState( ) ) || VmState.PENDING.equals( this.getRuntimeState( ) ) ) ) {
<<<<<<<
if ( this.runtimeState.isMarked( ) && ( this.getState( ).ordinal( ) > VmState.RUNNING.ordinal( ) ) ) {
this.runtimeState.set( this.getState( ), false );
=======
if ( this.runtimeState.isMarked( ) && this.getRuntimeState( ).ordinal( ) > VmState.RUNNING.ordinal( ) ) {
this.runtimeState.set( this.getRuntimeState( ), false );
>>>>>>>
if ( this.runtimeState.isMarked( ) && ( this.getRuntimeState( ).ordinal( ) > VmState.RUNNING.ordinal( ) ) ) {
this.runtimeState.set( this.getRuntimeState( ), false );
<<<<<<<
public void setState( final VmState newState, Reason reason, final String... extra ) {
final VmState oldState = this.runtimeState.getReference( );
=======
public void setState( final VmState newState, SystemState.Reason reason, String... extra ) {
this.updateWatch.split( );
if ( this.updateWatch.getSplitTime( ) > 1000 * 60 * 60 ) {
this.store( );
this.updateWatch.unsplit( );
} else {
this.updateWatch.unsplit( );
}
this.resetStopWatch( );
VmState oldState = this.runtimeState.getReference( );
>>>>>>>
public void setState( final VmState newState, Reason reason, final String... extra ) {
final VmState oldState = this.runtimeState.getReference( );
<<<<<<<
} else if ( ( VmState.TERMINATED.equals( newState ) && VmState.TERMINATED.equals( oldState ) ) || VmState.BURIED.equals( newState ) ) {
VmInstances.deregister( this.getName( ) );
} else if ( !this.getState( ).equals( newState ) ) {
=======
} else if ( VmState.TERMINATED.equals( newState ) && VmState.TERMINATED.equals( oldState ) ) {
VmInstances.getInstance( ).deregister( this.getName( ) );
try {
Transactions.delete( this );
} catch ( Exception ex ) {
LOG.error( ex, ex );
}
} else if ( !this.getRuntimeState( ).equals( newState ) ) {
>>>>>>>
} else if ( ( VmState.TERMINATED.equals( newState ) && VmState.TERMINATED.equals( oldState ) ) || VmState.BURIED.equals( newState ) ) {
VmInstances.deregister( this.getName( ) );
} else if ( !this.getRuntimeState( ).equals( newState ) ) {
<<<<<<<
if ( this.runtimeState.isMarked( ) && VmState.PENDING.equals( this.getState( ) ) ) {
=======
if ( this.runtimeState.isMarked( ) && VmState.PENDING.equals( this.getRuntimeState( ) ) ) {
>>>>>>>
if ( this.runtimeState.isMarked( ) && VmState.PENDING.equals( this.getRuntimeState( ) ) ) {
<<<<<<<
} else if ( this.runtimeState.isMarked( ) && VmState.SHUTTING_DOWN.equals( this.getState( ) ) ) {
LOG.debug( "Ignoring events for state transition because the instance is marked as pending: " + oldState + " to " + this.getState( ) );
} else if ( !this.runtimeState.isMarked( ) ) {
if ( ( oldState.ordinal( ) <= VmState.RUNNING.ordinal( ) ) && ( newState.ordinal( ) > VmState.RUNNING.ordinal( ) ) ) {
this.runtimeState.set( newState, false );
=======
} else if ( this.runtimeState.isMarked( ) && VmState.SHUTTING_DOWN.equals( this.getRuntimeState( ) ) ) {
LOG.debug( "Ignoring events for state transition because the instance is marked as pending: " + oldState + " to " + this.getRuntimeState( ) );
} else if ( !this.runtimeState.isMarked( ) ) {
if ( oldState.ordinal( ) <= VmState.RUNNING.ordinal( ) && newState.ordinal( ) > VmState.RUNNING.ordinal( ) ) {
this.runtimeState.set( newState, false );
>>>>>>>
} else if ( this.runtimeState.isMarked( ) && VmState.SHUTTING_DOWN.equals( this.getState( ) ) ) {
LOG.debug( "Ignoring events for state transition because the instance is marked as pending: " + oldState + " to " + this.getState( ) );
} else if ( !this.runtimeState.isMarked( ) ) {
if ( ( oldState.ordinal( ) <= VmState.RUNNING.ordinal( ) ) && ( newState.ordinal( ) > VmState.RUNNING.ordinal( ) ) ) {
this.runtimeState.set( newState, false );
<<<<<<<
=======
//TODO: GRZE!!!! 1111oneoneone1111111oneoneone
UserFullName ufn = ( UserFullName ) this.getOwner( );
>>>>>>>
<<<<<<<
this.getOwner( ).getUserId( ), this.getOwnerUserName( ),
this.getOwner( ).getAccountNumber( ), this.getOwnerAccountName( ),
=======
ufn.getUserId( ), ufn.getUserName( ), ufn.getAccountNumber( ),ufn.getAccountNumber( ),
>>>>>>>
this.getOwner( ).getUserId( ), this.getOwnerUserName( ),
this.getOwner( ).getAccountNumber( ), this.getOwnerAccountName( ),
<<<<<<<
db.merge( this );
db.commit( );
} catch ( final Exception ex ) {
db.rollback( );
LOG.debug( ex );
=======
Transactions.one( VmInstance.named( ( UserFullName ) this.getOwner( ), this.getDisplayName( ) ), new Callback<VmInstance>( ) {
@Override
public void fire( VmInstance t ) {
t.setBlockBytes( VmInstance.this.getBlockBytes( ) );
t.setNetworkBytes( VmInstance.this.getNetworkBytes( ) );
}
} );
} catch ( Exception ex ) {
LOG.error( ex, ex );
>>>>>>>
Entities.merge( this );
db.commit( );
} catch ( final Exception ex ) {
db.rollback( );
LOG.debug( ex );
<<<<<<<
this.instanceId, this.sshKeyPair, this.launchIndex, this.launchTime, this.networkConfig, this.networkGroups, this.getOwner( ),
this.clusterName, this.privateNetwork, this.reason, this.reservationId, this.runtimeState,
System.currentTimeMillis( ) - this.getLastUpdateTimestamp( ).getTime( ),
this.userData, this.vmType, this.transientVolumes );
=======
this.instanceId, this.sshKeyPair, this.launchIndex, this.launchTime, this.networkConfig, this.networks, this.getOwner( ),
this.clusterName, this.privateNetwork, this.reason, this.reservationId, this.runtimeState, this.stopWatch, this.userData, this.vmType,
this.transientVolumes );
>>>>>>>
this.instanceId, this.sshKeyPair, this.launchIndex, this.launchTime, this.networkConfig, this.networkGroups, this.getOwner( ),
this.clusterName, this.privateNetwork, this.reason, this.reservationId, this.runtimeState,
System.currentTimeMillis( ) - this.getLastUpdateTimestamp( ).getTime( ),
this.userData, this.vmType, this.transientVolumes ); |
<<<<<<<
import com.eucalyptus.cluster.callback.BundleCallback;
=======
import com.eucalyptus.component.Components;
import com.eucalyptus.config.Configuration;
import com.eucalyptus.event.EventFailedException;
import com.eucalyptus.event.ListenerRegistry;
>>>>>>>
import com.eucalyptus.component.Components;
import com.eucalyptus.config.Configuration;
import com.eucalyptus.event.EventFailedException;
import com.eucalyptus.event.ListenerRegistry;
import com.eucalyptus.cluster.callback.BundleCallback;
<<<<<<<
import com.eucalyptus.util.Exceptions;
=======
import com.eucalyptus.reporting.event.InstanceEvent;
import com.eucalyptus.util.EucalyptusCloudException;
>>>>>>>
import com.eucalyptus.reporting.event.InstanceEvent;
import com.eucalyptus.util.EucalyptusCloudException;
import com.eucalyptus.util.Exceptions;
<<<<<<<
public enum BundleState {
none( "none" ), pending( null ), storing( "bundling" ), canceling( null ), complete( "succeeded" ), failed( "failed" );
private String mappedState;
BundleState( String mappedState ) {
this.mappedState = mappedState;
}
public String getMappedState( ) {
return this.mappedState;
}
}
=======
private String uuid;
>>>>>>>
public enum BundleState {
none( "none" ), pending( null ), storing( "bundling" ), canceling( null ), complete( "succeeded" ), failed( "failed" );
private String mappedState;
BundleState( String mappedState ) {
this.mappedState = mappedState;
}
public String getMappedState( ) {
return this.mappedState;
}
}
private String uuid;
<<<<<<<
private final AtomicMarkableReference<BundleTask> bundleTask = new AtomicMarkableReference<BundleTask>( null, false );
private final ConcurrentMap<String,AttachedVolume> volumes = new ConcurrentSkipListMap<String,AttachedVolume>( );
=======
private final ConcurrentMap<String, AttachedVolume> volumes = new ConcurrentSkipListMap<String, AttachedVolume>( );
>>>>>>>
private final AtomicMarkableReference<BundleTask> bundleTask = new AtomicMarkableReference<BundleTask>( null, false );
private final ConcurrentMap<String, AttachedVolume> volumes = new ConcurrentSkipListMap<String, AttachedVolume>( );
<<<<<<<
EventRecord.here( VmInstance.class, EventClass.VM, EventType.VM_STATE )
.withDetails( this.getOwnerId( ), this.getInstanceId( ), "type", this.getVmTypeInfo( ).getName( ) )
.withDetails( "state", this.state.getReference( ).name( ) ).withDetails( "cluster", this.placement )
/** ASAP: FIXME: GRZE .withDetails( "image", this.imageInfo.getImageId( ) )**/.withDetails( "started", this.launchTime.getTime( ) + "" ).info( );
=======
try {
ListenerRegistry.getInstance( ).fireEvent( new InstanceEvent( this.uuid, this.instanceId, this.vmTypeInfo.getName( ), this.ownerId, this.placement,
this.partition, this.networkBytes, this.blockBytes ) );
} catch ( EventFailedException ex ) {
LOG.error( ex, ex );
}
// EventRecord.here( VmInstance.class, EventClass.VM, EventType.VM_STATE )
// .withDetails( this.getOwnerId( ), this.getInstanceId( ), "type", this.getVmTypeInfo( ).getName( ) )
// .withDetails( "state", this.state.getReference( ).name( ) ).withDetails( "cluster", this.placement )
// /** ASAP: FIXME: GRZE .withDetails( "image", this.imageInfo.getImageId( ) ) **/
// .withDetails( "started", this.launchTime.getTime( ) + "" ).info( );
>>>>>>>
try {
ListenerRegistry.getInstance( ).fireEvent( new InstanceEvent( this.uuid, this.instanceId, this.vmTypeInfo.getName( ), this.ownerId, this.placement,
this.partition, this.networkBytes, this.blockBytes ) );
} catch ( EventFailedException ex ) {
LOG.error( ex, ex );
}
// EventRecord.here( VmInstance.class, EventClass.VM, EventType.VM_STATE )
// .withDetails( this.getOwnerId( ), this.getInstanceId( ), "type", this.getVmTypeInfo( ).getName( ) )
// .withDetails( "state", this.state.getReference( ).name( ) ).withDetails( "cluster", this.placement )
// /** ASAP: FIXME: GRZE .withDetails( "image", this.imageInfo.getImageId( ) ) **/ |
<<<<<<<
import com.eucalyptus.compute.common.ImageMetadata;
import com.eucalyptus.compute.common.ImageMetadata.Platform;
=======
import com.eucalyptus.auth.principal.User;
import com.eucalyptus.auth.principal.UserFullName;
import com.eucalyptus.cloud.ImageMetadata;
import com.eucalyptus.cloud.ImageMetadata.Platform;
import com.eucalyptus.cloud.VmInstanceLifecycleHelpers;
>>>>>>>
import com.eucalyptus.auth.principal.User;
import com.eucalyptus.auth.principal.UserFullName;
import com.eucalyptus.compute.common.ImageMetadata;
import com.eucalyptus.compute.common.ImageMetadata.Platform;
import com.eucalyptus.cloud.VmInstanceLifecycleHelpers; |
<<<<<<<
private String dnsDomain;
private String nameserver;
private String nameserverAddress;
=======
private Integer maxUserPublicAddresses;
private boolean doDynamicPublicAddresses;
private Integer systemReservedPublicAddresses;
>>>>>>>
private Integer maxUserPublicAddresses;
private boolean doDynamicPublicAddresses;
private Integer systemReservedPublicAddresses;
private String dnsDomain;
private String nameserver;
private String nameserverAddress;
<<<<<<<
final String defaultRamdiskId,
final String dnsDomain,
final String nameserver,
final String nameserverAddress)
=======
final String defaultRamdiskId,
final Integer maxUserPublicAddresses,
final Boolean doDynamicPublicAddresses,
final Integer systemReservedPublicAddresses )
>>>>>>>
final String defaultRamdiskId,
final Integer maxUserPublicAddresses,
final Boolean doDynamicPublicAddresses,
final Integer systemReservedPublicAddresses,
final String dnsDomain,
final String nameserver,
final String nameserverAddress)
<<<<<<<
this.dnsDomain = dnsDomain;
this.nameserver = nameserver;
this.nameserverAddress = nameserverAddress;
=======
this.maxUserPublicAddresses = maxUserPublicAddresses;
this.systemReservedPublicAddresses = systemReservedPublicAddresses;
this.doDynamicPublicAddresses = doDynamicPublicAddresses;
>>>>>>>
this.dnsDomain = dnsDomain;
this.nameserver = nameserver;
this.nameserverAddress = nameserverAddress;
this.maxUserPublicAddresses = maxUserPublicAddresses;
this.systemReservedPublicAddresses = systemReservedPublicAddresses;
this.doDynamicPublicAddresses = doDynamicPublicAddresses;
<<<<<<<
public String getDnsDomain() {
return dnsDomain;
}
public void setDnsDomain(String dnsDomain) {
this.dnsDomain = dnsDomain;
}
public String getNameserver() {
return nameserver;
}
public void setNameserver(String nameserver) {
this.nameserver = nameserver;
}
public String getNameserverAddress() {
return nameserverAddress;
}
public void setNameserverAddress(String nameserverAddress) {
this.nameserverAddress = nameserverAddress;
}
=======
public Integer getMaxUserPublicAddresses() {
return maxUserPublicAddresses;
}
public void setMaxUserPublicAddresses( final Integer maxUserPublicAddresses ) {
this.maxUserPublicAddresses = maxUserPublicAddresses;
}
public Boolean isDoDynamicPublicAddresses() {
return doDynamicPublicAddresses;
}
public void setDoDynamicPublicAddresses( final Boolean doDynamicPublicAddresses ) {
this.doDynamicPublicAddresses = doDynamicPublicAddresses;
}
public Integer getSystemReservedPublicAddresses() {
return systemReservedPublicAddresses;
}
public void setSystemReservedPublicAddresses( final Integer systemReservedPublicAddresses ) {
this.systemReservedPublicAddresses = systemReservedPublicAddresses;
}
>>>>>>>
public String getDnsDomain() {
return dnsDomain;
}
public void setDnsDomain(String dnsDomain) {
this.dnsDomain = dnsDomain;
}
public String getNameserver() {
return nameserver;
}
public void setNameserver(String nameserver) {
this.nameserver = nameserver;
}
public String getNameserverAddress() {
return nameserverAddress;
}
public void setNameserverAddress(String nameserverAddress) {
this.nameserverAddress = nameserverAddress;
public Integer getMaxUserPublicAddresses() {
return maxUserPublicAddresses;
}
public void setMaxUserPublicAddresses( final Integer maxUserPublicAddresses ) {
this.maxUserPublicAddresses = maxUserPublicAddresses;
}
public Boolean isDoDynamicPublicAddresses() {
return doDynamicPublicAddresses;
}
public void setDoDynamicPublicAddresses( final Boolean doDynamicPublicAddresses ) {
this.doDynamicPublicAddresses = doDynamicPublicAddresses;
}
public Integer getSystemReservedPublicAddresses() {
return systemReservedPublicAddresses;
}
public void setSystemReservedPublicAddresses( final Integer systemReservedPublicAddresses ) {
this.systemReservedPublicAddresses = systemReservedPublicAddresses;
} |
<<<<<<<
import com.eucalyptus.auth.Groups;
import com.eucalyptus.auth.NoSuchGroupException;
import com.eucalyptus.auth.principal.Authorization;
import com.eucalyptus.auth.principal.AvailabilityZonePermission;
import com.eucalyptus.auth.principal.Group;
=======
>>>>>>>
import com.eucalyptus.auth.Groups;
import com.eucalyptus.auth.NoSuchGroupException;
import com.eucalyptus.auth.principal.Authorization;
import com.eucalyptus.auth.principal.AvailabilityZonePermission;
import com.eucalyptus.auth.principal.Group; |
<<<<<<<
@TypeMapper
public enum StatusTransform implements Function<VmInstance, InstanceStatusItemType> {
INSTANCE;
@Override
public InstanceStatusItemType apply( final VmInstance instance ) {
final InstanceStatusItemType instanceStatusItemType = new InstanceStatusItemType();
final VmState displayState = instance.getDisplayState();
instanceStatusItemType.setInstanceId( instance.getInstanceId() );
instanceStatusItemType.setAvailabilityZone( instance.getPlacement().getPartitionName() );
final InstanceStateType state = new InstanceStateType();
state.setCode( displayState.getCode() );
state.setName( displayState.getName() );
instanceStatusItemType.setInstanceState( state );
instanceStatusItemType.setInstanceStatus( buildStatus( displayState) );
instanceStatusItemType.setSystemStatus( buildStatus( displayState ) );
return instanceStatusItemType;
}
private InstanceStatusType buildStatus( final VmState vmState ) {
final InstanceStatusType instanceStatus = new InstanceStatusType();
if ( VmState.RUNNING == vmState ) {
final InstanceStatusDetailsSetItemType statusDetailsItem = new InstanceStatusDetailsSetItemType();
statusDetailsItem.setName( "reachability" );
statusDetailsItem.setStatus( "passed" );
final InstanceStatusDetailsSetType statusDetails = new InstanceStatusDetailsSetType();
statusDetails.getItem().add( statusDetailsItem );
instanceStatus.setStatus( "ok" );
instanceStatus.setDetails( statusDetails );
} else {
instanceStatus.setStatus( "not-applicable" );
}
return instanceStatus;
}
}
public Boolean getMonitoring() {
return this.getBootRecord().isMonitoring();
}
public void startMigration( ) {
this.runtimeState.startMigration( );
}
public void abortMigration( ) {
this.runtimeState.abortMigration( );
}
public VmMigrationTask getMigrationTask( ) {
return this.runtimeState.getMigrationTask( );
}
=======
>>>>>>>
@TypeMapper
public enum StatusTransform implements Function<VmInstance, InstanceStatusItemType> {
INSTANCE;
@Override
public InstanceStatusItemType apply( final VmInstance instance ) {
final InstanceStatusItemType instanceStatusItemType = new InstanceStatusItemType();
final VmState displayState = instance.getDisplayState();
instanceStatusItemType.setInstanceId( instance.getInstanceId() );
instanceStatusItemType.setAvailabilityZone( instance.getPlacement().getPartitionName() );
final InstanceStateType state = new InstanceStateType();
state.setCode( displayState.getCode() );
state.setName( displayState.getName() );
instanceStatusItemType.setInstanceState( state );
instanceStatusItemType.setInstanceStatus( buildStatus( displayState) );
instanceStatusItemType.setSystemStatus( buildStatus( displayState ) );
return instanceStatusItemType;
}
private InstanceStatusType buildStatus( final VmState vmState ) {
final InstanceStatusType instanceStatus = new InstanceStatusType();
if ( VmState.RUNNING == vmState ) {
final InstanceStatusDetailsSetItemType statusDetailsItem = new InstanceStatusDetailsSetItemType();
statusDetailsItem.setName( "reachability" );
statusDetailsItem.setStatus( "passed" );
final InstanceStatusDetailsSetType statusDetails = new InstanceStatusDetailsSetType();
statusDetails.getItem().add( statusDetailsItem );
instanceStatus.setStatus( "ok" );
instanceStatus.setDetails( statusDetails );
} else {
instanceStatus.setStatus( "not-applicable" );
}
return instanceStatus;
}
}
public Boolean getMonitoring() {
return this.getBootRecord().isMonitoring();
}
public void startMigration( ) {
this.runtimeState.startMigration( );
}
public void abortMigration( ) {
this.runtimeState.abortMigration( );
}
public VmMigrationTask getMigrationTask( ) {
return this.runtimeState.getMigrationTask( );
} |
<<<<<<<
import com.eucalyptus.auth.Accounts;
=======
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.eucalyptus.cloudformation.ValidationErrorException;
>>>>>>>
import com.eucalyptus.auth.Accounts;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.eucalyptus.cloudformation.ValidationErrorException;
<<<<<<<
import com.eucalyptus.cloudformation.resources.standard.propertytypes.CloudFormationResourceTag;
import com.eucalyptus.cloudformation.resources.standard.propertytypes.ElasticLoadBalancingAccessLoggingPolicy;
=======
import com.eucalyptus.cloudformation.resources.standard.propertytypes.ElasticLoadBalancingAppCookieStickinessPolicy;
import com.eucalyptus.cloudformation.resources.standard.propertytypes.ElasticLoadBalancingLBCookieStickinessPolicyType;
>>>>>>>
import com.eucalyptus.cloudformation.resources.standard.propertytypes.CloudFormationResourceTag;
import com.eucalyptus.cloudformation.resources.standard.propertytypes.ElasticLoadBalancingAccessLoggingPolicy;
import com.eucalyptus.cloudformation.resources.standard.propertytypes.ElasticLoadBalancingAppCookieStickinessPolicy;
import com.eucalyptus.cloudformation.resources.standard.propertytypes.ElasticLoadBalancingLBCookieStickinessPolicyType;
<<<<<<<
=======
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.netflix.glisten.WorkflowOperations;
>>>>>>>
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.netflix.glisten.WorkflowOperations;
<<<<<<<
import java.util.Objects;
=======
import java.util.Set;
import javax.annotation.Nullable;
>>>>>>>
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nullable; |
<<<<<<<
public static Logger LOG = Logger.getLogger( SystemState.class );
=======
public static Logger LOG = Logger.getLogger( SystemState.class );
@ConfigurableField( description = "Amount of time (in milliseconds) that a terminated VM will continue to be reported.", initial = "" + 60 * 60 * 1000 )
public static Integer BURY_TIME = 60 * 60 * 1000;
@ConfigurableField( description = "Amount of time (in milliseconds) before a VM which is not reported by a cluster will be marked as terminated.", initial = "" + 10 * 60 * 1000 )
public static Integer SHUT_DOWN_TIME = 10 * 60 * 1000;
public enum Reason {
NORMAL( "" ),
EXPIRED( "Instance expired after not being reported for %s ms.", SystemState.SHUT_DOWN_TIME ),
FAILED( "The instance failed to start on the NC." ),
USER_TERMINATED( "User initiated terminate." ),
USER_STOPPED( "User initiated stop." ),
BURIED( "Instance buried after timeout of %s ms.", SystemState.BURY_TIME ),
APPEND( "" );
private String message;
private Object[] args;
Reason( String message, Object... args ) {
this.message = message;
this.args = args;
}
@Override
public String toString( ) {
return String.format( this.message.toString( ), this.args );
}
}
>>>>>>>
public static Logger LOG = Logger.getLogger( SystemState.class );
<<<<<<<
VmInstance vm = VmInstances.lookup( vmId );
if ( vm.getSplitTime( ) > VmInstances.SHUT_DOWN_TIME ) {
vm.setState( VmState.TERMINATED, Reason.EXPIRED );
=======
VmInstance vm = VmInstances.getInstance( ).lookup( vmId );
if ( vm.getSplitTime( ) > SHUT_DOWN_TIME ) {
if ( VmState.RUNNING.equals( vm.getRuntimeState( ) ) || VmState.SHUTTING_DOWN.equals( vm.getRuntimeState( ) )
|| VmState.STOPPING.equals( vm.getRuntimeState( ) ) ) {
vm.setState( VmState.TERMINATED, Reason.EXPIRED );
}
>>>>>>>
VmInstance vm = VmInstances.lookup( vmId );
if ( vm.getSplitTime( ) > VmInstances.SHUT_DOWN_TIME ) {
vm.setState( VmState.TERMINATED, Reason.EXPIRED );
<<<<<<<
vm = VmInstances.lookupDisabled( runVm.getInstanceId( ) );
if ( !VmState.BURIED.equals( vm.getState( ) ) && vm.getSplitTime( ) > VmInstances.BURY_TIME ) {
=======
vm = VmInstances.getInstance( ).lookupDisabled( runVm.getInstanceId( ) );
if ( !VmState.BURIED.equals( vm.getRuntimeState( ) ) && vm.getSplitTime( ) > BURY_TIME ) {
>>>>>>>
vm = VmInstances.lookupDisabled( runVm.getInstanceId( ) );
if ( !VmState.BURIED.equals( vm.getRuntimeState( ) ) && vm.getSplitTime( ) > VmInstances.BURY_TIME ) {
<<<<<<<
} );
VmInstance vm = new VmInstance( ownerId, instanceId, instanceUuid, reservationId, launchIndex, placement, userData, runVm.getInstanceType( ), key,
vmType,
=======
}
VmInstance vm = new VmInstance( ownerId, instanceId, instanceUuid, reservationId, launchIndex, placement, userData, runVm.getInstanceType( ), key,
vmType,
>>>>>>>
} );
VmInstance vm = new VmInstance( ownerId, instanceId, instanceUuid, reservationId, launchIndex, placement, userData, runVm.getInstanceType( ), key,
vmType,
<<<<<<<
for ( VmInstance v : VmInstances.listDisabledValues( ) ) {
if ( VmState.BURIED.equals( v.getState( ) ) ) continue;
=======
for ( VmInstance v : VmInstances.getInstance( ).listDisabledValues( ) ) {
if ( VmState.BURIED.equals( v.getRuntimeState( ) ) ) continue;
>>>>>>>
for ( VmInstance v : VmInstances.listDisabledValues( ) ) {
if ( VmState.BURIED.equals( v.getState( ) ) ) continue; |
<<<<<<<
LOG.info("Volume: " + volumeId + " was marked for deletion. Cleaning up...");
try {
blockManager.deleteVolume(volumeId);
} catch (EucalyptusCloudException e) {
LOG.error(e, e);
continue;
}
vol.setStatus(StorageProperties.Status.deleted.toString());
vol.setDeletionTime(new Date());
EucaSemaphoreDirectory.removeSemaphore(volumeId); // who put it there ?
tran3.commit();
} catch(Exception e) {
LOG.error("Error deleting volume " + vol.getVolumeId() + ": " + e.getMessage());
LOG.debug("Exception during deleting volume " + vol.getVolumeId() + ".", e);
=======
>>>>>>> |
<<<<<<<
if ( event instanceof ComponentEvent ) {
ComponentEvent e = ( ComponentEvent ) event;
if ( !Component.walrus.equals( e.getComponent( ) ) && !Component.storage.equals( e.getComponent( ) ) && !Component.vmwarebroker.equals( e.getComponent( ) )) {
=======
if ( event instanceof LifecycleEvent ) {
LifecycleEvent e = ( LifecycleEvent ) event;
if ( !Component.walrus.equals( e.getPeer( ) ) && !Component.storage.equals( e.getPeer( ) ) ) {
>>>>>>>
if ( event instanceof LifecycleEvent ) {
LifecycleEvent e = ( LifecycleEvent ) event;
if ( !Component.walrus.equals( e.getPeer( ) ) && !Component.storage.equals( e.getPeer( ) ) && !Component.vmwarebroker.equals( e.getPeer( ) ) ) { |
<<<<<<<
//@Column(name="volume_id", nullable=false)
//private String volumeId;
=======
>>>>>>>
<<<<<<<
//this.volumeId = null;
=======
>>>>>>>
<<<<<<<
//this.volumeId = volumeId;
=======
>>>>>>>
<<<<<<<
/* public String getVolumeId()
{
return this.volumeId;
} */
=======
>>>>>>> |
<<<<<<<
if ( this.getMachine( ) instanceof StaticDiskImage ) {
String manifestLocation = DownloadManifestFactory.generateDownloadManifest(
new ImageManifestFile( ((StaticDiskImage)this.getMachine()).getManifestLocation(), BundleImageManifest.INSTANCE ),
=======
if ( this.getMachine( ) instanceof StaticDiskImage ) { // BootableImage+StaticDiskImage = MachineImageInfo
// generate download manifest and replace machine URL
VirtualBootRecord root = vmTypeInfo.lookupRoot();
String manifestLocation = DownloadManifestFactory.generateDownloadManifest(
new ImageManifestFile( ((MachineImageInfo)this.getMachine()).getRunManifestLocation(), BundleImageManifest.INSTANCE ),
>>>>>>>
if ( this.getMachine( ) instanceof StaticDiskImage ) { // BootableImage+StaticDiskImage = MachineImageInfo
// generate download manifest and replace machine URL
String manifestLocation = DownloadManifestFactory.generateDownloadManifest(
new ImageManifestFile( ((MachineImageInfo)this.getMachine()).getRunManifestLocation(), BundleImageManifest.INSTANCE ), |
<<<<<<<
@SuppressWarnings( { "UnnecessaryLocalVariable", "UnusedDeclaration" } )
@ComponentNamed("computeVpcManager")
=======
@SuppressWarnings( { "UnnecessaryLocalVariable", "UnusedDeclaration", "Guava", "Convert2Lambda", "RedundantTypeArguments", "StaticPseudoFunctionalStyleMethod" } )
@ComponentNamed
>>>>>>>
@SuppressWarnings( { "UnnecessaryLocalVariable", "UnusedDeclaration", "Guava", "Convert2Lambda", "RedundantTypeArguments", "StaticPseudoFunctionalStyleMethod" } )
@ComponentNamed("computeVpcManager") |
<<<<<<<
import com.eucalyptus.compute.common.internal.vm.VmInstance;
import com.eucalyptus.vm.VmInstances;
import com.eucalyptus.compute.common.internal.vm.VmInstance.Reason;
import com.eucalyptus.compute.common.internal.vm.VmInstance.VmState;
=======
>>>>>>>
import com.eucalyptus.compute.common.internal.vm.VmInstance;
import com.eucalyptus.vm.VmInstances;
import com.eucalyptus.compute.common.internal.vm.VmInstance.Reason;
import com.eucalyptus.compute.common.internal.vm.VmInstance.VmState;
<<<<<<<
LOG.debug("Image that failed conversion: " + imageId);
if ( imageId != null ) {
for( VmInstance vm : VmInstances.list( new InstanceByImageId(imageId)) ) {
LOG.debug("Shutting down instance: " + vm.getInstanceId());
VmInstances.setState( vm, VmState.SHUTTING_DOWN, Reason.FAILED );
}
}
=======
ImagingSupport.terminateInstancesWaitingImageConversion(imageId);
>>>>>>>
ImagingSupport.terminateInstancesWaitingImageConversion(imageId); |
<<<<<<<
=======
@Column( name = "zero_fill_volumes" )
private Boolean zeroFillVolumes;
@Configurable( description = "Domain name to use for DNS." )
>>>>>>>
@Configurable( description = "Domain name to use for DNS." )
<<<<<<<
public SystemConfiguration( ) {
}
public SystemConfiguration( final String defaultKernel, final String defaultRamdisk, final Integer maxUserPublicAddresses, final Boolean doDynamicPublicAddresses, final Integer systemReservedPublicAddresses, final String dnsDomain, final String nameserver,
final String nameserverAddress, final String cloudHost ) {
=======
public SystemConfiguration( ) {}
public SystemConfiguration( final String defaultKernel, final String defaultRamdisk, final Integer maxUserPublicAddresses,
final Boolean doDynamicPublicAddresses, final Integer systemReservedPublicAddresses, final Boolean zeroFillVolumes,
final String dnsDomain, final String nameserver, final String nameserverAddress, final String cloudHost ) {
>>>>>>>
public SystemConfiguration( ) {
}
public SystemConfiguration( final String defaultKernel, final String defaultRamdisk, final Integer maxUserPublicAddresses,
final Boolean doDynamicPublicAddresses, final Integer systemReservedPublicAddresses,
final String dnsDomain, final String nameserver, final String nameserverAddress, final String cloudHost ) {
<<<<<<<
=======
public Boolean getZeroFillVolumes( ) {
return zeroFillVolumes;
}
public void setZeroFillVolumes( Boolean zeroFillVolumes ) {
this.zeroFillVolumes = zeroFillVolumes;
}
>>>>>>> |
<<<<<<<
/*******************************************************************************
*Copyright (c) 2009 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Please contact Eucalyptus Systems, Inc., 130 Castilian
* Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/>
* if you need additional information or have any questions.
*
* This file may incorporate work covered under the following copyright and
* permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF
* THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE
* LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS
* SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA
* BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN
* THE REGENTS’ DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT
* OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR
* WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH
* ANY SUCH LICENSES OR RIGHTS.
*******************************************************************************/
/*
* Author: Neil Soman [email protected]
=======
/*******************************************************************************
*Copyright (c) 2009 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Please contact Eucalyptus Systems, Inc., 130 Castilian
* Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/>
* if you need additional information or have any questions.
*
* This file may incorporate work covered under the following copyright and
* permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF
* THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE
* LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS
* SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA
* BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN
* THE REGENTS’ DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT
* OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR
* WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH
* ANY SUCH LICENSES OR RIGHTS.
*******************************************************************************/
/*
*
* Author: Neil Soman [email protected]
>>>>>>>
/*
*Copyright (c) 2009 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Please contact Eucalyptus Systems, Inc., 130 Castilian
* Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/>
* if you need additional information or have any questions.
*
* This file may incorporate work covered under the following copyright and
* permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF
* THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE
* LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS
* SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA
* BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN
* THE REGENTS’ DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT
* OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR
* WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH
* ANY SUCH LICENSES OR RIGHTS.
*******************************************************************************/
/*
*
* Author: Neil Soman [email protected] |
<<<<<<<
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.FileChannel;
=======
>>>>>>>
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.FileChannel;
<<<<<<<
@ConfigurableField(type = ConfigurableFieldType.KEYVALUE, displayName = "SAN Host")
public static String SAN_HOST = "192.168.7.189";
@ConfigurableField(type = ConfigurableFieldType.KEYVALUE, displayName = "SAN Username")
public static String SAN_USERNAME = "grpadmin";
@ConfigurableField(type = ConfigurableFieldType.KEYVALUEHIDDEN, displayName = "SAN Password")
public static String SAN_PASSWORD = "zoomzoom";
=======
>>>>>>>
<<<<<<<
storageInfo = new StorageInfo(StorageProperties.NAME,
StorageProperties.MAX_TOTAL_VOLUME_SIZE,
null,
StorageProperties.MAX_VOLUME_SIZE,
null,
null,
SANManager.SAN_HOST,
SANManager.SAN_USERNAME,
BlockStorageUtil.encryptSCTargetPassword(SANManager.SAN_PASSWORD),
null);
db.add(storageInfo);
} catch (EucalyptusCloudException e) {
LOG.fatal("Unable to update password. " + e.getMessage());
=======
/*if("storage.san.san_password".equals(prop.getQualifiedName())) {
SANInfo.getStorageInfo().setSanPassword(prop.getValue());
} else {*/
ConfigurableProperty entry = PropertyDirectory.getPropertyEntry(prop.getQualifiedName());
//type parser will correctly covert the value
entry.setValue(prop.getValue());
//}
} catch (IllegalAccessException e) {
LOG.error(e, e);
>>>>>>>
ConfigurableProperty entry = PropertyDirectory.getPropertyEntry(prop.getQualifiedName());
//type parser will correctly covert the value
entry.setValue(prop.getValue());
} catch (IllegalAccessException e) {
LOG.error(e, e); |
<<<<<<<
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
=======
>>>>>>>
import java.util.concurrent.LinkedTransferQueue; |
<<<<<<<
private static Tracker tracker;
private final long CACHE_PROGRESS_TIMEOUT = 60000L; //a minute
private ConcurrentHashMap<String, ImageCacher> imageCachers = new ConcurrentHashMap<String, ImageCacher>();
=======
private final long CACHE_PROGRESS_TIMEOUT = 600000L; //ten minutes
private long CACHE_RETRY_TIMEOUT = 1000L;
private final int CACHE_RETRY_LIMIT = 3;
private static ConcurrentHashMap<String, ImageCacher> imageCachers = new ConcurrentHashMap<String, ImageCacher>();
>>>>>>>
private static Tracker tracker;
private final long CACHE_PROGRESS_TIMEOUT = 600000L; //ten minutes
private long CACHE_RETRY_TIMEOUT = 1000L;
private final int CACHE_RETRY_LIMIT = 3;
private static ConcurrentHashMap<String, ImageCacher> imageCachers = new ConcurrentHashMap<String, ImageCacher>();
<<<<<<<
=======
reply.setEtag(objectInfo.getEtag());
reply.setLastModified(DateUtils.format(objectInfo.getLastModified().getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z");
reply.setSize(objectInfo.getSize());
Status status = new Status();
status.setCode(200);
status.setDescription("OK");
reply.setStatus(status);
db.commit();
return reply;
} else {
db.rollback();
throw new AccessDeniedException(objectKey);
>>>>>>>
<<<<<<<
Reader reader = new Reader(bucketName, objectName, objectInfo.getSize(), getQueue, byteRangeStart, byteRangeEnd);
reader.start();
}
reply.setEtag(objectInfo.getEtag());
reply.setLastModified(DateUtils.format(objectInfo.getLastModified().getTime(), DateUtils.ISO8601_DATETIME_PATTERN));
if(byteRangeEnd > -1) {
if(byteRangeEnd <= objectInfo.getSize() && ((byteRangeEnd - byteRangeStart) > 0))
reply.setSize(byteRangeEnd - byteRangeStart);
else
reply.setSize(0L);
=======
Reader reader = new Reader(bucketName, objectName, objectInfo.getSize(), getQueue, byteRangeStart, byteRangeEnd);
reader.start();
}
reply.setEtag(objectInfo.getEtag());
reply.setLastModified(DateUtils.format(objectInfo.getLastModified().getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z");
if(byteRangeEnd > -1) {
if(byteRangeEnd <= objectInfo.getSize() && ((byteRangeEnd - byteRangeStart) > 0))
reply.setSize(byteRangeEnd - byteRangeStart);
else
reply.setSize(0L);
} else {
reply.setSize(objectInfo.getSize());
}
status.setCode(200);
status.setDescription("OK");
reply.setStatus(status);
>>>>>>>
Reader reader = new Reader(bucketName, objectName, objectInfo.getSize(), getQueue, byteRangeStart, byteRangeEnd);
reader.start();
}
reply.setEtag(objectInfo.getEtag());
reply.setLastModified(DateUtils.format(objectInfo.getLastModified().getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z");
if(byteRangeEnd > -1) {
if(byteRangeEnd <= objectInfo.getSize() && ((byteRangeEnd - byteRangeStart) > 0))
reply.setSize(byteRangeEnd - byteRangeStart);
else
reply.setSize(0L);
<<<<<<<
String sourceObjectName = sourceObjectInfo.getObjectName();
destinationObjectName = destinationObjectInfo.getObjectName();
=======
try {
storageManager.copyObject(sourceBucket, sourceObjectName, destinationBucket, destinationObjectName);
} catch(Exception ex) {
LOG.error(ex);
db.rollback();
throw new EucalyptusCloudException("Could not rename " + sourceObjectName + " to " + destinationObjectName);
}
reply.setEtag(etag);
reply.setLastModified(DateUtils.format(lastModified.getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z");
>>>>>>>
String sourceObjectName = sourceObjectInfo.getObjectName();
destinationObjectName = destinationObjectInfo.getObjectName();
<<<<<<<
=======
} else {
EntityWrapper<UserInfo> db2 = new EntityWrapper<UserInfo>();
UserInfo userInfo = new UserInfo(userId);
List<UserInfo> foundUserInfos = db2.query(userInfo);
if(foundUserInfos.size() == 0) {
db2.rollback();
db.rollback();
throw new AccessDeniedException(userId);
}
List<CertificateInfo> certInfos = foundUserInfos.get(0).getCertificates();
boolean signatureVerified = false;
for(CertificateInfo certInfo: certInfos) {
String alias = certInfo.getCertAlias();
try {
X509Certificate cert = userKeyStore.getCertificate(alias);
signatureVerified = canVerifySignature(sigVerifier, cert, signature, verificationString);
if (signatureVerified)
break;
} catch(Exception ex) {
db2.rollback();
db.rollback();
LOG.error(ex, ex);
throw new DecryptionFailedException("signature verification");
}
}
if(!signatureVerified) {
throw new NotAuthorizedException("Invalid signature");
}
db2.commit();
>>>>>>>
<<<<<<<
EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class);
ObjectInfo searchObjectInfo = new ObjectInfo(bucketName, manifestKey);
List<ObjectInfo> objectInfos = dbObject.query(searchObjectInfo);
if(objectInfos.size() > 0) {
ObjectInfo objectInfo = objectInfos.get(0);
if(objectInfo.canRead(userId)) {
EntityWrapper<ImageCacheInfo> db2 = new EntityWrapper<ImageCacheInfo>();
ImageCacheInfo searchImageCacheInfo = new ImageCacheInfo(bucketName, manifestKey);
List<ImageCacheInfo> foundImageCacheInfos = db2.query(searchImageCacheInfo);
db2.commit();
if(foundImageCacheInfos.size() == 0) {
cacheImage(bucketName, manifestKey, userId, request.isAdministrator());
reply.setSuccess(true);
=======
BucketInfo bucket = bucketList.get(0);
for(ObjectInfo objectInfo: bucket.getObjects()) {
if(objectInfo.getObjectKey().equals(manifestKey)) {
if(objectInfo.canRead(userId)) {
EntityWrapper<ImageCacheInfo> db2 = new EntityWrapper<ImageCacheInfo>();
ImageCacheInfo searchImageCacheInfo = new ImageCacheInfo(bucketName, manifestKey);
List<ImageCacheInfo> foundImageCacheInfos = db2.query(searchImageCacheInfo);
db2.commit();
if((foundImageCacheInfos.size() == 0) || (!imageCachers.containsKey(bucketName + manifestKey))) {
cacheImage(bucketName, manifestKey, userId, request.isAdministrator());
reply.setSuccess(true);
}
return reply;
} else {
db.rollback();
throw new AccessDeniedException(manifestKey);
>>>>>>>
EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class);
ObjectInfo searchObjectInfo = new ObjectInfo(bucketName, objectKey);
List<ObjectInfo> objectInfos = dbObject.query(searchObjectInfo);
if(objectInfos.size() > 0) {
ObjectInfo objectInfo = objectInfos.get(0);
if(objectInfo.canRead(userId)) {
checkManifest(bucketName, objectKey, userId);
reply.setSuccess(true);
db.commit();
return reply;
} else {
db.rollback();
throw new AccessDeniedException(objectKey);
}
} else {
db.rollback();
throw new NoSuchEntityException(objectKey);
}
} else {
db.rollback();
throw new NoSuchBucketException(bucketName);
}
}
private synchronized void cacheImage(String bucketName, String manifestKey, String userId, boolean isAdministrator) throws EucalyptusCloudException {
EntityWrapper<ImageCacheInfo> db = new EntityWrapper<ImageCacheInfo>();
ImageCacheInfo searchImageCacheInfo = new ImageCacheInfo(bucketName, manifestKey);
List<ImageCacheInfo> imageCacheInfos = db.query(searchImageCacheInfo);
String decryptedImageKey = null;
if(imageCacheInfos.size() != 0) {
ImageCacheInfo icInfo = imageCacheInfos.get(0);
if(!icInfo.getInCache()) {
decryptedImageKey = icInfo.getImageName();
} else {
db.commit();
return;
}
}
//unzip, untar image in the background
ImageCacher imageCacher = imageCachers.putIfAbsent(bucketName + manifestKey, new ImageCacher(bucketName, manifestKey, decryptedImageKey));
if(imageCacher == null) {
if(decryptedImageKey == null) {
decryptedImageKey = decryptImage(bucketName, manifestKey, userId, isAdministrator);
//decryption worked. Add it.
ImageCacheInfo foundImageCacheInfo = new ImageCacheInfo(bucketName, manifestKey);
foundImageCacheInfo.setImageName(decryptedImageKey);
foundImageCacheInfo.setInCache(false);
foundImageCacheInfo.setUseCount(0);
foundImageCacheInfo.setSize(0L);
db.add(foundImageCacheInfo);
}
db.commit();
imageCacher = imageCachers.get(bucketName + manifestKey);
imageCacher.setDecryptedImageKey(decryptedImageKey);
imageCacher.start();
} else {
db.commit();
}
}
public CacheImageResponseType CacheImage(CacheImageType request) throws EucalyptusCloudException {
CacheImageResponseType reply = (CacheImageResponseType) request.getReply();
reply.setSuccess(false);
String bucketName = request.getBucket();
String manifestKey = request.getKey();
String userId = request.getUserId();
EntityWrapper<BucketInfo> db = new EntityWrapper<BucketInfo>();
BucketInfo bucketInfo = new BucketInfo(bucketName);
List<BucketInfo> bucketList = db.query(bucketInfo);
if (bucketList.size() > 0) {
EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class);
ObjectInfo searchObjectInfo = new ObjectInfo(bucketName, manifestKey);
List<ObjectInfo> objectInfos = dbObject.query(searchObjectInfo);
if(objectInfos.size() > 0) {
ObjectInfo objectInfo = objectInfos.get(0);
if(objectInfo.canRead(userId)) {
EntityWrapper<ImageCacheInfo> db2 = new EntityWrapper<ImageCacheInfo>();
ImageCacheInfo searchImageCacheInfo = new ImageCacheInfo(bucketName, manifestKey);
List<ImageCacheInfo> foundImageCacheInfos = db2.query(searchImageCacheInfo);
db2.commit();
if((foundImageCacheInfos.size() == 0) || (!imageCachers.containsKey(bucketName + manifestKey))) {
cacheImage(bucketName, manifestKey, userId, request.isAdministrator());
reply.setSuccess(true); |
<<<<<<<
=======
import java.util.NoSuchElementException;
>>>>>>>
import java.util.NoSuchElementException;
<<<<<<<
import com.eucalyptus.component.ServiceConfigurations;
=======
import com.eucalyptus.component.ServiceConfigurations;
import com.eucalyptus.component.Topology;
>>>>>>>
import com.eucalyptus.component.ServiceConfigurations;
<<<<<<<
public DnsResponse lookupRecords( Record query ) {
if ( RequestType.PTR.apply( query ) ) {
final InetAddress ip = DomainNameRecords.inAddrArpaToInetAddress( query.getName( ) );
if ( InstanceDomainNames.isInstance( ip ) ) {
final String hostAddress = ip.getHostAddress( );
if ( Addresses.getInstance( ).contains( hostAddress ) ) {
VmInstances.lookupByPublicIp( hostAddress );//existence check
final Name dnsName = InstanceDomainNames.fromInetAddress( InstanceDomainNames.EXTERNAL, ip );
return DnsResponse.forName( query.getName( ) ).answer( DomainNameRecords.ptrRecord( dnsName, ip ) );
} else {
VmInstances.lookupByPrivateIp( hostAddress );//existence check
final Name dnsName = InstanceDomainNames.fromInetAddress( InstanceDomainNames.INTERNAL, ip );
return DnsResponse.forName( query.getName( ) ).answer( DomainNameRecords.ptrRecord( dnsName, ip ) );
}
}
}
return DnsResponse.forName( query.getName( ) ).nxdomain( );
}
=======
public DnsResponse lookupRecords( Record query ) {
Name name = query.getName( );
if ( RequestType.PTR.apply( query ) ) {
InetAddress ip = DomainNameRecords.inAddrArpaToInetAddress( name );
if ( InstanceDomainNames.isInstance( ip ) ) {
return DnsResponse.forName( name )
.answer( DomainNameRecords.ptrRecord( name, ip ) );
}
}
return DnsResponse.forName( name ).nxdomain( );
}
>>>>>>>
public DnsResponse lookupRecords( Record query ) {
if ( RequestType.PTR.apply( query ) ) {
final InetAddress ip = DomainNameRecords.inAddrArpaToInetAddress( query.getName( ) );
if ( InstanceDomainNames.isInstance( ip ) ) {
final String hostAddress = ip.getHostAddress( );
if ( Addresses.getInstance( ).contains( hostAddress ) ) {
VmInstances.lookupByPublicIp( hostAddress );//existence check
final Name dnsName = InstanceDomainNames.fromInetAddress( InstanceDomainNames.EXTERNAL, ip );
return DnsResponse.forName( query.getName( ) ).answer( DomainNameRecords.ptrRecord( dnsName, ip ) );
} else {
VmInstances.lookupByPrivateIp( hostAddress );//existence check
final Name dnsName = InstanceDomainNames.fromInetAddress( InstanceDomainNames.INTERNAL, ip );
return DnsResponse.forName( query.getName( ) ).answer( DomainNameRecords.ptrRecord( dnsName, ip ) );
}
}
}
return DnsResponse.forName( query.getName( ) ).nxdomain( );
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.