answer
stringlengths 17
10.2M
|
|---|
package com.planetmayo.debrief.satc_rcp.ui.widgets;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.ui.Layer;
public class ZoneChart
{
private Zone[] zones = new Zone[0];
private Map<Zone, IntervalMarker> zoneMarkers =
new HashMap<ZoneChart.Zone, IntervalMarker>();
private long[] timeValues = new long[0];
private long[] angleValues = new long[0];
public ChartComposite create(Composite parent, final Zone[] zones,
long[] timeValues, long[] angleValues)
{
this.zones = zones;
this.zoneMarkers.clear();
this.timeValues = timeValues;
this.angleValues = angleValues;
// build the jfreechart Plot
final XYSeries xySeries = new XYSeries("");
for (int i = 0; i < timeValues.length; i++)
{
xySeries.add(timeValues[i], angleValues[i]);
}
final XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(xySeries);
JFreeChart xylineChart =
ChartFactory.createXYLineChart("", "Time", "Angle", dataset,
PlotOrientation.VERTICAL, true, true, false);
final XYPlot plot = (XYPlot) xylineChart.getPlot();
NumberAxis xAxis = new NumberAxis();
xAxis.setTickUnit(new NumberTickUnit(1));
plot.setDomainAxis(xAxis);
for (Zone zone : zones)
{
IntervalMarker mrk = new IntervalMarker(zone.start, zone.end);
plot.addDomainMarker(mrk, Layer.FOREGROUND);
zoneMarkers.put(zone, mrk);
}
ChartComposite chartComposite = createChartUI(parent, zones, xylineChart);
return chartComposite;
}
private ChartComposite createChartUI(Composite parent, final Zone[] zones,
JFreeChart xylineChart)
{
final Cursor handCursor = new Cursor(Display.getDefault(), SWT.CURSOR_HAND);
final ChartComposite chartComposite =
new ChartComposite(parent, SWT.NONE, xylineChart, 400, 600, 300, 200,
1800, 1800, true, false, true, true, true, true)
{
double dragStartX = -1;
List<Zone> dragZones = new ArrayList<Zone>();
@Override
public void mouseDown(MouseEvent event)
{
dragZones.clear();
dragStartX = findDomainX(this,event.x);
for (Zone zone : zones)
{
// find the drag area zones
if (zone.start <= dragStartX && zone.end >= dragStartX)
{
dragZones.add(zone);
}
}
if (dragZones.isEmpty())
super.mouseDown(event);
}
@Override
public void mouseMove(MouseEvent event)
{
double currentX = findDomainX(this,event.x);
for (Zone zone : zones)
{
// find the drag area zones
if (zone.start <= currentX && zone.end >= currentX)
{
this.setCursor(handCursor);
break;
}
this.setCursor(null);
}
if (!dragZones.isEmpty() && dragStartX > 0)
{
double diff = Math.round(currentX - dragStartX);
if (diff != 0)
{
dragStartX = currentX;
for (Zone z : dragZones)
{
z.start += diff;
z.end += diff;
IntervalMarker intervalMarker = zoneMarkers.get(z);
assert intervalMarker != null;
intervalMarker.setStartValue(z.start);
intervalMarker.setEndValue(z.end);
}
}
}
else
super.mouseMove(event);
}
@Override
public void mouseUp(MouseEvent event)
{
dragStartX = -1;
dragZones.clear();
super.mouseUp(event);
}
};
xylineChart.setAntiAlias(false);
chartComposite.setDomainZoomable(false);
chartComposite.setRangeZoomable(false);
chartComposite.addDisposeListener(new DisposeListener()
{
@Override
public void widgetDisposed(DisposeEvent e)
{
handCursor.dispose();
}
});
return chartComposite;
}
private double findDomainX(ChartComposite composite, int x)
{
final Rectangle dataArea = composite.getScreenDataArea();
final Rectangle2D d2 =
new Rectangle2D.Double(dataArea.x, dataArea.y, dataArea.width,
dataArea.height);
final XYPlot plot = (XYPlot) composite.getChart().getPlot();
final double chartX =
plot.getDomainAxis().java2DToValue(x, d2, plot.getDomainAxisEdge());
return chartX;
}
public Zone[] getZones()
{
return zones;
}
public static class Zone
{
int start, end;
public Zone(int start, int end)
{
this.start = start;
this.end = end;
}
public int getStart()
{
return start;
}
public int getEnd()
{
return end;
}
@Override
public String toString()
{
return "Zone [start=" + start + ", end=" + end + "]";
}
}
}
|
package com.merakianalytics.orianna.datapipeline.riotapi;
import java.util.Iterator;
import java.util.Map;
import com.merakianalytics.datapipelines.PipelineContext;
import com.merakianalytics.datapipelines.iterators.CloseableIterator;
import com.merakianalytics.datapipelines.iterators.CloseableIterators;
import com.merakianalytics.datapipelines.sources.Get;
import com.merakianalytics.datapipelines.sources.GetMany;
import com.merakianalytics.orianna.datapipeline.common.HTTPClient;
import com.merakianalytics.orianna.datapipeline.common.QueryValidationException;
import com.merakianalytics.orianna.datapipeline.common.Utilities;
import com.merakianalytics.orianna.datapipeline.common.rates.RateLimiter;
import com.merakianalytics.orianna.datapipeline.riotapi.RiotAPI.Configuration;
import com.merakianalytics.orianna.types.common.Platform;
import com.merakianalytics.orianna.types.dto.summoner.Summoner;
public class SummonerAPI extends RiotAPIService {
public SummonerAPI(final Configuration config, final HTTPClient client, final Map<Platform, RateLimiter> applicationRateLimiters,
final Map<Platform, Object> applicationRateLimiterLocks) {
super(config, client, applicationRateLimiters, applicationRateLimiterLocks);
}
@SuppressWarnings("unchecked")
@GetMany(Summoner.class)
public CloseableIterator<Summoner> getManySummoner(final Map<String, Object> query, final PipelineContext context) {
final Platform platform = (Platform)query.get("platform");
Utilities.checkNotNull(platform, "platform");
final Iterable<String> puuids = (Iterable<String>)query.get("puuids");
final Iterable<String> accountIds = (Iterable<String>)query.get("accountIds");
final Iterable<String> summonerIds = (Iterable<String>)query.get("ids");
final Iterable<String> summonerNames = (Iterable<String>)query.get("names");
Utilities.checkAtLeastOneNotNull(puuids, "puuids", accountIds, "accountIds", summonerIds, "ids", summonerNames, "names");
final Iterator<String> iterator;
final String baseEndpoint;
final String limiter;
final boolean names;
if(puuids != null) {
iterator = puuids.iterator();
baseEndpoint = "lol/summoner/v4/summoners/by-puuid/";
limiter = "lol/summoner/v4/summoners/by-puuid/puuid";
names = false;
} else if(accountIds != null) {
iterator = accountIds.iterator();
baseEndpoint = "lol/summoner/v4/summoners/by-account/";
limiter = "lol/summoner/v4/summoners/by-account/accountId";
names = false;
} else if(summonerIds != null) {
iterator = summonerIds.iterator();
baseEndpoint = "lol/summoner/v4/summoners/";
limiter = "lol/summoner/v4/summoners/summonerId";
names = false;
} else if(summonerNames != null) {
iterator = summonerNames.iterator();
baseEndpoint = "lol/summoner/v4/summoners/by-name/";
limiter = "lol/summoner/v4/summoners/by-name/summonerName";
names = true;
} else {
return null;
}
return CloseableIterators.from(new Iterator<Summoner>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Summoner next() {
final String identifier = iterator.next();
if(names) {
try {
Utilities.checkSummonerName(identifier);
} catch(final QueryValidationException e) {
return null;
}
}
final String endpoint = baseEndpoint + identifier;
final Summoner data = get(Summoner.class, endpoint, platform, limiter);
if(data == null) {
return null;
}
data.setPlatform(platform.getTag());
return data;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
});
}
@Get(Summoner.class)
public Summoner getSummoner(final Map<String, Object> query, final PipelineContext context) {
final Platform platform = (Platform)query.get("platform");
Utilities.checkNotNull(platform, "platform");
final String puuid = (String)query.get("puuid");
final String accountId = (String)query.get("accountId");
final String summonerId = (String)query.get("id");
final String summonerName = (String)query.get("name");
Utilities.checkAtLeastOneNotNull(puuid, "puuid", accountId, "accountId", summonerId, "id", summonerName, "name");
String endpoint;
String limiter;
if(puuid != null) {
endpoint = "lol/summoner/v4/summoners/by-puuid/" + puuid;
limiter = "lol/summoner/v4/summoners/by-puuid/puuid";
} else if(accountId != null) {
endpoint = "lol/summoner/v4/summoners/by-account/" + accountId;
limiter = "lol/summoner/v4/summoners/by-account/accountId";
} else if(summonerId != null) {
endpoint = "lol/summoner/v4/summoners/" + summonerId;
limiter = "lol/summoner/v4/summoners/summonerId";
} else if(summonerName != null) {
try {
Utilities.checkSummonerName(summonerName);
} catch(final QueryValidationException e) {
return null;
}
endpoint = "lol/summoner/v4/summoners/by-name/" + summonerName;
limiter = "lol/summoner/v4/summoners/by-name/summonerName";
} else {
return null;
}
final Summoner data = get(Summoner.class, endpoint, platform, limiter);
if(data == null) {
return null;
}
data.setPlatform(platform.getTag());
return data;
}
}
|
package uk.ac.ebi.spot.goci.service;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.model.FilterAssociation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class FilteringService {
public Map<String, List<FilterAssociation>> groupByChromosomeName(List<FilterAssociation> associations){
Map<String, List<FilterAssociation>> byChrom =
associations.stream()
.collect(Collectors.groupingBy(FilterAssociation::getChromosomeName));
return byChrom;
}
public Map<String, List<FilterAssociation>> sortByBPLocation(Map<String, List<FilterAssociation>> byChrom){
Map<String, List<FilterAssociation>> byBPLocation = new HashMap<>();
byChrom.forEach((k, v) -> {
List<FilterAssociation> byChromBP = v.stream()
.sorted((v1, v2) -> Integer.compare(v1.getChromosomePosition(), v2.getChromosomePosition()))
.collect(Collectors.toList());
byBPLocation.put(k, byChromBP);
}) ;
return byBPLocation;
}
public List<FilterAssociation> filterTopAssociations(Map<String, List<FilterAssociation>> byBPLocation){
List<FilterAssociation> filtered = new ArrayList<>();
byBPLocation.forEach((chromName, associations) -> {
System.out.println("Processing chromosome " + chromName + " with " + associations.size() + " associations");
if(associations.size() == 1 && associations.get(0).getPvalueExponent() < -5){
associations.get(0).setIsTopAssociation(true);
}
else {
int i =0;
while(i < associations.size()) {
FilterAssociation current = associations.get(i);
if(current.getPvalueExponent() < -5) {
List<FilterAssociation> ldBlock = new ArrayList<>();
if(current.getLdBlock() != null){
boolean end = false;
ldBlock.add(current);
while (!end) {
if (i == associations.size() - 1) {
end = true;
}
else {
FilterAssociation b = associations.get(i + 1);
if (current.getLdBlock().equals(b.getLdBlock())) {
ldBlock.add(b);
i++;
}
else {
end = true;
}
}
}
}
else {
Integer distToPrev = null;
if (i > 0) {
distToPrev = current.getChromosomePosition() -
associations.get(i - 1).getChromosomePosition();
}
Integer distToNext = null;
if (i < associations.size() - 1) {
distToNext = associations.get(i + 1).getChromosomePosition() -
current.getChromosomePosition();
}
if (distToPrev != null && distToNext != null && distToPrev > 100000 &&
distToNext > 100000) {
current.setIsTopAssociation(true);
}
else if (distToPrev == null && distToNext != null && distToNext > 100000) {
current.setIsTopAssociation(true);
}
else if (distToPrev != null && distToNext == null && distToPrev > 100000) {
current.setIsTopAssociation(true);
}
else if (distToPrev != null && distToPrev < 100000 &&
!(associations.get(i - 1).getPvalueExponent() < -5)
&& ((distToNext != null && distToNext > 100000) || distToNext == null)) {
current.setIsTopAssociation(true);
}
else if (distToNext != null && distToNext < 100000) {
int j = i;
boolean end = false;
ldBlock.add(current);
while (!end) {
FilterAssociation a = associations.get(j);
FilterAssociation b = associations.get(j + 1);
Integer dist = b.getChromosomePosition() - a.getChromosomePosition();
if (dist < 100000) {
ldBlock.add(b);
j++;
}
else {
end = true;
}
if (j == associations.size() - 1) {
end = true;
}
}
i = j;
}
}
if(ldBlock.size() != 0) {
int min = ldBlock.get(0).getChromosomePosition();
int maxDist = ldBlock.get(ldBlock.size()-1).getChromosomePosition() - min;
if(maxDist > 100000){
setSecondaryBlocks(ldBlock);
}
else {
setMostSignificant(ldBlock);
}
}
}
i++;
}
}
filtered.addAll(associations);
});
return filtered;
}
public void setMostSignificant(List<FilterAssociation> ldBlock){
FilterAssociation mostSignificant;
List<FilterAssociation> secondary = new ArrayList<>();
if (ldBlock.size() > 1) {
List<FilterAssociation> byPval = ldBlock.stream()
.sorted((fa1, fa2) -> Double.compare(fa1.getPvalue(),
fa2.getPvalue()))
.collect(Collectors.toList());
mostSignificant = byPval.get(0);
if (mostSignificant.getPrecisionConcern()) {
for (int k = 1; k < byPval.size(); k++) {
FilterAssociation fa = byPval.get(k);
if (fa.getPvalueExponent() == mostSignificant.getPvalueExponent()) {
if (fa.getPvalueMantissa() < mostSignificant.getPvalueMantissa()) {
mostSignificant = fa;
}
else if (fa.getPvalueMantissa() ==
mostSignificant.getPvalueMantissa()) {
secondary.add(fa);
}
}
else {
break;
}
}
}
else {
boolean done = false;
int p = 0;
while(!done && p < byPval.size()-1) {
if (byPval.get(p).getPvalue() == byPval.get(p+1).getPvalue()) {
secondary.add(byPval.get(p+1));
p++;
}
else{
done = true;
}
}
}
}
else {
mostSignificant = ldBlock.get(0);
}
if (mostSignificant.getPvalueExponent() < -5) {
mostSignificant.setIsTopAssociation(true);
}
//account for the case where multiple p-values within the same LD block are identical
if (secondary.size() != 0){
mostSignificant.setIsAmbigious(true);
for(FilterAssociation s : secondary){
if(s.getPvalue() == mostSignificant.getPvalue()){
s.setIsTopAssociation(true);
s.setIsAmbigious(true);
}
}
}
}
//this method isn't complete yet
/*Secondary LD block algorithm:
*
* - start at first element, carry on until distance > 100KB
* - find the most significant association in this block
* - using the most significant association as a starting point, find any associations with
* distance to this one > 100kb
* - this is the 2nd block --> find the most significant associaton in this block
* - repeat if necessary
*
* */
public void setSecondaryBlocks(List<FilterAssociation> ldBlock){
Map<Integer, List<FilterAssociation>> secondaryBlocks = new HashMap<Integer, List<FilterAssociation>>();
List<Integer> mostSign = new ArrayList<>();
Integer index = 0;
boolean done = false;
while(!done){
int min = ldBlock.get(index).getChromosomePosition();
ArrayList<FilterAssociation> block = new ArrayList<FilterAssociation>();
boolean next = false;
int q = index+1;
while(!next && q < ldBlock.size()){
int max = ldBlock.get(q).getChromosomePosition();
if(max-min < 100000){
block.add(ldBlock.get(q));
q++;
}
else {
next = true;
}
}
FilterAssociation ms = findMostSignificantInBlock(block);
int i = ldBlock.indexOf(ms);
secondaryBlocks.put(index, block);
mostSign.add(i);
if(i == index){
index = i + block.size();
}
else {
index = i;
}
if(q == ldBlock.size()-1){
done = true;
}
}
for(Integer a : mostSign){
}
}
public FilterAssociation findMostSignificantInBlock(ArrayList<FilterAssociation> block){
List<FilterAssociation> byPval = block.stream()
.sorted((fa1, fa2) -> Double.compare(fa1.getPvalue(),
fa2.getPvalue()))
.collect(Collectors.toList());
return byPval.get(0);
}
}
|
package com.oracle.graal.truffle.nodes.typesystem;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.calc.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.calc.*;
import com.oracle.graal.nodes.extended.*;
import com.oracle.graal.nodes.spi.*;
import com.oracle.graal.nodes.type.*;
import com.oracle.graal.truffle.nodes.*;
import com.oracle.truffle.api.*;
/**
* Load of a final value from a location specified as an offset relative to an object.
*
* Substitution for method {@link CompilerDirectives#unsafeGetFinalObject} and friends.
*/
public class CustomizedUnsafeLoadFinalNode extends FixedWithNextNode implements Canonicalizable, Virtualizable, Lowerable {
@Input private ValueNode object;
@Input private ValueNode offset;
@Input private ValueNode condition;
@Input private ValueNode location;
private final Kind accessKind;
public CustomizedUnsafeLoadFinalNode(ValueNode object, ValueNode offset, ValueNode condition, ValueNode location, Kind accessKind) {
super(StampFactory.forKind(accessKind.getStackKind()));
this.object = object;
this.offset = offset;
this.condition = condition;
this.location = location;
this.accessKind = accessKind;
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (object.isConstant() && !object.isNullConstant() && offset.isConstant()) {
Constant constant = tool.getConstantReflection().readUnsafeConstant(accessKind, object.asConstant(), offset.asConstant().asLong());
return ConstantNode.forConstant(constant, tool.getMetaAccess(), graph());
}
return this;
}
/**
* @see UnsafeLoadNode#virtualize(VirtualizerTool)
*/
@Override
public void virtualize(VirtualizerTool tool) {
State state = tool.getObjectState(object);
if (state != null && state.getState() == EscapeState.Virtual) {
ValueNode offsetValue = tool.getReplacedValue(offset);
if (offsetValue.isConstant()) {
long constantOffset = offsetValue.asConstant().asLong();
int entryIndex = state.getVirtualObject().entryIndexForOffset(constantOffset);
if (entryIndex != -1) {
ValueNode entry = state.getEntry(entryIndex);
if (entry.getKind() == getKind() || state.getVirtualObject().entryKind(entryIndex) == accessKind) {
tool.replaceWith(entry);
}
}
}
}
}
@Override
public void lower(LoweringTool tool) {
CompareNode compare = CompareNode.createCompareNode(graph(), Condition.EQ, condition, ConstantNode.forBoolean(true, graph()));
LocationIdentity locationIdentity;
if (!location.isConstant() || location.asConstant().isNull()) {
locationIdentity = LocationIdentity.ANY_LOCATION;
} else {
locationIdentity = ObjectLocationIdentity.create(location.asConstant());
}
UnsafeLoadNode result = graph().add(new UnsafeLoadNode(object, offset, accessKind, locationIdentity, compare));
graph().replaceFixedWithFixed(this, result);
result.lower(tool);
}
@SuppressWarnings("unused")
@NodeIntrinsic
public static <T> T load(Object object, long offset, boolean condition, Object locationIdentity, @ConstantNodeParameter Kind kind) {
return UnsafeLoadNode.load(object, offset, kind, null);
}
}
|
package org.pentaho.reporting.libraries.formula.function.datetime;
import org.pentaho.reporting.libraries.formula.FormulaTestBase;
import java.math.BigDecimal;
/**
* @author Cedric Pronzato
*/
public class MinuteFunctionTest extends FormulaTestBase {
public Object[][] createDataTest() {
return new Object[][]
{
{ "MINUTE(1/(24*60))", new BigDecimal( 1 ) }, // Changed as a result of PRD-5734 - should be the same as =MINUTE("00:01:00")
{ "MINUTE(TODAY()+1/(24*60))", new BigDecimal( 1 ) }, // Changed as a result of PRD-5734 - should be the same as =MINUTE("00:01:00")
{ "MINUTE(1/24)", new BigDecimal( 0 ) },
{ "MINUTE(TIME(11;37;05))", new BigDecimal( 37 ) },
{ "MINUTE(TIME(11;37;52))", new BigDecimal( 37 ) }, // No rounding ... PRD-5499
{ "MINUTE(TIME(00;00;59))", new BigDecimal( 0 ) },
{ "MINUTE(TIME(00;01;00))", new BigDecimal( 1 ) },
{ "MINUTE(TIME(00;01;59))", new BigDecimal( 1 ) },
{ "MINUTE(\"00:00:59\")", new BigDecimal( 0 ) },
{ "MINUTE(\"00:01:00\")", new BigDecimal( 1 ) },
{ "MINUTE(\"00:01:59\")", new BigDecimal( 1 ) },
{ "MINUTE(\"00:29:59\")", new BigDecimal( 29 ) },
{ "MINUTE(\"00:30:00\")", new BigDecimal( 30 ) },
{ "MINUTE(\"00:30:59\")", new BigDecimal( 30 ) },
{ "MINUTE(TIMEVALUE(\"00:00:59\"))", new BigDecimal( 0 ) },
{ "MINUTE(TIMEVALUE(\"00:01:00\"))", new BigDecimal( 1 ) },
{ "MINUTE(TIMEVALUE(\"00:01:59\"))", new BigDecimal( 1 ) },
{ "MINUTE(TIMEVALUE(\"00:29:59\"))", new BigDecimal( 29 ) },
{ "MINUTE(TIMEVALUE(\"00:30:00\"))", new BigDecimal( 30 ) },
{ "MINUTE(TIMEVALUE(\"00:30:59\"))", new BigDecimal( 30 ) },
{ "MINUTE(15/24/60/60+timevalue(\"00:30:00\"))", new BigDecimal( 30 ) }
};
}
public void testDefault() throws Exception {
runDefaultTest();
}
}
|
package io.github.codefalling.recyclerviewswipedismiss;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.os.SystemClock;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SwipeDismissRecyclerViewTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private RecyclerView mRecyclerView;
private DismissCallbacks mCallbacks;
private boolean mIsVertical;
private OnItemTouchCallBack mItemTouchCallback;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
public interface DismissCallbacks {
boolean canDismiss(int position);
void onDismiss(View view);
}
public interface OnItemTouchCallBack {
void onTouch(int index);
}
public SwipeDismissRecyclerViewTouchListener(Builder builder) {
ViewConfiguration vc = ViewConfiguration.get(builder.mRecyclerView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = builder.mRecyclerView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mRecyclerView = builder.mRecyclerView;
mCallbacks = builder.mCallbacks;
mIsVertical = builder.mIsVertical;
mItemTouchCallback = builder.mItemTouchCallback;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mIsVertical ? mRecyclerView.getHeight() : mRecyclerView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mRecyclerView.getChildCount();
int[] listViewCoords = new int[2];
mRecyclerView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
mDownView = mRecyclerView.findChildViewUnder(x,y);
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
mDownPosition = mRecyclerView.getChildPosition(mDownView);
if (mCallbacks.canDismiss(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
return false;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null && mSwiping) {
// cancel
if (mIsVertical) {
mDownView.animate()
.translationY(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
} else {
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = RecyclerView.NO_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_UP: {
if(!mSwiping&&mDownView!=null&&mItemTouchCallback != null) {
mItemTouchCallback.onTouch(mRecyclerView.getChildPosition(mDownView));
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
return true;
}
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float velocityY = mVelocityTracker.getYVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (mIsVertical) {
if (Math.abs(deltaY) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaY > 0;
} else if (mMinFlingVelocity <= absVelocityY && absVelocityY <= mMaxFlingVelocity
&& absVelocityX < absVelocityY && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityY < 0) == (deltaY < 0);
dismissRight = mVelocityTracker.getYVelocity() > 0;
}
if (dismiss && mDownPosition != ListView.INVALID_POSITION) {
// dismiss
final View downView = mDownView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
mDownView.animate()
.translationY(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
mDownView.animate()
.translationY(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
} else {
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss && mDownPosition != ListView.INVALID_POSITION) {
// dismiss
final View downView = mDownView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
mDownView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (mIsVertical) {
if (Math.abs(deltaY) > mSlop && Math.abs(deltaX) < Math.abs(deltaY) / 2) {
mSwiping = true;
mSwipingSlop = (deltaY > 0 ? mSlop : -mSlop);
mRecyclerView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mRecyclerView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mDownView.setTranslationY(deltaY - mSwipingSlop);
mDownView.setAlpha(Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaY) / mViewWidth)));
return true;
}
} else {
if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
mRecyclerView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mRecyclerView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mDownView.setTranslationX(deltaX - mSwipingSlop);
mDownView.setAlpha(Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
}
break;
}
}
return false;
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
@Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight;
if(mIsVertical)
originalHeight = dismissView.getWidth();
else
originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i
dismissPositions[i] = mPendingDismisses.get(i).position;
}
mCallbacks.onDismiss(dismissView);
// Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
// animation with a stale position
mDownPosition = ListView.INVALID_POSITION;
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(1f);
if(mIsVertical)
pendingDismiss.view.setTranslationY(0);
else
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
if(mIsVertical)
lp.width = originalHeight;
else
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
// Send a cancel event
long time = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(time, time,
MotionEvent.ACTION_CANCEL, 0, 0, 0);
mRecyclerView.dispatchTouchEvent(cancelEvent);
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
if(mIsVertical)
lp.width = (Integer) valueAnimator.getAnimatedValue();
else
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
static public class Builder{
private RecyclerView mRecyclerView;
private DismissCallbacks mCallbacks;
private OnItemTouchCallBack mItemTouchCallback = null;
private boolean mIsVertical = false;
public Builder(RecyclerView recyclerView,DismissCallbacks callbacks){
mRecyclerView = recyclerView;
mCallbacks = callbacks;
}
public Builder setIsVertical(boolean isVertical){
mIsVertical = isVertical;
return this;
}
public Builder setItemTouchCallback(OnItemTouchCallBack callBack){
mItemTouchCallback = callBack;
return this;
}
public SwipeDismissRecyclerViewTouchListener create(){
return new SwipeDismissRecyclerViewTouchListener(this);
}
}
}
|
package net.sf.qualitycheck.immutableobject.generator;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
import net.sf.qualitycheck.Check;
import net.sf.qualitycheck.immutableobject.domain.CollectionVariant;
import net.sf.qualitycheck.immutableobject.domain.Field;
import net.sf.qualitycheck.immutableobject.domain.ImmutableSettings;
import net.sf.qualitycheck.immutableobject.domain.ReservedWord;
import net.sf.qualitycheck.immutableobject.domain.Static;
import net.sf.qualitycheck.immutableobject.domain.Type;
import org.stringtemplate.v4.AttributeRenderer;
@ThreadSafe
final class FieldRenderer implements AttributeRenderer {
public enum Option {
/**
* Rendering as attribute
*/
ATTRIBUTE,
/**
* Access as attribute, will be copied in new data structure if necessary (for iterables and maps)
*/
COPY,
/**
* Access by accessor method of an object with corresponding interface, will be copied in new data structure if
* necessary (for iterables and maps)
*/
COPY_FROM_INTERFACE,
/**
* Access as attribute, will be copied in immutable data structure if necessary (for iterables and maps)
*/
IMMUTABLE,
/**
* Undefined format, will be rendered as field access
*/
UNDEFINED;
@Nonnull
public static Option evaluate(@Nonnull final String option) {
Check.notNull(option, "option");
Option ret = UNDEFINED;
for (final Option value : values()) {
if (value.toString().equals(option.trim().toUpperCase())) {
ret = value;
break;
}
}
return ret;
}
}
private static final String CHECK_NONNEGATIVE = "Check.notNegative(%s, \"%s\")";
private static final String CHECK_NONNULL = "Check.notNull(%s, \"%s\")";
@Nonnull
private static String convertIfReservedWord(@Nonnull final String name) {
return ReservedWord.isReserved(name) ? name + "1" : name;
}
@Nonnull
public static String determineGeneric(@Nonnull final Type type) {
return type.getGenericDeclaration().isUndefined() ? "" : "<" + type.getGenericDeclaration().getDeclaration() + ">";
}
@Nonnull
static String surroundWithCheck(@Nonnull final Field field, @Nonnull final String referenceAccess) {
Check.notEmpty(referenceAccess, "referenceAccess");
String result = referenceAccess;
if (field.isNonnegative()) {
result = String.format(CHECK_NONNEGATIVE, result, result);
} else if (field.isNonnull()) {
result = String.format(CHECK_NONNULL, result, result);
}
return result;
}
@Nonnull
private final ImmutableSettings _settings;
public FieldRenderer(@Nonnull final ImmutableSettings settings) {
_settings = Check.notNull(settings, "settings");
}
@Nonnull
String copyCollection(@Nonnull final Field field, @Nonnull final String currentResult) {
String result = currentResult;
final CollectionVariant variant = CollectionVariant.evaluate(field.getType());
if (variant != null) {
if (_settings.hasGuava()) {
result = String.format(variant.getGuavaCopy(), result);
} else {
final String generic = determineGeneric(field.getType());
result = String.format(variant.getDefaultCopy(), generic, result);
}
}
return result;
}
@Nonnull
String makeCollectionImmutable(@Nonnull final Field field, @Nonnull final String currentResult) {
String result = currentResult;
final CollectionVariant variant = CollectionVariant.evaluate(field.getType());
if (variant != null) {
if (_settings.hasGuava()) {
result = String.format(variant.getGuavaImmutable(), result);
} else {
final String generic = determineGeneric(field.getType());
result = String.format(variant.getDefaultImmutable(), generic, result);
}
}
return result;
}
private String regardPrefix(final Field field, final Option option) {
return Static.STATIC != field.getStatic() && option != Option.ATTRIBUTE ? _settings.getFieldPrefix() + field.getName() : field
.getName();
}
@Nonnull
@Override
public String toString(final Object o, final String formatOption, final Locale locale) {
final Field field = (Field) o;
final Option option = formatOption != null ? Option.evaluate(formatOption) : Option.UNDEFINED;
String result = convertIfReservedWord(regardPrefix(field, option));
if (option == Option.COPY || option == Option.COPY_FROM_INTERFACE || option == Option.IMMUTABLE) {
if (Option.COPY_FROM_INTERFACE == option) {
final String argumentName = BasicFormatRenderer.toLowerCamelCase(_settings.getMainInterface().getType().getName());
result = argumentName + "." + field.getAccessorMethodName() + "()";
} else {
result = convertIfReservedWord(field.getName());
}
if (_settings.hasQualityCheck()) {
result = surroundWithCheck(field, result);
}
if (option == Option.IMMUTABLE) {
result = makeCollectionImmutable(field, result);
} else if (option == Option.COPY || option == Option.COPY_FROM_INTERFACE) {
result = copyCollection(field, result);
}
}
return result;
}
}
|
package org.opennms.netmgt.poller.pollables;
import static org.easymock.EasyMock.anyInt;
import static org.easymock.EasyMock.endsWith;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.opennms.core.utils.InetAddressUtils.addr;
import java.io.File;
import java.io.FileWriter;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opennms.core.db.DataSourceFactory;
import org.opennms.core.test.MockLogAppender;
import org.opennms.core.test.db.MockDatabase;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.PollOutagesConfigFactory;
import org.opennms.netmgt.config.PollerConfig;
import org.opennms.netmgt.config.poller.Package;
import org.opennms.netmgt.config.poller.Rrd;
import org.opennms.netmgt.dao.mock.EventAnticipator;
import org.opennms.netmgt.dao.mock.MockEventIpcManager;
import org.opennms.netmgt.dao.support.NullRrdStrategy;
import org.opennms.netmgt.eventd.EventIpcManagerFactory;
import org.opennms.netmgt.filter.FilterDao;
import org.opennms.netmgt.filter.FilterDaoFactory;
import org.opennms.netmgt.mock.MockNetwork;
import org.opennms.netmgt.model.PollStatus;
import org.opennms.netmgt.model.events.EventBuilder;
import org.opennms.netmgt.model.events.EventIpcManager;
import org.opennms.netmgt.poller.MonitoredService;
import org.opennms.netmgt.poller.ServiceMonitor;
import org.opennms.netmgt.rrd.RrdDataSource;
import org.opennms.netmgt.rrd.RrdStrategy;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.test.mock.EasyMockUtils;
import org.springframework.core.io.FileSystemResource;
public class LatencyStoringServiceMonitorAdaptorTest {
private EasyMockUtils m_mocks;
private PollerConfig m_pollerConfig;
private RrdStrategy<Object,Object> m_rrdStrategy;
@Before
// Cannot avoid this warning since there is no way to fetch the class object for an interface
// that uses generics
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
m_mocks = new EasyMockUtils();
m_pollerConfig = m_mocks.createMock(PollerConfig.class);
m_rrdStrategy = m_mocks.createMock(RrdStrategy.class);
MockLogAppender.setupLogging();
RrdUtils.setStrategy(new NullRrdStrategy());
RrdUtils.setStrategy(m_rrdStrategy);
System.setProperty("opennms.home", "src/test/resources");
PollOutagesConfigFactory.init();
}
@After
public void tearDown() throws Throwable {
MockLogAppender.assertNoWarningsOrGreater();
}
@SuppressWarnings("unchecked")
@Test
public void testUpdateRrdWithLocaleThatUsesCommasForDecimals() throws Exception {
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.FRENCH);
// Make sure we actually have a valid test
NumberFormat nf = NumberFormat.getInstance();
Assert.assertEquals("ensure that the newly set default locale (" + Locale.getDefault() + ") uses ',' as the decimal marker", "1,5", nf.format(1.5));
LatencyStoringServiceMonitorAdaptor adaptor = new LatencyStoringServiceMonitorAdaptor(null, m_pollerConfig, new Package());
LinkedHashMap<String, Number> map = new LinkedHashMap<String, Number>();
map.put("cheese", 1.5);
expect(m_pollerConfig.getStep(isA(Package.class))).andReturn(0).anyTimes();
expect(m_pollerConfig.getRRAList(isA(Package.class))).andReturn(new ArrayList<String>(0));
expect(m_rrdStrategy.getDefaultFileExtension()).andReturn(".rrd").anyTimes();
expect(m_rrdStrategy.createDefinition(isA(String.class), isA(String.class), isA(String.class), anyInt(), isAList(RrdDataSource.class), isAList(String.class))).andReturn(new Object());
m_rrdStrategy.createFile(isA(Object.class), (Map<String, String>) eq(null));
expect(m_rrdStrategy.openFile(isA(String.class))).andReturn(new Object());
m_rrdStrategy.updateFile(isA(Object.class), isA(String.class), endsWith(":1.5"));
m_rrdStrategy.closeFile(isA(Object.class));
m_mocks.replayAll();
adaptor.updateRRD("foo", InetAddress.getLocalHost(), "baz", map);
m_mocks.verifyAll();
Locale.setDefault(defaultLocale);
}
@Test
public void testThresholds() throws Exception {
EventBuilder bldr = new EventBuilder(EventConstants.HIGH_THRESHOLD_EVENT_UEI, "LatencyStoringServiceMonitorAdaptorTest");
bldr.setNodeid(1);
bldr.setInterface(addr("127.0.0.1"));
bldr.setService("ICMP");
EventAnticipator anticipator = new EventAnticipator();
anticipator.anticipateEvent(bldr.getEvent());
executeThresholdTest(anticipator);
anticipator.verifyAnticipated();
}
// TODO: This test will fail if you have a default locale with >3 characters for month, e.g. Locale.FRENCH
@Test
public void testThresholdsWithScheduledOutage() throws Exception {
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
sb.append("<outages>");
sb.append("<outage name=\"junit outage\" type=\"specific\">");
sb.append("<time begins=\"");
sb.append(formatter.format(new Date(System.currentTimeMillis() - 3600000)));
sb.append("\" ends=\"");
sb.append(formatter.format(new Date(System.currentTimeMillis() + 3600000)));
sb.append("\"/>");
sb.append("<interface address=\"match-any\"/>");
sb.append("</outage>");
sb.append("</outages>");
File file = new File("target/poll-outages.xml");
FileWriter writer = new FileWriter(file);
writer.write(sb.toString());
writer.close();
PollOutagesConfigFactory oldFactory = PollOutagesConfigFactory.getInstance();
PollOutagesConfigFactory.setInstance(new PollOutagesConfigFactory(new FileSystemResource(file)));
PollOutagesConfigFactory.getInstance().afterPropertiesSet();
EventAnticipator anticipator = new EventAnticipator();
executeThresholdTest(anticipator);
anticipator.verifyAnticipated();
// Reset the state of the PollOutagesConfigFactory for any subsequent tests
PollOutagesConfigFactory.setInstance(oldFactory);
file.delete();
}
@SuppressWarnings("unchecked")
private void executeThresholdTest(EventAnticipator anticipator) throws Exception {
System.setProperty("opennms.home", "src/test/resources");
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("rrd-repository", "/tmp");
parameters.put("ds-name", "icmp");
parameters.put("rrd-base-name", "icmp");
parameters.put("thresholding-enabled", "true");
FilterDao filterDao = m_mocks.createMock(FilterDao.class);
expect(filterDao.getActiveIPAddressList((String)EasyMock.anyObject())).andReturn(Collections.singletonList(addr("127.0.0.1"))).anyTimes();
filterDao.flushActiveIpAddressListCache();
EasyMock.expectLastCall().anyTimes();
FilterDaoFactory.setInstance(filterDao);
MonitoredService svc = m_mocks.createMock(MonitoredService.class);
expect(svc.getNodeId()).andReturn(1);
expect(svc.getIpAddr()).andReturn("127.0.0.1");
expect(svc.getAddress()).andReturn(InetAddressUtils.addr("127.0.0.1"));
expect(svc.getSvcName()).andReturn("ICMP");
ServiceMonitor service = m_mocks.createMock(ServiceMonitor.class);
PollStatus value = PollStatus.get(PollStatus.SERVICE_AVAILABLE, 100.0);
expect(service.poll(svc, parameters)).andReturn(value);
int step = 300;
List<String> rras = Collections.singletonList("RRA:AVERAGE:0.5:1:2016");
Package pkg = new Package();
Rrd rrd = new Rrd();
rrd.setStep(step);
rrd.setRras(rras);
pkg.setRrd(rrd);
expect(m_pollerConfig.getRRAList(pkg)).andReturn(rras);
expect(m_pollerConfig.getStep(pkg)).andReturn(step).anyTimes();
expect(m_rrdStrategy.getDefaultFileExtension()).andReturn(".rrd").anyTimes();
expect(m_rrdStrategy.createDefinition(isA(String.class), isA(String.class), isA(String.class), anyInt(), isAList(RrdDataSource.class), isAList(String.class))).andReturn(new Object());
m_rrdStrategy.createFile(isA(Object.class), (Map<String, String>) eq(null));
expect(m_rrdStrategy.openFile(isA(String.class))).andReturn(new Object());
m_rrdStrategy.updateFile(isA(Object.class), isA(String.class), endsWith(":100"));
m_rrdStrategy.closeFile(isA(Object.class));
MockEventIpcManager eventMgr = new MockEventIpcManager();
eventMgr.setEventAnticipator(anticipator);
eventMgr.setSynchronous(true);
EventIpcManager eventdIpcMgr = (EventIpcManager)eventMgr;
EventIpcManagerFactory.setIpcManager(eventdIpcMgr);
MockNetwork network = new MockNetwork();
network.setCriticalService("ICMP");
network.addNode(1, "testNode");
network.addInterface("127.0.0.1");
network.setIfAlias("eth0");
network.addService("ICMP");
network.addService("SNMP");
MockDatabase db = new MockDatabase();
db.populate(network);
db.update("update snmpinterface set snmpifname=?, snmpifdescr=? where id=?", "eth0", "eth0", 1);
DataSourceFactory.setInstance(db);
m_mocks.replayAll();
LatencyStoringServiceMonitorAdaptor adaptor = new LatencyStoringServiceMonitorAdaptor(service, m_pollerConfig, pkg);
adaptor.poll(svc, parameters);
m_mocks.verifyAll();
}
@SuppressWarnings("unchecked")
private static <T> List<T> isAList(Class<T> clazz) {
return isA(List.class);
}
}
|
package org.csstudio.display.builder.model.properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamWriter;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.WidgetPropertyDescriptor;
import org.csstudio.display.builder.model.persist.XMLTags;
import org.csstudio.display.builder.model.persist.XMLUtil;
import org.w3c.dom.Element;
/** Widget property that describes scripts.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class ScriptsWidgetProperty extends WidgetProperty<List<ScriptInfo>>
{
/** Constructor
* @param descriptor Property descriptor
* @param widget Widget that holds the property and handles listeners
* @param default_value Default and initial value
*/
public ScriptsWidgetProperty(
final WidgetPropertyDescriptor<List<ScriptInfo>> descriptor,
final Widget widget,
final List<ScriptInfo> default_value)
{
super(descriptor, widget, default_value);
}
/** @param value Must be ScriptInfo array(!), not List */
@Override
public void setValueFromObject(final Object value) throws Exception
{
if (value instanceof ScriptInfo[])
setValue(Arrays.asList((ScriptInfo[]) value));
else
throw new Exception("Need ScriptInfo[], got " + value);
}
@Override
public void writeToXML(final XMLStreamWriter writer) throws Exception
{
// <script file="..">
// <pv trigger="true">pv_name</pv>
// </script>
for (final ScriptInfo info : value)
{
writer.writeStartElement(XMLTags.SCRIPT);
writer.writeAttribute(XMLTags.FILE, info.getFile());
final String text = info.getText();
if (text != null)
{
writer.writeStartElement(XMLTags.TEXT);
writer.writeCData(text);
writer.writeEndElement();
}
for (final ScriptPV pv : info.getPVs())
{
writer.writeStartElement(XMLTags.PV_NAME);
if (! pv.isTrigger())
writer.writeAttribute(XMLTags.TRIGGER, Boolean.FALSE.toString());
writer.writeCharacters(pv.getName());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
@Override
public void readFromXML(final Element property_xml) throws Exception
{
// Also handles legacy XML
// <path pathString="test.py" checkConnect="true" sfe="false" seoe="false">
// <scriptText><![CDATA[ print "Hi!" ]]></scriptText>
// <pv trig="true">input1</pv>
// </path>
Iterable<Element> script_xml;
if (XMLUtil.getChildElement(property_xml, XMLTags.SCRIPT) != null)
script_xml = XMLUtil.getChildElements(property_xml, XMLTags.SCRIPT);
else // Fall back to legacy tag
script_xml = XMLUtil.getChildElements(property_xml, "path");
final List<ScriptInfo> scripts = new ArrayList<>();
for (final Element xml : script_xml)
{
String file = xml.getAttribute(XMLTags.FILE);
if (file.isEmpty())
file = xml.getAttribute("pathString");
if (file.isEmpty())
Logger.getLogger(getClass().getName())
.log(Level.WARNING, "Missing script 'file'");
// Script content embedded in XML?
Element text_xml = XMLUtil.getChildElement(xml, XMLTags.TEXT);
if (text_xml == null) // Fall back to legacy tag
text_xml = XMLUtil.getChildElement(xml, "scriptText");
final String text = text_xml != null
? text_xml.getFirstChild().getNodeValue()
: null;
final List<ScriptPV> pvs = readPVs(xml);
scripts.add(new ScriptInfo(file, text, pvs));
}
setValue(scripts);
}
private List<ScriptPV> readPVs(final Element xml)
{
final List<ScriptPV> pvs = new ArrayList<>();
// Legacy used just 'pv'
final Iterable<Element> pvs_xml;
if (XMLUtil.getChildElement(xml, XMLTags.PV_NAME) != null)
pvs_xml = XMLUtil.getChildElements(xml, XMLTags.PV_NAME);
else
pvs_xml = XMLUtil.getChildElements(xml, "pv");
for (final Element pv_xml : pvs_xml)
{ // Unless either the new or old attribute is _present_ and set to false,
// default to triggering on this PV
final boolean trigger =
XMLUtil.parseBoolean(pv_xml.getAttribute(XMLTags.TRIGGER), true) &&
XMLUtil.parseBoolean(pv_xml.getAttribute("trig"), true);
final String name = XMLUtil.getString(pv_xml);
pvs.add(new ScriptPV(name, trigger));
}
return pvs;
}
}
|
package org.eclipse.emf.emfstore.common.model.util;
import java.util.Stack;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.emfstore.common.model.impl.NotifiableIdEObjectCollectionImpl;
/**
* Notifies a about changes in its containment hierarchy.
*
* @author koegel
* @author emueller
*/
public class EObjectChangeNotifier extends EContentAdapter {
private final NotifiableIdEObjectCollectionImpl collection;
private boolean isInitializing;
private Stack<Notification> currentNotifications;
private Stack<EObject> removedModelElements;
private int reentrantCallToAddAdapterCounter;
private boolean notificationDisabled;
/**
* Constructor. Attaches an Adapter to the given {@link Notifier} and forwards notifications to the given
* NotifiableIdEObjectCollection, that reacts appropriately.
*
* @param notifiableCollection
* a NotifiableIdEObjectCollection
* @param notifier
* the {@link Notifier} to listen to
*/
public EObjectChangeNotifier(NotifiableIdEObjectCollectionImpl notifiableCollection, Notifier notifier) {
this.collection = notifiableCollection;
isInitializing = true;
currentNotifications = new Stack<Notification>();
removedModelElements = new Stack<EObject>();
notifier.eAdapters().add(this);
isInitializing = false;
reentrantCallToAddAdapterCounter = 0;
notificationDisabled = false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.util.EContentAdapter#addAdapter(org.eclipse.emf.common.notify.Notifier)
*/
@Override
protected void addAdapter(Notifier notifier) {
try {
reentrantCallToAddAdapterCounter += 1;
if (!notifier.eAdapters().contains(this)) {
super.addAdapter(notifier);
}
} finally {
reentrantCallToAddAdapterCounter -= 1;
}
if (reentrantCallToAddAdapterCounter > 0 || currentNotifications.isEmpty()) {
// any other than the first call in re-entrant calls to addAdapter
// are going to call the project
return;
}
Notification currentNotification = currentNotifications.peek();
if (currentNotification != null && !currentNotification.isTouch() && !isInitializing
&& notifier instanceof EObject && !ModelUtil.isIgnoredDatatype((EObject) notifier)) {
EObject modelElement = (EObject) notifier;
if (!collection.containsInstance(modelElement) && isInCollection(modelElement)) {
collection.modelElementAdded(collection, modelElement);
}
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.util.EContentAdapter#removeAdapter(org.eclipse.emf.common.notify.Notifier)
*/
@Override
protected void removeAdapter(Notifier notifier) {
if (isInitializing || currentNotifications.isEmpty()) {
return;
}
Notification currentNotification = currentNotifications.peek();
if (currentNotification != null && currentNotification.isTouch()) {
return;
}
if (currentNotification != null && currentNotification.getFeature() instanceof EReference) {
EReference eReference = (EReference) currentNotification.getFeature();
if (eReference.isContainment() && eReference.getEOpposite() != null
&& !eReference.getEOpposite().isTransient()) {
return;
}
}
if (notifier instanceof EObject) {
EObject modelElement = (EObject) notifier;
if (!isInCollection(modelElement)
&& (collection.containsInstance(modelElement) || collection.getDeletedModelElementId(modelElement) != null)
&& removedModelElements.size() > 0) {
removedModelElements.pop();
removedModelElements.push(modelElement);
}
}
}
/**
* Checks whether the given {@link EObject} is within the collection.
*
* @param modelElement
* the {@link EObject} whose containment should be checked
* @return true, if the {@link EObject} is contained in the collection,
* false otherwise
*/
private boolean isInCollection(EObject modelElement) {
EObject parent = modelElement.eContainer();
if (parent == null) {
return false;
}
if (parent == collection) {
return true;
}
if (collection.containsInstance(parent)) {
return true;
}
return isInCollection(parent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.util.EContentAdapter#notifyChanged(org.eclipse.emf.common.notify.Notification)
*/
@Override
public void notifyChanged(Notification notification) {
if (notificationDisabled) {
return;
}
currentNotifications.push(notification);
// push null to ensure that stack has same size as call stack
// will be replaced with an actual removed element by removeAdapter method if there is any
removedModelElements.push(null);
Object feature = notification.getFeature();
Object notifier = notification.getNotifier();
if (feature instanceof EReference) {
EReference eReference = (EReference) feature;
// Do not create notifications for transient features
if (eReference.isTransient()) {
return;
}
if (eReference.isContainer()) {
handleContainer(notification, eReference);
}
}
super.notifyChanged(notification);
currentNotifications.pop();
// collection itself is not a valid model element
if (!notification.isTouch() && notifier instanceof EObject) {
collection.notify(notification, collection, (EObject) notifier);
}
EObject removedElement = removedModelElements.pop();
if (removedElement != null) {
collection.modelElementRemoved(collection, removedElement);
}
}
/**
* @param notification
*/
private void handleContainer(Notification notification, EReference eReference) {
if (notification.getEventType() == Notification.SET) {
Object newValue = notification.getNewValue();
Object oldValue = notification.getOldValue();
if (newValue == null && oldValue != null) {
removeAdapter((Notifier) notification.getNotifier());
}
}
}
/**
* @param notificationDisabled
* the notificationDisabled to set
*/
public void disableNotifications(boolean notificationDisabled) {
this.notificationDisabled = notificationDisabled;
}
}
|
package org.eclipse.mylyn.internal.tasks.ui.deprecated;
import java.io.File;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ControlContribution;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.mylyn.commons.core.DateUtil;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonThemes;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.internal.tasks.core.CommentQuoter;
import org.eclipse.mylyn.internal.tasks.core.RepositoryQuery;
import org.eclipse.mylyn.internal.tasks.core.TaskContainerDelta;
import org.eclipse.mylyn.internal.tasks.core.deprecated.AbstractLegacyDuplicateDetector;
import org.eclipse.mylyn.internal.tasks.core.deprecated.AbstractLegacyRepositoryConnector;
import org.eclipse.mylyn.internal.tasks.core.deprecated.AbstractTaskDataHandler;
import org.eclipse.mylyn.internal.tasks.core.deprecated.RepositoryAttachment;
import org.eclipse.mylyn.internal.tasks.core.deprecated.RepositoryOperation;
import org.eclipse.mylyn.internal.tasks.core.deprecated.RepositoryTaskAttribute;
import org.eclipse.mylyn.internal.tasks.core.deprecated.RepositoryTaskData;
import org.eclipse.mylyn.internal.tasks.core.deprecated.TaskComment;
import org.eclipse.mylyn.internal.tasks.ui.AttachmentUtil;
import org.eclipse.mylyn.internal.tasks.ui.PersonProposalLabelProvider;
import org.eclipse.mylyn.internal.tasks.ui.PersonProposalProvider;
import org.eclipse.mylyn.internal.tasks.ui.TaskListHyperlink;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.actions.AbstractTaskEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.AttachAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.AttachScreenshotAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.ClearOutgoingAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.CopyAttachmentToClipboardJob;
import org.eclipse.mylyn.internal.tasks.ui.actions.DownloadAttachmentJob;
import org.eclipse.mylyn.internal.tasks.ui.actions.NewSubTaskAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.SynchronizeEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.ToggleTaskActivationAction;
import org.eclipse.mylyn.internal.tasks.ui.editors.AttachmentTableLabelProvider;
import org.eclipse.mylyn.internal.tasks.ui.editors.AttachmentsTableContentProvider;
import org.eclipse.mylyn.internal.tasks.ui.editors.ContentOutlineTools;
import org.eclipse.mylyn.internal.tasks.ui.editors.IRepositoryTaskAttributeListener;
import org.eclipse.mylyn.internal.tasks.ui.editors.IRepositoryTaskSelection;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryAttachmentEditorInput;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskEditorDropListener;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskOutlineNode;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskOutlinePage;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskSelection;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskListChangeAdapter;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskUrlHyperlink;
import org.eclipse.mylyn.internal.tasks.ui.search.SearchHitCollector;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.internal.tasks.ui.views.UpdateRepositoryConfigurationAction;
import org.eclipse.mylyn.tasks.core.AbstractDuplicateDetector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskElement;
import org.eclipse.mylyn.tasks.core.ITaskListChangeListener;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.ITask.SynchronizationState;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.mylyn.tasks.ui.editors.AbstractRenderingEngine;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationAdapter;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.internal.ObjectActionContributorManager;
import org.eclipse.ui.internal.WorkbenchImages;
import org.eclipse.ui.keys.IBindingService;
import org.eclipse.ui.themes.IThemeManager;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
* Extend to provide customized task editing.
*
* @author Mik Kersten
* @author Rob Elves
* @author Jeff Pound (Attachment work)
* @author Steffen Pingel
* @author Xiaoyang Guan (Wiki HTML preview)
* @since 2.0
* @deprecated use {@link AbstractTaskEditorPage} instead
*/
@Deprecated
public abstract class AbstractRepositoryTaskEditor extends TaskFormPage {
private static final String PREF_SORT_ORDER_PREFIX = "org.eclipse.mylyn.editor.comments.sortDirectionUp.";
private static final String ERROR_NOCONNECTIVITY = "Unable to submit at this time. Check connectivity and retry.";
private static final String LABEL_HISTORY = "History";
private static final String LABEL_REPLY = "Reply";
private static final String LABEL_JOB_SUBMIT = "Submitting to repository";
private static final String HEADER_DATE_FORMAT = "yyyy-MM-dd HH:mm";
private static final String ATTACHMENT_DEFAULT_NAME = "attachment";
private static final String CTYPE_ZIP = "zip";
private static final String CTYPE_OCTET_STREAM = "octet-stream";
private static final String CTYPE_TEXT = "text";
private static final String CTYPE_HTML = "html";
private static final String LABEL_BROWSER = "Browser";
private static final String LABEL_DEFAULT_EDITOR = "Default Editor";
private static final String LABEL_TEXT_EDITOR = "Text Editor";
protected static final String CONTEXT_MENU_ID = "#MylynRepositoryEditor";
private FormToolkit toolkit;
private ScrolledForm form;
protected TaskRepository repository;
private static final int RADIO_OPTION_WIDTH = 120;
private static final Font TITLE_FONT = JFaceResources.getBannerFont();
protected static final Font TEXT_FONT = JFaceResources.getDefaultFont();
private static final int DESCRIPTION_WIDTH = 79 * 7; // 500;
private static final int DESCRIPTION_HEIGHT = 10 * 14;
protected static final int SUMMARY_HEIGHT = 20;
private static final String LABEL_BUTTON_SUBMIT = "Submit";
private static final String LABEL_COPY_URL_TO_CLIPBOARD = "Copy &URL";
private static final String LABEL_COPY_TO_CLIPBOARD = "Copy Contents";
private static final String LABEL_SAVE = "Save...";
private static final String LABEL_SEARCH_DUPS = "Search";
private static final String LABEL_SELECT_DETECTOR = "Duplicate Detection";
private RepositoryTaskEditorInput editorInput;
private TaskEditor parentEditor = null;
private RepositoryTaskOutlineNode taskOutlineModel = null;
private boolean expandedStateAttributes = false;
protected Button submitButton;
private Table attachmentsTable;
private boolean refreshEnabled = true;
private TableViewer attachmentsTableViewer;
private final String[] attachmentsColumns = { "Name", "Description", "Type", "Size", "Creator", "Created" };
private final int[] attachmentsColumnWidths = { 140, 160, 100, 70, 100, 100 };
private Composite editorComposite;
protected TextViewer summaryTextViewer;
private ImageHyperlink sortHyperlink;
private boolean commentSortIsUp = true;
private boolean commentSortEnable = false;
private Composite addCommentsComposite;
/**
* WARNING: This is present for backward compatibility only. You can get and set text on this widget but all ui
* related changes to this widget will have no affect as ui is now being presented with a StyledText widget. This
* simply proxies get/setText calls to the StyledText widget.
*/
protected Text summaryText;
private TextViewer newCommentTextViewer;
private org.eclipse.swt.widgets.List ccList;
private Section commentsSection;
private Color colorIncoming;
private boolean hasAttributeChanges = false;
private boolean showAttachments = true;
private boolean attachContextEnabled = true;
protected Button searchForDuplicates;
protected CCombo duplicateDetectorChooser;
protected Label duplicateDetectorLabel;
private boolean ignoreLocationEvents = false;
private boolean refreshing = false;
private TaskComment selectedComment = null;
/**
* @author Raphael Ackermann (bug 195514)
*/
private class TabVerifyKeyListener implements VerifyKeyListener {
public void verifyKey(VerifyEvent event) {
// if there is a tab key, do not "execute" it and instead select the Status control
if (event.keyCode == SWT.TAB) {
event.doit = false;
if (headerInfoComposite != null) {
headerInfoComposite.setFocus();
}
}
}
}
protected enum SECTION_NAME {
ATTRIBTUES_SECTION("Attributes"), ATTACHMENTS_SECTION("Attachments"), DESCRIPTION_SECTION("Description"), COMMENTS_SECTION(
"Comments"), NEWCOMMENT_SECTION("New Comment"), ACTIONS_SECTION("Actions"), PEOPLE_SECTION("People"), RELATEDBUGS_SECTION(
"Related Tasks");
private String prettyName;
public String getPrettyName() {
return prettyName;
}
SECTION_NAME(String prettyName) {
this.prettyName = prettyName;
}
}
private final List<IRepositoryTaskAttributeListener> attributesListeners = new ArrayList<IRepositoryTaskAttributeListener>();
protected RepositoryTaskData taskData;
protected final ISelectionProvider selectionProvider = new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
public ISelection getSelection() {
RepositoryTaskSelection selection = new RepositoryTaskSelection(taskData.getTaskId(),
taskData.getRepositoryUrl(), taskData.getConnectorKind(), "", selectedComment,
taskData.getSummary());
selection.setIsDescription(true);
return selection;
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
public void setSelection(ISelection selection) {
// No implementation.
}
};
private final ITaskListChangeListener TASKLIST_CHANGE_LISTENER = new TaskListChangeAdapter() {
@Override
public void containersChanged(Set<TaskContainerDelta> containers) {
ITask taskToRefresh = null;
for (TaskContainerDelta taskContainerDelta : containers) {
if (repositoryTask != null && repositoryTask.equals(taskContainerDelta.getTarget())) {
if (taskContainerDelta.getKind().equals(TaskContainerDelta.Kind.CONTENT)
&& !taskContainerDelta.isTransient() && !refreshing) {
taskToRefresh = (ITask) taskContainerDelta.getTarget();
break;
}
}
}
if (taskToRefresh != null) {
Thread.dumpStack();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
// if (repositoryTask.getSynchronizationState() == SynchronizationState.INCOMING
// || repositoryTask.getSynchronizationState() == SynchronizationState.CONFLICT) {
parentEditor.setMessage("Task has incoming changes", IMessageProvider.WARNING,
new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
refreshEditor();
}
});
setSubmitEnabled(false);
// } else {
// refreshEditor();
}
});
}
}
};
private final List<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
private IRepositoryTaskSelection lastSelected = null;
/**
* Focuses on form widgets when an item in the outline is selected.
*/
private final ISelectionListener selectionListener = new ISelectionListener() {
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if ((part instanceof ContentOutline) && (selection instanceof StructuredSelection)) {
Object select = ((StructuredSelection) selection).getFirstElement();
if (select instanceof RepositoryTaskOutlineNode) {
RepositoryTaskOutlineNode n = (RepositoryTaskOutlineNode) select;
if (lastSelected != null
&& ContentOutlineTools.getHandle(n).equals(ContentOutlineTools.getHandle(lastSelected))) {
// we don't need to set the selection if it is already
// set
return;
}
lastSelected = n;
boolean highlight = true;
if (n.getKey().equals(RepositoryTaskOutlineNode.LABEL_COMMENTS)) {
highlight = false;
}
Object data = n.getData();
if (n.getKey().equals(RepositoryTaskOutlineNode.LABEL_NEW_COMMENT)) {
selectNewComment();
} else if (n.getKey().equals(RepositoryTaskOutlineNode.LABEL_DESCRIPTION)
&& descriptionTextViewer.isEditable()) {
focusDescription();
} else if (data != null) {
select(data, highlight);
}
}
part.setFocus();
}
}
};
private AbstractTask repositoryTask;
private Set<RepositoryTaskAttribute> changedAttributes;
private Menu menu;
private SynchronizeEditorAction synchronizeEditorAction;
private ToggleTaskActivationAction activateAction;
private Action historyAction;
private Action clearOutgoingAction;
private Action openBrowserAction;
private NewSubTaskAction newSubTaskAction;
private Control lastFocusControl;
/**
* Call upon change to attribute value
*
* @param attribute
* changed attribute
*/
protected boolean attributeChanged(RepositoryTaskAttribute attribute) {
if (attribute == null) {
return false;
}
changedAttributes.add(attribute);
markDirty(true);
validateInput();
return true;
}
@Override
public void init(IEditorSite site, IEditorInput input) {
if (!(input instanceof RepositoryTaskEditorInput)) {
return;
}
initTaskEditor(site, (RepositoryTaskEditorInput) input);
if (taskData != null) {
editorInput.setToolTipText(taskData.getLabel());
taskOutlineModel = RepositoryTaskOutlineNode.parseBugReport(taskData);
}
hasAttributeChanges = hasVisibleAttributeChanges();
TasksUiInternal.getTaskList().addChangeListener(TASKLIST_CHANGE_LISTENER);
}
protected void initTaskEditor(IEditorSite site, RepositoryTaskEditorInput input) {
changedAttributes = new HashSet<RepositoryTaskAttribute>();
editorInput = input;
repositoryTask = editorInput.getRepositoryTask();
repository = editorInput.getRepository();
taskData = editorInput.getTaskData();
if (repositoryTask != null) {
TasksUiPlugin.getTaskDataManager().setTaskRead(repositoryTask, true);
}
connector = (AbstractLegacyRepositoryConnector) TasksUi.getRepositoryManager().getRepositoryConnector(
repository.getConnectorKind());
commentSortIsUp = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
PREF_SORT_ORDER_PREFIX + repository.getConnectorKind());
setSite(site);
setInput(input);
isDirty = false;
}
public AbstractTask getRepositoryTask() {
return repositoryTask;
}
// @Override
// public void markDirty(boolean dirty) {
// if (repositoryTask != null) {
// repositoryTask.setDirty(dirty);
// super.markDirty(dirty);
// /**
// * Update task state
// */
// protected void updateTask() {
// if (taskData == null)
// return;
// if (repositoryTask != null) {
// TasksUiPlugin.getSynchronizationManager().saveOutgoing(repositoryTask, changedAttributes);
// if (parentEditor != null) {
// parentEditor.notifyTaskChanged();
// markDirty(false);
protected abstract void validateInput();
/**
* Creates a new <code>AbstractTaskEditor</code>.
*/
public AbstractRepositoryTaskEditor(FormEditor editor) {
// set the scroll increments so the editor scrolls normally with the
// scroll wheel
super(editor, "id", "label"); //$NON-NLS-1$ //$NON-NLS-2$
}
protected boolean supportsCommentSort() {
return false;
}
@Override
protected void createFormContent(final IManagedForm managedForm) {
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
colorIncoming = themeManager.getCurrentTheme().getColorRegistry().get(CommonThemes.COLOR_INCOMING_BACKGROUND);
super.createFormContent(managedForm);
form = managedForm.getForm();
form.setRedraw(false);
try {
refreshEnabled = false;
toolkit = managedForm.getToolkit();
registerDropListener(form);
editorComposite = form.getBody();
GridLayout editorLayout = new GridLayout();
editorComposite.setLayout(editorLayout);
editorComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
if (taskData != null) {
createSections();
}
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(repository.getConnectorKind());
if (connectorUi == null) {
parentEditor.setMessage("The editor may not be fully loaded", IMessageProvider.INFORMATION,
new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
refreshEditor();
}
});
}
updateHeaderControls();
if (summaryTextViewer != null) {
summaryTextViewer.getTextWidget().setFocus();
}
form.setRedraw(true);
} finally {
refreshEnabled = true;
}
form.reflow(true);
}
private void updateHeaderControls() {
if (taskData == null) {
parentEditor.setMessage(
"Task data not available. Press synchronize button (right) to retrieve latest data.",
IMessageProvider.WARNING, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
if (synchronizeEditorAction != null) {
synchronizeEditorAction.run();
}
}
});
}
getParentEditor().updateHeaderToolBar();
}
/**
* Override for customizing the toolbar.
*
* @since 2.1 (NOTE: likely to change for 3.0)
*/
public void fillToolBar(IToolBarManager toolBarManager) {
ControlContribution repositoryLabelControl = new ControlContribution("Title") { //$NON-NLS-1$
@Override
protected Control createControl(Composite parent) {
Composite composite = toolkit.createComposite(parent);
composite.setLayout(new RowLayout());
composite.setBackground(null);
String label = repository.getRepositoryLabel();
if (label.indexOf("
label = label.substring((repository.getRepositoryUrl().indexOf("
}
Hyperlink link = new Hyperlink(composite, SWT.NONE);
link.setText(label);
link.setFont(TITLE_FONT);
link.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
TasksUiUtil.openEditRepositoryWizard(repository);
}
});
return composite;
}
};
toolBarManager.add(repositoryLabelControl);
if ((taskData != null && !taskData.isNew()) || repositoryTask != null) {
synchronizeEditorAction = new SynchronizeEditorAction();
synchronizeEditorAction.selectionChanged(new StructuredSelection(this));
toolBarManager.add(synchronizeEditorAction);
}
if (taskData != null && !taskData.isNew()) {
if (repositoryTask != null) {
clearOutgoingAction = new ClearOutgoingAction(Collections.singletonList((ITaskElement) repositoryTask));
if (clearOutgoingAction.isEnabled()) {
toolBarManager.add(clearOutgoingAction);
}
newSubTaskAction = new NewSubTaskAction();
newSubTaskAction.selectionChanged(newSubTaskAction, new StructuredSelection(getRepositoryTask()));
if (newSubTaskAction.isEnabled()) {
toolBarManager.add(newSubTaskAction);
}
}
if (getHistoryUrl() != null) {
historyAction = new Action() {
@Override
public void run() {
TasksUiUtil.openUrl(getHistoryUrl());
}
};
historyAction.setImageDescriptor(TasksUiImages.TASK_REPOSITORY_HISTORY);
historyAction.setToolTipText(LABEL_HISTORY);
toolBarManager.add(historyAction);
}
if (connector != null) {
String taskUrl = connector.getTaskUrl(taskData.getRepositoryUrl(), taskData.getTaskKey());
if (taskUrl == null && repositoryTask != null && TasksUiInternal.hasValidUrl(repositoryTask)) {
taskUrl = repositoryTask.getUrl();
}
final String taskUrlToOpen = taskUrl;
if (taskUrlToOpen != null) {
openBrowserAction = new Action() {
@Override
public void run() {
TasksUiUtil.openUrl(taskUrlToOpen);
}
};
openBrowserAction.setImageDescriptor(CommonImages.BROWSER_OPEN_TASK);
openBrowserAction.setToolTipText("Open with Web Browser");
toolBarManager.add(openBrowserAction);
}
}
}
}
private void createSections() {
createSummaryLayout(editorComposite);
Composite attribComp = createAttributeSection();
createAttributeLayout(attribComp);
createCustomAttributeLayout(attribComp);
createRelatedBugsSection(editorComposite);
if (showAttachments) {
createAttachmentLayout(editorComposite);
}
createDescriptionLayout(editorComposite);
createCommentLayout(editorComposite);
createNewCommentLayout(editorComposite);
Composite bottomComposite = toolkit.createComposite(editorComposite);
bottomComposite.setLayout(new GridLayout(2, false));
GridDataFactory.fillDefaults().grab(true, false).applyTo(bottomComposite);
createActionsLayout(bottomComposite);
createPeopleLayout(bottomComposite);
bottomComposite.pack(true);
getSite().getPage().addSelectionListener(selectionListener);
getSite().setSelectionProvider(selectionProvider);
FocusListener listener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
lastFocusControl = (Control) e.widget;
}
};
addFocusListener(editorComposite, listener);
}
private void addFocusListener(Composite composite, FocusListener listener) {
Control[] children = composite.getChildren();
for (Control control : children) {
if ((control instanceof Text) || (control instanceof Button) || (control instanceof Combo)
|| (control instanceof CCombo) || (control instanceof Tree) || (control instanceof Table)
|| (control instanceof Spinner) || (control instanceof Link) || (control instanceof List)
|| (control instanceof TabFolder) || (control instanceof CTabFolder)
|| (control instanceof Hyperlink) || (control instanceof FilteredTree)
|| (control instanceof StyledText)) {
control.addFocusListener(listener);
}
if (control instanceof Composite) {
addFocusListener((Composite) control, listener);
}
}
}
private void removeSections() {
menu = editorComposite.getMenu();
setMenu(editorComposite, null);
for (Control control : editorComposite.getChildren()) {
control.dispose();
}
lastFocusControl = null;
}
/**
* @author Raphael Ackermann (modifications) (bug 195514)
*/
protected void createSummaryLayout(Composite composite) {
addSummaryText(composite);
if (summaryTextViewer != null) {
summaryTextViewer.prependVerifyKeyListener(new TabVerifyKeyListener());
}
headerInfoComposite = toolkit.createComposite(composite);
GridLayout headerLayout = new GridLayout(11, false);
headerLayout.verticalSpacing = 1;
headerLayout.marginHeight = 1;
headerLayout.marginHeight = 1;
headerLayout.marginWidth = 1;
headerLayout.horizontalSpacing = 6;
headerInfoComposite.setLayout(headerLayout);
RepositoryTaskAttribute statusAtribute = taskData.getAttribute(RepositoryTaskAttribute.STATUS);
addNameValue(headerInfoComposite, statusAtribute);
toolkit.paintBordersFor(headerInfoComposite);
RepositoryTaskAttribute priorityAttribute = taskData.getAttribute(RepositoryTaskAttribute.PRIORITY);
addNameValue(headerInfoComposite, priorityAttribute);
String idLabel = (repositoryTask != null) ? repositoryTask.getTaskKey() : taskData.getTaskKey();
if (idLabel != null) {
Composite nameValue = toolkit.createComposite(headerInfoComposite);
nameValue.setLayout(new GridLayout(2, false));
Label label = toolkit.createLabel(nameValue, "ID:");// .setFont(TITLE_FONT);
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
// toolkit.createText(nameValue, idLabel, SWT.FLAT | SWT.READ_ONLY);
Text text = new Text(nameValue, SWT.FLAT | SWT.READ_ONLY);
toolkit.adapt(text, true, true);
text.setText(idLabel);
}
String openedDateString = "";
String modifiedDateString = "";
final AbstractTaskDataHandler taskDataManager = connector.getLegacyTaskDataHandler();
if (taskDataManager != null) {
Date created = taskData.getAttributeFactory().getDateForAttributeType(
RepositoryTaskAttribute.DATE_CREATION, taskData.getCreated());
openedDateString = created != null ? new SimpleDateFormat(HEADER_DATE_FORMAT).format(created) : "";
Date modified = taskData.getAttributeFactory().getDateForAttributeType(
RepositoryTaskAttribute.DATE_MODIFIED, taskData.getLastModified());
modifiedDateString = modified != null ? new SimpleDateFormat(HEADER_DATE_FORMAT).format(modified) : "";
}
RepositoryTaskAttribute creationAttribute = taskData.getAttribute(RepositoryTaskAttribute.DATE_CREATION);
if (creationAttribute != null) {
Composite nameValue = toolkit.createComposite(headerInfoComposite);
nameValue.setLayout(new GridLayout(2, false));
createLabel(nameValue, creationAttribute);
// toolkit.createText(nameValue, openedDateString, SWT.FLAT |
// SWT.READ_ONLY);
Text text = new Text(nameValue, SWT.FLAT | SWT.READ_ONLY);
toolkit.adapt(text, true, true);
text.setText(openedDateString);
}
RepositoryTaskAttribute modifiedAttribute = taskData.getAttribute(RepositoryTaskAttribute.DATE_MODIFIED);
if (modifiedAttribute != null) {
Composite nameValue = toolkit.createComposite(headerInfoComposite);
nameValue.setLayout(new GridLayout(2, false));
createLabel(nameValue, modifiedAttribute);
// toolkit.createText(nameValue, modifiedDateString, SWT.FLAT |
// SWT.READ_ONLY);
Text text = new Text(nameValue, SWT.FLAT | SWT.READ_ONLY);
toolkit.adapt(text, true, true);
text.setText(modifiedDateString);
}
}
private void addNameValue(Composite parent, RepositoryTaskAttribute attribute) {
Composite nameValue = toolkit.createComposite(parent);
nameValue.setLayout(new GridLayout(2, false));
if (attribute != null) {
createLabel(nameValue, attribute);
createTextField(nameValue, attribute, SWT.FLAT | SWT.READ_ONLY);
}
}
/**
* Utility method to create text field sets background to TaskListColorsAndFonts.COLOR_ATTRIBUTE_CHANGED if
* attribute has changed.
*
* @param composite
* @param attribute
* @param style
*/
protected Text createTextField(Composite composite, RepositoryTaskAttribute attribute, int style) {
String value;
if (attribute == null || attribute.getValue() == null) {
value = "";
} else {
value = attribute.getValue();
}
final Text text;
if ((SWT.READ_ONLY & style) == SWT.READ_ONLY) {
text = new Text(composite, style);
toolkit.adapt(text, true, true);
text.setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE);
text.setText(value);
} else {
text = toolkit.createText(composite, value, style);
}
if (attribute != null && !attribute.isReadOnly()) {
text.setData(attribute);
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String newValue = text.getText();
RepositoryTaskAttribute attribute = (RepositoryTaskAttribute) text.getData();
attribute.setValue(newValue);
attributeChanged(attribute);
}
});
}
if (hasChanged(attribute)) {
text.setBackground(colorIncoming);
}
return text;
}
protected Label createLabel(Composite composite, RepositoryTaskAttribute attribute) {
Label label;
if (hasOutgoingChange(attribute)) {
label = toolkit.createLabel(composite, "*" + attribute.getName());
} else {
label = toolkit.createLabel(composite, attribute.getName());
}
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
return label;
}
public String getSectionLabel(SECTION_NAME labelName) {
return labelName.getPrettyName();
}
protected Composite createAttributeSection() {
attributesSection = createSection(editorComposite, getSectionLabel(SECTION_NAME.ATTRIBTUES_SECTION),
expandedStateAttributes || hasAttributeChanges);
Composite toolbarComposite = toolkit.createComposite(attributesSection);
toolbarComposite.setBackground(null);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
UpdateRepositoryConfigurationAction repositoryConfigRefresh = new UpdateRepositoryConfigurationAction() {
@Override
public void performUpdate(TaskRepository repository, AbstractRepositoryConnector connector,
IProgressMonitor monitor) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
setGlobalBusy(true);
}
});
try {
super.performUpdate(repository, connector, monitor);
if (connector != null) {
TasksUiInternal.synchronizeTask(connector, repositoryTask, true, new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshEditor();
}
});
}
});
}
} catch (Exception e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshEditor();
}
});
}
}
};
repositoryConfigRefresh.setImageDescriptor(TasksUiImages.REPOSITORY_SYNCHRONIZE);
repositoryConfigRefresh.selectionChanged(new StructuredSelection(repository));
repositoryConfigRefresh.setToolTipText("Refresh attributes");
ToolBarManager barManager = new ToolBarManager(SWT.FLAT);
barManager.add(repositoryConfigRefresh);
repositoryConfigRefresh.setEnabled(supportsRefreshAttributes());
barManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
barManager.createControl(toolbarComposite);
attributesSection.setTextClient(toolbarComposite);
// Attributes Composite- this holds all the combo fields and text fields
final Composite attribComp = toolkit.createComposite(attributesSection);
attribComp.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
Control focus = event.display.getFocusControl();
if (focus instanceof Text && ((Text) focus).getEditable() == false) {
form.setFocus();
}
}
});
attributesSection.setClient(attribComp);
GridLayout attributesLayout = new GridLayout();
attributesLayout.numColumns = 4;
attributesLayout.horizontalSpacing = 5;
attributesLayout.verticalSpacing = 4;
attribComp.setLayout(attributesLayout);
GridData attributesData = new GridData(GridData.FILL_BOTH);
attributesData.horizontalSpan = 1;
attributesData.grabExcessVerticalSpace = false;
attribComp.setLayoutData(attributesData);
return attribComp;
}
/**
* @since 2.2
*/
protected boolean supportsRefreshAttributes() {
return true;
}
/**
* Creates the attribute section, which contains most of the basic attributes of the task (some of which are
* editable).
*/
protected void createAttributeLayout(Composite attributesComposite) {
int numColumns = ((GridLayout) attributesComposite.getLayout()).numColumns;
int currentCol = 1;
for (final RepositoryTaskAttribute attribute : taskData.getAttributes()) {
if (attribute.isHidden()) {
continue;
}
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
data.horizontalSpan = 1;
if (attribute.hasOptions() && !attribute.isReadOnly()) {
Label label = createLabel(attributesComposite, attribute);
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
final CCombo attributeCombo = new CCombo(attributesComposite, SWT.FLAT | SWT.READ_ONLY);
toolkit.adapt(attributeCombo, true, true);
attributeCombo.setFont(TEXT_FONT);
attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
if (hasChanged(attribute)) {
attributeCombo.setBackground(colorIncoming);
}
attributeCombo.setLayoutData(data);
List<String> values = attribute.getOptions();
if (values != null) {
for (String val : values) {
if (val != null) {
attributeCombo.add(val);
}
}
}
String value = attribute.getValue();
if (value == null) {
value = "";
}
if (attributeCombo.indexOf(value) != -1) {
attributeCombo.select(attributeCombo.indexOf(value));
}
attributeCombo.clearSelection();
attributeCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (attributeCombo.getSelectionIndex() > -1) {
String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex());
attribute.setValue(sel);
attributeChanged(attribute);
attributeCombo.clearSelection();
}
}
});
currentCol += 2;
} else {
Label label = createLabel(attributesComposite, attribute);
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
Composite textFieldComposite = toolkit.createComposite(attributesComposite);
GridLayout textLayout = new GridLayout();
textLayout.marginWidth = 1;
textLayout.marginHeight = 2;
textFieldComposite.setLayout(textLayout);
GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
textData.horizontalSpan = 1;
textData.widthHint = 135;
if (attribute.isReadOnly()) {
final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT | SWT.READ_ONLY);
text.setLayoutData(textData);
} else {
final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT);
// text.setFont(COMMENT_FONT);
text.setLayoutData(textData);
toolkit.paintBordersFor(textFieldComposite);
text.setData(attribute);
if (hasContentAssist(attribute)) {
ContentAssistCommandAdapter adapter = applyContentAssist(text,
createContentProposalProvider(attribute));
ILabelProvider propsalLabelProvider = createProposalLabelProvider(attribute);
if (propsalLabelProvider != null) {
adapter.setLabelProvider(propsalLabelProvider);
}
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}
}
currentCol += 2;
}
if (currentCol > numColumns) {
currentCol -= numColumns;
}
}
// make sure that we are in the first column
if (currentCol > 1) {
while (currentCol <= numColumns) {
toolkit.createLabel(attributesComposite, "");
currentCol++;
}
}
toolkit.paintBordersFor(attributesComposite);
}
/**
* Adds a related bugs section to the bug editor
*/
protected void createRelatedBugsSection(Composite composite) {
// Section relatedBugsSection = createSection(editorComposite, getSectionLabel(SECTION_NAME.RELATEDBUGS_SECTION));
// Composite relatedBugsComposite = toolkit.createComposite(relatedBugsSection);
// relatedBugsComposite.setLayout(new GridLayout(4, false));
// relatedBugsComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
// relatedBugsSection.setClient(relatedBugsComposite);
// relatedBugsSection.setExpanded(repositoryTask == null);
// List<AbstractDuplicateDetector> allCollectors = new ArrayList<AbstractDuplicateDetector>();
// if (getDuplicateSearchCollectorsList() != null) {
// allCollectors.addAll(getDuplicateSearchCollectorsList());
// if (!allCollectors.isEmpty()) {
// duplicateDetectorLabel = new Label(relatedBugsComposite, SWT.LEFT);
// duplicateDetectorLabel.setText(LABEL_SELECT_DETECTOR);
// duplicateDetectorChooser = new CCombo(relatedBugsComposite, SWT.FLAT | SWT.READ_ONLY | SWT.BORDER);
// duplicateDetectorChooser.setLayoutData(GridDataFactory.swtDefaults().hint(150, SWT.DEFAULT).create());
// duplicateDetectorChooser.setFont(TEXT_FONT);
// Collections.sort(allCollectors, new Comparator<AbstractDuplicateDetector>() {
// public int compare(AbstractDuplicateDetector c1, AbstractDuplicateDetector c2) {
// return c1.getName().compareToIgnoreCase(c2.getName());
// for (AbstractDuplicateDetector detector : allCollectors) {
// duplicateDetectorChooser.add(detector.getName());
// duplicateDetectorChooser.select(0);
// duplicateDetectorChooser.setEnabled(true);
// duplicateDetectorChooser.setData(allCollectors);
// if (allCollectors.size() > 0) {
// searchForDuplicates = toolkit.createButton(relatedBugsComposite, LABEL_SEARCH_DUPS, SWT.NONE);
// GridData searchDuplicatesButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
// searchForDuplicates.setLayoutData(searchDuplicatesButtonData);
// searchForDuplicates.addListener(SWT.Selection, new Listener() {
// public void handleEvent(Event e) {
// searchForDuplicates();
// } else {
// Label label = new Label(relatedBugsComposite, SWT.LEFT);
// label.setText(LABEL_NO_DETECTOR);
}
/**
* @since 3.0
*/
protected AbstractLegacyDuplicateDetector getDuplicateDetector(String name) {
String duplicateDetectorName = name.equals("default") ? "Stack Trace" : name;
Set<AbstractLegacyDuplicateDetector> allDetectors = getDuplicateDetectorList();
for (AbstractLegacyDuplicateDetector detector : allDetectors) {
if (detector.getName().equals(duplicateDetectorName)) {
return detector;
}
}
// didn't find it
return null;
}
/**
* @since 3.0
*/
protected Set<AbstractLegacyDuplicateDetector> getDuplicateDetectorList() {
Set<AbstractLegacyDuplicateDetector> duplicateDetectors = new HashSet<AbstractLegacyDuplicateDetector>();
for (AbstractDuplicateDetector abstractDuplicateDetector : TasksUiPlugin.getDefault()
.getDuplicateSearchCollectorsList()) {
if (abstractDuplicateDetector instanceof AbstractLegacyDuplicateDetector
&& (abstractDuplicateDetector.getConnectorKind() == null || abstractDuplicateDetector.getConnectorKind()
.equals(getConnector().getConnectorKind()))) {
duplicateDetectors.add((AbstractLegacyDuplicateDetector) abstractDuplicateDetector);
}
}
return duplicateDetectors;
}
public boolean searchForDuplicates() {
String duplicateDetectorName = duplicateDetectorChooser.getItem(duplicateDetectorChooser.getSelectionIndex());
AbstractLegacyDuplicateDetector duplicateDetector = getDuplicateDetector(duplicateDetectorName);
if (duplicateDetector != null) {
RepositoryQuery duplicatesQuery = duplicateDetector.getDuplicatesQuery(repository, taskData);
if (duplicatesQuery != null) {
SearchHitCollector collector = new SearchHitCollector(TasksUiInternal.getTaskList(), repository,
duplicatesQuery);
NewSearchUI.runQueryInBackground(collector);
return true;
}
}
return false;
}
/**
* Adds content assist to the given text field.
*
* @param text
* text field to decorate.
* @param proposalProvider
* instance providing content proposals
* @return the ContentAssistCommandAdapter for the field.
*/
protected ContentAssistCommandAdapter applyContentAssist(Text text, IContentProposalProvider proposalProvider) {
ControlDecoration controlDecoration = new ControlDecoration(text, (SWT.TOP | SWT.LEFT));
controlDecoration.setMarginWidth(0);
controlDecoration.setShowHover(true);
controlDecoration.setShowOnlyOnFocus(true);
FieldDecoration contentProposalImage = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_CONTENT_PROPOSAL);
controlDecoration.setImage(contentProposalImage.getImage());
TextContentAdapter textContentAdapter = new TextContentAdapter();
ContentAssistCommandAdapter adapter = new ContentAssistCommandAdapter(text, textContentAdapter,
proposalProvider, "org.eclipse.ui.edit.text.contentAssist.proposals", new char[0]);
IBindingService bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class);
controlDecoration.setDescriptionText(NLS.bind("Content Assist Available ({0})",
bindingService.getBestActiveBindingFormattedFor(adapter.getCommandId())));
return adapter;
}
/**
* Creates an IContentProposalProvider to provide content assist proposals for the given attribute.
*
* @param attribute
* attribute for which to provide content assist.
* @return the IContentProposalProvider.
*/
protected IContentProposalProvider createContentProposalProvider(RepositoryTaskAttribute attribute) {
return new PersonProposalProvider(repositoryTask, taskData);
}
/**
* Creates an IContentProposalProvider to provide content assist proposals for the given operation.
*
* @param operation
* operation for which to provide content assist.
* @return the IContentProposalProvider.
*/
protected IContentProposalProvider createContentProposalProvider(RepositoryOperation operation) {
return new PersonProposalProvider(repositoryTask, taskData);
}
protected ILabelProvider createProposalLabelProvider(RepositoryTaskAttribute attribute) {
return new PersonProposalLabelProvider();
}
protected ILabelProvider createProposalLabelProvider(RepositoryOperation operation) {
return new PersonProposalLabelProvider();
}
/**
* Called to check if there's content assist available for the given attribute.
*
* @param attribute
* the attribute
* @return true if content assist is available for the specified attribute.
*/
protected boolean hasContentAssist(RepositoryTaskAttribute attribute) {
return false;
}
/**
* Called to check if there's content assist available for the given operation.
*
* @param operation
* the operation
* @return true if content assist is available for the specified operation.
*/
protected boolean hasContentAssist(RepositoryOperation operation) {
return false;
}
/**
* Adds a text editor with spell checking enabled to display and edit the task's summary.
*
* @author Raphael Ackermann (modifications) (bug 195514)
* @param attributesComposite
* The composite to add the text editor to.
*/
protected void addSummaryText(Composite attributesComposite) {
Composite summaryComposite = toolkit.createComposite(attributesComposite);
GridLayout summaryLayout = new GridLayout(2, false);
summaryLayout.verticalSpacing = 0;
summaryLayout.marginHeight = 2;
summaryComposite.setLayout(summaryLayout);
GridDataFactory.fillDefaults().grab(true, false).applyTo(summaryComposite);
if (taskData != null) {
RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.SUMMARY);
if (attribute == null) {
taskData.setAttributeValue(RepositoryTaskAttribute.SUMMARY, "");
attribute = taskData.getAttribute(RepositoryTaskAttribute.SUMMARY);
}
final RepositoryTaskAttribute summaryAttribute = attribute;
summaryTextViewer = addTextEditor(repository, summaryComposite, attribute.getValue(), true, SWT.FLAT
| SWT.SINGLE);
Composite hiddenComposite = new Composite(summaryComposite, SWT.NONE);
hiddenComposite.setLayout(new GridLayout());
GridData hiddenLayout = new GridData();
hiddenLayout.exclude = true;
hiddenComposite.setLayoutData(hiddenLayout);
// bugg#210695 - work around for 2.0 api breakage
summaryText = new Text(hiddenComposite, SWT.NONE);
summaryText.setText(attribute.getValue());
summaryText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (summaryTextViewer != null && !summaryTextViewer.getTextWidget().isDisposed()) {
String newValue = summaryText.getText();
String oldValue = summaryTextViewer.getTextWidget().getText();
if (!newValue.equals(oldValue)) {
summaryTextViewer.getTextWidget().setText(newValue);
summaryAttribute.setValue(newValue);
attributeChanged(summaryAttribute);
}
}
}
public void keyReleased(KeyEvent e) {
// ignore
}
});
summaryText.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
summaryTextViewer.getTextWidget().setFocus();
}
public void focusLost(FocusEvent e) {
// ignore
}
});
summaryTextViewer.setEditable(true);
summaryTextViewer.getTextWidget().setIndent(2);
GridDataFactory.fillDefaults().grab(true, false).applyTo(summaryTextViewer.getControl());
if (hasChanged(attribute)) {
summaryTextViewer.getTextWidget().setBackground(colorIncoming);
}
summaryTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
summaryTextViewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
String newValue = summaryTextViewer.getTextWidget().getText();
if (!newValue.equals(summaryAttribute.getValue())) {
summaryAttribute.setValue(newValue);
attributeChanged(summaryAttribute);
}
if (summaryText != null && !newValue.equals(summaryText.getText())) {
summaryText.setText(newValue);
}
}
});
}
toolkit.paintBordersFor(summaryComposite);
}
protected boolean supportsAttachmentDelete() {
return false;
}
protected void deleteAttachment(RepositoryAttachment attachment) {
}
protected void createAttachmentLayout(Composite composite) {
// TODO: expand to show new attachments
Section section = createSection(composite, getSectionLabel(SECTION_NAME.ATTACHMENTS_SECTION), false);
section.setText(section.getText() + " (" + taskData.getAttachments().size() + ")");
final Composite attachmentsComposite = toolkit.createComposite(section);
attachmentsComposite.setLayout(new GridLayout(1, false));
attachmentsComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
section.setClient(attachmentsComposite);
if (taskData.getAttachments().size() > 0) {
attachmentsTable = toolkit.createTable(attachmentsComposite, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
attachmentsTable.setLinesVisible(true);
attachmentsTable.setHeaderVisible(true);
attachmentsTable.setLayout(new GridLayout());
GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
attachmentsTable.setLayoutData(tableGridData);
for (int i = 0; i < attachmentsColumns.length; i++) {
TableColumn column = new TableColumn(attachmentsTable, SWT.LEFT, i);
column.setText(attachmentsColumns[i]);
column.setWidth(attachmentsColumnWidths[i]);
}
attachmentsTable.getColumn(3).setAlignment(SWT.RIGHT);
attachmentsTableViewer = new TableViewer(attachmentsTable);
attachmentsTableViewer.setUseHashlookup(true);
attachmentsTableViewer.setColumnProperties(attachmentsColumns);
ColumnViewerToolTipSupport.enableFor(attachmentsTableViewer, ToolTip.NO_RECREATE);
final AbstractTaskDataHandler offlineHandler = connector.getLegacyTaskDataHandler();
if (offlineHandler != null) {
attachmentsTableViewer.setSorter(new ViewerSorter() {
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
RepositoryAttachment attachment1 = (RepositoryAttachment) e1;
RepositoryAttachment attachment2 = (RepositoryAttachment) e2;
Date created1 = taskData.getAttributeFactory().getDateForAttributeType(
RepositoryTaskAttribute.ATTACHMENT_DATE, attachment1.getDateCreated());
Date created2 = taskData.getAttributeFactory().getDateForAttributeType(
RepositoryTaskAttribute.ATTACHMENT_DATE, attachment2.getDateCreated());
if (created1 != null && created2 != null) {
return created1.compareTo(created2);
} else if (created1 == null && created2 != null) {
return -1;
} else if (created1 != null && created2 == null) {
return 1;
} else {
return 0;
}
}
});
}
attachmentsTableViewer.setContentProvider(new AttachmentsTableContentProvider(taskData.getAttachments()));
attachmentsTableViewer.setLabelProvider(new AttachmentTableLabelProvider(this, new LabelProvider(),
PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
attachmentsTableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
if (!event.getSelection().isEmpty()) {
StructuredSelection selection = (StructuredSelection) event.getSelection();
RepositoryAttachment attachment = (RepositoryAttachment) selection.getFirstElement();
TasksUiUtil.openUrl(attachment.getUrl());
}
}
});
attachmentsTableViewer.setInput(taskData);
final Action openWithBrowserAction = new Action(LABEL_BROWSER) {
@Override
public void run() {
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
if (attachment != null) {
TasksUiUtil.openUrl(attachment.getUrl());
}
}
};
final Action openWithDefaultAction = new Action(LABEL_DEFAULT_EDITOR) {
@Override
public void run() {
// browser shortcut
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
if (attachment == null) {
return;
}
if (attachment.getContentType().endsWith(CTYPE_HTML)) {
TasksUiUtil.openUrl(attachment.getUrl());
return;
}
IStorageEditorInput input = new RepositoryAttachmentEditorInput(repository, attachment);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (page == null) {
return;
}
IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(
input.getName());
try {
page.openEditor(input, desc.getId());
} catch (PartInitException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Unable to open editor for: " + attachment.getDescription(), e));
}
}
};
final Action openWithTextEditorAction = new Action(LABEL_TEXT_EDITOR) {
@Override
public void run() {
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
IStorageEditorInput input = new RepositoryAttachmentEditorInput(repository, attachment);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (page == null) {
return;
}
try {
page.openEditor(input, "org.eclipse.ui.DefaultTextEditor");
} catch (PartInitException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Unable to open editor for: " + attachment.getDescription(), e));
}
}
};
final Action saveAction = new Action(LABEL_SAVE) {
@Override
public void run() {
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
/* Launch Browser */
FileDialog fileChooser = new FileDialog(attachmentsTable.getShell(), SWT.SAVE);
String fname = attachment.getAttributeValue(RepositoryTaskAttribute.ATTACHMENT_FILENAME);
// Default name if none is found
if (fname.equals("")) {
String ctype = attachment.getContentType();
if (ctype.endsWith(CTYPE_HTML)) {
fname = ATTACHMENT_DEFAULT_NAME + ".html";
} else if (ctype.startsWith(CTYPE_TEXT)) {
fname = ATTACHMENT_DEFAULT_NAME + ".txt";
} else if (ctype.endsWith(CTYPE_OCTET_STREAM)) {
fname = ATTACHMENT_DEFAULT_NAME;
} else if (ctype.endsWith(CTYPE_ZIP)) {
fname = ATTACHMENT_DEFAULT_NAME + "." + CTYPE_ZIP;
} else {
fname = ATTACHMENT_DEFAULT_NAME + "." + ctype.substring(ctype.indexOf("/") + 1);
}
}
fileChooser.setFileName(fname);
String filePath = fileChooser.open();
// Check if the dialog was canceled or an error occurred
if (filePath == null) {
return;
}
DownloadAttachmentJob job = new DownloadAttachmentJob(attachment, new File(filePath));
job.setUser(true);
job.schedule();
}
};
final Action copyURLToClipAction = new Action(LABEL_COPY_URL_TO_CLIPBOARD) {
@Override
public void run() {
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
Clipboard clip = new Clipboard(PlatformUI.getWorkbench().getDisplay());
clip.setContents(new Object[] { attachment.getUrl() },
new Transfer[] { TextTransfer.getInstance() });
clip.dispose();
}
};
final Action copyToClipAction = new Action(LABEL_COPY_TO_CLIPBOARD) {
@Override
public void run() {
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
CopyAttachmentToClipboardJob job = new CopyAttachmentToClipboardJob(attachment);
job.setUser(true);
job.schedule();
}
};
final MenuManager popupMenu = new MenuManager();
final Menu menu = popupMenu.createContextMenu(attachmentsTable);
attachmentsTable.setMenu(menu);
final MenuManager openMenu = new MenuManager("Open With");
popupMenu.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
popupMenu.removeAll();
IStructuredSelection selection = (IStructuredSelection) attachmentsTableViewer.getSelection();
if (selection.isEmpty()) {
return;
}
if (selection.size() == 1) {
RepositoryAttachment att = (RepositoryAttachment) ((StructuredSelection) selection).getFirstElement();
// reinitialize open menu
popupMenu.add(openMenu);
openMenu.removeAll();
IStorageEditorInput input = new RepositoryAttachmentEditorInput(repository, att);
IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(
input.getName());
if (desc != null) {
openMenu.add(openWithDefaultAction);
}
openMenu.add(openWithBrowserAction);
openMenu.add(openWithTextEditorAction);
popupMenu.add(new Separator());
popupMenu.add(saveAction);
popupMenu.add(copyURLToClipAction);
if (att.getContentType().startsWith(CTYPE_TEXT) || att.getContentType().endsWith("xml")) {
popupMenu.add(copyToClipAction);
}
}
popupMenu.add(new Separator("actions"));
// TODO: use workbench mechanism for this?
ObjectActionContributorManager.getManager().contributeObjectActions(
AbstractRepositoryTaskEditor.this, popupMenu, attachmentsTableViewer);
}
});
} else {
Label label = toolkit.createLabel(attachmentsComposite, "No attachments");
registerDropListener(label);
}
final Composite attachmentControlsComposite = toolkit.createComposite(attachmentsComposite);
attachmentControlsComposite.setLayout(new GridLayout(2, false));
attachmentControlsComposite.setLayoutData(new GridData(GridData.BEGINNING));
Button attachFileButton = toolkit.createButton(attachmentControlsComposite, AttachAction.LABEL, SWT.PUSH);
attachFileButton.setImage(WorkbenchImages.getImage(ISharedImages.IMG_OBJ_FILE));
Button attachScreenshotButton = toolkit.createButton(attachmentControlsComposite, AttachScreenshotAction.LABEL,
SWT.PUSH);
attachScreenshotButton.setImage(CommonImages.getImage(CommonImages.IMAGE_CAPTURE));
final ITask task = TasksUiInternal.getTaskList().getTask(repository.getRepositoryUrl(), taskData.getTaskId());
if (task == null) {
attachFileButton.setEnabled(false);
attachScreenshotButton.setEnabled(false);
}
attachFileButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// ignore
}
public void widgetSelected(SelectionEvent e) {
AbstractTaskEditorAction attachFileAction = new AttachAction();
attachFileAction.selectionChanged(new StructuredSelection(task));
attachFileAction.setEditor(parentEditor);
attachFileAction.run();
}
});
attachScreenshotButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// ignore
}
public void widgetSelected(SelectionEvent e) {
AttachScreenshotAction attachScreenshotAction = new AttachScreenshotAction();
attachScreenshotAction.selectionChanged(new StructuredSelection(task));
attachScreenshotAction.setEditor(parentEditor);
attachScreenshotAction.run();
}
});
Button deleteAttachmentButton = null;
if (supportsAttachmentDelete()) {
deleteAttachmentButton = toolkit.createButton(attachmentControlsComposite, "Delete Attachment...", SWT.PUSH);
deleteAttachmentButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// ignore
}
public void widgetSelected(SelectionEvent e) {
ITask task = TasksUiInternal.getTaskList().getTask(repository.getRepositoryUrl(),
taskData.getTaskId());
if (task == null) {
// Should not happen
return;
}
if (AbstractRepositoryTaskEditor.this.isDirty
|| task.getSynchronizationState().equals(SynchronizationState.OUTGOING)) {
MessageDialog.openInformation(attachmentsComposite.getShell(),
"Task not synchronized or dirty editor",
"Commit edits or synchronize task before deleting attachments.");
return;
} else {
if (attachmentsTableViewer != null
&& attachmentsTableViewer.getSelection() != null
&& ((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement() != null) {
RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement());
deleteAttachment(attachment);
submitToRepository();
}
}
}
});
}
registerDropListener(section);
registerDropListener(attachmentsComposite);
registerDropListener(attachFileButton);
if (supportsAttachmentDelete()) {
registerDropListener(deleteAttachmentButton);
}
}
private void registerDropListener(final Control control) {
DropTarget target = new DropTarget(control, DND.DROP_COPY | DND.DROP_DEFAULT);
final TextTransfer textTransfer = TextTransfer.getInstance();
final FileTransfer fileTransfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[] { textTransfer, fileTransfer };
target.setTransfer(types);
// Adapted from eclipse.org DND Article by Veronika Irvine, IBM OTI Labs
// http://www.eclipse.org/articles/Article-SWT-DND/DND-in-SWT.html#_dt10D
target.addDropListener(new RepositoryTaskEditorDropListener(this, repository, taskData, fileTransfer,
textTransfer, control));
}
protected void createDescriptionLayout(Composite composite) {
Section descriptionSection = createSection(composite, getSectionLabel(SECTION_NAME.DESCRIPTION_SECTION));
final Composite sectionComposite = toolkit.createComposite(descriptionSection);
descriptionSection.setClient(sectionComposite);
GridLayout addCommentsLayout = new GridLayout();
addCommentsLayout.numColumns = 1;
sectionComposite.setLayout(addCommentsLayout);
RepositoryTaskAttribute attribute = taskData.getDescriptionAttribute();
if (attribute != null && !attribute.isReadOnly()) {
if (getRenderingEngine() != null) {
// composite with StackLayout to hold text editor and preview widget
Composite descriptionComposite = toolkit.createComposite(sectionComposite);
descriptionComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
GridData descriptionGridData = new GridData(GridData.FILL_BOTH);
descriptionGridData.widthHint = DESCRIPTION_WIDTH;
descriptionGridData.minimumHeight = DESCRIPTION_HEIGHT;
descriptionGridData.grabExcessHorizontalSpace = true;
descriptionComposite.setLayoutData(descriptionGridData);
final StackLayout descriptionLayout = new StackLayout();
descriptionComposite.setLayout(descriptionLayout);
descriptionTextViewer = addTextEditor(repository, descriptionComposite, taskData.getDescription(),
true, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
descriptionLayout.topControl = descriptionTextViewer.getControl();
descriptionComposite.layout();
// composite for edit/preview button
Composite buttonComposite = toolkit.createComposite(sectionComposite);
buttonComposite.setLayout(new GridLayout());
createPreviewButton(buttonComposite, descriptionTextViewer, descriptionComposite, descriptionLayout);
} else {
descriptionTextViewer = addTextEditor(repository, sectionComposite, taskData.getDescription(), true,
SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
// wrap text at this margin, see comment below
gd.widthHint = DESCRIPTION_WIDTH;
gd.minimumHeight = DESCRIPTION_HEIGHT;
gd.grabExcessHorizontalSpace = true;
descriptionTextViewer.getControl().setLayoutData(gd);
descriptionTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
// the goal is to make the text viewer as big as the text so it does not require scrolling when first drawn
// on screen: when the descriptionTextViewer calculates its height it wraps the text according to the widthHint
// which does not reflect the actual size of the widget causing the widget to be taller
// (actual width > gd.widhtHint) or shorter (actual width < gd.widthHint) therefore the widthHint is tweaked
// once in the listener
sectionComposite.addControlListener(new ControlAdapter() {
private boolean first;
@Override
public void controlResized(ControlEvent e) {
if (!first) {
first = true;
int width = sectionComposite.getSize().x;
Point size = descriptionTextViewer.getTextWidget().computeSize(width, SWT.DEFAULT, true);
// limit width to parent widget
gd.widthHint = width;
// limit height to avoid dynamic resizing of the text widget
gd.heightHint = Math.min(Math.max(DESCRIPTION_HEIGHT, size.y), DESCRIPTION_HEIGHT * 4);
sectionComposite.layout();
}
}
});
}
descriptionTextViewer.setEditable(true);
descriptionTextViewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
String newValue = descriptionTextViewer.getTextWidget().getText();
RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.DESCRIPTION);
if (attribute != null && !newValue.equals(attribute.getValue())) {
attribute.setValue(newValue);
attributeChanged(attribute);
taskData.setDescription(newValue);
}
}
});
StyledText styledText = descriptionTextViewer.getTextWidget();
controlBySelectableObject.put(taskData.getDescription(), styledText);
} else {
String text = taskData.getDescription();
descriptionTextViewer = addTextViewer(repository, sectionComposite, text, SWT.MULTI | SWT.WRAP);
StyledText styledText = descriptionTextViewer.getTextWidget();
GridDataFactory.fillDefaults().hint(DESCRIPTION_WIDTH, SWT.DEFAULT).applyTo(
descriptionTextViewer.getControl());
controlBySelectableObject.put(text, styledText);
}
if (hasChanged(taskData.getAttribute(RepositoryTaskAttribute.DESCRIPTION))) {
descriptionTextViewer.getTextWidget().setBackground(colorIncoming);
}
descriptionTextViewer.getTextWidget().addListener(SWT.FocusIn, new DescriptionListener());
Composite replyComp = toolkit.createComposite(descriptionSection);
replyComp.setLayout(new RowLayout());
replyComp.setBackground(null);
createReplyHyperlink(0, replyComp, taskData.getDescription());
descriptionSection.setTextClient(replyComp);
addDuplicateDetection(sectionComposite);
toolkit.paintBordersFor(sectionComposite);
if (descriptionTextViewer.isEditable()) {
descriptionSection.setExpanded(true);
}
}
protected ImageHyperlink createReplyHyperlink(final int commentNum, Composite composite, final String commentBody) {
final ImageHyperlink replyLink = new ImageHyperlink(composite, SWT.NULL);
toolkit.adapt(replyLink, true, true);
replyLink.setImage(CommonImages.getImage(TasksUiImages.COMMENT_REPLY));
replyLink.setToolTipText(LABEL_REPLY);
// no need for the background - transparency will take care of it
replyLink.setBackground(null);
// replyLink.setBackground(section.getTitleBarGradientBackground());
replyLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
String oldText = newCommentTextViewer.getDocument().get();
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(oldText);
if (strBuilder.length() != 0) {
strBuilder.append("\n");
}
strBuilder.append(" (In reply to comment #" + commentNum + ")\n");
CommentQuoter quoter = new CommentQuoter();
strBuilder.append(quoter.quote(commentBody));
newCommentTextViewer.getDocument().set(strBuilder.toString());
RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW);
if (attribute != null) {
attribute.setValue(strBuilder.toString());
attributeChanged(attribute);
}
selectNewComment();
newCommentTextViewer.getTextWidget().setCaretOffset(strBuilder.length());
}
});
return replyLink;
}
protected void addDuplicateDetection(Composite composite) {
List<AbstractLegacyDuplicateDetector> allCollectors = new ArrayList<AbstractLegacyDuplicateDetector>();
if (getDuplicateDetectorList() != null) {
allCollectors.addAll(getDuplicateDetectorList());
}
if (!allCollectors.isEmpty()) {
Section duplicatesSection = toolkit.createSection(composite, ExpandableComposite.TWISTIE
| ExpandableComposite.SHORT_TITLE_BAR);
duplicatesSection.setText(LABEL_SELECT_DETECTOR);
duplicatesSection.setLayout(new GridLayout());
GridDataFactory.fillDefaults().indent(SWT.DEFAULT, 15).applyTo(duplicatesSection);
Composite relatedBugsComposite = toolkit.createComposite(duplicatesSection);
relatedBugsComposite.setLayout(new GridLayout(4, false));
relatedBugsComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
duplicatesSection.setClient(relatedBugsComposite);
duplicateDetectorLabel = new Label(relatedBugsComposite, SWT.LEFT);
duplicateDetectorLabel.setText("Detector:");
duplicateDetectorChooser = new CCombo(relatedBugsComposite, SWT.FLAT | SWT.READ_ONLY);
toolkit.adapt(duplicateDetectorChooser, true, true);
duplicateDetectorChooser.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
duplicateDetectorChooser.setFont(TEXT_FONT);
duplicateDetectorChooser.setLayoutData(GridDataFactory.swtDefaults().hint(150, SWT.DEFAULT).create());
Collections.sort(allCollectors, new Comparator<AbstractLegacyDuplicateDetector>() {
public int compare(AbstractLegacyDuplicateDetector c1, AbstractLegacyDuplicateDetector c2) {
return c1.getName().compareToIgnoreCase(c2.getName());
}
});
for (AbstractLegacyDuplicateDetector detector : allCollectors) {
duplicateDetectorChooser.add(detector.getName());
}
duplicateDetectorChooser.select(0);
duplicateDetectorChooser.setEnabled(true);
duplicateDetectorChooser.setData(allCollectors);
if (allCollectors.size() > 0) {
searchForDuplicates = toolkit.createButton(relatedBugsComposite, LABEL_SEARCH_DUPS, SWT.NONE);
GridData searchDuplicatesButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
searchForDuplicates.setLayoutData(searchDuplicatesButtonData);
searchForDuplicates.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
searchForDuplicates();
}
});
}
// } else {
// Label label = new Label(composite, SWT.LEFT);
// label.setText(LABEL_NO_DETECTOR);
toolkit.paintBordersFor(relatedBugsComposite);
}
}
protected void createCustomAttributeLayout(Composite composite) {
// override
}
protected void createPeopleLayout(Composite composite) {
Section peopleSection = createSection(composite, getSectionLabel(SECTION_NAME.PEOPLE_SECTION));
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).grab(true, true).applyTo(peopleSection);
Composite peopleComposite = toolkit.createComposite(peopleSection);
GridLayout layout = new GridLayout(2, false);
layout.marginWidth = 5;
peopleComposite.setLayout(layout);
addAssignedTo(peopleComposite);
boolean haveRealName = false;
RepositoryTaskAttribute reporterAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER_NAME);
if (reporterAttribute == null) {
reporterAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER);
} else {
haveRealName = true;
}
if (reporterAttribute != null) {
Label label = createLabel(peopleComposite, reporterAttribute);
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
Text textField = createTextField(peopleComposite, reporterAttribute, SWT.FLAT | SWT.READ_ONLY);
GridDataFactory.fillDefaults().grab(true, false).applyTo(textField);
if (haveRealName) {
textField.setText(textField.getText() + " <"
+ taskData.getAttributeValue(RepositoryTaskAttribute.USER_REPORTER) + ">");
}
}
addSelfToCC(peopleComposite);
addCCList(peopleComposite);
getManagedForm().getToolkit().paintBordersFor(peopleComposite);
peopleSection.setClient(peopleComposite);
peopleSection.setEnabled(true);
}
protected void addCCList(Composite attributesComposite) {
RepositoryTaskAttribute addCCattribute = taskData.getAttribute(RepositoryTaskAttribute.NEW_CC);
if (addCCattribute == null) {
// TODO: remove once TRAC is priming taskData with NEW_CC attribute
taskData.setAttributeValue(RepositoryTaskAttribute.NEW_CC, "");
addCCattribute = taskData.getAttribute(RepositoryTaskAttribute.NEW_CC);
}
if (addCCattribute != null) {
Label label = createLabel(attributesComposite, addCCattribute);
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
Text text = createTextField(attributesComposite, addCCattribute, SWT.FLAT);
GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(text);
if (hasContentAssist(addCCattribute)) {
ContentAssistCommandAdapter adapter = applyContentAssist(text,
createContentProposalProvider(addCCattribute));
ILabelProvider propsalLabelProvider = createProposalLabelProvider(addCCattribute);
if (propsalLabelProvider != null) {
adapter.setLabelProvider(propsalLabelProvider);
}
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}
}
RepositoryTaskAttribute CCattribute = taskData.getAttribute(RepositoryTaskAttribute.USER_CC);
if (CCattribute != null) {
Label label = createLabel(attributesComposite, CCattribute);
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).applyTo(label);
ccList = new org.eclipse.swt.widgets.List(attributesComposite, SWT.MULTI | SWT.V_SCROLL);// SWT.BORDER
ccList.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
ccList.setFont(TEXT_FONT);
GridData ccListData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
ccListData.horizontalSpan = 1;
ccListData.widthHint = 150;
ccListData.heightHint = 95;
ccList.setLayoutData(ccListData);
if (hasChanged(taskData.getAttribute(RepositoryTaskAttribute.USER_CC))) {
ccList.setBackground(colorIncoming);
}
java.util.List<String> ccs = taskData.getCc();
if (ccs != null) {
for (String cc : ccs) {
ccList.add(cc);
}
}
java.util.List<String> removedCCs = taskData.getAttributeValues(RepositoryTaskAttribute.REMOVE_CC);
if (removedCCs != null) {
for (String item : removedCCs) {
int i = ccList.indexOf(item);
if (i != -1) {
ccList.select(i);
}
}
}
ccList.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
for (String cc : ccList.getItems()) {
int index = ccList.indexOf(cc);
if (ccList.isSelected(index)) {
List<String> remove = taskData.getAttributeValues(RepositoryTaskAttribute.REMOVE_CC);
if (!remove.contains(cc)) {
taskData.addAttributeValue(RepositoryTaskAttribute.REMOVE_CC, cc);
}
} else {
taskData.removeAttributeValue(RepositoryTaskAttribute.REMOVE_CC, cc);
}
}
attributeChanged(taskData.getAttribute(RepositoryTaskAttribute.REMOVE_CC));
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
toolkit.createLabel(attributesComposite, "");
label = toolkit.createLabel(attributesComposite, "(Select to remove)");
GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).applyTo(label);
}
}
/**
* A listener for selection of the summary field.
*
* @since 2.1
*/
protected class DescriptionListener implements Listener {
public DescriptionListener() {
}
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(
new RepositoryTaskSelection(taskData.getTaskId(), taskData.getRepositoryUrl(),
taskData.getConnectorKind(), getSectionLabel(SECTION_NAME.DESCRIPTION_SECTION), true,
taskData.getSummary()))));
}
}
protected boolean supportsCommentDelete() {
return false;
}
protected void deleteComment(TaskComment comment) {
}
private boolean expandCommentSection() {
for (final TaskComment taskComment : taskData.getComments()) {
if ((repositoryTask != null && repositoryTask.getLastReadTimeStamp() == null)
|| editorInput.getOldTaskData() == null) {
return true;
} else if (isNewComment(taskComment)) {
return true;
}
}
if (taskData.getComments() == null || taskData.getComments().size() == 0) {
return false;
} else if (editorInput.getTaskData() != null && editorInput.getOldTaskData() != null) {
List<TaskComment> newTaskComments = editorInput.getTaskData().getComments();
List<TaskComment> oldTaskComments = editorInput.getOldTaskData().getComments();
if (newTaskComments == null || oldTaskComments == null) {
return true;
} else if (newTaskComments.size() != oldTaskComments.size()) {
return true;
}
}
return false;
}
protected void createCommentLayout(Composite composite) {
commentsSection = createSection(composite, getSectionLabel(SECTION_NAME.COMMENTS_SECTION),
expandCommentSection());
commentsSection.setText(commentsSection.getText() + " (" + taskData.getComments().size() + ")");
final Composite commentsSectionClient = toolkit.createComposite(commentsSection);
RowLayout rowLayout = new RowLayout();
rowLayout.pack = true;
rowLayout.marginLeft = 0;
rowLayout.marginBottom = 0;
rowLayout.marginTop = 0;
commentsSectionClient.setLayout(rowLayout);
commentsSectionClient.setBackground(null);
if (supportsCommentSort()) {
sortHyperlink = new ImageHyperlink(commentsSectionClient, SWT.NONE);
sortHyperlink.setToolTipText("Change order of comments");
toolkit.adapt(sortHyperlink, true, true);
sortHyperlink.setBackground(null);
sortHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
sortComments();
}
});
sortHyperlinkState(false);
}
if (taskData.getComments().size() > 0) {
commentsSection.setEnabled(true);
commentsSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
if (commentsSection.isExpanded()) {
if (supportsCommentSort()) {
sortHyperlinkState(true);
}
} else {
if (supportsCommentSort()) {
sortHyperlinkState(false);
}
}
}
});
ImageHyperlink collapseAllHyperlink = new ImageHyperlink(commentsSectionClient, SWT.NONE);
collapseAllHyperlink.setToolTipText("Collapse All Comments");
toolkit.adapt(collapseAllHyperlink, true, true);
collapseAllHyperlink.setBackground(null);
collapseAllHyperlink.setImage(CommonImages.getImage(CommonImages.COLLAPSE_ALL));
collapseAllHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
hideAllComments();
}
});
ImageHyperlink expandAllHyperlink = new ImageHyperlink(commentsSectionClient, SWT.NONE);
expandAllHyperlink.setToolTipText("Expand All Comments");
toolkit.adapt(expandAllHyperlink, true, true);
expandAllHyperlink.setBackground(null);
expandAllHyperlink.setImage(CommonImages.getImage(CommonImages.EXPAND_ALL));
expandAllHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() {
public void run() {
revealAllComments();
if (supportsCommentSort()) {
sortHyperlinkState(true);
}
}
});
}
});
commentsSection.setTextClient(commentsSectionClient);
} else {
commentsSection.setEnabled(false);
}
// Additional (read-only) Comments Area
addCommentsComposite = toolkit.createComposite(commentsSection);
commentsSection.setClient(addCommentsComposite);
GridLayout addCommentsLayout = new GridLayout();
addCommentsLayout.numColumns = 1;
addCommentsComposite.setLayout(addCommentsLayout);
GridDataFactory.fillDefaults().grab(true, false).applyTo(addCommentsComposite);
boolean foundNew = false;
for (final TaskComment taskComment : taskData.getComments()) {
final ExpandableComposite expandableComposite = toolkit.createExpandableComposite(addCommentsComposite,
ExpandableComposite.TREE_NODE | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT);
expandableComposite.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE));
final Composite toolbarComp = toolkit.createComposite(expandableComposite);
rowLayout = new RowLayout();
rowLayout.pack = true;
rowLayout.marginLeft = 0;
rowLayout.marginBottom = 0;
rowLayout.marginTop = 0;
toolbarComp.setLayout(rowLayout);
toolbarComp.setBackground(null);
ImageHyperlink formHyperlink = toolkit.createImageHyperlink(toolbarComp, SWT.NONE);
formHyperlink.setBackground(null);
formHyperlink.setFont(expandableComposite.getFont());
formHyperlink.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
if (taskComment.getAuthor() != null && taskComment.getAuthor().equalsIgnoreCase(repository.getUserName())) {
formHyperlink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_NARROW));
} else {
formHyperlink.setImage(CommonImages.getImage(CommonImages.PERSON_NARROW));
}
String authorName = taskComment.getAuthorName();
String tooltipText = taskComment.getAuthor();
if (authorName.length() == 0) {
authorName = taskComment.getAuthor();
tooltipText = null;
}
formHyperlink.setText(taskComment.getNumber() + ": " + authorName + ", "
+ formatDate(taskComment.getCreated()));
formHyperlink.setToolTipText(tooltipText);
formHyperlink.setEnabled(true);
formHyperlink.setUnderlined(false);
final Composite toolbarButtonComp = toolkit.createComposite(toolbarComp);
RowLayout buttonCompLayout = new RowLayout();
buttonCompLayout.marginBottom = 0;
buttonCompLayout.marginTop = 0;
toolbarButtonComp.setLayout(buttonCompLayout);
toolbarButtonComp.setBackground(null);
if (supportsCommentDelete()) {
final ImageHyperlink deleteComment = new ImageHyperlink(toolbarButtonComp, SWT.NULL);
toolkit.adapt(deleteComment, true, true);
deleteComment.setImage(CommonImages.getImage(CommonImages.REMOVE));
deleteComment.setToolTipText("Remove");
deleteComment.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
deleteComment(taskComment);
submitToRepository();
}
});
}
final ImageHyperlink replyLink = createReplyHyperlink(taskComment.getNumber(), toolbarButtonComp,
taskComment.getText());
formHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
toggleExpandableComposite(!expandableComposite.isExpanded(), expandableComposite);
}
@Override
public void linkEntered(HyperlinkEvent e) {
replyLink.setUnderlined(true);
super.linkEntered(e);
}
@Override
public void linkExited(HyperlinkEvent e) {
replyLink.setUnderlined(false);
super.linkExited(e);
}
});
expandableComposite.setTextClient(toolbarComp);
toolbarButtonComp.setVisible(expandableComposite.isExpanded());
// HACK: This is necessary
// due to a bug in SWT's ExpandableComposite.
// 165803: Expandable bars should expand when clicking anywhere
expandableComposite.setData(toolbarButtonComp);
expandableComposite.setLayout(new GridLayout());
expandableComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
final Composite ecComposite = toolkit.createComposite(expandableComposite);
GridLayout ecLayout = new GridLayout();
ecLayout.marginHeight = 0;
ecLayout.marginBottom = 3;
ecLayout.marginLeft = 15;
ecComposite.setLayout(ecLayout);
ecComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
expandableComposite.setClient(ecComposite);
// code for outline
commentComposites.add(expandableComposite);
controlBySelectableObject.put(taskComment, expandableComposite);
expandableComposite.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
toolbarButtonComp.setVisible(expandableComposite.isExpanded());
TextViewer viewer = null;
if (e.getState() && expandableComposite.getData("viewer") == null) {
viewer = addTextViewer(repository, ecComposite, taskComment.getText().trim(), SWT.MULTI
| SWT.WRAP);
expandableComposite.setData("viewer", viewer.getTextWidget());
viewer.getTextWidget().addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
selectedComment = taskComment;
}
public void focusLost(FocusEvent e) {
selectedComment = null;
}
});
StyledText styledText = viewer.getTextWidget();
GridDataFactory.fillDefaults().hint(DESCRIPTION_WIDTH, SWT.DEFAULT).applyTo(styledText);
resetLayout();
} else {
// dispose viewer
if (expandableComposite.getData("viewer") instanceof StyledText) {
((StyledText) expandableComposite.getData("viewer")).dispose();
expandableComposite.setData("viewer", null);
}
resetLayout();
}
}
});
if ((repositoryTask != null && repositoryTask.getLastReadTimeStamp() == null)
|| editorInput.getOldTaskData() == null) {
// hit or lost task data, expose all comments
toggleExpandableComposite(true, expandableComposite);
foundNew = true;
} else if (isNewComment(taskComment)) {
expandableComposite.setBackground(colorIncoming);
toggleExpandableComposite(true, expandableComposite);
foundNew = true;
}
}
if (supportsCommentSort()) {
if (commentSortIsUp) {
commentSortIsUp = !commentSortIsUp;
sortComments();
} else {
sortHyperlinkState(commentSortEnable);
}
}
if (foundNew) {
if (supportsCommentSort()) {
sortHyperlinkState(true);
}
} else if (taskData.getComments() == null || taskData.getComments().size() == 0) {
if (supportsCommentSort()) {
sortHyperlinkState(false);
}
} else if (editorInput.getTaskData() != null && editorInput.getOldTaskData() != null) {
List<TaskComment> newTaskComments = editorInput.getTaskData().getComments();
List<TaskComment> oldTaskComments = editorInput.getOldTaskData().getComments();
if (newTaskComments == null || oldTaskComments == null) {
if (supportsCommentSort()) {
sortHyperlinkState(true);
}
} else if (newTaskComments.size() != oldTaskComments.size()) {
if (supportsCommentSort()) {
sortHyperlinkState(true);
}
}
}
}
public String formatDate(String dateString) {
return dateString;
}
private boolean isNewComment(TaskComment comment) {
// Simple test (will not reveal new comments if offline data was lost
if (editorInput.getOldTaskData() != null) {
return (comment.getNumber() > editorInput.getOldTaskData().getComments().size());
}
return false;
// OLD METHOD FOR DETERMINING NEW COMMENTS
// if (repositoryTask != null) {
// if (repositoryTask.getLastSyncDateStamp() == null) {
// // new hit
// return true;
// AbstractRepositoryConnector connector = (AbstractRepositoryConnector)
// TasksUiPlugin.getRepositoryManager()
// .getRepositoryConnector(taskData.getRepositoryKind());
// AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler();
// if (offlineHandler != null) {
// Date lastSyncDate =
// taskData.getAttributeFactory().getDateForAttributeType(
// RepositoryTaskAttribute.DATE_MODIFIED,
// repositoryTask.getLastSyncDateStamp());
// if (lastSyncDate != null) {
// // reduce granularity to minutes
// Calendar calLastMod = Calendar.getInstance();
// calLastMod.setTimeInMillis(lastSyncDate.getTime());
// calLastMod.set(Calendar.SECOND, 0);
// Date commentDate =
// taskData.getAttributeFactory().getDateForAttributeType(
// RepositoryTaskAttribute.COMMENT_DATE, comment.getCreated());
// if (commentDate != null) {
// Calendar calComment = Calendar.getInstance();
// calComment.setTimeInMillis(commentDate.getTime());
// calComment.set(Calendar.SECOND, 0);
// if (calComment.after(calLastMod)) {
// return true;
// return false;
}
/**
* Subclasses that support HTML preview of ticket description and comments override this method to return an
* instance of AbstractRenderingEngine
*
* @return <code>null</code> if HTML preview is not supported for the repository (default)
* @since 2.1
*/
protected AbstractRenderingEngine getRenderingEngine() {
return null;
}
protected void createNewCommentLayout(Composite composite) {
// Section newCommentSection = createSection(composite,
// getSectionLabel(SECTION_NAME.NEWCOMMENT_SECTION));
Section newCommentSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR);
newCommentSection.setText(getSectionLabel(SECTION_NAME.NEWCOMMENT_SECTION));
newCommentSection.setLayout(new GridLayout());
newCommentSection.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite newCommentsComposite = toolkit.createComposite(newCommentSection);
newCommentsComposite.setLayout(new GridLayout());
if (taskData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW) == null) {
taskData.setAttributeValue(RepositoryTaskAttribute.COMMENT_NEW, "");
}
final RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW);
if (getRenderingEngine() != null) {
// composite with StackLayout to hold text editor and preview widget
Composite editPreviewComposite = toolkit.createComposite(newCommentsComposite);
GridData editPreviewData = new GridData(GridData.FILL_BOTH);
editPreviewData.widthHint = DESCRIPTION_WIDTH;
editPreviewData.minimumHeight = DESCRIPTION_HEIGHT;
editPreviewData.grabExcessHorizontalSpace = true;
editPreviewComposite.setLayoutData(editPreviewData);
editPreviewComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
final StackLayout editPreviewLayout = new StackLayout();
editPreviewComposite.setLayout(editPreviewLayout);
newCommentTextViewer = addTextEditor(repository, editPreviewComposite, attribute.getValue(), true, SWT.FLAT
| SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
editPreviewLayout.topControl = newCommentTextViewer.getControl();
editPreviewComposite.layout();
// composite for edit/preview button
Composite buttonComposite = toolkit.createComposite(newCommentsComposite);
buttonComposite.setLayout(new GridLayout());
createPreviewButton(buttonComposite, newCommentTextViewer, editPreviewComposite, editPreviewLayout);
} else {
newCommentTextViewer = addTextEditor(repository, newCommentsComposite, attribute.getValue(), true, SWT.FLAT
| SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
GridData addCommentsTextData = new GridData(GridData.FILL_BOTH);
addCommentsTextData.widthHint = DESCRIPTION_WIDTH;
addCommentsTextData.minimumHeight = DESCRIPTION_HEIGHT;
addCommentsTextData.grabExcessHorizontalSpace = true;
newCommentTextViewer.getControl().setLayoutData(addCommentsTextData);
newCommentTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
}
newCommentTextViewer.setEditable(true);
newCommentTextViewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
String newValue = addCommentsTextBox.getText();
if (!newValue.equals(attribute.getValue())) {
attribute.setValue(newValue);
attributeChanged(attribute);
}
}
});
newCommentTextViewer.getTextWidget().addListener(SWT.FocusIn, new NewCommentListener());
addCommentsTextBox = newCommentTextViewer.getTextWidget();
newCommentSection.setClient(newCommentsComposite);
toolkit.paintBordersFor(newCommentsComposite);
}
private Browser addBrowser(Composite parent, int style) {
Browser browser = new Browser(parent, style);
// intercept links to open tasks in rich editor and urls in separate browser
browser.addLocationListener(new LocationAdapter() {
@Override
public void changing(LocationEvent event) {
// ignore events that are caused by manually setting the contents of the browser
if (ignoreLocationEvents) {
return;
}
if (event.location != null && !event.location.startsWith("about")) {
event.doit = false;
IHyperlink link = new TaskUrlHyperlink(
new Region(0, 0)/* a fake region just to make constructor happy */, event.location);
link.open();
}
}
});
return browser;
}
/**
* Creates and sets up the button for switching between text editor and HTML preview. Subclasses that support HTML
* preview of new comments must override this method.
*
* @param buttonComposite
* the composite that holds the button
* @param editor
* the TextViewer for editing text
* @param previewBrowser
* the Browser for displaying the preview
* @param editorLayout
* the StackLayout of the <code>editorComposite</code>
* @param editorComposite
* the composite that holds <code>editor</code> and <code>previewBrowser</code>
* @since 2.1
*/
private void createPreviewButton(final Composite buttonComposite, final TextViewer editor,
final Composite editorComposite, final StackLayout editorLayout) {
// create an anonymous object that encapsulates the edit/preview button together with
// its state and String constants for button text;
// this implementation keeps all information needed to set up the button
// in this object and the method parameters, and this method is reused by both the
// description section and new comments section.
new Object() {
private static final String LABEL_BUTTON_PREVIEW = "Preview";
private static final String LABEL_BUTTON_EDIT = "Edit";
private int buttonState = 0;
private Button previewButton;
private Browser previewBrowser;
{
previewButton = toolkit.createButton(buttonComposite, LABEL_BUTTON_PREVIEW, SWT.PUSH);
GridData previewButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
previewButtonData.widthHint = 100;
//previewButton.setImage(TasksUiImages.getImage(TasksUiImages.PREVIEW));
previewButton.setLayoutData(previewButtonData);
previewButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
if (previewBrowser == null) {
previewBrowser = addBrowser(editorComposite, SWT.NONE);
}
buttonState = ++buttonState % 2;
if (buttonState == 1) {
setText(previewBrowser, "Loading preview...");
previewWiki(previewBrowser, editor.getTextWidget().getText());
}
previewButton.setText(buttonState == 0 ? LABEL_BUTTON_PREVIEW : LABEL_BUTTON_EDIT);
editorLayout.topControl = (buttonState == 0 ? editor.getControl() : previewBrowser);
editorComposite.layout();
}
});
}
};
}
private void setText(Browser browser, String html) {
try {
ignoreLocationEvents = true;
browser.setText((html != null) ? html : "");
} finally {
ignoreLocationEvents = false;
}
}
private void previewWiki(final Browser browser, String sourceText) {
final class PreviewWikiJob extends Job {
private final String sourceText;
private String htmlText;
private IStatus jobStatus;
public PreviewWikiJob(String sourceText) {
super("Formatting Wiki Text");
if (sourceText == null) {
throw new IllegalArgumentException("source text must not be null");
}
this.sourceText = sourceText;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
AbstractRenderingEngine htmlRenderingEngine = getRenderingEngine();
if (htmlRenderingEngine == null) {
jobStatus = new RepositoryStatus(repository, IStatus.INFO, TasksUiPlugin.ID_PLUGIN,
RepositoryStatus.ERROR_INTERNAL, "The repository does not support HTML preview.");
return Status.OK_STATUS;
}
jobStatus = Status.OK_STATUS;
try {
htmlText = htmlRenderingEngine.renderAsHtml(repository, sourceText, monitor);
} catch (CoreException e) {
jobStatus = e.getStatus();
}
return Status.OK_STATUS;
}
public String getHtmlText() {
return htmlText;
}
public IStatus getStatus() {
return jobStatus;
}
}
final PreviewWikiJob job = new PreviewWikiJob(sourceText);
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(final IJobChangeEvent event) {
if (!form.isDisposed()) {
if (job.getStatus().isOK()) {
getPartControl().getDisplay().asyncExec(new Runnable() {
public void run() {
AbstractRepositoryTaskEditor.this.setText(browser, job.getHtmlText());
parentEditor.setMessage(null, IMessageProvider.NONE);
}
});
} else {
getPartControl().getDisplay().asyncExec(new Runnable() {
public void run() {
parentEditor.setMessage(job.getStatus().getMessage(), IMessageProvider.ERROR);
}
});
}
}
super.done(event);
}
});
job.setUser(true);
job.schedule();
}
/**
* Creates the button layout. This displays options and buttons at the bottom of the editor to allow actions to be
* performed on the bug.
*/
protected void createActionsLayout(Composite composite) {
Section section = createSection(composite, getSectionLabel(SECTION_NAME.ACTIONS_SECTION));
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).grab(true, true).applyTo(section);
Composite buttonComposite = toolkit.createComposite(section);
GridLayout buttonLayout = new GridLayout();
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).applyTo(buttonComposite);
buttonLayout.numColumns = 4;
buttonComposite.setLayout(buttonLayout);
addRadioButtons(buttonComposite);
addActionButtons(buttonComposite);
section.setClient(buttonComposite);
}
protected Section createSection(Composite composite, String title) {
return createSection(composite, title, true);
}
/**
* @Since 2.3
*/
private Section createSection(Composite composite, String title, boolean expandedState) {
int style = ExpandableComposite.TITLE_BAR | Section.TWISTIE;
if (expandedState) {
style |= ExpandableComposite.EXPANDED;
}
Section section = toolkit.createSection(composite, style);
section.setText(title);
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return section;
}
/**
* Adds buttons to this composite. Subclasses can override this method to provide different/additional buttons.
*
* @param buttonComposite
* Composite to add the buttons to.
*/
protected void addActionButtons(Composite buttonComposite) {
submitButton = toolkit.createButton(buttonComposite, LABEL_BUTTON_SUBMIT, SWT.NONE);
GridData submitButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
submitButtonData.widthHint = 100;
submitButton.setImage(CommonImages.getImage(TasksUiImages.REPOSITORY_SUBMIT));
submitButton.setLayoutData(submitButtonData);
submitButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
submitToRepository();
}
});
setSubmitEnabled(true);
toolkit.createLabel(buttonComposite, " ");
ITask task = TasksUiInternal.getTaskList().getTask(repository.getRepositoryUrl(), taskData.getTaskId());
if (attachContextEnabled && task != null) {
addAttachContextButton(buttonComposite, task);
}
}
private void setSubmitEnabled(boolean enabled) {
if (submitButton != null && !submitButton.isDisposed()) {
submitButton.setEnabled(enabled);
if (enabled) {
submitButton.setToolTipText("Submit to " + this.repository.getRepositoryUrl());
}
}
}
/**
* Override to make hyperlink available. If not overridden hyperlink will simply not be displayed.
*
* @return url String form of url that points to task's past activity
*/
protected String getHistoryUrl() {
return null;
}
protected void saveTaskOffline(IProgressMonitor progressMonitor) {
if (taskData == null) {
return;
}
if (repositoryTask != null) {
TasksUiPlugin.getTaskDataManager().saveOutgoing(repositoryTask, changedAttributes);
}
if (repositoryTask != null) {
TasksUiInternal.getTaskList().notifyElementChanged(repositoryTask);
}
markDirty(false);
}
// once the following bug is fixed, this check for first focus is probably
// not needed -> Bug# 172033: Restore editor focus
private boolean firstFocus = true;
@Override
public void setFocus() {
if (lastFocusControl != null && !lastFocusControl.isDisposed()) {
lastFocusControl.setFocus();
} else if (firstFocus && summaryTextViewer != null) {
summaryTextViewer.getControl().setFocus();
firstFocus = false;
}
}
/**
* Updates the title of the editor
*
*/
protected void updateEditorTitle() {
setPartName(editorInput.getName());
((TaskEditor) this.getEditor()).updateTitle(editorInput.getName());
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void doSave(IProgressMonitor monitor) {
saveTaskOffline(monitor);
updateEditorTitle();
updateHeaderControls();
// fillToolBar(getParentEditor().getTopForm().getToolBarManager());
}
@Override
public void doSaveAs() {
// we don't save, so no need to implement
}
/**
* @return The composite for the whole editor.
*/
public Composite getEditorComposite() {
return editorComposite;
}
@Override
public void dispose() {
TasksUiInternal.getTaskList().removeChangeListener(TASKLIST_CHANGE_LISTENER);
getSite().getPage().removeSelectionListener(selectionListener);
if (waitCursor != null) {
waitCursor.dispose();
}
if (activateAction != null) {
activateAction.dispose();
}
super.dispose();
}
/**
* Fires a <code>SelectionChangedEvent</code> to all listeners registered under
* <code>selectionChangedListeners</code>.
*
* @param event
* The selection event.
*/
protected void fireSelectionChanged(final SelectionChangedEvent event) {
Object[] listeners = selectionChangedListeners.toArray();
for (Object listener : listeners) {
final ISelectionChangedListener l = (ISelectionChangedListener) listener;
SafeRunnable.run(new SafeRunnable() {
public void run() {
l.selectionChanged(event);
}
});
}
}
private final HashMap<Object, Control> controlBySelectableObject = new HashMap<Object, Control>();
private final List<ExpandableComposite> commentComposites = new ArrayList<ExpandableComposite>();
private StyledText addCommentsTextBox = null;
protected TextViewer descriptionTextViewer = null;
private void revealAllComments() {
try {
form.setRedraw(false);
refreshEnabled = false;
if (supportsCommentSort()) {
sortHyperlinkState(false);
}
if (commentsSection != null && !commentsSection.isExpanded()) {
commentsSection.setExpanded(true);
if (supportsCommentSort()) {
sortHyperlinkState(true);
}
}
for (ExpandableComposite composite : commentComposites) {
if (composite.isDisposed()) {
continue;
}
if (!composite.isExpanded()) {
toggleExpandableComposite(true, composite);
}
// Composite comp = composite.getParent();
// while (comp != null && !comp.isDisposed()) {
// if (comp instanceof ExpandableComposite && !comp.isDisposed()) {
// ExpandableComposite ex = (ExpandableComposite) comp;
// setExpandableCompositeState(true, ex);
// // HACK: This is necessary
// // due to a bug in SWT's ExpandableComposite.
// // 165803: Expandable bars should expand when clicking
// // anywhere
// if (ex.getData() != null && ex.getData() instanceof Composite) {
// ((Composite) ex.getData()).setVisible(true);
// break;
// comp = comp.getParent();
}
} finally {
refreshEnabled = true;
form.setRedraw(true);
}
resetLayout();
}
private void hideAllComments() {
try {
refreshEnabled = false;
for (ExpandableComposite composite : commentComposites) {
if (composite.isDisposed()) {
continue;
}
if (composite.isExpanded()) {
toggleExpandableComposite(false, composite);
}
// Composite comp = composite.getParent();
// while (comp != null && !comp.isDisposed()) {
// if (comp instanceof ExpandableComposite && !comp.isDisposed()) {
// ExpandableComposite ex = (ExpandableComposite) comp;
// setExpandableCompositeState(false, ex);
// // HACK: This is necessary
// // due to a bug in SWT's ExpandableComposite.
// // 165803: Expandable bars should expand when clicking anywhere
// if (ex.getData() != null && ex.getData() instanceof Composite) {
// ((Composite) ex.getData()).setVisible(false);
// break;
// comp = comp.getParent();
}
// if (commentsSection != null) {
// commentsSection.setExpanded(false);
} finally {
refreshEnabled = true;
}
resetLayout();
}
private void sortHyperlinkState(boolean enabled) {
commentSortEnable = enabled;
if (sortHyperlink == null) {
return;
}
sortHyperlink.setEnabled(enabled);
if (enabled) {
if (commentSortIsUp) {
sortHyperlink.setImage(CommonImages.getImage(TasksUiImages.COMMENT_SORT_UP));
} else {
sortHyperlink.setImage(CommonImages.getImage(TasksUiImages.COMMENT_SORT_DOWN));
}
} else {
if (commentSortIsUp) {
sortHyperlink.setImage(CommonImages.getImage(TasksUiImages.COMMENT_SORT_UP_GRAY));
} else {
sortHyperlink.setImage(CommonImages.getImage(TasksUiImages.COMMENT_SORT_DOWN_GRAY));
}
}
}
private void sortComments() {
if (addCommentsComposite != null) {
Control[] commentControlList = addCommentsComposite.getChildren();
int commentControlListLength = commentControlList.length;
for (int i = 1; i < commentControlListLength; i++) {
commentControlList[commentControlListLength - i].moveAbove(commentControlList[0]);
}
}
commentSortIsUp = !commentSortIsUp;
TasksUiPlugin.getDefault().getPreferenceStore().setValue(
PREF_SORT_ORDER_PREFIX + repository.getConnectorKind(), commentSortIsUp);
sortHyperlinkState(commentSortEnable);
resetLayout();
}
/**
* Selects the given object in the editor.
*
* @param o
* The object to be selected.
* @param highlight
* Whether or not the object should be highlighted.
*/
public boolean select(Object o, boolean highlight) {
Control control = controlBySelectableObject.get(o);
if (control != null && !control.isDisposed()) {
// expand all children
if (control instanceof ExpandableComposite) {
ExpandableComposite ex = (ExpandableComposite) control;
if (!ex.isExpanded()) {
toggleExpandableComposite(true, ex);
}
}
// expand all parents of control
Composite comp = control.getParent();
while (comp != null) {
if (comp instanceof Section) {
if (!((Section) comp).isExpanded()) {
((Section) comp).setExpanded(true);
}
} else if (comp instanceof ExpandableComposite) {
ExpandableComposite ex = (ExpandableComposite) comp;
if (!ex.isExpanded()) {
toggleExpandableComposite(true, ex);
}
// HACK: This is necessary
// due to a bug in SWT's ExpandableComposite.
// 165803: Expandable bars should expand when clicking anywhere
if (ex.getData() != null && ex.getData() instanceof Composite) {
((Composite) ex.getData()).setVisible(true);
}
}
comp = comp.getParent();
}
focusOn(control, highlight);
} else if (o instanceof RepositoryTaskData) {
focusOn(null, highlight);
} else {
return false;
}
return true;
}
/**
* Programmatically expand the provided ExpandableComposite, using reflection to fire the expansion listeners (see
* bug#70358)
*
* @param comp
*/
private void toggleExpandableComposite(boolean expanded, ExpandableComposite comp) {
if (comp.isExpanded() != expanded) {
Method method = null;
try {
method = comp.getClass().getDeclaredMethod("programmaticToggleState");
method.setAccessible(true);
method.invoke(comp);
} catch (Exception e) {
// ignore
}
}
}
private void selectNewComment() {
focusOn(addCommentsTextBox, false);
}
/**
* @author Raphael Ackermann (bug 195514)
* @since 2.1
*/
protected void focusAttributes() {
if (attributesSection != null) {
focusOn(attributesSection, false);
}
}
private void focusDescription() {
if (descriptionTextViewer != null) {
focusOn(descriptionTextViewer.getTextWidget(), false);
}
}
/**
* Scroll to a specified piece of text
*
* @param selectionComposite
* The StyledText to scroll to
*/
private void focusOn(Control selectionComposite, boolean highlight) {
int pos = 0;
// if (previousText != null && !previousText.isDisposed()) {
// previousText.setsetSelection(0);
// if (selectionComposite instanceof FormText)
// previousText = (FormText) selectionComposite;
if (selectionComposite != null) {
// if (highlight && selectionComposite instanceof FormText &&
// !selectionComposite.isDisposed())
// ((FormText) selectionComposite).set.setSelection(0, ((FormText)
// selectionComposite).getText().length());
// get the position of the text in the composite
pos = 0;
Control s = selectionComposite;
if (s.isDisposed()) {
return;
}
s.setEnabled(true);
s.setFocus();
s.forceFocus();
while (s != null && s != getEditorComposite()) {
if (!s.isDisposed()) {
pos += s.getLocation().y;
s = s.getParent();
}
}
pos = pos - 60; // form.getOrigin().y;
}
if (!form.getBody().isDisposed()) {
form.setOrigin(0, pos);
}
}
private RepositoryTaskOutlinePage outlinePage = null;
@SuppressWarnings("unchecked")
@Override
public Object getAdapter(Class adapter) {
return getAdapterDelgate(adapter);
}
public Object getAdapterDelgate(Class<?> adapter) {
if (IContentOutlinePage.class.equals(adapter)) {
if (outlinePage == null && editorInput != null && taskOutlineModel != null) {
outlinePage = new RepositoryTaskOutlinePage(taskOutlineModel);
}
return outlinePage;
}
return super.getAdapter(adapter);
}
public RepositoryTaskOutlinePage getOutline() {
return outlinePage;
}
private Button[] radios;
private Control[] radioOptions;
private Button attachContextButton;
private AbstractLegacyRepositoryConnector connector;
private Cursor waitCursor;
private boolean formBusy = false;
private Composite headerInfoComposite;
private Section attributesSection;
public void close() {
Display activeDisplay = getSite().getShell().getDisplay();
activeDisplay.asyncExec(new Runnable() {
public void run() {
if (getSite() != null && getSite().getPage() != null && !getManagedForm().getForm().isDisposed()) {
if (parentEditor != null) {
getSite().getPage().closeEditor(parentEditor, false);
} else {
getSite().getPage().closeEditor(AbstractRepositoryTaskEditor.this, false);
}
}
}
});
}
public void addAttributeListener(IRepositoryTaskAttributeListener listener) {
attributesListeners.add(listener);
}
public void removeAttributeListener(IRepositoryTaskAttributeListener listener) {
attributesListeners.remove(listener);
}
public void setParentEditor(TaskEditor parentEditor) {
this.parentEditor = parentEditor;
}
/**
* @since 2.1
*/
public TaskEditor getParentEditor() {
return parentEditor;
}
public RepositoryTaskOutlineNode getTaskOutlineModel() {
return taskOutlineModel;
}
public void setTaskOutlineModel(RepositoryTaskOutlineNode taskOutlineModel) {
this.taskOutlineModel = taskOutlineModel;
}
/**
* A listener for selection of the textbox where a new comment is entered in.
*/
private class NewCommentListener implements Listener {
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(
new RepositoryTaskSelection(taskData.getTaskId(), taskData.getRepositoryUrl(),
taskData.getConnectorKind(), getSectionLabel(SECTION_NAME.NEWCOMMENT_SECTION), false,
taskData.getSummary()))));
}
}
public Control getControl() {
return form;
}
public void setSummaryText(String text) {
if (summaryTextViewer != null && summaryTextViewer.getTextWidget() != null) {
summaryTextViewer.getTextWidget().setText(text);
}
}
public void setDescriptionText(String text) {
this.descriptionTextViewer.getDocument().set(text);
}
protected void addRadioButtons(Composite buttonComposite) {
int i = 0;
Button selected = null;
radios = new Button[taskData.getOperations().size()];
radioOptions = new Control[taskData.getOperations().size()];
for (RepositoryOperation o : taskData.getOperations()) {
radios[i] = toolkit.createButton(buttonComposite, "", SWT.RADIO);
radios[i].setFont(TEXT_FONT);
GridData radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
if (!o.hasOptions() && !o.isInput()) {
radioData.horizontalSpan = 4;
} else {
radioData.horizontalSpan = 1;
}
radioData.heightHint = 20;
String opName = o.getOperationName();
opName = opName.replaceAll("</.*>", "");
opName = opName.replaceAll("<.*>", "");
radios[i].setText(opName);
radios[i].setLayoutData(radioData);
// radios[i].setBackground(background);
radios[i].addSelectionListener(new RadioButtonListener());
if (o.hasOptions()) {
radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
radioData.horizontalSpan = 3;
radioData.heightHint = 20;
radioData.widthHint = RADIO_OPTION_WIDTH;
radioOptions[i] = new CCombo(buttonComposite, SWT.FLAT | SWT.READ_ONLY);
radioOptions[i].setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
toolkit.adapt(radioOptions[i], true, true);
radioOptions[i].setFont(TEXT_FONT);
radioOptions[i].setLayoutData(radioData);
Object[] a = o.getOptionNames().toArray();
Arrays.sort(a);
for (int j = 0; j < a.length; j++) {
if (a[j] != null) {
((CCombo) radioOptions[i]).add((String) a[j]);
if (((String) a[j]).equals(o.getOptionSelection())) {
((CCombo) radioOptions[i]).select(j);
}
}
}
((CCombo) radioOptions[i]).addSelectionListener(new RadioButtonListener());
} else if (o.isInput()) {
radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
radioData.horizontalSpan = 3;
radioData.widthHint = RADIO_OPTION_WIDTH - 10;
String assignmentValue = "";
// NOTE: removed this because we now have content assit
// if (opName.equals(REASSIGN_BUG_TO)) {
// assignmentValue = repository.getUserName();
radioOptions[i] = toolkit.createText(buttonComposite, assignmentValue);
radioOptions[i].setFont(TEXT_FONT);
radioOptions[i].setLayoutData(radioData);
// radioOptions[i].setBackground(background);
((Text) radioOptions[i]).setText(o.getInputValue());
((Text) radioOptions[i]).addModifyListener(new RadioButtonListener());
if (hasContentAssist(o)) {
ContentAssistCommandAdapter adapter = applyContentAssist((Text) radioOptions[i],
createContentProposalProvider(o));
ILabelProvider propsalLabelProvider = createProposalLabelProvider(o);
if (propsalLabelProvider != null) {
adapter.setLabelProvider(propsalLabelProvider);
}
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}
}
if (i == 0 || o.isChecked()) {
if (selected != null) {
selected.setSelection(false);
}
selected = radios[i];
radios[i].setSelection(true);
if (o.hasOptions() && o.getOptionSelection() != null) {
int j = 0;
for (String s : ((CCombo) radioOptions[i]).getItems()) {
if (s.compareTo(o.getOptionSelection()) == 0) {
((CCombo) radioOptions[i]).select(j);
}
j++;
}
}
taskData.setSelectedOperation(o);
}
i++;
}
toolkit.paintBordersFor(buttonComposite);
}
/**
* If implementing custom attributes you may need to override this method
*
* @return true if one or more attributes exposed in the editor have
*/
protected boolean hasVisibleAttributeChanges() {
if (taskData == null) {
return false;
}
for (RepositoryTaskAttribute attribute : taskData.getAttributes()) {
if (!attribute.isHidden()) {
if (hasChanged(attribute)) {
return true;
}
}
}
return false;
}
protected boolean hasOutgoingChange(RepositoryTaskAttribute newAttribute) {
return editorInput.getOldEdits().contains(newAttribute);
}
protected boolean hasChanged(RepositoryTaskAttribute newAttribute) {
if (newAttribute == null) {
return false;
}
RepositoryTaskData oldTaskData = editorInput.getOldTaskData();
if (oldTaskData == null) {
return false;
}
if (hasOutgoingChange(newAttribute)) {
return false;
}
RepositoryTaskAttribute oldAttribute = oldTaskData.getAttribute(newAttribute.getId());
if (oldAttribute == null) {
return true;
}
if (oldAttribute.getValue() != null && !oldAttribute.getValue().equals(newAttribute.getValue())) {
return true;
} else if (oldAttribute.getValues() != null && !oldAttribute.getValues().equals(newAttribute.getValues())) {
return true;
}
return false;
}
protected void addAttachContextButton(Composite buttonComposite, ITask task) {
attachContextButton = toolkit.createButton(buttonComposite, "Attach Context", SWT.CHECK);
attachContextButton.setImage(CommonImages.getImage(TasksUiImages.CONTEXT_ATTACH));
}
/**
* Creates a check box for adding the repository user to the cc list. Does nothing if the repository does not have a
* valid username, the repository user is the assignee, reporter or already on the the cc list.
*/
protected void addSelfToCC(Composite composite) {
if (repository.getUserName() == null) {
return;
}
RepositoryTaskAttribute owner = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED);
if (owner != null && owner.getValue().indexOf(repository.getUserName()) != -1) {
return;
}
RepositoryTaskAttribute reporter = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER);
if (reporter != null && reporter.getValue().indexOf(repository.getUserName()) != -1) {
return;
}
RepositoryTaskAttribute ccAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_CC);
if (ccAttribute != null && ccAttribute.getValues().contains(repository.getUserName())) {
return;
}
FormToolkit toolkit = getManagedForm().getToolkit();
toolkit.createLabel(composite, "");
final Button addSelfButton = toolkit.createButton(composite, "Add me to CC", SWT.CHECK);
addSelfButton.setSelection(RepositoryTaskAttribute.TRUE.equals(taskData.getAttributeValue(RepositoryTaskAttribute.ADD_SELF_CC)));
addSelfButton.setImage(CommonImages.getImage(CommonImages.PERSON));
addSelfButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (addSelfButton.getSelection()) {
taskData.setAttributeValue(RepositoryTaskAttribute.ADD_SELF_CC, RepositoryTaskAttribute.TRUE);
} else {
taskData.setAttributeValue(RepositoryTaskAttribute.ADD_SELF_CC, RepositoryTaskAttribute.FALSE);
}
RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.ADD_SELF_CC);
changedAttributes.add(attribute);
markDirty(true);
}
});
}
public boolean getAttachContext() {
if (attachContextButton == null || attachContextButton.isDisposed()) {
return false;
} else {
return attachContextButton.getSelection();
}
}
public void setExpandAttributeSection(boolean expandAttributeSection) {
this.expandedStateAttributes = expandAttributeSection;
}
public void setAttachContextEnabled(boolean attachContextEnabled) {
this.attachContextEnabled = attachContextEnabled;
// if (attachContextButton != null && attachContextButton.isEnabled()) {
// attachContextButton.setSelection(attachContext);
}
@Override
public void showBusy(boolean busy) {
if (!getManagedForm().getForm().isDisposed() && busy != formBusy) {
// parentEditor.showBusy(busy);
if (synchronizeEditorAction != null) {
synchronizeEditorAction.setEnabled(!busy);
}
if (activateAction != null) {
activateAction.setEnabled(!busy);
}
if (openBrowserAction != null) {
openBrowserAction.setEnabled(!busy);
}
if (historyAction != null) {
historyAction.setEnabled(!busy);
}
if (newSubTaskAction != null) {
newSubTaskAction.setEnabled(!busy);
}
if (clearOutgoingAction != null) {
clearOutgoingAction.setEnabled(!busy);
}
if (submitButton != null && !submitButton.isDisposed()) {
submitButton.setEnabled(!busy);
}
setEnabledState(editorComposite, !busy);
formBusy = busy;
}
}
private void setEnabledState(Composite composite, boolean enabled) {
if (!composite.isDisposed()) {
composite.setEnabled(enabled);
for (Control control : composite.getChildren()) {
control.setEnabled(enabled);
if (control instanceof Composite) {
setEnabledState(((Composite) control), enabled);
}
}
}
}
public void setGlobalBusy(boolean busy) {
if (parentEditor != null) {
parentEditor.showBusy(busy);
} else {
showBusy(busy);
}
}
public void submitToRepository() {
setGlobalBusy(true);
if (isDirty()) {
saveTaskOffline(new NullProgressMonitor());
markDirty(false);
}
final boolean attachContext = getAttachContext();
Job submitJob = new Job(LABEL_JOB_SUBMIT) {
@Override
protected IStatus run(IProgressMonitor monitor) {
AbstractTask modifiedTask = null;
try {
monitor.beginTask("Submitting task", 3);
String taskId = connector.getLegacyTaskDataHandler().postTaskData(repository, taskData,
new SubProgressMonitor(monitor, 1));
final boolean isNew = taskData.isNew();
if (isNew) {
if (taskId != null) {
modifiedTask = updateSubmittedTask(taskId, new SubProgressMonitor(monitor, 1));
} else {
// null taskId, assume task could not be created...
throw new CoreException(
new RepositoryStatus(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
RepositoryStatus.ERROR_INTERNAL,
"Task could not be created. No additional information was provided by the connector."));
}
} else {
modifiedTask = (AbstractTask) TasksUiInternal.getTaskList().getTask(
repository.getRepositoryUrl(), taskData.getTaskId());
}
// Synchronization accounting...
if (modifiedTask != null) {
// Attach context if required
if (attachContext && connector.getAttachmentHandler() != null) {
AttachmentUtil.attachContext(connector.getAttachmentHandler(), repository, modifiedTask,
"", new SubProgressMonitor(monitor, 1));
}
modifiedTask.setSubmitting(true);
final AbstractTask finalModifiedTask = modifiedTask;
TasksUiInternal.synchronizeTask(connector, modifiedTask, true, new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
if (isNew) {
close();
TasksUiPlugin.getTaskDataManager().setTaskRead(finalModifiedTask, true);
TasksUiUtil.openEditor(finalModifiedTask, false);
} else {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshEditor();
}
});
}
}
});
TasksUiPlugin.getSynchronizationScheduler().synchronize(repository);
} else {
close();
// For some reason the task wasn't retrieved.
// Try to
// open local then via web browser...
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
TasksUiUtil.openTask(repository.getRepositoryUrl(), taskData.getTaskId(),
connector.getTaskUrl(taskData.getRepositoryUrl(), taskData.getTaskId()));
}
});
}
return Status.OK_STATUS;
} catch (OperationCanceledException e) {
if (modifiedTask != null) {
modifiedTask.setSubmitting(false);
}
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
setGlobalBusy(false);// enableButtons();
}
});
return Status.CANCEL_STATUS;
} catch (CoreException e) {
if (modifiedTask != null) {
modifiedTask.setSubmitting(false);
}
return handleSubmitError(e);
} catch (Exception e) {
if (modifiedTask != null) {
modifiedTask.setSubmitting(false);
}
StatusHandler.fail(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, e.getMessage(), e));
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
setGlobalBusy(false);// enableButtons();
}
});
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
};
IJobChangeListener jobListener = getSubmitJobListener();
if (jobListener != null) {
submitJob.addJobChangeListener(jobListener);
}
submitJob.schedule();
}
/**
* @since 2.0 If existing task editor, update contents in place
*/
public void refreshEditor() {
try {
if (!getManagedForm().getForm().isDisposed()) {
if (this.isDirty && taskData != null && !taskData.isNew()) {
this.doSave(new NullProgressMonitor());
}
setGlobalBusy(true);
changedAttributes.clear();
commentComposites.clear();
controlBySelectableObject.clear();
editorInput.refreshInput();
// Note: Marking read must run synchronously
// If not, incomings resulting from subsequent synchronization
// can get marked as read (without having been viewed by user
if (repositoryTask != null) {
try {
refreshing = true;
TasksUiPlugin.getTaskDataManager().setTaskRead(repositoryTask, true);
} finally {
refreshing = false;
}
}
this.setInputWithNotify(this.getEditorInput());
this.init(this.getEditorSite(), this.getEditorInput());
// Header must be updated after init is called to task data is available
updateHeaderControls();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (editorComposite != null && !editorComposite.isDisposed()) {
if (taskData != null) {
updateEditorTitle();
menu = editorComposite.getMenu();
removeSections();
editorComposite.setMenu(menu);
createSections();
form.reflow(true);
// setFormHeaderLabel();
markDirty(false);
parentEditor.setMessage(null, 0);
AbstractRepositoryTaskEditor.this.getEditor().setActivePage(
AbstractRepositoryTaskEditor.this.getId());
// Activate editor disabled: bug#179078
// AbstractTaskEditor.this.getEditor().getEditorSite().getPage().activate(
// AbstractTaskEditor.this);
// TODO: expand sections that were previously
// expanded
if (taskOutlineModel != null && outlinePage != null
&& !outlinePage.getControl().isDisposed()) {
outlinePage.getOutlineTreeViewer().setInput(taskOutlineModel);
outlinePage.getOutlineTreeViewer().refresh(true);
}
// if (repositoryTask != null) {
// TasksUiPlugin.getTaskDataManager().setTaskRead(repositoryTask, true);
setSubmitEnabled(true);
}
}
}
});
} else {
// Editor possibly closed as part of submit, mark read
// Note: Marking read must run synchronously
// If not, incomings resulting from subsequent synchronization
// can get marked as read (without having been viewed by user
if (repositoryTask != null) {
TasksUiPlugin.getTaskDataManager().setTaskRead(repositoryTask, true);
}
}
} finally {
if (!getManagedForm().getForm().isDisposed()) {
setGlobalBusy(false);
}
}
}
/**
* Used to prevent form menu from being disposed when disposing elements on the form during refresh
*/
private void setMenu(Composite comp, Menu menu) {
if (!comp.isDisposed()) {
comp.setMenu(null);
for (Control child : comp.getChildren()) {
child.setMenu(null);
if (child instanceof Composite) {
setMenu((Composite) child, menu);
}
}
}
}
protected IJobChangeListener getSubmitJobListener() {
return null;
}
protected AbstractTaskCategory getCategory() {
return null;
}
protected IStatus handleSubmitError(final CoreException exception) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (form != null && !form.isDisposed()) {
if (exception.getStatus().getCode() == RepositoryStatus.ERROR_IO) {
parentEditor.setMessage(ERROR_NOCONNECTIVITY, IMessageProvider.ERROR);
StatusHandler.log(exception.getStatus());
} else if (exception.getStatus().getCode() == RepositoryStatus.REPOSITORY_COMMENT_REQUIRED) {
TasksUiInternal.displayStatus("Comment required", exception.getStatus());
if (!getManagedForm().getForm().isDisposed() && newCommentTextViewer != null
&& !newCommentTextViewer.getControl().isDisposed()) {
newCommentTextViewer.getControl().setFocus();
}
} else if (exception.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) {
if (TasksUiUtil.openEditRepositoryWizard(repository) == MessageDialog.OK) {
submitToRepository();
return;
}
} else {
TasksUiInternal.displayStatus("Submit failed", exception.getStatus());
}
setGlobalBusy(false);
}
}
});
return Status.OK_STATUS;
}
protected AbstractTask updateSubmittedTask(String postResult, IProgressMonitor monitor) throws CoreException {
final AbstractTask newTask = (AbstractTask) TasksUiInternal.createTask(repository, postResult, monitor);
if (newTask != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (getCategory() != null) {
TasksUiInternal.getTaskList().addTask(newTask, getCategory());
}
}
});
}
return newTask;
}
/**
* Class to handle the selection change of the radio buttons.
*/
private class RadioButtonListener implements SelectionListener, ModifyListener {
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
Button selected = null;
for (Button radio : radios) {
if (radio.getSelection()) {
selected = radio;
}
}
// determine the operation to do to the bug
for (int i = 0; i < radios.length; i++) {
if (radios[i] != e.widget && radios[i] != selected) {
radios[i].setSelection(false);
}
if (e.widget == radios[i]) {
RepositoryOperation o = taskData.getOperation(radios[i].getText());
taskData.setSelectedOperation(o);
markDirty(true);
} else if (e.widget == radioOptions[i]) {
RepositoryOperation o = taskData.getOperation(radios[i].getText());
o.setOptionSelection(((CCombo) radioOptions[i]).getItem(((CCombo) radioOptions[i]).getSelectionIndex()));
if (taskData.getSelectedOperation() != null) {
taskData.getSelectedOperation().setChecked(false);
}
o.setChecked(true);
taskData.setSelectedOperation(o);
radios[i].setSelection(true);
if (selected != null && selected != radios[i]) {
selected.setSelection(false);
}
markDirty(true);
}
}
validateInput();
}
public void modifyText(ModifyEvent e) {
Button selected = null;
for (Button radio : radios) {
if (radio.getSelection()) {
selected = radio;
}
}
// determine the operation to do to the bug
for (int i = 0; i < radios.length; i++) {
if (radios[i] != e.widget && radios[i] != selected) {
radios[i].setSelection(false);
}
if (e.widget == radios[i]) {
RepositoryOperation o = taskData.getOperation(radios[i].getText());
taskData.setSelectedOperation(o);
markDirty(true);
} else if (e.widget == radioOptions[i]) {
RepositoryOperation o = taskData.getOperation(radios[i].getText());
o.setInputValue(((Text) radioOptions[i]).getText());
if (taskData.getSelectedOperation() != null) {
taskData.getSelectedOperation().setChecked(false);
}
o.setChecked(true);
taskData.setSelectedOperation(o);
radios[i].setSelection(true);
if (selected != null && selected != radios[i]) {
selected.setSelection(false);
}
markDirty(true);
}
}
validateInput();
}
}
public AbstractRepositoryConnector getConnector() {
return connector;
}
public void setShowAttachments(boolean showAttachments) {
this.showAttachments = showAttachments;
}
public String getCommonDateFormat() {
return HEADER_DATE_FORMAT;
}
public Color getColorIncoming() {
return colorIncoming;
}
/**
* @see #select(Object, boolean)
*/
public void addSelectableControl(Object item, Control control) {
controlBySelectableObject.put(item, control);
}
/**
* @see #addSelectableControl(Object, Control)
*/
public void removeSelectableControl(Object item) {
controlBySelectableObject.remove(item);
}
/**
* This method allow you to overwrite the generation of the form area for "assigned to" in the peopleLayout.<br>
* <br>
* The overwrite is used for Bugzilla Versions > 3.0
*
* @since 2.1
* @author Frank Becker (bug 198027)
*/
protected void addAssignedTo(Composite peopleComposite) {
boolean haveRealName = false;
RepositoryTaskAttribute assignedAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED_NAME);
if (assignedAttribute == null) {
assignedAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED);
} else {
haveRealName = true;
}
if (assignedAttribute != null) {
Label label = createLabel(peopleComposite, assignedAttribute);
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
Text textField;
if (assignedAttribute.isReadOnly()) {
textField = createTextField(peopleComposite, assignedAttribute, SWT.FLAT | SWT.READ_ONLY);
} else {
textField = createTextField(peopleComposite, assignedAttribute, SWT.FLAT);
ContentAssistCommandAdapter adapter = applyContentAssist(textField,
createContentProposalProvider(assignedAttribute));
ILabelProvider propsalLabelProvider = createProposalLabelProvider(assignedAttribute);
if (propsalLabelProvider != null) {
adapter.setLabelProvider(propsalLabelProvider);
}
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}
GridDataFactory.fillDefaults().grab(true, false).applyTo(textField);
if (haveRealName) {
textField.setText(textField.getText() + " <"
+ taskData.getAttributeValue(RepositoryTaskAttribute.USER_ASSIGNED) + ">");
}
}
}
/**
* force a re-layout of entire form
*/
protected void resetLayout() {
if (refreshEnabled) {
form.layout(true, true);
form.reflow(true);
}
}
/**
* @since 2.3
*/
protected Hyperlink createTaskListHyperlink(Composite parent, final String taskId, final String taskUrl,
final AbstractTask task) {
TaskListHyperlink hyperlink = new TaskListHyperlink(parent, SWT.SHORT
| getManagedForm().getToolkit().getOrientation());
getManagedForm().getToolkit().adapt(hyperlink, true, true);
getManagedForm().getToolkit().getHyperlinkGroup().add(hyperlink);
hyperlink.setTask(task);
if (task == null) {
hyperlink.setText(taskId);
}
hyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
if (task != null) {
TasksUiInternal.refreshAndOpenTaskListElement(task);
} else {
TasksUiUtil.openTask(repository.getRepositoryUrl(), taskId, taskUrl);
}
}
});
return hyperlink;
}
}
|
package com.intellij.remoteServer.impl.configuration;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonShortcuts;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.MasterDetailsComponent;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.util.Condition;
import com.intellij.remoteServer.ServerType;
import com.intellij.remoteServer.configuration.RemoteServer;
import com.intellij.remoteServer.configuration.RemoteServersManager;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.IconUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.Convertor;
import com.intellij.util.text.UniqueNameGenerator;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author nik
*/
public class RemoteServerListConfigurable extends MasterDetailsComponent implements SearchableConfigurable {
@NonNls
public static final String ID = "RemoteServers";
private final RemoteServersManager myServersManager;
@Nullable private final ServerType<?> myServerType;
private RemoteServer<?> myLastSelectedServer;
public RemoteServerListConfigurable(@NotNull RemoteServersManager manager) {
this(manager, null);
}
private RemoteServerListConfigurable(@NotNull RemoteServersManager manager, @Nullable ServerType<?> type) {
myServersManager = manager;
myServerType = type;
initTree();
}
public static RemoteServerListConfigurable createConfigurable(@NotNull ServerType<?> type) {
return new RemoteServerListConfigurable(RemoteServersManager.getInstance(), type);
}
@Nls
@Override
public String getDisplayName() {
return "Clouds";
}
@Override
public void reset() {
myRoot.removeAllChildren();
for (RemoteServer<?> server : getServers()) {
addServerNode(server, false);
}
super.reset();
}
private List<? extends RemoteServer<?>> getServers() {
if (myServerType == null) {
return myServersManager.getServers();
}
else {
return myServersManager.getServers(myServerType);
}
}
private MyNode addServerNode(RemoteServer<?> server, boolean isNew) {
MyNode node = new MyNode(new SingleRemoteServerConfigurable(server, TREE_UPDATER, isNew));
addNode(node, myRoot);
return node;
}
@NotNull
@Override
public String getId() {
return ID;
}
@Nullable
@Override
public Runnable enableSearch(final String option) {
return new Runnable() {
@Override
public void run() {
ObjectUtils.assertNotNull(SpeedSearchSupply.getSupply(myTree, true)).findAndSelectElement(option);
}
};
}
@Override
protected void initTree() {
super.initTree();
new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
@Override
public String convert(final TreePath treePath) {
return ((MyNode)treePath.getLastPathComponent()).getDisplayName();
}
}, true);
}
@Override
protected void processRemovedItems() {
Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>();
for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
servers.add(configurable.getEditableObject());
}
List<RemoteServer<?>> toDelete = new ArrayList<RemoteServer<?>>();
for (RemoteServer<?> server : getServers()) {
if (!servers.contains(server)) {
toDelete.add(server);
}
}
for (RemoteServer<?> server : toDelete) {
myServersManager.removeServer(server);
}
}
@Override
public void apply() throws ConfigurationException {
super.apply();
Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(getServers());
for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
RemoteServer<?> server = configurable.getEditableObject();
server.setName(configurable.getDisplayName());
if (!servers.contains(server)) {
myServersManager.addServer(server);
}
}
}
@Nullable
@Override
protected ArrayList<AnAction> createActions(boolean fromPopup) {
ArrayList<AnAction> actions = new ArrayList<AnAction>();
if (myServerType == null) {
actions.add(new AddRemoteServerGroup());
}
else {
actions.add(new AddRemoteServerAction(myServerType, IconUtil.getAddIcon()));
}
actions.add(new MyDeleteAction());
return actions;
}
@Override
protected boolean wasObjectStored(Object editableObject) {
return true;
}
@Override
public String getHelpTopic() {
return ObjectUtils.notNull(super.getHelpTopic(), "reference.settings.clouds");
}
@Override
public void disposeUIResources() {
Object selectedObject = getSelectedObject();
myLastSelectedServer = selectedObject instanceof RemoteServer<?> ? (RemoteServer)selectedObject : null;
super.disposeUIResources();
}
@Nullable
public RemoteServer<?> getLastSelectedServer() {
return myLastSelectedServer;
}
private List<NamedConfigurable<RemoteServer<?>>> getConfiguredServers() {
List<NamedConfigurable<RemoteServer<?>>> configurables = new ArrayList<NamedConfigurable<RemoteServer<?>>>();
for (int i = 0; i < myRoot.getChildCount(); i++) {
MyNode node = (MyNode)myRoot.getChildAt(i);
configurables.add((NamedConfigurable<RemoteServer<?>>)node.getConfigurable());
}
return configurables;
}
private class AddRemoteServerGroup extends ActionGroup implements ActionGroupWithPreselection {
private AddRemoteServerGroup() {
super("Add", "", IconUtil.getAddIcon());
registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
ServerType[] serverTypes = ServerType.EP_NAME.getExtensions();
AnAction[] actions = new AnAction[serverTypes.length];
for (int i = 0; i < serverTypes.length; i++) {
actions[i] = new AddRemoteServerAction(serverTypes[i], serverTypes[i].getIcon());
}
return actions;
}
@Override
public ActionGroup getActionGroup() {
return this;
}
@Override
public int getDefaultIndex() {
return 0;
}
}
private class AddRemoteServerAction extends DumbAwareAction {
private final ServerType<?> myServerType;
private AddRemoteServerAction(ServerType<?> serverType, final Icon icon) {
super(serverType.getPresentableName(), null, icon);
myServerType = serverType;
}
@Override
public void actionPerformed(AnActionEvent e) {
String name = UniqueNameGenerator.generateUniqueName(myServerType.getPresentableName(), new Condition<String>() {
@Override
public boolean value(String s) {
for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
if (configurable.getDisplayName().equals(s)) {
return false;
}
}
return true;
}
});
MyNode node = addServerNode(myServersManager.createServer(myServerType, name), true);
selectNodeInTree(node);
}
}
}
|
package org.jetbrains.plugins.groovy.intentions.style.parameterToEntry;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.JavaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TestFixtureBuilder;
import junit.framework.Assert;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.util.TestUtils;
import java.io.*;
/**
* @author ilyas
*/
public class ParameterToMapEntryTest extends UsefulTestCase {
protected CodeInsightTestFixture myFixture;
protected Project myProject;
protected void setUp() throws Exception {
super.setUp();
final TestFixtureBuilder<IdeaProjectTestFixture> builder = JavaTestFixtureFactory.createFixtureBuilder();
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(builder.getFixture());
final JavaModuleFixtureBuilder moduleBuilder = builder.addModule(JavaModuleFixtureBuilder.class);
moduleBuilder.addJdk(TestUtils.getMockJdkHome());
myFixture.setTestDataPath(TestUtils.getTestDataPath() + "/paramToMap" + "/" + getTestName(true));
moduleBuilder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
myFixture.setUp();
myProject = myFixture.getProject();
storeSettings();
setSettings();
}
@Override
protected CodeStyleSettings getCurrentCodeStyleSettings() {
return CodeStyleSettingsManager.getSettings(myProject);
}
@Override
protected void tearDown() throws Exception {
CodeStyleSettingsManager.getInstance(myProject).dropTemporarySettings();
checkForSettingsDamage();
myFixture.tearDown();
super.tearDown();
}
public void testParam1() throws Throwable {
doTestImpl("A.groovy");
}
public void testFormatter() throws Throwable {
doTestImpl("A.groovy");
}
public void testClosureAtEnd() throws Throwable {
doTestImpl("A.groovy");
}
public void testClosure1() throws Throwable {
doTestImpl("A.groovy");
}
public void testNewMap() throws Throwable {
doTestImpl("A.groovy");
}
public void testTestError() throws Throwable {
doTestImpl("A.groovy");
}
public void testSecondClosure() throws Throwable {
doTestImpl("A.groovy");
}
private void doTestImpl(String filePath) throws Throwable {
myFixture.configureByFile(filePath);
int offset = myFixture.getEditor().getCaretModel().getOffset();
final PsiFile file = myFixture.getFile();
final ConvertParameterToMapEntryIntention intention = new ConvertParameterToMapEntryIntention();
PsiElement element = file.findElementAt(offset);
while (element != null && !(element instanceof GrReferenceExpression || element instanceof GrParameter)) {
element = element.getParent();
}
Assert.assertNotNull(element);
final PsiElementPredicate condition = intention.getElementPredicate();
Assert.assertTrue(condition.satisfiedBy(element));
// Launch it!
intention.processIntention(element);
final String result = file.getText();
//System.out.println(result);
String expected = getExpectedResult(filePath);
Assert.assertEquals(result, expected);
}
private String getExpectedResult(final String filePath) {
Assert.assertTrue(filePath.endsWith(".groovy"));
String testFilePath = StringUtil.trimEnd(filePath, "groovy") + "test";
final File file = new File(TestUtils.getTestDataPath() + "/paramToMap" + "/" + getTestName(true) + "/" + testFilePath);
assertTrue(file.exists());
String expected = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) {
expected += line;
line = reader.readLine();
if (line != null) expected += "\n";
}
reader.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return expected;
}
private void setSettings() {
CodeStyleSettings mySettings = getCurrentCodeStyleSettings().clone();
mySettings.getIndentOptions(GroovyFileType.GROOVY_FILE_TYPE).INDENT_SIZE = 2;
mySettings.getIndentOptions(GroovyFileType.GROOVY_FILE_TYPE).CONTINUATION_INDENT_SIZE = 4;
mySettings.getIndentOptions(GroovyFileType.GROOVY_FILE_TYPE).TAB_SIZE = 2;
CodeStyleSettingsManager.getInstance(myProject).setTemporarySettings(mySettings);
}
}
|
package se.crisp.codekvast.agent.daemon.worker.impl;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import se.crisp.codekvast.agent.daemon.beans.DaemonConfig;
import se.crisp.codekvast.agent.daemon.worker.DataExporter;
import java.io.File;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author [email protected]
*/
@RunWith(MockitoJUnitRunner.class)
public class ZipFileDataExporterImplTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Mock
private JdbcTemplate jdbcTemplate;
private DaemonConfig config;
private DataExporter dataExporter;
@Before
public void before() throws Exception {
config = DaemonConfig.createSampleDaemonConfig()
.toBuilder()
.exportFile(new File(temporaryFolder.getRoot(), "codekvast-data.zip"))
.build();
dataExporter = new ZipFileDataExporterImpl(jdbcTemplate, config);
}
@Test
public void should_exportData() throws Exception {
assertThat(config.getExportFile().exists(), is(false));
dataExporter.exportData();
//noinspection UseOfSystemOutOrSystemErr
System.out.println("exportFile = " + config.getExportFile());
assertThat(config.getExportFile().exists(), is(true));
}
}
|
package org.ow2.proactive.resourcemanager.nodesource.infrastructure;
import java.io.IOException;
import java.security.KeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.objectweb.proactive.core.node.Node;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.process.ProcessExecutor;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.exception.RMException;
import org.ow2.proactive.resourcemanager.nodesource.common.Configurable;
import org.ow2.proactive.resourcemanager.utils.CommandLineBuilder;
import org.ow2.proactive.resourcemanager.utils.OperatingSystem;
import org.ow2.proactive.resourcemanager.utils.RMNodeStarter;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
public class LocalInfrastructure extends InfrastructureManager {
public static final int DEFAULT_NODE_NUMBER = Math.max(2, Runtime.getRuntime().availableProcessors() - 1);
public static final long DEFAULT_TIMEOUT = 30000;
@Configurable(description = "Absolute path to credentials file\nused to add the node to the Resource Manager", credential = true)
private Credentials credentials;
@Configurable(description = "Maximum number of nodes to\nbe deployed on Resource Manager machine")
private int maxNodes = DEFAULT_NODE_NUMBER;
@Configurable(description = "in ms. After this timeout expired\nthe node is considered to be lost")
private long nodeTimeout = DEFAULT_TIMEOUT;
@Configurable(description = "Additional ProActive properties")
private String paProperties = "";
/**
* key to retrieve the number of nodes which are acquired in the persisted
* infrastructure variables
*/
private static final String NB_ACQUIRED_NODES_KEY = "nbAcquiredNodes";
private static final String NB_LOST_NODES_KEY = "nbLostNodes";
private static final String NB_HANDLED_NODES_KEY = "nbHandledNodes";
/**
* Index of deployment, if startNodes is called multiple times, each time a new process will be created.
* The index is used to prevent conflicts in nodes urls
*/
private static final String LAST_NODE_STARTED_INDEX_KEY = "lastNodeStartedIndex";
/**
* A map containing process executors, associated with their corresponding deployment node urls.
*/
private transient ConcurrentHashMap<ProcessExecutor, List<String>> processExecutors = new ConcurrentHashMap<>();
@Override
public String getDescription() {
return "Deploys nodes on Resource Manager's machine";
}
@Override
public void acquireAllNodes() {
this.readLock.lock();
try {
// Check if we need to handle more nodes (we want to reach the max)
int amountOfNewNodesToHandle = 0;
int differenceBetweenHandledAndMaxNodes = maxNodes - getNumberOfHandledNodesWithLock();
if (differenceBetweenHandledAndMaxNodes > 0) {
amountOfNewNodesToHandle = differenceBetweenHandledAndMaxNodes;
}
// Check if some current *and future* handled nodes are not acquired (lost or new) and acquire them
int differenceBetweenHandledAndAcquiredNodes = getDifferenceBetweenNumberOfHandledAndAcquiredNodesWithLock() +
amountOfNewNodesToHandle;
if (differenceBetweenHandledAndAcquiredNodes > 0) {
logger.info("Starting " + differenceBetweenHandledAndAcquiredNodes + " nodes");
startNodes(differenceBetweenHandledAndAcquiredNodes);
}
} catch (RuntimeException e) {
logger.error("Could not start nodes of local infrastructure " + this.nodeSource.getName(), e);
} finally {
this.readLock.unlock();
}
}
@Override
public void acquireNode() {
if (maxNodes - getNumberOfAcquiredNodesWithLock() > 0) {
logger.info("Starting a node from " + this.getClass().getSimpleName());
startNodes(1);
}
}
@Override
public void acquireNodes(int numberOfNodes, Map<String, ?> nodeConfiguration) {
if (numberOfNodes > 0 && (maxNodes - (getNumberOfAcquiredNodesWithLock() + numberOfNodes)) >= 0) {
logger.info("Starting " + numberOfNodes + " nodes from " + this.getClass().getSimpleName());
startNodes(numberOfNodes);
}
}
private void startNodes(final int numberOfNodes) {
this.nodeSource.executeInParallel(() -> {
increaseNumberOfHandledNodesWithLockAndPersist(numberOfNodes);
LocalInfrastructure.this.startNodeProcess(numberOfNodes);
});
}
private void startNodeProcess(int numberOfNodes) {
logger.debug("Starting a new process to acquire " + numberOfNodes + " nodes");
int currentIndex = getIndexAndIncrementWithLockAndPersist();
String baseNodeName = "local-" + this.nodeSource.getName() + "-" + currentIndex;
OperatingSystem os = OperatingSystem.UNIX;
// assuming no cygwin, windows or the "others"...
if (System.getProperty("os.name").contains("Windows")) {
os = OperatingSystem.WINDOWS;
}
String rmHome = PAResourceManagerProperties.RM_HOME.getValueAsString();
if (!rmHome.endsWith(os.fs)) {
rmHome += os.fs;
}
CommandLineBuilder clb = this.getDefaultCommandLineBuilder(os);
// RM_Home set in bin/unix/env script
clb.setRmHome(rmHome);
ArrayList<String> paPropList = new ArrayList<>();
if (!this.paProperties.contains(CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getName())) {
paPropList.add(CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getCmdLine() + rmHome + "config" + os.fs +
"security.java.policy-client");
}
if (!this.paProperties.contains(CentralPAPropertyRepository.PA_CONFIGURATION_FILE.getName())) {
paPropList.add(CentralPAPropertyRepository.PA_CONFIGURATION_FILE.getCmdLine() + rmHome + "config" + os.fs +
"network" + os.fs + "node.ini");
}
if (!this.paProperties.contains(PAResourceManagerProperties.RM_HOME.getKey())) {
paPropList.add(PAResourceManagerProperties.RM_HOME.getCmdLine() + rmHome);
}
if (!this.paProperties.contains("java.library.path")) {
paPropList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
}
if (!this.paProperties.isEmpty()) {
Collections.addAll(paPropList, this.paProperties.split(" "));
}
clb.setPaProperties(paPropList);
clb.setNodeName(baseNodeName);
clb.setNumberOfNodes(numberOfNodes);
try {
clb.setCredentialsValueAndNullOthers(new String(this.credentials.getBase64()));
} catch (KeyException e) {
createLostNodes(baseNodeName, numberOfNodes, "Cannot decrypt credentials value", e);
return;
}
List<String> cmd;
try {
cmd = clb.buildCommandLineAsList(false);
} catch (IOException e) {
createLostNodes(baseNodeName, numberOfNodes, "Cannot build command line", e);
return;
}
// The printed cmd with obfuscated credentials
final String obfuscatedCmd = Joiner.on(' ').join(cmd);
List<String> depNodeURLs = new ArrayList<>(numberOfNodes);
final List<String> createdNodeNames = RMNodeStarter.getWorkersNodeNames(baseNodeName, numberOfNodes);
ProcessExecutor processExecutor = null;
try {
depNodeURLs.addAll(addMultipleDeployingNodes(createdNodeNames,
obfuscatedCmd,
"Node launched locally",
this.nodeTimeout));
// Deobfuscate the cred value
Collections.replaceAll(cmd, CommandLineBuilder.OBFUSC, clb.getCredentialsValue());
processExecutor = new ProcessExecutor(baseNodeName, cmd, false, true);
processExecutor.start();
this.processExecutors.put(processExecutor, depNodeURLs);
final ProcessExecutor tmpProcessExecutor = processExecutor;
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (tmpProcessExecutor != null && !tmpProcessExecutor.isProcessFinished()) {
tmpProcessExecutor.killProcess();
}
}));
logger.debug("Local Nodes command started : " + obfuscatedCmd);
} catch (IOException e) {
String lf = System.lineSeparator();
String mess = "Cannot launch rm node " + baseNodeName + lf + Throwables.getStackTraceAsString(e);
multipleDeclareDeployingNodeLost(depNodeURLs, mess);
if (processExecutor != null) {
processExecutor.killProcess();
this.processExecutors.remove(processExecutor);
}
}
}
/**
* Creates a lost node to indicate that the deployment has failed while
* building the command line.
*/
private void createLostNodes(String baseName, int numberOfNodes, String message, Throwable e) {
List<String> createdNodeNames = RMNodeStarter.getWorkersNodeNames(baseName, numberOfNodes);
for (int nodeIndex = 0; nodeIndex < numberOfNodes; nodeIndex++) {
String name = createdNodeNames.get(nodeIndex);
String lf = System.lineSeparator();
String url = super.addDeployingNode(name,
"deployed as daemon",
"Deploying a local infrastructure node",
this.nodeTimeout);
String st = Throwables.getStackTraceAsString(e);
super.declareDeployingNodeLost(url, message + lf + st);
}
}
/**
* args[0] = credentials args[1] = max nodes args[2] = timeout args[3] = pa
* props
*/
@Override
protected void configure(Object... args) {
int index = 0;
try {
this.credentials = Credentials.getCredentialsBase64((byte[]) args[index++]);
} catch (KeyException e1) {
throw new IllegalArgumentException("Cannot decrypt credentials", e1);
}
try {
this.maxNodes = Integer.parseInt(args[index++].toString());
this.persistedInfraVariables.put(NB_HANDLED_NODES_KEY, 0);
} catch (Exception e) {
throw new IllegalArgumentException("Cannot determine max node");
}
try {
this.nodeTimeout = Integer.parseInt(args[index++].toString());
} catch (Exception e) {
logger.warn("Cannot determine node timeout, using default:" + this.nodeTimeout, e);
}
this.paProperties = args[index].toString();
}
/**
* {@inheritDoc}
*/
@Override
protected void notifyDeployingNodeLost(String pnURL) {
incrementNumberOfLostNodesWithLockAndPersist();
}
@Override
protected void notifyAcquiredNode(Node arg0) throws RMException {
incrementNumberOfAcquiredNodesWithLockAndPersist();
}
@Override
public void removeNode(Node node) throws RMException {
logger.info("The node " + node.getNodeInformation().getURL() + " is removed from " +
this.getClass().getSimpleName());
removeNodeAndShutdownProcessIfNeeded(node.getNodeInformation().getURL());
}
@Override
public void notifyDownNode(String nodeName, String nodeUrl, Node node) {
logger.debug("A down node is detected: " + nodeUrl + " from " + this.getClass().getSimpleName());
decrementNumberOfAcquiredNodesWithLockAndPersist();
}
@Override
public void onDownNodeReconnection(Node node) {
incrementNumberOfAcquiredNodesWithLockAndPersist();
}
@Override
public void shutDown() {
for (ProcessExecutor processExecutor : this.processExecutors.keySet()) {
if (processExecutor != null) {
processExecutor.killProcess();
}
}
this.processExecutors.clear();
// do not set processExecutor to null here or NPE can appear in the startProcess method, running in a different thread.
logger.info("All process associated with node source '" + this.nodeSource.getName() + "' are being destroyed.");
}
@Override
public String toString() {
return "Local Infrastructure";
}
@Override
protected void initializePersistedInfraVariables() {
this.persistedInfraVariables.put(NB_ACQUIRED_NODES_KEY, 0);
this.persistedInfraVariables.put(NB_LOST_NODES_KEY, 0);
this.persistedInfraVariables.put(NB_HANDLED_NODES_KEY, 0);
this.persistedInfraVariables.put(LAST_NODE_STARTED_INDEX_KEY, 0);
}
private void removeNodeAndShutdownProcessIfNeeded(String nodeUrlToRemove) {
// Update handle & acquire/lost nodes persistent counters
decrementNumberOfHandledNodesWithLockAndPersist();
if (nodeSource.getNodeInDeployingOrLostNodes(nodeUrlToRemove) == null) {
decrementNumberOfAcquiredNodesWithLockAndPersist();
} else {
decrementNumberOfLostNodesWithLockAndPersist();
}
Iterator<Map.Entry<ProcessExecutor, List<String>>> processIterator = processExecutors.entrySet().iterator();
while (processIterator.hasNext()) {
Map.Entry<ProcessExecutor, List<String>> processExecutor = processIterator.next();
// Remove the nodeUrl if present
Iterator<String> nodesIterator = processExecutor.getValue().iterator();
boolean nodeFound = false;
while (nodesIterator.hasNext()) {
String nodeUrl = nodesIterator.next();
String nodeName = nodeUrl.substring(nodeUrl.lastIndexOf('/'));
if (nodeUrlToRemove.endsWith(nodeName)) {
nodeFound = true;
nodesIterator.remove();
break;
}
}
// Kill the associated JVM process if it doesn't have remaining node
if (nodeFound) {
if (processExecutor.getValue().isEmpty()) {
logger.debug("No nodes remaining after deleting node " + nodeUrlToRemove +
", killing process from " + this.getClass().getSimpleName());
if (processExecutor.getKey() != null) {
processExecutor.getKey().killProcess();
}
processIterator.remove();
}
break;
}
}
}
// Below are wrapper methods around the runtime variables map
private int getNumberOfHandledNodesWithLock() {
return getPersistedInfraVariable(() -> (int) this.persistedInfraVariables.get(NB_HANDLED_NODES_KEY));
}
private int getNumberOfAcquiredNodesWithLock() {
return getPersistedInfraVariable(() -> (int) this.persistedInfraVariables.get(NB_ACQUIRED_NODES_KEY));
}
private void increaseNumberOfHandledNodesWithLockAndPersist(final int additionalNumberOfNodes) {
setPersistedInfraVariable(() -> {
int updated = (int) this.persistedInfraVariables.get(NB_HANDLED_NODES_KEY) + additionalNumberOfNodes;
this.persistedInfraVariables.put(NB_HANDLED_NODES_KEY, updated);
return updated;
});
}
private void incrementNumberOfAcquiredNodesWithLockAndPersist() {
setPersistedInfraVariable(() -> {
int updated = (int) this.persistedInfraVariables.get(NB_ACQUIRED_NODES_KEY) + 1;
this.persistedInfraVariables.put(NB_ACQUIRED_NODES_KEY, updated);
return updated;
});
}
private void incrementNumberOfLostNodesWithLockAndPersist() {
setPersistedInfraVariable(() -> {
int updated = (int) this.persistedInfraVariables.get(NB_LOST_NODES_KEY) + 1;
this.persistedInfraVariables.put(NB_LOST_NODES_KEY, updated);
return updated;
});
}
private void decrementNumberOfHandledNodesWithLockAndPersist() {
setPersistedInfraVariable(() -> {
int updated = (int) this.persistedInfraVariables.get(NB_HANDLED_NODES_KEY) - 1;
this.persistedInfraVariables.put(NB_HANDLED_NODES_KEY, updated);
return updated;
});
}
private void decrementNumberOfAcquiredNodesWithLockAndPersist() {
setPersistedInfraVariable(() -> {
int updated = (int) this.persistedInfraVariables.get(NB_ACQUIRED_NODES_KEY) - 1;
this.persistedInfraVariables.put(NB_ACQUIRED_NODES_KEY, updated);
return updated;
});
}
private void decrementNumberOfLostNodesWithLockAndPersist() {
setPersistedInfraVariable(() -> {
int updated = (int) this.persistedInfraVariables.get(NB_LOST_NODES_KEY) - 1;
this.persistedInfraVariables.put(NB_LOST_NODES_KEY, updated);
return updated;
});
}
private int getIndexAndIncrementWithLockAndPersist() {
return setPersistedInfraVariable(() -> {
int deployedNodeIndex = (int) this.persistedInfraVariables.get(LAST_NODE_STARTED_INDEX_KEY);
this.persistedInfraVariables.put(LAST_NODE_STARTED_INDEX_KEY, deployedNodeIndex + 1);
return deployedNodeIndex;
});
}
private int getDifferenceBetweenNumberOfHandledAndAcquiredNodesWithLock() {
return getPersistedInfraVariable(() -> (int) this.persistedInfraVariables.get(NB_HANDLED_NODES_KEY) -
(int) this.persistedInfraVariables.get(NB_ACQUIRED_NODES_KEY));
}
}
|
package net.runelite.client.plugins.achievementdiary.diaries;
import net.runelite.api.Quest;
import net.runelite.api.Skill;
import net.runelite.client.plugins.achievementdiary.CombatLevelRequirement;
import net.runelite.client.plugins.achievementdiary.GenericDiaryRequirement;
import net.runelite.client.plugins.achievementdiary.QuestRequirement;
import net.runelite.client.plugins.achievementdiary.SkillRequirement;
public class WesternDiaryRequirement extends GenericDiaryRequirement
{
public WesternDiaryRequirement()
{
// EASY
add("Catch a Copper Longtail.",
new SkillRequirement(Skill.HUNTER, 9));
add("Complete a novice game of Pest Control.",
new CombatLevelRequirement(40));
add("Mine some Iron Ore near Piscatoris.",
new SkillRequirement(Skill.MINING, 15));
add("Claim any Chompy bird hat from Rantz.",
new QuestRequirement(Quest.BIG_CHOMPY_BIRD_HUNTING));
add("Have Brimstail teleport you to the Essence mine.",
new QuestRequirement(Quest.RUNE_MYSTERIES));
add("Fletch an Oak shortbow from the Gnome Stronghold.",
new SkillRequirement(Skill.FLETCHING, 20));
// MEDIUM
add("Take the agility shortcut from the Grand Tree to Otto's Grotto.",
new SkillRequirement(Skill.AGILITY, 37),
new QuestRequirement(Quest.TREE_GNOME_VILLAGE),
new QuestRequirement(Quest.THE_GRAND_TREE));
add("Travel to the Gnome Stronghold by Spirit Tree.",
new QuestRequirement(Quest.TREE_GNOME_VILLAGE));
add("Trap a Spined Larupia.",
new SkillRequirement(Skill.HUNTER, 31));
add("Fish some Bass on Ape Atoll.",
new SkillRequirement(Skill.FISHING, 46),
new QuestRequirement(Quest.MONKEY_MADNESS_I, true));
add("Chop and burn some teak logs on Ape Atoll.",
new SkillRequirement(Skill.WOODCUTTING, 35),
new SkillRequirement(Skill.FIREMAKING, 35),
new QuestRequirement(Quest.MONKEY_MADNESS_I, true));
add("Complete an intermediate game of Pest Control.",
new CombatLevelRequirement(70));
add("Travel to the Feldip Hills by Gnome Glider.",
new QuestRequirement(Quest.ONE_SMALL_FAVOUR),
new QuestRequirement(Quest.THE_GRAND_TREE));
add("Claim a Chompy bird hat from Rantz after registering at least 125 kills.",
new QuestRequirement(Quest.BIG_CHOMPY_BIRD_HUNTING));
add("Travel from Eagles' Peak to the Feldip Hills by Eagle.",
new QuestRequirement(Quest.EAGLES_PEAK));
add("Make a Chocolate Bomb at the Grand Tree.",
new SkillRequirement(Skill.COOKING, 42));
add("Complete a delivery for the Gnome Restaurant.",
new SkillRequirement(Skill.COOKING, 29));
add("Turn your small crystal seed into a Crystal saw.",
new QuestRequirement(Quest.THE_EYES_OF_GLOUPHRIE));
add("Mine some Gold ore underneath the Grand Tree.",
new SkillRequirement(Skill.MINING, 40),
new QuestRequirement(Quest.THE_GRAND_TREE));
// HARD
add("Kill an Elf with a Crystal bow.",
new SkillRequirement(Skill.RANGED, 70),
new SkillRequirement(Skill.AGILITY, 56),
new QuestRequirement(Quest.ROVING_ELVES));
add("Catch and cook a Monkfish in Piscatoris.",
new SkillRequirement(Skill.FISHING, 62),
new SkillRequirement(Skill.COOKING, 62),
new QuestRequirement(Quest.SWAN_SONG));
add("Complete a Veteran game of Pest Control.",
new CombatLevelRequirement(100));
add("Catch a Dashing Kebbit.",
new SkillRequirement(Skill.HUNTER, 69));
add("Complete a lap of the Ape Atoll agility course.",
new SkillRequirement(Skill.AGILITY, 48),
new QuestRequirement(Quest.MONKEY_MADNESS_I));
add("Chop and burn some Mahogany logs on Ape Atoll.",
new SkillRequirement(Skill.WOODCUTTING, 50),
new SkillRequirement(Skill.FIREMAKING, 50),
new QuestRequirement(Quest.MONKEY_MADNESS_I));
add("Mine some Adamantite ore in Tirannwn.",
new SkillRequirement(Skill.MINING, 70),
new QuestRequirement(Quest.REGICIDE));
add("Check the health of your Palm tree in Lletya.",
new SkillRequirement(Skill.FARMING, 68),
new QuestRequirement(Quest.MOURNINGS_END_PART_I, true));
add("Claim a Chompy bird hat from Rantz after registering at least 300 kills.",
new QuestRequirement(Quest.BIG_CHOMPY_BIRD_HUNTING));
add("Build an Isafdar painting in your POH Quest hall.",
new SkillRequirement(Skill.CONSTRUCTION, 65),
new QuestRequirement(Quest.ROVING_ELVES));
add("Kill Zulrah.",
new QuestRequirement(Quest.REGICIDE, true));
add("Teleport to Ape Atoll.",
new SkillRequirement(Skill.MAGIC, 64),
new QuestRequirement(Quest.RECIPE_FOR_DISASTER, true));
add("Pickpocket a Gnome.",
new SkillRequirement(Skill.THIEVING, 75),
new QuestRequirement(Quest.TREE_GNOME_VILLAGE));
// ELITE
add("Fletch a Magic Longbow in Tirannwn.",
new SkillRequirement(Skill.FLETCHING, 85),
new QuestRequirement(Quest.MOURNINGS_END_PART_I));
add("Kill the Thermonuclear Smoke devil (Does not require task).",
new SkillRequirement(Skill.SLAYER, 93));
add("Have Prissy Scilla protect your Magic tree.",
new SkillRequirement(Skill.FARMING, 75));
add("Use the Elven overpass advanced cliffside shortcut.",
new SkillRequirement(Skill.AGILITY, 85),
new QuestRequirement(Quest.UNDERGROUND_PASS));
add("Claim a Chompy bird hat from Rantz after registering at least 1000 kills.",
new QuestRequirement(Quest.BIG_CHOMPY_BIRD_HUNTING));
add("Pickpocket an Elf.",
new SkillRequirement(Skill.THIEVING, 85),
new QuestRequirement(Quest.MOURNINGS_END_PART_I, true));
}
}
|
package uk.org.taverna.scufl2.translator.t2flow.defaultactivities;
import java.net.URI;
import uk.org.taverna.scufl2.api.activity.Activity;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.io.ReaderException;
import uk.org.taverna.scufl2.api.property.PropertyLiteral;
import uk.org.taverna.scufl2.api.property.PropertyResource;
import uk.org.taverna.scufl2.translator.t2flow.T2FlowParser;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.ActivityPortDefinitionBean;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.ConfigBean;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.RShellConfig;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.RShellSymanticType;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.RetryConfig;
public class RshellActivityParser extends AbstractActivityParser {
private static URI activityRavenURI =
T2FlowParser.ravenURI.resolve("net.sf.taverna.t2.activities/rshell-activity/");
private static String activityClassName = "net.sf.taverna.t2.activities.rshell.RshellActivity";
public static URI ACTIVITY_URI = URI
.create("http://ns.taverna.org.uk/2010/activity/rshell");
@Override
public boolean canHandlePlugin(URI activityURI) {
String activityUriStr = activityURI.toASCIIString();
return activityUriStr.startsWith(activityRavenURI.toASCIIString())
&& activityUriStr.endsWith(activityClassName);
}
@Override
public URI mapT2flowRavenIdToScufl2URI(URI t2flowActivity) {
return ACTIVITY_URI;
}
@Override
public Configuration parseConfiguration(T2FlowParser t2FlowParser,
ConfigBean configBean) throws ReaderException {
RShellConfig rshellConfig = unmarshallConfig(t2FlowParser, configBean, "xstream", RShellConfig.class);
Configuration configuration = new Configuration();
configuration.setParent(getParserState().getCurrentProfile());
PropertyResource configResource = configuration.getPropertyResource();
configResource.setTypeURI(ACTIVITY_URI.resolve("#Config"));
// Basic properties
String script = rshellConfig.getScript();
configResource.addPropertyAsString(ACTIVITY_URI.resolve("#script"), script);
if (rshellConfig.getRVersion() != null) {
configResource.addPropertyAsString(ACTIVITY_URI.resolve("#rVersion"), rshellConfig.getRVersion());
}
// Connection
PropertyResource connection = configResource.addPropertyAsNewResource(ACTIVITY_URI.resolve("#connection"), ACTIVITY_URI.resolve("#Connection"));
connection.addPropertyAsString(ACTIVITY_URI.resolve("#hostname"), rshellConfig.getConnectionSettings().getHost());
PropertyLiteral port = new PropertyLiteral(rshellConfig.getConnectionSettings().getPort());
port.setLiteralType(PropertyLiteral.XSD_UNSIGNEDSHORT);
connection.addProperty(ACTIVITY_URI.resolve("#port"), port);
// ignored - Taverna 2.3+ uses credential manager
// connection.addPropertyAsString(ACTIVITY_URI.resolve("#username"),
// rshellConfig.getConnectionSettings().getUsername());
// connection.addPropertyAsString(ACTIVITY_URI.resolve("#password"),
// rshellConfig.getConnectionSettings().getPassword());
connection.addProperty(ACTIVITY_URI.resolve("#keepSessionAlive"),
new PropertyLiteral(rshellConfig.getConnectionSettings().isKeepSessionAlive()));
// ignoooooored - we won't support the legacy ones anymore
// if (rshellConfig.getConnectionSettings().isNewRVersion() == null || ! rshellConfig.getConnectionSettings().isNewRVersion()) {
// connection.addProperty(ACTIVITY_URI.resolve("#legacy"),
// new PropertyLiteral(true));
// Activity ports
Activity activity = getParserState().getCurrentActivity();
activity.getInputPorts().clear();
activity.getOutputPorts().clear();
for (ActivityPortDefinitionBean portBean : rshellConfig
.getInputs().getNetSfTavernaT2WorkflowmodelProcessorActivityConfigActivityInputPortDefinitionBean()
) {
parseAndAddInputPortDefinition(portBean, configuration, activity);
}
for (ActivityPortDefinitionBean portBean : rshellConfig
.getOutputs()
.getNetSfTavernaT2WorkflowmodelProcessorActivityConfigActivityOutputPortDefinitionBean()) {
parseAndAddOutputPortDefinition(portBean, configuration, activity);
}
// TODO: Semantic types
RShellSymanticType inputSymanticTypes = rshellConfig.getInputSymanticTypes();
inputSymanticTypes.getNetSfTavernaT2ActivitiesRshellRShellPortSymanticTypeBean();
return configuration;
}
}
|
package rres.knetminer.datasource.server.datasetinfo;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping ( path = "/{ds}/dataset-info", method = { RequestMethod.GET, RequestMethod.POST } )
@CrossOrigin
public class DatasetInfoService
{
@RequestMapping ( path = "" )
public DatasetInfo datasetInfo ()
{
// TODO: mockup data that need to be replaced with a real fetch from config
return new DatasetInfo () {
{
this.setTitle ( "AraTiny Dataset" );
this.setOrganization ( "Rothamsted Research" );
this.setSpecies ( List.of (
new SpecieInfo ( "3702", "Thale cress", "Arabidopsis Thaliana" ),
new SpecieInfo ( "4565", "Bread Wheat", "Triticum aestivum" ),
new SpecieInfo ( "4577", "Maize", "Zea mays" )
));
}
};
}
@RequestMapping ( path = "/basemap.xml", produces = MediaType.APPLICATION_XML_VALUE )
public String basemapXml ( @RequestParam String taxId )
{
return null;
}
@RequestMapping ( path = "/sample-query.xml", produces = MediaType.APPLICATION_XML_VALUE )
public String sampleQueryXml () // TODO: do we need taxId?
{
return null;
}
@RequestMapping ( path = "/chromosome-ids" )
public List<String> chromosomeIds ( @RequestParam String taxId )
{
// TODO: Use XPath and parse them from basemap.xml (initially here, later on some utility function)
// TODO: check the right output is returned (a JSON array)
// uk.ac.ebi.utils.xml.XPathReader might be useful
return null;
}
@RequestMapping ( path = "/release-notes.html", produces = MediaType.TEXT_HTML_VALUE )
public String releaseNotesHtml ()
{
return null;
}
@RequestMapping ( path = "/background-image" )
public ResponseEntity<byte[]> getBackgroundImage () // TODO: do we need taxId?
{
try
{
Path bkgPath = Path.of ( "TODO: fetch this from config" );
String mime = Files.probeContentType ( bkgPath );
byte[] content = Files.readAllBytes ( bkgPath );
bkgPath.toFile ();
return ResponseEntity
.ok ()
.header ( "Content-Type", mime )
.body ( content );
}
catch ( IOException ex )
{
throw new UncheckedIOException (
"Error while fetching application background: " + ex.getMessage (),
ex
);
}
}
}
|
package stroom.dropwizard.common;
import stroom.event.logging.rs.api.AutoLogged;
import stroom.event.logging.rs.api.AutoLogged.OperationType;
import stroom.event.logging.rs.impl.AnnotationUtil;
import stroom.security.api.SecurityContext;
import stroom.util.ConsoleColour;
import stroom.util.NullSafe;
import stroom.util.shared.FetchWithIntegerId;
import stroom.util.shared.FetchWithLongId;
import stroom.util.shared.FetchWithTemplate;
import stroom.util.shared.FetchWithUuid;
import stroom.util.shared.RestResource;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Strings;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.Tuple4;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Provider;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
class TestRestResources {
private static final Logger LOGGER = LoggerFactory.getLogger(TestRestResources.class);
// @Disabled // Temp while REST resource refactoring / annotation work is ongoing.
@TestFactory
@SuppressWarnings("unchecked")
Stream<DynamicTest> buildQualityAssuranceTests() {
try (ScanResult result = new ClassGraph()
.whitelistPackages("stroom")
.enableClassInfo()
.ignoreClassVisibility()
.enableAnnotationInfo()
.scan()) {
final List<? extends Class<? extends RestResource>> classes = result.getAllClasses()
.stream()
.filter(classInfo -> classInfo.implementsInterface(RestResource.class.getName()))
.map(classInfo -> (Class<? extends RestResource>) classInfo.loadClass())
.sorted(Comparator.comparing(Class::getName))
.collect(Collectors.toList());
LOGGER.info("Found {} classes to test", classes.size());
return classes.stream()
.map(resourceClass ->
DynamicTest.dynamicTest(
resourceClass.getSimpleName() + " (" + resourceClass.getPackageName() + ")",
() ->
doResourceClassAsserts(resourceClass)));
}
}
// @Disabled // manually run only
@Test
@SuppressWarnings("unchecked")
void listMethods() {
try (ScanResult result = new ClassGraph()
.whitelistPackages("stroom")
.enableClassInfo()
.ignoreClassVisibility()
.enableAnnotationInfo()
.scan()) {
final List<? extends Class<? extends RestResource>> classes = result.getAllClasses()
.stream()
.filter(classInfo -> classInfo.implementsInterface(RestResource.class.getName()))
.map(classInfo -> (Class<? extends RestResource>) classInfo.loadClass())
.sorted(Comparator.comparing(Class::getName))
.collect(Collectors.toList());
LOGGER.info("Found {} classes to test", classes.size());
final Map<Tuple2<String, String>, List<Tuple4<String, String, String, String>>> results = classes.stream()
.flatMap(clazz ->
Arrays.stream(clazz.getMethods())
.map(method -> Tuple.of(clazz, method)))
.filter(clazzMethod -> hasJaxRsAnnotation(clazzMethod._1, clazzMethod._2, false))
.map(clazzMethod -> Tuple.of(
clazzMethod._2.getName(),
getJaxRsHttpMethod(clazzMethod._2),
getMethodSig(clazzMethod._1, clazzMethod._2),
getJaxRsPath(clazzMethod._1, clazzMethod._2)))
.collect(Collectors.groupingBy(
tuple ->
Tuple.of(tuple._1, tuple._2),
Collectors.toList()));
final StringBuilder stringBuilder = new StringBuilder();
results.entrySet()
.stream()
.sorted(Entry.comparingByKey())
.forEach(entry -> {
final Tuple2<String, String> key = entry.getKey();
final List<Tuple4<String, String, String, String>> value = entry.getValue();
stringBuilder
.append(key._1)
.append(" (")
.append(ConsoleColour.yellow(key._2))
.append(")\n");
value.stream()
.sorted()
.forEach(tuple4 -> {
final String path = Strings.padEnd(tuple4._4, 50, ' ');
stringBuilder
.append(" ")
.append(ConsoleColour.blue(path))
.append(" ")
.append(tuple4._3)
.append("\n");
});
});
LOGGER.info("Methods:\n{}", stringBuilder.toString());
}
}
private String getMethodSig(final Class<?> clazz,
final Method method) {
final String methodeSig = method.getReturnType().getSimpleName() +
" " +
ConsoleColour.yellow(method.getName()) +
"(" +
Arrays.stream(method.getParameters())
.map(parameter ->
parameter.getType().getSimpleName())
.collect(Collectors.joining(", ")) +
")";
return Strings.padEnd(methodeSig, 80, ' ') +
" [" +
ConsoleColour.cyan(clazz.getSimpleName()) +
"]";
}
private String getJaxRsPath(final Class<? extends RestResource> clazz,
final Method method) {
final String basePath = NullSafe.getOrElse(clazz.getAnnotation(Path.class), Path::value, "");
final String subPath = NullSafe.getOrElse(method.getAnnotation(Path.class), Path::value, "/");
return basePath + subPath;
}
private String getJaxRsHttpMethod(final Method method) {
final Set<Class<? extends Annotation>> httpMethodAnnos = Set.of(
GET.class,
PUT.class,
DELETE.class,
HEAD.class,
PATCH.class,
POST.class,
OPTIONS.class);
return Arrays.stream(method.getAnnotations())
.filter(anno -> httpMethodAnnos.contains(anno.annotationType()))
.findFirst()
.map(annotation -> annotation.annotationType().getSimpleName())
.orElse("???");
// .orElseThrow(() -> new RuntimeException("Method " + method + "has no jaxrs anno, e.g. GET/PUT/etc."));
}
private void doResourceClassAsserts(final Class<? extends RestResource> resourceClass) {
final boolean isInterface = resourceClass.isInterface();
final String typeName = isInterface
? "interface"
: "class";
SoftAssertions.assertSoftly(softAssertions -> {
if (isInterface) {
testInterface(resourceClass, typeName, softAssertions);
} else {
testImplementation(resourceClass, typeName, softAssertions);
}
});
}
private void testInterface(final Class<? extends RestResource> resourceClass,
final String typeName,
final SoftAssertions softAssertions) {
LOGGER.info("Doing @Api... asserts");
// Check that the interface has no @Autologged annotations.
checkForUnexpectedAnnotations(
resourceClass,
softAssertions,
annotationClass -> annotationClass.equals(AutoLogged.class),
AutoLogged.class.getName());
// Check that the interface has no @Timed annotations.
checkForUnexpectedAnnotations(
resourceClass,
softAssertions,
annotationClass -> annotationClass.equals(Timed.class),
Timed.class.getName());
final boolean classHasTagAnnotation = resourceClass.isAnnotationPresent(Tag.class);
final String[] apiAnnotationTags = classHasTagAnnotation
? Arrays
.stream(resourceClass.getAnnotationsByType(Tag.class))
.map(Tag::name)
.toArray(String[]::new)
: new String[0];
softAssertions.assertThat(classHasTagAnnotation)
.withFailMessage(() -> typeName + " must have class annotation like " +
"@Tag(tags = \"Nodes\")")
.isTrue();
if (classHasTagAnnotation) {
LOGGER.info("Class has @Tag annotation");
softAssertions.assertThat(apiAnnotationTags.length)
.withFailMessage(() -> "@Tag must have tags property set, e.g. @Api(tags = \"Nodes\")")
.isGreaterThanOrEqualTo(1);
if (apiAnnotationTags.length >= 1) {
softAssertions.assertThat(apiAnnotationTags[0])
.withFailMessage(() -> "@Tag must have tags property set, e.g. @Api(tags = \"Nodes\")")
.isNotEmpty();
}
} else {
LOGGER.info("Class doesn't have @Tag annotation");
}
// We need to get a set of unique methods otherwise we end up seeing duplicates from inherited interfaces.
final Set<MethodSignature> uniqueMethods = Arrays
.stream(resourceClass.getMethods())
.filter(method -> !Modifier.isPrivate(method.getModifiers()))
.filter(method -> hasJaxRsAnnotation(resourceClass, method, true))
.map(method -> new MethodSignature(method.getName(), method.getParameterTypes()))
.collect(Collectors.toSet());
uniqueMethods
.forEach(methodSignature -> {
try {
final Method method = resourceClass.getMethod(methodSignature.getName(),
methodSignature.getParameterTypes());
final List<Class<? extends Annotation>> methodAnnotationTypes = Arrays
.stream(method.getAnnotations())
.map(Annotation::annotationType)
.collect(Collectors.toList());
LOGGER.debug("Found annotations {}", methodAnnotationTypes);
final boolean hasOperationAnno = methodAnnotationTypes.contains(Operation.class);
softAssertions
.assertThat(hasOperationAnno)
.withFailMessage(() -> "Method '" + method.getName() + "' must be annotated " +
"with @Operation(summary = \"Some description of what the method does\")")
.isTrue();
if (hasOperationAnno) {
final Class<?> methodReturnClass = method.getReturnType();
final Operation operation = AnnotationUtil
.getInheritedMethodAnnotation(Operation.class, method);
final ApiResponse[] responses = operation.responses();
final Map<String, String> operationIdMap = new HashMap<>();
softAssertions
.assertThat(operation.operationId())
.withFailMessage(() ->
"Method '" +
method.getName() +
"' declares an @Operation annotation but has no `operationId`")
.isNotBlank();
if (!operation.operationId().isBlank()) {
final String existing = operationIdMap.put(
operation.operationId(),
resourceClass.getName() + "::" + methodSignature.getName());
final String existingOperation;
if (existing != null) {
existingOperation = existing;
} else {
existingOperation = resourceClass.getName() + "::" + methodSignature.getName();
}
if (!existingOperation.equals(resourceClass.getName() + "::" +
methodSignature.getName())) {
LOGGER.warn("Method '" +
method.getName() +
"' does not have a globally unique `operationId` '" +
operation.operationId() +
"'" +
" exists in " +
existingOperation);
}
softAssertions
.assertThat(existingOperation)
.withFailMessage(() ->
"Method '" +
method.getName() +
"' does not have a globally unique `operationId` '" +
operation.operationId() +
"'" +
" exists in " +
existingOperation)
.isEqualTo(resourceClass.getName() + "::" + methodSignature.getName());
}
// Only need to set response when Response is used
if (Response.class.equals(methodReturnClass)) {
softAssertions
.assertThat(responses.length)
.withFailMessage(() ->
"Method '" + method.getName() + "' must have response " +
"set in @Operation, e.g. @Operation(summary = \"xxx\" " +
"response = Node.class)")
.isNotZero();
}
}
} catch (final NoSuchMethodException e) {
throw new RuntimeException(e.getMessage(), e);
}
});
}
private void testImplementation(final Class<? extends RestResource> resourceClass,
final String typeName,
final SoftAssertions softAssertions) {
final boolean superImplementsRestResource = Arrays.stream(resourceClass.getInterfaces())
.filter(iface ->
!RestResource.class.equals(iface))
.anyMatch(iface ->
Arrays.asList(iface.getInterfaces())
.contains(RestResource.class));
LOGGER.info("Inspecting {} {}, superImplementsRestResource; {}",
typeName, resourceClass.getName(), superImplementsRestResource);
// Check that this is an implementation of a rest resource interface.
softAssertions.assertThat(superImplementsRestResource)
.withFailMessage(
"Unexpected class that is not an interface and does not implement " +
RestResource.class.getName())
.isTrue();
// Check that we have no JAX_RS annotations.
checkForUnexpectedAnnotations(
resourceClass,
softAssertions,
annotationClass -> annotationClass.getPackageName().equals(Path.class.getPackageName()),
"JAX RS");
// Check that we have no swagger annotations.
checkForUnexpectedAnnotations(
resourceClass,
softAssertions,
annotationClass -> annotationClass.getPackageName().contains("swagger"),
"Swagger");
// Check auto logging
final boolean classIsAutoLogged = resourceClass.isAnnotationPresent(AutoLogged.class);
LOGGER.info("classIsAutoLogged: {}", classIsAutoLogged);
// Check that all member variables are providers.
assertProviders(resourceClass, softAssertions);
// Check that resource doesn't attempt to handle security
assertNoSecurityContext(resourceClass, softAssertions);
Arrays.stream(resourceClass.getMethods())
.filter(method -> !Modifier.isPrivate(method.getModifiers()))
.filter(method -> hasJaxRsAnnotation(resourceClass, method, true))
.forEach(method -> {
final boolean methodIsAutoLogged = method.isAnnotationPresent(AutoLogged.class);
softAssertions.assertThat(classIsAutoLogged || methodIsAutoLogged)
.withFailMessage(() -> "Method " + method.getName() +
"(...) or its class must be annotated with @AutoLogged")
.isTrue();
OperationType effectiveLoggingType = null;
if (classIsAutoLogged) {
effectiveLoggingType = resourceClass.getAnnotation(AutoLogged.class).value();
}
if (methodIsAutoLogged) {
effectiveLoggingType = method.getAnnotation(AutoLogged.class).value();
}
if (method.getReturnType().equals(Void.TYPE)) {
softAssertions.assertThat(effectiveLoggingType)
.withFailMessage(() -> "Method " + method.getName() +
"(...) returns void, so autologger can't operate on it. " +
"Either change the return type, manually log and annotate" +
" with @AutoLogged(MANUALLY_LOGGED), or " +
"annotate with @AutoLogged(UNLOGGED).")
.isIn(OperationType.MANUALLY_LOGGED, OperationType.UNLOGGED);
}
});
assertFetchDeclared(resourceClass, softAssertions);
}
private void assertFetchDeclared(final Class<? extends RestResource> resourceClass,
final SoftAssertions softAssertions) {
boolean fetchMethodPresent = Arrays.stream(resourceClass.getMethods())
.filter(m -> m.getName().equals("fetch") && m.getParameterCount() == 1).findFirst().isPresent();
boolean updateOrDeleteMethodPresent = Arrays.stream(resourceClass.getMethods())
.filter(m -> m.getName().equals("update") || m.getName().equals("delete")).findFirst().isPresent();
if (fetchMethodPresent && updateOrDeleteMethodPresent) {
if (!FetchWithUuid.class.isAssignableFrom(resourceClass) &&
!FetchWithIntegerId.class.isAssignableFrom(resourceClass) &&
!FetchWithLongId.class.isAssignableFrom(resourceClass) &&
!FetchWithTemplate.class.isAssignableFrom(resourceClass)) {
softAssertions.fail("Resource classes that support fetch() should" +
" declare the appropriate FetchWithSomething<FetchedThing> interface");
}
}
}
private void assertProviders(final Class<? extends RestResource> resourceClass,
final SoftAssertions softAssertions) {
List<Class<?>> nonProvidedFields = Arrays.stream(resourceClass.getDeclaredFields())
.filter(field ->
Modifier.isPrivate(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())
&& !Modifier.isStatic(field.getModifiers()))
.map(Field::getType)
.filter(clazz ->
!Provider.class.equals(clazz))
.collect(Collectors.toList());
if (!nonProvidedFields.isEmpty()) {
LOGGER.warn("Non provided fields {}", nonProvidedFields);
softAssertions.assertThat(nonProvidedFields)
.withFailMessage("Resource implementations/classes must inject all objects " +
"via Providers.")
.isEmpty();
}
}
private void assertNoSecurityContext(final Class<? extends RestResource> resourceClass,
final SoftAssertions softAssertions) {
List<Field> securityContextFields = Arrays.stream(resourceClass.getDeclaredFields())
.filter(field -> {
if (SecurityContext.class.isAssignableFrom(field.getType())) {
return true;
} else if (Provider.class.isAssignableFrom(field.getType())) {
//Really would like to check for presence of Provider<SecurityContext>
//but not possible in Java.
// Check for what we can manage, which is a field of type that extends Provider<SecurityContext>
if (field.getType().getGenericSuperclass() instanceof ParameterizedType) {
ParameterizedType providerType = (ParameterizedType) field.getType().getGenericSuperclass();
return Arrays.stream(providerType.getActualTypeArguments())
.filter(type -> SecurityContext.class.isAssignableFrom(type.getClass()))
.findAny()
.isPresent();
}
}
return false;
})
.collect(Collectors.toList());
if (!securityContextFields.isEmpty()) {
LOGGER.warn("SecurityContext fields {}", securityContextFields);
softAssertions.assertThat(securityContextFields)
.withFailMessage("Resource implementations/classes should delegate SecurityContext " +
"operations to an internal service.")
.isEmpty();
}
}
private boolean hasJaxRsAnnotation(final Class<?> clazz, final Method method, final boolean checkInterfaces) {
boolean thisMethodHasJaxRs = Arrays.stream(method.getAnnotations())
.anyMatch(annotation ->
annotation.annotationType().getPackageName().equals("javax.ws.rs"));
if (!checkInterfaces) {
return thisMethodHasJaxRs;
} else {
if (!thisMethodHasJaxRs) {
final Class<?> restInterface = Arrays.stream(clazz.getInterfaces())
.filter(iface -> Arrays.asList(iface.getInterfaces()).contains(RestResource.class))
.findAny()
.orElse(null);
if (restInterface == null) {
return false;
} else {
// now find the same method on the interface
final Optional<Method> optIfaceMethod = Arrays.stream(restInterface.getMethods())
.filter(ifaceMethod -> areMethodsEqual(method, ifaceMethod))
.findAny();
return optIfaceMethod.map(ifaceMethod -> hasJaxRsAnnotation(restInterface,
ifaceMethod,
checkInterfaces))
.orElse(false);
}
} else {
return true;
}
}
}
private boolean areMethodsEqual(final Method method1, final Method method2) {
if (method1.equals(method2)) {
return true;
} else {
return method1.getName().equals(method2.getName())
&& method1.getReturnType().equals(method2.getReturnType())
&& method1.getGenericReturnType().equals(method2.getGenericReturnType())
&& Arrays.equals(method1.getParameterTypes(), method2.getParameterTypes())
&& Arrays.equals(method1.getGenericParameterTypes(), method2.getGenericParameterTypes());
}
}
private void checkForUnexpectedAnnotations(final Class<? extends RestResource> resourceClass,
final SoftAssertions softAssertions,
final Function<Class<? extends Annotation>, Boolean> testFunction,
final String annotationType) {
// Check that we have no JAX_RS annotations.
final boolean hasClassAnnotation = Arrays.stream(resourceClass.getAnnotations())
.anyMatch(annotation ->
testFunction.apply(annotation.annotationType()));
softAssertions.assertThat(hasClassAnnotation)
.withFailMessage(
"Class " +
resourceClass.getName() +
" name Unexpected " +
annotationType +
" annotations")
.isFalse();
Arrays.stream(resourceClass.getMethods())
.forEach(method -> {
final boolean hasMethodAnnotation = Arrays.stream(method.getAnnotations())
.anyMatch(annotation ->
testFunction.apply(annotation.annotationType()));
softAssertions.assertThat(hasMethodAnnotation)
.withFailMessage(
"Class " +
resourceClass.getName() +
" name Unexpected " +
annotationType +
" annotations on " +
method.getName())
.isFalse();
});
}
private static class MethodSignature {
private final String name;
private final Class<?>[] parameterTypes;
public MethodSignature(final String name, final Class<?>[] parameterTypes) {
this.name = name;
this.parameterTypes = parameterTypes;
}
public String getName() {
return name;
}
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final MethodSignature that = (MethodSignature) o;
return Objects.equals(name, that.name) && Arrays.equals(parameterTypes, that.parameterTypes);
}
@Override
public int hashCode() {
int result = Objects.hash(name);
result = 31 * result + Arrays.hashCode(parameterTypes);
return result;
}
@Override
public String toString() {
return "MethodSignature{" +
"name='" + name + '\'' +
", parameterTypes=" + Arrays.toString(parameterTypes) +
'}';
}
}
}
|
package com.tjh.swivel.controller;
import com.tjh.swivel.model.RequestHandler;
import com.tjh.swivel.model.ShuntRequestHandler;
import com.tjh.swivel.model.StubRequestHandler;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.log4j.Logger;
import vanderbilt.util.Block;
import vanderbilt.util.Block2;
import vanderbilt.util.Lists;
import vanderbilt.util.Maps;
import vanderbilt.util.PopulatingMap;
import vanderbilt.util.Strings;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class RequestRouter {
public static final String SHUNT_NODE = "^shunt";
public static final String STUB_NODE = "^stub";
private Logger logger = Logger.getLogger(RequestRouter.class);
protected final Map<String, Map<String, Object>> uriHandlers = new PopulatingMap<String, Map<String, Object>>(
new ConcurrentHashMap<String, Map<String, Object>>(),
new Block2<Map<String, Map<String, Object>>, Object, Map<String, Object>>() {
@Override
public Map<String, Object> invoke(Map<String, Map<String, Object>> stringMapMap, Object o) {
return new PopulatingMap<String, Object>(new ConcurrentHashMap<String, Object>(),
new Block2<Map<String, Object>, Object, Object>() {
@Override
public Object invoke(Map<String, Object> stringObjectMap, Object o) {
Object result = null;
if (STUB_NODE.equals(o)) {
result = new CopyOnWriteArrayList();
}
return result;
}
});
}
}
);
private ClientConnectionManager clientConnectionManager;
private HttpParams httpParams = new BasicHttpParams();
@SuppressWarnings({"ConstantConditions", "unchecked"})
public HttpResponse route(HttpRequestBase request) {
RequestHandler result = null;
Deque<String> pathElements = new LinkedList<String>(Arrays.asList(toKeys(request.getURI())));
String matchedPath;
do {
matchedPath = Strings.join(pathElements.toArray(new String[pathElements.size()]), "/");
if (uriHandlers.containsKey(matchedPath)) {
Map<String, Object> stringObjectMap = uriHandlers.get(matchedPath);
result = findStub(stringObjectMap, request);
if (result == null && stringObjectMap.containsKey(SHUNT_NODE)) {
result = (RequestHandler) stringObjectMap.get(SHUNT_NODE);
}
}
pathElements.removeLast();
}
while (result == null && !pathElements.isEmpty());
logger.debug(String.format("Routing <%1$s> to <%2$s>. Matched path is: <%3$s>", request, result, matchedPath));
return result.handle(request, URI.create(matchedPath), createClient());
}
@SuppressWarnings("unchecked")
private RequestHandler findStub(Map<String, Object> stringObjectMap, final HttpUriRequest request) {
return Lists.find((Collection<StubRequestHandler>) stringObjectMap.get(STUB_NODE),
new Block<StubRequestHandler, Boolean>() {
@Override
public Boolean invoke(StubRequestHandler requestHandler) {
return requestHandler.matches(request);
}
});
}
@SuppressWarnings("unchecked")
public void removeStub(URI localUri, final int stubHandlerId) {
List<StubRequestHandler> handlers = (List<StubRequestHandler>) uriHandlers
.get(localUri.getPath())
.get(STUB_NODE);
StubRequestHandler target = Lists.find(handlers, new Block<StubRequestHandler, Boolean>() {
@Override
public Boolean invoke(StubRequestHandler stubRequestHandler) {
return stubRequestHandler.getId() == stubHandlerId;
}
});
logger.debug(String.format("Removing <%1$s> from path <%2$s>", target, localUri));
handlers.remove(target);
}
public void setShunt(URI localURI, ShuntRequestHandler requestHandler) {
logger.debug(String.format("Setting shunt <%1$s> at <%2$s>", requestHandler, localURI));
uriHandlers.get(localURI.getPath()).put(SHUNT_NODE, requestHandler);
}
@SuppressWarnings("unchecked")
public void addStub(URI localUri, StubRequestHandler stubRequestHandler) {
logger.debug(String.format("Adding stub <%1$s> to <%2$s>", stubRequestHandler, localUri));
((List) uriHandlers.get(localUri.getPath())
.get(STUB_NODE))
.add(0, stubRequestHandler);
}
public void deleteShunt(URI localURI) {
String path = localURI.getPath();
Map<String, Object> handlerMap = uriHandlers.get(path);
ShuntRequestHandler shuntRequestHandler = (ShuntRequestHandler) handlerMap
.remove(SHUNT_NODE);
if (handlerMap.isEmpty()) {
uriHandlers.remove(path);
}
logger.debug(String.format("Removed <%1$s> from <%2$s>", shuntRequestHandler, localURI));
}
protected HttpClient createClient() { return new DefaultHttpClient(clientConnectionManager, httpParams); }
private String[] toKeys(URI localURI) {return localURI.getPath().split("/");}
//<editor-fold desc="bean">
public Map<String, Map<String, Object>> getUriHandlers() {
final HashMap<String, Map<String, Object>> result = new HashMap<String, Map<String, Object>>(uriHandlers);
Maps.eachPair(result, new Block2<String, Map<String, Object>, Object>() {
@Override
public Object invoke(String s, Map<String, Object> stringObjectMap) {
result.put(s, new HashMap<String, Object>(stringObjectMap));
return null;
}
});
return result;
}
public void setClientConnectionManager(ClientConnectionManager clientConnectionManager) {
this.clientConnectionManager = clientConnectionManager;
}
public void setHttpParams(HttpParams httpParams) { this.httpParams = httpParams; }
//</editor-fold>
}
|
package org.barbon.mangaget;
import android.app.Activity;
import android.app.Instrumentation;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.ListView;
import org.barbon.mangaget.tests.Utils;
public class SearchTest extends ActivityInstrumentationTestCase2<MangaSearch> {
private MangaSearch activity;
public SearchTest() {
super("org.barbon.mangaget", MangaSearch.class);
}
public Intent searchIntent(String query) {
Context targetContext = getInstrumentation().getTargetContext();
Intent intent = new Intent(targetContext, MangaSearch.class);
intent.setAction(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, query);
return intent;
}
@Override
protected void setUp() throws Exception {
super.setUp();
Utils.setupTestEnvironment(this);
Utils.setupTestDatabase(this);
setActivityInitialTouchMode(false);
}
public void testSimpleSearch() throws Exception {
setActivityIntent(searchIntent(""));
activity = (MangaSearch) getActivity();
ListView resultList = activity.getListView();
while (resultList.getCount() == 0)
Thread.sleep(500);
assertEquals(48, resultList.getCount());
}
}
|
package com.alibaba.nacos.test.naming;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.naming.NamingApp;
import com.alibaba.nacos.naming.selector.Selector;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import static com.alibaba.nacos.test.naming.NamingBase.*;
/**
* @author nkorange
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NamingApp.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MultiTenant_ITCase {
private NamingService naming;
private NamingService naming1;
private NamingService naming2;
@LocalServerPort
private int port;
private volatile List<Instance> instances = Collections.emptyList();
@Before
public void init() throws Exception {
Thread.sleep(6000L);
NamingBase.prepareServer(port);
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
while (true) {
if (!"UP".equals(naming.getServerStatus())) {
Thread.sleep(1000L);
continue;
}
break;
}
Properties properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, "namespace-1");
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
naming1 = NamingFactory.createNamingService(properties);
properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, "namespace-2");
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
naming2 = NamingFactory.createNamingService(properties);
}
/**
* @TCDescription : IPport
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_registerInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
naming2.registerInstance(serviceName, "22.22.22.22", 80);
naming.registerInstance(serviceName, "33.33.33.33", 8888);
naming.registerInstance(serviceName, "44.44.44.44", 8888);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
instances = naming2.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("22.22.22.22", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(2, instances.size());
}
/**
* @TCDescription : Group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_multiGroup_registerInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming2.registerInstance(serviceName, TEST_GROUP_2,"22.22.22.22", 80);
naming.registerInstance(serviceName, "33.33.33.33", 8888);
naming.registerInstance(serviceName, "44.44.44.44", 8888);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
instances = naming2.getAllInstances(serviceName, TEST_GROUP_2);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("22.22.22.22", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(2, instances.size());
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"22.22.22.22", 80);
}
/**
* @TCDescription : IPport
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_equalIP() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
naming2.registerInstance(serviceName, "11.11.11.11", 80);
naming.registerInstance(serviceName, "11.11.11.11", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
instances = naming2.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
}
/**
* @TCDescription : IPport
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_selectInstances() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT);
naming2.registerInstance(serviceName, "22.22.22.22", 80);
naming.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT);
naming.registerInstance(serviceName, "44.44.44.44", 8888);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.selectInstances(serviceName, true);
Assert.assertEquals(1, instances.size());
Assert.assertEquals(TEST_IP_4_DOM_1, instances.get(0).getIp());
Assert.assertEquals(TEST_PORT, instances.get(0).getPort());
instances = naming2.selectInstances(serviceName, false);
Assert.assertEquals(0, instances.size());
instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(2, instances.size());
}
/**
* @TCDescription : ,GroupIPport
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_equalIP() throws Exception {
String serviceName = randomDomainName();
System.out.println(serviceName);
naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming2.registerInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80);
naming.registerInstance(serviceName, Constants.DEFAULT_GROUP,"11.11.11.11", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
instances = naming2.getAllInstances(serviceName, TEST_GROUP_2);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
}
/**
* @TCDescription : ,GroupIPport, group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_getInstances() throws Exception {
String serviceName = randomDomainName();
System.out.println(serviceName);
naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming1.registerInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80);
naming.registerInstance(serviceName, Constants.DEFAULT_GROUP,"11.11.11.11", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
Assert.assertEquals(0, instances.size());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80);
}
/**
* @TCDescription :
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_getServicesOfServer() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView = naming1.getServicesOfServer(1, 20);
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView1 = naming1.getServicesOfServer(1, 20);
Assert.assertEquals(listView.getCount(), listView1.getCount());
}
/**
* @TCDescription : , group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_getServicesOfServer() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_GROUP_1, TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_GROUP_2, TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView = naming1.getServicesOfServer(1, 20);
Assert.assertEquals(0, listView.getCount());
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView1 = naming1.getServicesOfServer(1, 20, TEST_GROUP_1);
Assert.assertEquals(listView.getCount(), listView1.getCount());
}
/**
* @TCDescription :
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_subscribe() throws Exception {
String serviceName = randomDomainName();
naming1.subscribe(serviceName, new EventListener() {
@Override
public void onEvent(Event event) {
instances = ((NamingEvent) event).getInstances();
}
});
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
Assert.assertEquals(1, instances.size());
TimeUnit.SECONDS.sleep(2L);
Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName)));
}
/**
* @TCDescription : group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_subscribe() throws Exception {
String serviceName = randomDomainName();
naming1.subscribe(serviceName, TEST_GROUP_1, new EventListener() {
@Override
public void onEvent(Event event) {
instances = ((NamingEvent) event).getInstances();
}
});
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1,"33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
TimeUnit.SECONDS.sleep(2L);
Assert.assertEquals(1, instances.size());
TimeUnit.SECONDS.sleep(2L);
Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName, TEST_GROUP_1)));
naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"33.33.33.33", TEST_PORT, "c1");
}
/**
* @TCDescription :
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_unSubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent)event).getServiceName());
instances = ((NamingEvent)event).getInstances();
}
};
naming1.subscribe(serviceName, listener);
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
naming1.unsubscribe(serviceName, listener);
TimeUnit.SECONDS.sleep(5L);
Assert.assertEquals(0, naming1.getSubscribeServices().size());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
}
/**
* @TCDescription : ,group, group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_nosubscribe_unSubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent)event).getServiceName());
instances = ((NamingEvent)event).getInstances();
}
};
naming1.subscribe(serviceName, TEST_GROUP_1, listener);
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
naming1.unsubscribe(serviceName, listener); //group
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(1, naming1.getSubscribeServices().size());
naming1.unsubscribe(serviceName, TEST_GROUP_1, listener); //group
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(0, naming1.getSubscribeServices().size());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
}
/**
* @TCDescription : ,group, group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_unSubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent)event).getServiceName());
instances = ((NamingEvent)event).getInstances();
}
};
naming1.subscribe(serviceName, Constants.DEFAULT_GROUP, listener);
naming1.subscribe(serviceName, TEST_GROUP_2, listener);
naming1.subscribe(serviceName, TEST_GROUP_1, listener);
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
TimeUnit.SECONDS.sleep(2L);
Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
Assert.assertEquals(3, naming1.getSubscribeServices().size());
naming1.unsubscribe(serviceName, listener);
naming1.unsubscribe(serviceName, TEST_GROUP_2, listener);
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(1, naming1.getSubscribeServices().size());
Assert.assertEquals(TEST_GROUP_1, naming1.getSubscribeServices().get(0).getGroupName());
naming1.unsubscribe(serviceName, TEST_GROUP_1, listener);
}
/**
* @TCDescription : server
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_serverStatus() throws Exception {
Assert.assertEquals(TEST_SERVER_STATUS, naming1.getServerStatus());
Assert.assertEquals(TEST_SERVER_STATUS, naming2.getServerStatus());
}
/**
* @TCDescription :
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_deregisterInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c1");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 2, serviceName);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(12);
Assert.assertEquals(1, naming1.getAllInstances(serviceName).size());
Assert.assertEquals(1, naming2.getAllInstances(serviceName).size());
}
/**
* @TCDescription : , groupgroup
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_deregisterInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 2, serviceName);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"22.22.22.22", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(12);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
}
/**
* @TCDescription : , groupclusterName
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_cluster_deregisterInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 2, serviceName);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT);
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
}
/**
* @TCDescription :
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_selectOneHealthyInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
naming2.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c3");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 2, serviceName);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c1"));
Assert.assertEquals("11.11.11.11", instance.getIp());
naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(12);
instance = naming1.selectOneHealthyInstance(serviceName);
Assert.assertEquals("22.22.22.22", instance.getIp());
}
/**
* @TCDescription : group
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_selectOneHealthyInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c3");
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
verifyInstanceListForNaming(naming1, 0, serviceName);
Assert.assertEquals(0, naming1.getAllInstances(serviceName).size()); //defalut group
Instance instance = naming1.selectOneHealthyInstance(serviceName, TEST_GROUP, Arrays.asList("c1"));
Assert.assertEquals("11.11.11.11", instance.getIp());
instance = naming1.selectOneHealthyInstance(serviceName, TEST_GROUP_1);
Assert.assertEquals("22.22.22.22", instance.getIp());
naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c3");
}
/**
* @TCDescription : groupgroup
* @TestStep :
* @ExpectResult :
*/
@Test(expected = IllegalStateException.class)
public void multipleTenant_noGroup_selectOneHealthyInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
verifyInstanceListForNaming(naming1, 0, serviceName);
Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c1"));
naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
}
private void verifyInstanceListForNaming(NamingService naming, int size, String serviceName) throws Exception {
int i = 0;
while ( i < 20 ) {
List<Instance> instances = naming.getAllInstances(serviceName);
if (instances.size() == size) {
break;
} else {
TimeUnit.SECONDS.sleep(3);
i++;
}
}
}
}
|
package org.eclipse.hono.tests.client;
import static java.net.HttpURLConnection.HTTP_CONFLICT;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static org.eclipse.hono.tests.IntegrationTestSupport.*;
import java.net.InetAddress;
import java.util.stream.IntStream;
import org.apache.qpid.proton.message.Message;
import org.eclipse.hono.client.HonoClient;
import org.eclipse.hono.client.HonoClient.HonoClientBuilder;
import org.eclipse.hono.client.RegistrationClient;
import org.eclipse.hono.client.TelemetryConsumer;
import org.eclipse.hono.client.TelemetrySender;
import org.eclipse.hono.util.MessageHelper;
import org.eclipse.hono.util.RegistrationResult;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.proton.ProtonClientOptions;
/**
* A simple test that uses the {@code TelemetryClient} to send some messages to
* Hono server and verifies they are forwarded to the downstream host.
*/
@RunWith(VertxUnitRunner.class)
public class TelemetryClientIT {
private static final Logger LOGGER = LoggerFactory.getLogger(TelemetryClientIT.class);
// connection parameters
private static final String DEFAULT_HOST = InetAddress.getLoopbackAddress().getHostAddress();
private static final String HONO_HOST = System.getProperty(PROPERTY_HONO_HOST, DEFAULT_HOST);
private static final int HONO_PORT = Integer.getInteger(PROPERTY_HONO_PORT, 5672);
private static final String DOWNSTREAM_HOST = System.getProperty(PROPERTY_DOWNSTREAM_HOST, DEFAULT_HOST);
private static final int DOWNSTREAM_PORT = Integer.getInteger(PROPERTY_DOWNSTREAM_PORT, 15672);
private static final String PATH_SEPARATOR = System.getProperty("hono.telemetry.pathSeparator", "/");
// test constants
private static final int MSG_COUNT = 50;
private static final String TEST_TENANT_ID = "DEFAULT_TENANT";
private static final String DEVICE_ID = "device-0";
private static final String CONTENT_TYPE_TEXT_PLAIN = "text/plain";
private static Vertx vertx = Vertx.vertx();
private static HonoClient honoClient;
private static HonoClient downstreamClient;
private static RegistrationClient registrationClient;
private static TelemetrySender sender;
private static TelemetryConsumer consumer;
@BeforeClass
public static void connect(final TestContext ctx) throws Exception {
final Async done = ctx.async();
Future<TelemetrySender> setupTracker = Future.future();
Future<HonoClient> downstreamTracker = Future.future();
CompositeFuture.all(setupTracker, downstreamTracker).setHandler(r -> {
if (r.succeeded()) {
sender = setupTracker.result();
done.complete();
} else {
LOGGER.error("cannot connect to Hono", r.cause());
}
});
downstreamClient = HonoClientBuilder.newClient()
.vertx(vertx)
.host(DOWNSTREAM_HOST)
.port(DOWNSTREAM_PORT)
.pathSeparator(PATH_SEPARATOR)
.user("user1@HONO")
.password("pw")
.build();
downstreamClient.connect(new ProtonClientOptions(), downstreamTracker.completer());
// step 1
// connect to Hono server
Future<HonoClient> honoTracker = Future.future();
honoClient = HonoClientBuilder.newClient()
.vertx(vertx)
.host(HONO_HOST)
.port(HONO_PORT)
.user("hono-client")
.password("secret")
.build();
honoClient.connect(new ProtonClientOptions(), honoTracker.completer());
honoTracker.compose(hono -> {
// step 2
// create client for registering device with Hono
Future<RegistrationClient> regTracker = Future.future();
hono.createRegistrationClient(TEST_TENANT_ID, regTracker.completer());
return regTracker;
}).compose(regClient -> {
// step 3
// create client for sending telemetry data to Hono server
registrationClient = regClient;
honoClient.createTelemetrySender(TEST_TENANT_ID, setupTracker.completer());
}, setupTracker);
done.await(5000);
}
@After
public void deregister(final TestContext ctx) {
if (registrationClient != null) {
final Async done = ctx.async();
LOGGER.debug("deregistering device [{}]", DEVICE_ID);
registrationClient.deregister(DEVICE_ID, r -> {
if (r.succeeded()) {
done.complete();
}
});
done.await(2000);
}
}
@AfterClass
public static void disconnect(final TestContext ctx) throws InterruptedException {
final Async shutdown = ctx.async();
final Future<Void> honoTracker = Future.future();
final Future<Void> qpidTracker = Future.future();
CompositeFuture.all(honoTracker, qpidTracker).setHandler(r -> {
if (r.succeeded()) {
shutdown.complete();
}
});
if (sender != null) {
final Future<Void> regClientTracker = Future.future();
registrationClient.close(regClientTracker.completer());
regClientTracker.compose(r -> {
Future<Void> senderTracker = Future.future();
sender.close(senderTracker.completer());
return senderTracker;
}).compose(r -> {
honoClient.shutdown(honoTracker.completer());
}, honoTracker);
} else {
honoTracker.complete();
}
Future<Void> receiverTracker = Future.future();
if (consumer != null) {
consumer.close(receiverTracker.completer());
} else {
receiverTracker.complete();
}
receiverTracker.compose(r -> {
downstreamClient.shutdown(qpidTracker.completer());
}, qpidTracker);
shutdown.await(1000);
}
@Test
public void testSendingMessages(final TestContext ctx) throws Exception {
final Async received = ctx.async(MSG_COUNT);
final Async setup = ctx.async();
final Future<TelemetryConsumer> setupTracker = Future.future();
setupTracker.setHandler(ctx.asyncAssertSuccess(ok -> {
consumer = setupTracker.result();
setup.complete();
}));
Future<RegistrationResult> regTracker = Future.future();
registrationClient.register(DEVICE_ID, null, regTracker.completer());
regTracker.compose(r -> {
if (r.getStatus() == HTTP_CREATED || r.getStatus() == HTTP_CONFLICT) {
// test can also commence if device already exists
LOGGER.debug("registration succeeded");
downstreamClient.createTelemetryConsumer(
TEST_TENANT_ID,
msg -> {
LOGGER.trace("received {}", msg);
assertMessagePropertiesArePresent(ctx, msg);
received.countDown();
},
setupTracker.completer());
} else {
LOGGER.debug("device registration failed with status [{}]", r);
setupTracker.fail("failed to register device");
}
}, setupTracker);
setup.await(1000);
IntStream.range(0, MSG_COUNT).forEach(i -> {
Async latch = ctx.async();
sender.send(DEVICE_ID, "payload" + i, CONTENT_TYPE_TEXT_PLAIN, capacityAvailable -> {
latch.complete();
});
LOGGER.trace("sent message {}", i);
latch.await();
});
received.await(5000);
}
@Test(timeout = 2000l)
public void testCreateSenderFailsForTenantWithoutAuthorization(final TestContext ctx) {
honoClient.createTelemetrySender("non-authorized", ctx.asyncAssertFailure(failed -> {
LOGGER.debug("creation of sender failed");
}));
}
@Test(timeout = 2000l)
public void testCreateReceiverFailsForTenantWithoutAuthorization(final TestContext ctx) {
downstreamClient.createTelemetryConsumer("non-authorized", message -> {}, ctx.asyncAssertFailure());
}
private static void assertMessagePropertiesArePresent(final TestContext ctx, final Message msg) {
ctx.assertNotNull(MessageHelper.getDeviceId(msg));
// Qpid Dispatch Router < 0.7.0 does not forward custom message annotations
// thus, the following checks are disabled for now
// ctx.assertNotNull(MessageHelper.getTenantIdAnnotation(msg));
// ctx.assertNotNull(MessageHelper.getDeviceIdAnnotation(msg));
}
}
|
package io.spine.testing.core.given;
import io.spine.base.Identifier;
import io.spine.core.UserId;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Factory methods for creating test values of {@link io.spine.core.UserId UserId}.
*/
public final class GivenUserId {
/**
* The prefix for generated user identifiers.
*/
private static final String USER_PREFIX = "user-";
/** Prevent instantiation of this utility class. */
private GivenUserId() {
}
/**
* Creates a new user ID instance by passed string value.
*
* @param value new user ID value
* @return new instance
*/
public static UserId of(String value) {
checkNotNull(value);
checkArgument(!value.isEmpty(), "UserId cannot be empty");
return UserId.newBuilder()
.setValue(value)
.build();
}
/**
* Generates a new UUID-based {@code UserId}.
*/
public static UserId newUuid() {
return of(USER_PREFIX + Identifier.newUuid());
}
/**
* Generates a new UUID-based {@code UserId}.
*
* @apiNote This method is an alias for {@link #newUuid()}. The reason for having it this.
* The code {@code GivenUserId.newUuid()} is somewhat awkward to read and pronounce.
* Some tests or test environments require setup where the code {@code GivenUserId.generated()}
* reads natural as it tells a story. In other places having {@code newUuid()}
* (which is statically imported) looks better, and it also clearly tells what it does.
*
* <p>So, this method is meant to be used with the class name, while its
* {@linkplain #newUuid() sibling} is meant to be used when statically imported.
*/
public static UserId generated() {
return newUuid();
}
/**
* Creates a test value of {@code UserId} based on the simple class name of a test suite.
*/
public static UserId byTestClass(Class<?> cls) {
checkNotNull(cls);
return of(cls.getSimpleName());
}
}
|
package io.spine.tools.protoc;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.Message;
import io.spine.base.UuidValue;
import io.spine.code.proto.FileName;
import io.spine.type.MessageType;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
/**
* An abstract base for generated methods scanners.
*
* @param <G>
* generated code configuration
*/
public abstract class TypeScanner<G extends Message> {
protected TypeScanner() {
}
/**
* Finds methods to be generated for the given type.
*/
public ImmutableList<CompilerOutput> scan(MessageType type) {
if (UuidValue.classifier()
.test(type)) {
return uuidMessage(type);
}
if (type.isEnrichment()) {
return enrichmentMessage(type);
}
ImmutableList<CompilerOutput> result = filePatterns()
.stream()
.filter(isNotBlank())
.filter(customFilter(type))
.filter(matchesPattern(type))
.map(filePatternMapper(type))
.flatMap(List::stream)
.collect(toImmutableList());
return result;
}
protected abstract ImmutableList<CompilerOutput> enrichmentMessage(MessageType type);
protected abstract ImmutableList<CompilerOutput> uuidMessage(MessageType type);
protected abstract List<G> filePatterns();
/**
* Creates a file type pattern matcher predicate.
*/
protected abstract MatchesPattern matchesPattern(MessageType type);
/**
* Creates a predicate that ensured that a target code generation field is not empty.
*/
protected abstract IsNotBlank isNotBlank();
protected Predicate<G> customFilter(MessageType type) {
return configuration -> true;
}
/**
* Creates a file pattern mapping function.
*/
protected abstract Function<G, ImmutableList<CompilerOutput>>
filePatternMapper(MessageType type);
protected class IsNotBlank implements Predicate<G> {
private final Function<G, String> targetExtractor;
public IsNotBlank(Function<G, String> targetExtractor) {
this.targetExtractor = targetExtractor;
}
@Override
public boolean test(G configuration) {
String target = targetExtractor.apply(configuration);
return target != null && !target.trim()
.isEmpty();
}
}
protected class MatchesPattern implements Predicate<G> {
private final FileName protoFileName;
private final Function<G, FilePattern> typeFilterExtractor;
public MatchesPattern(MessageType type, Function<G, FilePattern> typeFilterExtractor) {
checkNotNull(type);
this.protoFileName = type.declaringFileName();
this.typeFilterExtractor = typeFilterExtractor;
}
@Override
public boolean test(G configuration) {
checkNotNull(configuration);
FilePattern pattern = typeFilterExtractor.apply(configuration);
String nameWithExtension = protoFileName.nameWithExtension();
switch (pattern.getValueCase()) {
case FILE_POSTFIX:
return nameWithExtension.endsWith(pattern.getFilePostfix());
case FILE_PREFIX:
return nameWithExtension.startsWith(pattern.getFilePrefix());
case REGEX:
String fullFilePath = protoFileName.value();
return fullFilePath.matches(pattern.getRegex());
case VALUE_NOT_SET:
default:
return false;
}
}
}
}
|
package org.elasticsearch.xpack.search;
import org.apache.lucene.store.AlreadyClosedException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.InternalTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.metrics.InternalMax;
import org.elasticsearch.search.aggregations.metrics.InternalMin;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESIntegTestCase.SuiteScopeTestCase;
import org.elasticsearch.xpack.core.XPackPlugin;
import org.elasticsearch.xpack.core.search.action.AsyncSearchResponse;
import org.elasticsearch.xpack.core.search.action.AsyncStatusResponse;
import org.elasticsearch.xpack.core.search.action.SubmitAsyncSearchRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
@SuiteScopeTestCase
public class AsyncSearchActionIT extends AsyncSearchIntegTestCase {
private static String indexName;
private static int numShards;
private static int numKeywords;
private static Map<String, AtomicInteger> keywordFreqs;
private static float maxMetric = Float.NEGATIVE_INFINITY;
private static float minMetric = Float.POSITIVE_INFINITY;
@Override
public void setupSuiteScopeCluster() throws InterruptedException {
indexName = "test-async";
numShards = randomIntBetween(1, 20);
int numDocs = randomIntBetween(100, 1000);
createIndex(indexName, Settings.builder()
.put("index.number_of_shards", numShards)
.build());
numKeywords = randomIntBetween(1, 100);
keywordFreqs = new HashMap<>();
Set<String> keywordSet = new HashSet<>();
for (int i = 0; i < numKeywords; i++) {
keywordSet.add(randomAlphaOfLengthBetween(10, 20));
}
numKeywords = keywordSet.size();
String[] keywords = keywordSet.toArray(String[]::new);
List<IndexRequestBuilder> reqs = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
float metric = randomFloat();
maxMetric = Math.max(metric, maxMetric);
minMetric = Math.min(metric, minMetric);
String keyword = keywords[randomIntBetween(0, numKeywords-1)];
keywordFreqs.compute(keyword,
(k, v) -> {
if (v == null) {
return new AtomicInteger(1);
}
v.incrementAndGet();
return v;
});
reqs.add(client().prepareIndex(indexName).setSource("terms", keyword, "metric", metric));
}
indexRandom(true, true, reqs);
}
public void testMaxMinAggregation() throws Exception {
int step = numShards > 2 ? randomIntBetween(2, numShards) : 2;
int numFailures = randomBoolean() ? randomIntBetween(0, numShards) : 0;
SearchSourceBuilder source = new SearchSourceBuilder()
.aggregation(AggregationBuilders.min("min").field("metric"))
.aggregation(AggregationBuilders.max("max").field("metric"));
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, source, numFailures, step)) {
AsyncSearchResponse response = it.next();
while (it.hasNext()) {
response = it.next();
assertNotNull(response.getSearchResponse());
if (response.getSearchResponse().getSuccessfulShards() > 0) {
assertNotNull(response.getSearchResponse().getAggregations());
assertNotNull(response.getSearchResponse().getAggregations().get("max"));
assertNotNull(response.getSearchResponse().getAggregations().get("min"));
InternalMax max = response.getSearchResponse().getAggregations().get("max");
InternalMin min = response.getSearchResponse().getAggregations().get("min");
assertThat((float) min.getValue(), greaterThanOrEqualTo(minMetric));
assertThat((float) max.getValue(), lessThanOrEqualTo(maxMetric));
}
}
if (numFailures == numShards) {
assertNotNull(response.getFailure());
} else {
assertNotNull(response.getSearchResponse());
assertNotNull(response.getSearchResponse().getAggregations());
assertNotNull(response.getSearchResponse().getAggregations().get("max"));
assertNotNull(response.getSearchResponse().getAggregations().get("min"));
InternalMax max = response.getSearchResponse().getAggregations().get("max");
InternalMin min = response.getSearchResponse().getAggregations().get("min");
if (numFailures == 0) {
assertThat((float) min.getValue(), equalTo(minMetric));
assertThat((float) max.getValue(), equalTo(maxMetric));
} else {
assertThat((float) min.getValue(), greaterThanOrEqualTo(minMetric));
assertThat((float) max.getValue(), lessThanOrEqualTo(maxMetric));
}
}
deleteAsyncSearch(response.getId());
ensureTaskRemoval(response.getId());
}
}
public void testTermsAggregation() throws Exception {
int step = numShards > 2 ? randomIntBetween(2, numShards) : 2;
int numFailures = randomBoolean() ? randomIntBetween(0, numShards) : 0;
SearchSourceBuilder source = new SearchSourceBuilder()
.aggregation(AggregationBuilders.terms("terms").field("terms.keyword").size(numKeywords));
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, source, numFailures, step)) {
AsyncSearchResponse response = it.next();
while (it.hasNext()) {
response = it.next();
assertNotNull(response.getSearchResponse());
if (response.getSearchResponse().getSuccessfulShards() > 0) {
assertNotNull(response.getSearchResponse().getAggregations());
assertNotNull(response.getSearchResponse().getAggregations().get("terms"));
StringTerms terms = response.getSearchResponse().getAggregations().get("terms");
assertThat(terms.getBuckets().size(), greaterThanOrEqualTo(0));
assertThat(terms.getBuckets().size(), lessThanOrEqualTo(numKeywords));
for (InternalTerms.Bucket<?> bucket : terms.getBuckets()) {
long count = keywordFreqs.getOrDefault(bucket.getKeyAsString(), new AtomicInteger(0)).get();
assertThat(bucket.getDocCount(), lessThanOrEqualTo(count));
}
}
}
if (numFailures == numShards) {
assertNotNull(response.getFailure());
} else {
assertNotNull(response.getSearchResponse());
assertNotNull(response.getSearchResponse().getAggregations());
assertNotNull(response.getSearchResponse().getAggregations().get("terms"));
StringTerms terms = response.getSearchResponse().getAggregations().get("terms");
assertThat(terms.getBuckets().size(), greaterThanOrEqualTo(0));
assertThat(terms.getBuckets().size(), lessThanOrEqualTo(numKeywords));
for (InternalTerms.Bucket<?> bucket : terms.getBuckets()) {
long count = keywordFreqs.getOrDefault(bucket.getKeyAsString(), new AtomicInteger(0)).get();
if (numFailures > 0) {
assertThat(bucket.getDocCount(), lessThanOrEqualTo(count));
} else {
assertThat(bucket.getDocCount(), equalTo(count));
}
}
}
deleteAsyncSearch(response.getId());
ensureTaskRemoval(response.getId());
}
}
public void testRestartAfterCompletion() throws Exception {
final AsyncSearchResponse initial;
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, new SearchSourceBuilder(), 0, 2)) {
initial = it.next();
while (it.hasNext()) {
it.next();
}
}
ensureTaskCompletion(initial.getId());
restartTaskNode(initial.getId(), indexName);
AsyncSearchResponse response = getAsyncSearch(initial.getId());
assertNotNull(response.getSearchResponse());
assertFalse(response.isRunning());
assertFalse(response.isPartial());
AsyncStatusResponse statusResponse = getAsyncStatus(initial.getId());
assertFalse(statusResponse.isRunning());
assertFalse(statusResponse.isPartial());
assertEquals(numShards, statusResponse.getTotalShards());
assertEquals(numShards, statusResponse.getSuccessfulShards());
assertEquals(RestStatus.OK, statusResponse.getCompletionStatus());
deleteAsyncSearch(response.getId());
ensureTaskRemoval(response.getId());
}
public void testDeleteCancelRunningTask() throws Exception {
final AsyncSearchResponse initial;
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, new SearchSourceBuilder(), randomBoolean() ? 1 : 0, 2)) {
initial = it.next();
deleteAsyncSearch(initial.getId());
it.close();
ensureTaskCompletion(initial.getId());
ensureTaskRemoval(initial.getId());
}
}
public void testDeleteCleanupIndex() throws Exception {
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, new SearchSourceBuilder(), randomBoolean() ? 1 : 0, 2)) {
AsyncSearchResponse response = it.next();
deleteAsyncSearch(response.getId());
it.close();
ensureTaskCompletion(response.getId());
ensureTaskRemoval(response.getId());
}
}
public void testCleanupOnFailure() throws Exception {
final AsyncSearchResponse initial;
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, new SearchSourceBuilder(), numShards, 2)) {
initial = it.next();
}
ensureTaskCompletion(initial.getId());
AsyncSearchResponse response = getAsyncSearch(initial.getId());
assertFalse(response.isRunning());
assertNotNull(response.getFailure());
assertTrue(response.isPartial());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getShardFailures().length, equalTo(numShards));
AsyncStatusResponse statusResponse = getAsyncStatus(initial.getId());
assertFalse(statusResponse.isRunning());
assertTrue(statusResponse.isPartial());
assertEquals(numShards, statusResponse.getTotalShards());
assertEquals(0, statusResponse.getSuccessfulShards());
assertEquals(numShards, statusResponse.getFailedShards());
assertThat(statusResponse.getCompletionStatus().getStatus(), greaterThanOrEqualTo(400));
deleteAsyncSearch(initial.getId());
ensureTaskRemoval(initial.getId());
}
public void testInvalidId() throws Exception {
try (SearchResponseIterator it =
assertBlockingIterator(indexName, numShards, new SearchSourceBuilder(), randomBoolean() ? 1 : 0, 2)) {
AsyncSearchResponse response = it.next();
ExecutionException exc = expectThrows(ExecutionException.class, () -> getAsyncSearch("invalid"));
assertThat(exc.getCause(), instanceOf(IllegalArgumentException.class));
assertThat(exc.getMessage(), containsString("invalid id"));
while (it.hasNext()) {
response = it.next();
}
assertFalse(response.isRunning());
}
ExecutionException exc = expectThrows(ExecutionException.class, () -> getAsyncStatus("invalid"));
assertThat(exc.getCause(), instanceOf(IllegalArgumentException.class));
assertThat(exc.getMessage(), containsString("invalid id"));
}
public void testNoIndex() throws Exception {
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest("invalid-*");
request.setWaitForCompletionTimeout(TimeValue.timeValueMillis(1));
AsyncSearchResponse response = submitAsyncSearch(request);
assertNotNull(response.getSearchResponse());
assertFalse(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(0));
request = new SubmitAsyncSearchRequest("invalid");
request.setWaitForCompletionTimeout(TimeValue.timeValueMillis(1));
response = submitAsyncSearch(request);
assertNull(response.getSearchResponse());
assertNotNull(response.getFailure());
assertFalse(response.isRunning());
Exception exc = response.getFailure();
assertThat(exc.getMessage(), containsString("error while executing search"));
assertThat(exc.getCause().getMessage(), containsString("no such index"));
}
public void testCancellation() throws Exception {
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(indexName);
request.getSearchRequest().source(
new SearchSourceBuilder().aggregation(new CancellingAggregationBuilder("test", randomLong()))
);
request.setWaitForCompletionTimeout(TimeValue.timeValueMillis(1));
AsyncSearchResponse response = submitAsyncSearch(request);
assertNotNull(response.getSearchResponse());
assertTrue(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(0));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
response = getAsyncSearch(response.getId());
assertNotNull(response.getSearchResponse());
assertTrue(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(0));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
AsyncStatusResponse statusResponse = getAsyncStatus(response.getId());
assertTrue(statusResponse.isRunning());
assertEquals(numShards, statusResponse.getTotalShards());
assertEquals(0, statusResponse.getSuccessfulShards());
assertEquals(0, statusResponse.getSkippedShards());
assertEquals(0, statusResponse.getFailedShards());
deleteAsyncSearch(response.getId());
ensureTaskRemoval(response.getId());
}
public void testUpdateRunningKeepAlive() throws Exception {
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(indexName);
request.getSearchRequest()
.source(new SearchSourceBuilder().aggregation(new CancellingAggregationBuilder("test", randomLong())));
long now = System.currentTimeMillis();
request.setWaitForCompletionTimeout(TimeValue.timeValueMillis(1));
AsyncSearchResponse response = submitAsyncSearch(request);
assertNotNull(response.getSearchResponse());
assertTrue(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(0));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
assertThat(response.getExpirationTime(), greaterThan(now));
long expirationTime = response.getExpirationTime();
response = getAsyncSearch(response.getId());
assertNotNull(response.getSearchResponse());
assertTrue(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(0));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
response = getAsyncSearch(response.getId(), TimeValue.timeValueDays(6));
assertThat(response.getExpirationTime(), greaterThan(expirationTime));
assertTrue(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(0));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
AsyncStatusResponse statusResponse = getAsyncStatus(response.getId());
assertTrue(statusResponse.isRunning());
assertTrue(statusResponse.isPartial());
assertThat(statusResponse.getExpirationTime(), greaterThan(expirationTime));
assertThat(statusResponse.getStartTime(), lessThan(statusResponse.getExpirationTime()));
assertEquals(numShards, statusResponse.getTotalShards());
assertEquals(0, statusResponse.getSuccessfulShards());
assertEquals(0, statusResponse.getFailedShards());
assertEquals(0, statusResponse.getSkippedShards());
assertEquals(null, statusResponse.getCompletionStatus());
expirationTime = response.getExpirationTime();
response = getAsyncSearch(response.getId(), TimeValue.timeValueMinutes(between(1, 24 * 60)));
assertThat(response.getExpirationTime(), equalTo(expirationTime));
response = getAsyncSearch(response.getId(), TimeValue.timeValueDays(10));
assertThat(response.getExpirationTime(), greaterThan(expirationTime));
deleteAsyncSearch(response.getId());
ensureTaskNotRunning(response.getId());
ensureTaskRemoval(response.getId());
}
public void testUpdateStoreKeepAlive() throws Exception {
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(indexName);
long now = System.currentTimeMillis();
request.setWaitForCompletionTimeout(TimeValue.timeValueMinutes(10));
request.setKeepOnCompletion(true);
AsyncSearchResponse response = submitAsyncSearch(request);
assertNotNull(response.getSearchResponse());
assertFalse(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
assertThat(response.getExpirationTime(), greaterThan(now));
long expirationTime = response.getExpirationTime();
response = getAsyncSearch(response.getId());
assertNotNull(response.getSearchResponse());
assertFalse(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
response = getAsyncSearch(response.getId(), TimeValue.timeValueDays(8));
assertThat(response.getExpirationTime(), greaterThan(expirationTime));
expirationTime = response.getExpirationTime();
assertFalse(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
response = getAsyncSearch(response.getId(), TimeValue.timeValueMillis(1));
assertThat(response.getExpirationTime(), equalTo(expirationTime));
response = getAsyncSearch(response.getId(), TimeValue.timeValueDays(10));
assertThat(response.getExpirationTime(), greaterThan(expirationTime));
deleteAsyncSearch(response.getId());
ensureTaskNotRunning(response.getId());
ensureTaskRemoval(response.getId());
}
public void testRemoveAsyncIndex() throws Exception {
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(indexName);
request.setWaitForCompletionTimeout(TimeValue.timeValueMinutes(10));
request.setKeepOnCompletion(true);
long now = System.currentTimeMillis();
AsyncSearchResponse response = submitAsyncSearch(request);
assertNotNull(response.getSearchResponse());
assertFalse(response.isRunning());
assertThat(response.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getSuccessfulShards(), equalTo(numShards));
assertThat(response.getSearchResponse().getFailedShards(), equalTo(0));
assertThat(response.getExpirationTime(), greaterThan(now));
// remove the async search index
client().admin().indices().prepareDelete(XPackPlugin.ASYNC_RESULTS_INDEX).get();
Exception exc = expectThrows(Exception.class, () -> getAsyncSearch(response.getId()));
Throwable cause = exc instanceof ExecutionException ?
ExceptionsHelper.unwrapCause(exc.getCause()) : ExceptionsHelper.unwrapCause(exc);
assertThat(ExceptionsHelper.status(cause).getStatus(), equalTo(404));
SubmitAsyncSearchRequest newReq = new SubmitAsyncSearchRequest(indexName);
newReq.getSearchRequest().source(
new SearchSourceBuilder().aggregation(new CancellingAggregationBuilder("test", randomLong()))
);
newReq.setWaitForCompletionTimeout(TimeValue.timeValueMillis(1)).setKeepAlive(TimeValue.timeValueSeconds(1));
AsyncSearchResponse newResp = submitAsyncSearch(newReq);
assertNotNull(newResp.getSearchResponse());
assertTrue(newResp.isRunning());
assertThat(newResp.getSearchResponse().getTotalShards(), equalTo(numShards));
assertThat(newResp.getSearchResponse().getSuccessfulShards(), equalTo(0));
assertThat(newResp.getSearchResponse().getFailedShards(), equalTo(0));
// check garbage collection
ensureTaskNotRunning(newResp.getId());
ensureTaskRemoval(newResp.getId());
}
public void testSearchPhaseFailure() throws Exception {
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(indexName);
request.setKeepOnCompletion(true);
request.setWaitForCompletionTimeout(TimeValue.timeValueMinutes(10));
request.getSearchRequest().allowPartialSearchResults(false);
request.getSearchRequest()
.source(new SearchSourceBuilder().query(new ThrowingQueryBuilder(randomLong(), new AlreadyClosedException("boom"), 0)));
AsyncSearchResponse response = submitAsyncSearch(request);
assertFalse(response.isRunning());
assertTrue(response.isPartial());
assertThat(response.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
assertNotNull(response.getFailure());
ensureTaskNotRunning(response.getId());
}
}
|
package game.view;
import game.control.packets.Packet01Disconnect;
import game.logic.StealthGame;
import gameworld.TestPush;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class StartUpScreen extends JPanel {
public static boolean LOCAL = true;
private final int WIDTH = 680;
private final int HEIGHT = 420;
private final int BTN_WIDTH = 250;
private final int BTN_HEIGHT = 80;
private GuiButton joinBtn;
private GuiButton hostBtn;
private GuiButton[] buttons = new GuiButton[2];
private JFrame frame;
public StartUpScreen() {
setLayout(new BorderLayout());
frame = new JFrame();
// setup btn
joinBtn = new GuiButton("Join", BTN_WIDTH, BTN_HEIGHT);
hostBtn = new GuiButton("Host", BTN_WIDTH, BTN_HEIGHT);
buttons[0] = joinBtn;
buttons[1] = hostBtn;
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case 72:
host();
break;
case 74:
join();
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
});
// add mouse listener
frame.addMouseListener(new MouseListener());
frame.addMouseMotionListener(new MouseMotionListener());
// add(start, BorderLayout.CENTER);
// add buttons
joinBtn.setPos((WIDTH / 2) - (BTN_WIDTH / 2), HEIGHT - BTN_HEIGHT - 60);
hostBtn.setPos((WIDTH / 2) - (BTN_WIDTH / 2), HEIGHT - BTN_HEIGHT * 2
- 80);
frame.setSize(WIDTH, HEIGHT);
frame.add(this);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.pack();
frame.repaint();
}
public void paintComponent(Graphics g) {
java.net.URL imageURL = getClass().getResource("StealthTitle.png");
BufferedImage image = null;
try {
image = ImageIO.read(imageURL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
g.drawImage(image, 0, 0, null);
joinBtn.draw(g);
hostBtn.draw(g);
}
private String[] showLoginWindowClient() {
JTextField username = new JTextField();
JTextField ip = new JTextField();
Object[] message = { "Username:", username, "IP:", ip };
int option = JOptionPane.showConfirmDialog(null, message, "Login",
JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
return new String[] { username.getText(), ip.getText() };
} else {
System.out.println("Login canceled");
}
return null;
}
private String[] showLoginWindowHost() {
JTextField username = new JTextField();
Object[] message = { "Username:", username};
int option = JOptionPane.showConfirmDialog(null, message, "Login",
JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
return new String[] { username.getText()};
} else {
System.out.println("Login canceled");
}
return null;
}
private void join() {
String[] login = showLoginWindowClient();
if(login==null){
return;
}
// TestPush client = new TestPush(false, login[0], login[1]);
StealthGame game = new StealthGame(false, login[0], login[1]);
game.start();
// new MainFrame();
frame.dispose();
}
private void host() {
String[] login = showLoginWindowHost();
if(login==null){
return;
}
login[1] = (login[1] == null) ? "localhost" : login[1];
StealthGame game = new StealthGame(true, login[0], login[1]);
game.start();
// TestPush host = new TestPush(true, login[0], login[1]);
frame.dispose();
}
public static void main(String args[]) {
new StartUpScreen();
}
private class MouseListener implements java.awt.event.MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
for (int i = 0; i < buttons.length; i++) {
if (buttons[i].isHovered()) {
switch (buttons[i].getName()) {
case "Join":
join();
break;
case "Host":
host();
break;
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
private class MouseMotionListener implements
java.awt.event.MouseMotionListener {
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
for (int i = 0; i < buttons.length; i++) {
buttons[i].checkHovered(e.getX(), e.getY());
}
frame.repaint();
}
}
}
|
package com.example.georgekaraolanis.project10_inventoryapp;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.LoaderManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.georgekaraolanis.project10_inventoryapp.data.InventoryContract;
import com.example.georgekaraolanis.project10_inventoryapp.data.InventoryContract.InventoryEntry;
public class DetailActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor>{
/*Loader id*/
private static final int INVENTORY_LOADER = 1;
/*Current item*/
Uri currentUri;
/*Views in layout*/
ImageView itemImageView;
TextView itemNameTextView;
TextView itemQuantityTextView;
TextView itemPriceTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
/*Get intent data*/
Intent intent = getIntent();
currentUri = intent.getData();
getLoaderManager().initLoader(INVENTORY_LOADER, null, this);
/*references to views*/
itemImageView = (ImageView) findViewById(R.id.item_image);
itemNameTextView = (TextView) findViewById(R.id.item_name);
itemQuantityTextView = (TextView) findViewById(R.id.item_quantity);
itemPriceTextView = (TextView) findViewById(R.id.item_price);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// Since the editor shows all pet attributes, define a projection that contains
// all columns from the pet table
String[] projection = {
InventoryEntry._ID,
InventoryEntry.COLUMN_ITEM_NAME,
InventoryEntry.COLUMN_ITEM_QUANTITY,
InventoryEntry.COLUMN_ITEM_PRICE,
InventoryEntry.COLUMN_ITEM_IMAGE };
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
currentUri, // Query the content URI for the current pet
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Bail early if the cursor is null or there is less than 1 row in the cursor
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_NAME);
int quantityColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_QUANTITY);
int priceColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_PRICE);
int imageColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_IMAGE);
// Extract out the value from the Cursor for the given column index
String name = cursor.getString(nameColumnIndex);
Integer quantity = cursor.getInt(quantityColumnIndex);
Float price = cursor.getFloat(priceColumnIndex);
// Update the views on the screen with the values from the database
itemNameTextView.setText(name);
itemQuantityTextView.setText(quantity.toString());
itemPriceTextView.setText(price.toString());
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// If the loader is invalidated, clear out all the data from the input fields.
}
}
|
package net.jhorstmann.propertychangesupport;
import net.jhorstmann.propertychangesupport.api.PropertyChangeEventSource;
import java.beans.Introspector;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.*;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;
public class PropertyChangeSupportAdapter extends ClassAdapter {
private String classname;
private String propertyChangeSupportField;
private boolean hasSupport;
public PropertyChangeSupportAdapter(ClassVisitor cv) {
super(cv);
this.propertyChangeSupportField = "_propertyChangeSupport";
}
@Override
public void visit(final int version, final int access, final String classname, final String signature, final String superName, final String[] interfaces) {
Set<String> newinterfaces = new HashSet<String>(Arrays.asList(interfaces));
newinterfaces.add(PropertyChangeEventSource.class.getName().replace('.', '/'));
super.visit(version, access, classname, signature, superName, newinterfaces.toArray(new String[newinterfaces.size()]));
this.classname = classname;
}
@Override
public void visitEnd() {
if (!hasSupport) {
super.visitField(ACC_PRIVATE | ACC_FINAL | ACC_SYNTHETIC, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;", null, null);
{
MethodVisitor mv = super.visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, "addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, classname, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;");
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/beans/PropertyChangeSupport", "addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V");
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}
{
MethodVisitor mv = super.visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, "removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, classname, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;");
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/beans/PropertyChangeSupport", "removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V");
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}
{
MethodVisitor mv = super.visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, "addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, classname, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;");
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 2);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/beans/PropertyChangeSupport", "addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V");
mv.visitInsn(RETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
}
{
MethodVisitor mv = super.visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, "removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, classname, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;");
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 2);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/beans/PropertyChangeSupport", "removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V");
mv.visitInsn(RETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
}
}
}
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
if (name.equals("<init>")) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new AdviceAdapter(mv, access, name, desc) {
@Override
public void onMethodEnter() {
visitVarInsn(ALOAD, 0);
visitTypeInsn(NEW, "java/beans/PropertyChangeSupport");
visitInsn(DUP);
visitVarInsn(ALOAD, 0);
visitMethodInsn(INVOKESPECIAL, "java/beans/PropertyChangeSupport", "<init>", "(Ljava/lang/Object;)V");
visitFieldInsn(PUTFIELD, classname, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;");
}
@Override
public void visitMaxs(int maxStack, int maxLocals) {
super.visitMaxs(Math.max(maxStack, 4), maxLocals);
}
};
} else if (ASMHelper.isPublicSetter(access, name, desc)) {
final String propertyName = Introspector.decapitalize(name.substring(3));
final String getter = "get" + name.substring(3);
final Type type = Type.getArgumentTypes(desc)[0];
final String arg = type.getDescriptor();
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new AdviceAdapter(mv, access, name, desc) {
private int oldValue;
@Override
public void onMethodEnter() {
oldValue = super.newLocal(type);
loadThis();
visitMethodInsn(INVOKEVIRTUAL, classname, getter, "()" + arg);
storeLocal(oldValue, type);
}
@Override
public void onMethodExit(int opcode) {
loadThis();
visitFieldInsn(GETFIELD, classname, propertyChangeSupportField, "Ljava/beans/PropertyChangeSupport;");
// Stack: _propertyChangeSupport
visitLdcInsn(propertyName);
// Stack: _propertyChangeSupport, propertyName
loadLocal(oldValue, type);
ASMHelper.generateAutoBoxIfNeccessary(this, arg);
// Stack: _propertyChangeSupport, propertyName, oldValue
visitVarInsn(type.getOpcode(ILOAD), 1);
ASMHelper.generateAutoBoxIfNeccessary(this, arg);
// Stack: _propertyChangeSupport, propertyName, oldValue, newValue
visitMethodInsn(INVOKEVIRTUAL, "java/beans/PropertyChangeSupport", "firePropertyChange", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V");
}
@Override
public void visitMaxs(int maxStack, int maxLocals) {
super.visitMaxs(Math.max(maxStack, 4), Math.max(maxLocals, 3));
}
};
} else {
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
}
|
package eu.bcvsolutions.idm.acc.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.ImmutableList;
import eu.bcvsolutions.idm.acc.domain.ReconciliationMissingAccountActionType;
import eu.bcvsolutions.idm.acc.domain.SynchronizationActionType;
import eu.bcvsolutions.idm.acc.domain.SynchronizationLinkedActionType;
import eu.bcvsolutions.idm.acc.domain.SynchronizationMissingEntityActionType;
import eu.bcvsolutions.idm.acc.domain.SynchronizationUnlinkedActionType;
import eu.bcvsolutions.idm.acc.domain.SystemEntityType;
import eu.bcvsolutions.idm.acc.domain.SystemOperationType;
import eu.bcvsolutions.idm.acc.dto.filter.SchemaAttributeFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SyncActionLogFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SyncItemLogFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SynchronizationConfigFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SynchronizationLogFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SystemAttributeMappingFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SystemMappingFilter;
import eu.bcvsolutions.idm.acc.entity.SysSchemaAttribute;
import eu.bcvsolutions.idm.acc.entity.SysSchemaObjectClass;
import eu.bcvsolutions.idm.acc.entity.SysSyncActionLog;
import eu.bcvsolutions.idm.acc.entity.SysSyncConfig;
import eu.bcvsolutions.idm.acc.entity.SysSyncItemLog;
import eu.bcvsolutions.idm.acc.entity.SysSyncLog;
import eu.bcvsolutions.idm.acc.entity.SysSystem;
import eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping;
import eu.bcvsolutions.idm.acc.entity.SysSystemMapping;
import eu.bcvsolutions.idm.acc.entity.TestTreeResource;
import eu.bcvsolutions.idm.acc.exception.ProvisioningException;
import eu.bcvsolutions.idm.acc.service.api.SynchronizationService;
import eu.bcvsolutions.idm.acc.service.api.SysSchemaAttributeService;
import eu.bcvsolutions.idm.acc.service.api.SysSyncActionLogService;
import eu.bcvsolutions.idm.acc.service.api.SysSyncConfigService;
import eu.bcvsolutions.idm.acc.service.api.SysSyncItemLogService;
import eu.bcvsolutions.idm.acc.service.api.SysSyncLogService;
import eu.bcvsolutions.idm.acc.service.api.SysSystemAttributeMappingService;
import eu.bcvsolutions.idm.acc.service.api.SysSystemMappingService;
import eu.bcvsolutions.idm.acc.service.api.SysSystemService;
import eu.bcvsolutions.idm.acc.service.impl.DefaultSynchronizationService;
import eu.bcvsolutions.idm.core.api.dto.filter.TreeNodeFilter;
import eu.bcvsolutions.idm.core.eav.entity.AbstractFormValue;
import eu.bcvsolutions.idm.core.eav.entity.IdmFormDefinition;
import eu.bcvsolutions.idm.core.eav.service.api.FormService;
import eu.bcvsolutions.idm.core.exception.TreeNodeException;
import eu.bcvsolutions.idm.core.model.entity.IdmTreeNode;
import eu.bcvsolutions.idm.core.model.entity.IdmTreeType;
import eu.bcvsolutions.idm.core.model.service.api.IdmTreeNodeService;
import eu.bcvsolutions.idm.core.model.service.api.IdmTreeTypeService;
import eu.bcvsolutions.idm.test.api.AbstractIntegrationTest;
/**
* Tree synchronization tests
*
* @author Svanda
*
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Rollback(false)
@Service
public class DefaultTreeSynchronizationServiceTest extends AbstractIntegrationTest {
private static final String SYNC_CONFIG_NAME = "syncConfigName";
private static final String SYSTEM_NAME = "systemTreeName";
private static final String TREE_TYPE_TEST = "TREE_TEST";
private static final String NODE_NAME = "name";
private static final String ATTRIBUTE_NAME = "__NAME__";
private static final String CHANGED = "changed";
@Autowired
private ApplicationContext context;
@Autowired
private SysSystemService systemService;
@Autowired
private SysSystemMappingService systemMappingService;
@Autowired
private SysSystemAttributeMappingService schemaAttributeMappingService;
@Autowired
private SysSchemaAttributeService schemaAttributeService;
@Autowired
private SysSyncConfigService syncConfigService;
@Autowired
private SysSyncLogService syncLogService;
@Autowired
private SysSyncItemLogService syncItemLogService;
@Autowired
private SysSyncActionLogService syncActionLogService;
@Autowired
private EntityManager entityManager;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private IdmTreeTypeService treeTypeService;
@Autowired
private IdmTreeNodeService treeNodeService;
@Autowired
private FormService formService;
@Autowired
DataSource dataSource;
// Only for call method createTestSystem
@Autowired
private DefaultSysAccountManagementServiceTest defaultSysAccountManagementServiceTest;
private SysSystem system;
private SynchronizationService synchornizationService;
@Before
public void init() {
loginAsAdmin("admin");
synchornizationService = context.getAutowireCapableBeanFactory().createBean(DefaultSynchronizationService.class);
}
@After
public void logout() {
super.logout();
}
@Test
@Transactional
public void doCreateSyncConfig() {
initData();
SystemMappingFilter mappingFilter = new SystemMappingFilter();
mappingFilter.setEntityType(SystemEntityType.TREE);
mappingFilter.setSystemId(system.getId());
mappingFilter.setOperationType(SystemOperationType.SYNCHRONIZATION);
List<SysSystemMapping> mappings = systemMappingService.find(mappingFilter, null).getContent();
Assert.assertEquals(1, mappings.size());
SysSystemMapping mapping = mappings.get(0);
SystemAttributeMappingFilter attributeMappingFilter = new SystemAttributeMappingFilter();
attributeMappingFilter.setSystemMappingId(mapping.getId());
List<SysSystemAttributeMapping> attributes = schemaAttributeMappingService.find(attributeMappingFilter, null)
.getContent();
SysSystemAttributeMapping uidAttribute = attributes.stream().filter(attribute -> {
return attribute.isUid();
}).findFirst().get();
// Create default synchronization config
SysSyncConfig syncConfigCustom = new SysSyncConfig();
syncConfigCustom.setReconciliation(true);
syncConfigCustom.setCustomFilter(true);
syncConfigCustom.setSystemMapping(mapping);
syncConfigCustom.setCorrelationAttribute(uidAttribute);
syncConfigCustom.setReconciliation(true);
syncConfigCustom.setName(SYNC_CONFIG_NAME);
syncConfigCustom.setLinkedAction(SynchronizationLinkedActionType.IGNORE);
syncConfigCustom.setUnlinkedAction(SynchronizationUnlinkedActionType.IGNORE);
syncConfigCustom.setMissingEntityAction(SynchronizationMissingEntityActionType.CREATE_ENTITY);
syncConfigCustom.setMissingAccountAction(ReconciliationMissingAccountActionType.IGNORE);
syncConfigService.save(syncConfigCustom);
SynchronizationConfigFilter configFilter = new SynchronizationConfigFilter();
configFilter.setSystemId(system.getId());
Assert.assertEquals(1, syncConfigService.find(configFilter, null).getTotalElements());
}
@Test
public void doStartSyncA_MissingEntity() {
SynchronizationConfigFilter configFilter = new SynchronizationConfigFilter();
configFilter.setName(SYNC_CONFIG_NAME);
List<SysSyncConfig> syncConfigs = syncConfigService.find(configFilter, null).getContent();
Assert.assertEquals(1, syncConfigs.size());
SysSyncConfig syncConfigCustom = syncConfigs.get(0);
Assert.assertFalse(syncConfigService.isRunning(syncConfigCustom));
synchornizationService.setSynchronizationConfigId(syncConfigCustom.getId());
synchornizationService.process();
SynchronizationLogFilter logFilter = new SynchronizationLogFilter();
logFilter.setSynchronizationConfigId(syncConfigCustom.getId());
List<SysSyncLog> logs = syncLogService.find(logFilter, null).getContent();
Assert.assertEquals(1, logs.size());
SysSyncLog log = logs.get(0);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
SyncActionLogFilter actionLogFilter = new SyncActionLogFilter();
actionLogFilter.setSynchronizationLogId(log.getId());
List<SysSyncActionLog> actions = syncActionLogService.find(actionLogFilter, null).getContent();
Assert.assertEquals(1, actions.size());
SysSyncActionLog createEntityActionLog = actions.stream().filter(action -> {
return SynchronizationActionType.CREATE_ENTITY == action.getSyncAction();
}).findFirst().get();
SyncItemLogFilter itemLogFilter = new SyncItemLogFilter();
itemLogFilter.setSyncActionLogId(createEntityActionLog.getId());
List<SysSyncItemLog> items = syncItemLogService.find(itemLogFilter, null).getContent();
Assert.assertEquals(6, items.size());
IdmTreeType treeType = treeTypeService.find(null).getContent().stream().filter(tree -> {
return tree.getName().equals(TREE_TYPE_TEST);
}).findFirst().get();
Assert.assertEquals(1, treeNodeService.findRoots(treeType.getId(), null).getContent().size());
// Delete log
syncLogService.delete(log);
}
@Test
public void doStartSyncB_Linked_doEntityUpdate() {
SynchronizationConfigFilter configFilter = new SynchronizationConfigFilter();
configFilter.setName(SYNC_CONFIG_NAME);
List<SysSyncConfig> syncConfigs = syncConfigService.find(configFilter, null).getContent();
//Change node code to changed
this.getBean().changeOne();
Assert.assertEquals(1, syncConfigs.size());
SysSyncConfig syncConfigCustom = syncConfigs.get(0);
Assert.assertFalse(syncConfigService.isRunning(syncConfigCustom));
// Set sync config
syncConfigCustom.setLinkedAction(SynchronizationLinkedActionType.UPDATE_ENTITY);
syncConfigCustom.setUnlinkedAction(SynchronizationUnlinkedActionType.IGNORE);
syncConfigCustom.setMissingEntityAction(SynchronizationMissingEntityActionType.IGNORE);
syncConfigCustom.setMissingAccountAction(ReconciliationMissingAccountActionType.IGNORE);
syncConfigService.save(syncConfigCustom);
// Check state before sync
TreeNodeFilter nodeFilter = new TreeNodeFilter();
nodeFilter.setProperty(NODE_NAME);
nodeFilter.setValue("111");
IdmTreeNode treeNode = treeNodeService.find(nodeFilter, null).getContent().get(0);
Assert.assertEquals("111", treeNode.getCode());
synchornizationService.setSynchronizationConfigId(syncConfigCustom.getId());
synchornizationService.process();
SynchronizationLogFilter logFilter = new SynchronizationLogFilter();
logFilter.setSynchronizationConfigId(syncConfigCustom.getId());
List<SysSyncLog> logs = syncLogService.find(logFilter, null).getContent();
Assert.assertEquals(1, logs.size());
SysSyncLog log = logs.get(0);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
SyncActionLogFilter actionLogFilter = new SyncActionLogFilter();
actionLogFilter.setSynchronizationLogId(log.getId());
List<SysSyncActionLog> actions = syncActionLogService.find(actionLogFilter, null).getContent();
Assert.assertEquals(1, actions.size());
SysSyncActionLog actionLog = actions.stream().filter(action -> {
return SynchronizationActionType.UPDATE_ENTITY == action.getSyncAction();
}).findFirst().get();
SyncItemLogFilter itemLogFilter = new SyncItemLogFilter();
itemLogFilter.setSyncActionLogId(actionLog.getId());
List<SysSyncItemLog> items = syncItemLogService.find(itemLogFilter, null).getContent();
Assert.assertEquals(6, items.size());
// Check state after sync
treeNode = treeNodeService.get(treeNode.getId());
Assert.assertEquals(CHANGED, treeNode.getCode());
// Delete log
syncLogService.delete(log);
}
@Test
public void doStartSyncB_MissingAccount_DeleteEntity() {
SynchronizationConfigFilter configFilter = new SynchronizationConfigFilter();
configFilter.setName(SYNC_CONFIG_NAME);
List<SysSyncConfig> syncConfigs = syncConfigService.find(configFilter, null).getContent();
//Remove node code to changed
this.getBean().removeOne();
Assert.assertEquals(1, syncConfigs.size());
SysSyncConfig syncConfigCustom = syncConfigs.get(0);
Assert.assertFalse(syncConfigService.isRunning(syncConfigCustom));
// Set sync config
syncConfigCustom.setLinkedAction(SynchronizationLinkedActionType.IGNORE);
syncConfigCustom.setUnlinkedAction(SynchronizationUnlinkedActionType.IGNORE);
syncConfigCustom.setMissingEntityAction(SynchronizationMissingEntityActionType.IGNORE);
syncConfigCustom.setMissingAccountAction(ReconciliationMissingAccountActionType.DELETE_ENTITY);
syncConfigService.save(syncConfigCustom);
// Check state before sync
TreeNodeFilter nodeFilter = new TreeNodeFilter();
nodeFilter.setProperty(NODE_NAME);
nodeFilter.setValue("111");
IdmTreeNode treeNode = treeNodeService.find(nodeFilter, null).getContent().get(0);
Assert.assertNotNull(treeNode.getCode());
synchornizationService.setSynchronizationConfigId(syncConfigCustom.getId());
synchornizationService.process();
SynchronizationLogFilter logFilter = new SynchronizationLogFilter();
logFilter.setSynchronizationConfigId(syncConfigCustom.getId());
List<SysSyncLog> logs = syncLogService.find(logFilter, null).getContent();
Assert.assertEquals(1, logs.size());
SysSyncLog log = logs.get(0);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
SyncActionLogFilter actionLogFilter = new SyncActionLogFilter();
actionLogFilter.setSynchronizationLogId(log.getId());
List<SysSyncActionLog> actions = syncActionLogService.find(actionLogFilter, null).getContent();
Assert.assertEquals(3, actions.size());
SysSyncActionLog actionLog = actions.stream().filter(action -> {
return SynchronizationActionType.DELETE_ENTITY == action.getSyncAction();
}).findFirst().get();
SyncItemLogFilter itemLogFilter = new SyncItemLogFilter();
itemLogFilter.setSyncActionLogId(actionLog.getId());
List<SysSyncItemLog> items = syncItemLogService.find(itemLogFilter, null).getContent();
Assert.assertEquals(1, items.size());
// Check state after sync
treeNode = treeNodeService.get(treeNode.getId());
Assert.assertNull(treeNode);
// Delete log
syncLogService.delete(log);
}
@Test
public void doStartSyncC_MissingEntity() {
SynchronizationConfigFilter configFilter = new SynchronizationConfigFilter();
configFilter.setName(SYNC_CONFIG_NAME);
List<SysSyncConfig> syncConfigs = syncConfigService.find(configFilter, null).getContent();
Assert.assertEquals(1, syncConfigs.size());
SysSyncConfig syncConfigCustom = syncConfigs.get(0);
Assert.assertFalse(syncConfigService.isRunning(syncConfigCustom));
syncConfigCustom.setRootsFilterScript("if(account){ def parentValue = account.getAttributeByName(\"PARENT\").getValue();"
+ " def uidValue = account.getAttributeByName(\"__NAME__\").getValue();"
+ " if(parentValue != null && parentValue.equals(uidValue)){"
+ " account.getAttributeByName(\"PARENT\").setValues(null); return Boolean.TRUE;}}"
+ " \nreturn Boolean.FALSE;");
// Set sync config
syncConfigCustom.setLinkedAction(SynchronizationLinkedActionType.IGNORE);
syncConfigCustom.setUnlinkedAction(SynchronizationUnlinkedActionType.IGNORE);
syncConfigCustom.setMissingEntityAction(SynchronizationMissingEntityActionType.CREATE_ENTITY);
syncConfigCustom.setMissingAccountAction(ReconciliationMissingAccountActionType.IGNORE);
syncConfigService.save(syncConfigCustom);
synchornizationService.setSynchronizationConfigId(syncConfigCustom.getId());
synchornizationService.process();
SynchronizationLogFilter logFilter = new SynchronizationLogFilter();
logFilter.setSynchronizationConfigId(syncConfigCustom.getId());
List<SysSyncLog> logs = syncLogService.find(logFilter, null).getContent();
Assert.assertEquals(1, logs.size());
SysSyncLog log = logs.get(0);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
SyncActionLogFilter actionLogFilter = new SyncActionLogFilter();
actionLogFilter.setSynchronizationLogId(log.getId());
List<SysSyncActionLog> actions = syncActionLogService.find(actionLogFilter, null).getContent();
Assert.assertEquals(2, actions.size());
SysSyncActionLog createEntityActionLog = actions.stream().filter(action -> {
return SynchronizationActionType.CREATE_ENTITY == action.getSyncAction();
}).findFirst().get();
SyncItemLogFilter itemLogFilter = new SyncItemLogFilter();
itemLogFilter.setSyncActionLogId(createEntityActionLog.getId());
List<SysSyncItemLog> items = syncItemLogService.find(itemLogFilter, null).getContent();
Assert.assertEquals(6, items.size());
IdmTreeType treeType = treeTypeService.find(null).getContent().stream().filter(tree -> {
return tree.getName().equals(TREE_TYPE_TEST);
}).findFirst().get();
Assert.assertEquals(2, treeNodeService.findRoots(treeType.getId(), null).getContent().size());
// Delete log
syncLogService.delete(log);
}
@Test
@Transactional
public void provisioningA_CreateAccount_withOutMapping() {
// Delete all resource data
this.deleteAllResourceData();
IdmTreeType treeType = treeTypeService.find(null).getContent().stream().filter(tree -> {
return tree.getName().equals(TREE_TYPE_TEST);
}).findFirst().get();
// Create root node in IDM tree
IdmTreeNode nodeRoot = new IdmTreeNode();
nodeRoot.setCode("P1");
nodeRoot.setName(nodeRoot.getCode());
nodeRoot.setParent(null);
nodeRoot.setTreeType(treeType);
nodeRoot = treeNodeService.save(nodeRoot);
// Create node in IDM tree
IdmTreeNode nodeOne = new IdmTreeNode();
nodeOne.setCode("P12");
nodeOne.setName(nodeOne.getCode());
nodeOne.setParent(nodeRoot);
nodeOne.setTreeType(treeType);
nodeOne = treeNodeService.save(nodeOne);
// Check state before provisioning
TestTreeResource one = entityManager.find(TestTreeResource.class, "P12");
Assert.assertNull(one);
}
@Test(expected = ProvisioningException.class) // Provisioning tree in incorrect order
public void provisioningB_CreateAccounts_withException() {
TreeNodeFilter filter = new TreeNodeFilter();
filter.setProperty(NODE_NAME);
filter.setValue("P1");
IdmTreeNode nodeRoot = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeRoot);
filter.setValue("P12");
IdmTreeNode nodeOne = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeOne);
// Check state before provisioning
TestTreeResource one = entityManager.find(TestTreeResource.class, "P12");
Assert.assertNull(one);
// Create mapping for provisioning
this.createProvisionigMapping();
// Save IDM node (must invoke provisioning)
// We didn't provisioning for root first ... expect throw exception
treeNodeService.save(nodeOne);
}
@Test
@Transactional
public void provisioningC_CreateAccounts_correct() {
TreeNodeFilter filter = new TreeNodeFilter();
filter.setProperty(NODE_NAME);
filter.setValue("P1");
IdmTreeNode nodeRoot = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeRoot);
filter.setValue("P12");
IdmTreeNode nodeOne = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeOne);
// Check state before provisioning
TestTreeResource one = entityManager.find(TestTreeResource.class, "P12");
Assert.assertNull(one);
TestTreeResource root = entityManager.find(TestTreeResource.class, "P1");
Assert.assertNull(root);
// Save IDM node again (must invoke provisioning)
// Root first
treeNodeService.save(nodeRoot);
// Node next
treeNodeService.save(nodeOne);
// Check state before provisioning
root = entityManager.find(TestTreeResource.class, "P1");
Assert.assertNotNull(root);
one = entityManager.find(TestTreeResource.class, "P12");
Assert.assertNotNull(one);
}
@Test
public void provisioningD_UpdateAccount() {
TreeNodeFilter filter = new TreeNodeFilter();
filter.setProperty(NODE_NAME);
filter.setValue("P1");
IdmTreeNode nodeRoot = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeRoot);
filter.setValue("P12");
IdmTreeNode nodeOne = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeOne);
// Check state before provisioning
TestTreeResource one = entityManager.find(TestTreeResource.class, "P12");
Assert.assertNotNull(one);
Assert.assertEquals("P12", one.getCode());
nodeOne.setCode(CHANGED);
// Save IDM changed node (must invoke provisioning)
treeNodeService.save(nodeOne);
// Check state before provisioning
one = entityManager.find(TestTreeResource.class, "P12");
Assert.assertNotNull(one);
Assert.assertEquals(CHANGED, one.getCode());
}
@Test(expected=TreeNodeException.class)
public void provisioningE_DeleteAccount_IntegrityException() {
TreeNodeFilter filter = new TreeNodeFilter();
filter.setProperty(NODE_NAME);
filter.setValue("P1");
IdmTreeNode nodeRoot = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeRoot);
// Delete IDM node (must invoke provisioning) .. We delete node with some children ... must throw integrity exception
// Generally we counts with provisioning on every node ... include children (Recursively delete is not good idea!)
treeNodeService.delete(nodeRoot);
}
@Test
public void provisioningF_DeleteAccount() {
TreeNodeFilter filter = new TreeNodeFilter();
filter.setProperty(NODE_NAME);
filter.setValue("P12");
IdmTreeNode nodeOne = treeNodeService.find(filter, null).getContent().get(0);
Assert.assertNotNull(nodeOne);
// Delete IDM node (must invoke provisioning) .. We delete child
treeNodeService.delete(nodeOne);
Assert.assertTrue(treeNodeService.find(filter, null).getContent().isEmpty());
}
@Transactional
public void deleteAllResourceData() {
// Delete all
Query q = entityManager.createNativeQuery("DELETE FROM test_tree_resource");
q.executeUpdate();
}
private void createProvisionigMapping() {
SynchronizationConfigFilter configFilter = new SynchronizationConfigFilter();
configFilter.setName(SYNC_CONFIG_NAME);
List<SysSyncConfig> syncConfigs = syncConfigService.find(configFilter, null).getContent();
Assert.assertEquals(1, syncConfigs.size());
SysSyncConfig syncConfigCustom = syncConfigs.get(0);
SysSystemMapping systemMappingSync = syncConfigCustom.getSystemMapping();
// Create provisioning mapping
SysSystemMapping systemMapping = new SysSystemMapping();
systemMapping.setName("default_" + System.currentTimeMillis());
systemMapping.setEntityType(SystemEntityType.TREE);
systemMapping.setTreeType(systemMappingSync.getTreeType());
systemMapping.setOperationType(SystemOperationType.PROVISIONING);
systemMapping.setObjectClass(systemMappingSync.getObjectClass());
final SysSystemMapping syncMapping = systemMappingService.save(systemMapping);
createMapping(systemMappingSync.getSystem(), syncMapping);
}
private void initData() {
// create test system
system = defaultSysAccountManagementServiceTest.createTestSystem("test_tree_resource");
system.setName(SYSTEM_NAME);
system = systemService.save(system);
// key to EAV
IdmFormDefinition savedFormDefinition = systemService.getConnectorFormDefinition(system.getConnectorInstance());
List<AbstractFormValue<SysSystem>> values = formService.getValues(system, savedFormDefinition);
AbstractFormValue<SysSystem> changeLogColumn = values.stream().filter(value -> {return "keyColumn".equals(value.getFormAttribute().getCode());}).findFirst().get();
formService.saveValues(system, changeLogColumn.getFormAttribute(), ImmutableList.of("ID"));
// generate schema for system
List<SysSchemaObjectClass> objectClasses = systemService.generateSchema(system);
IdmTreeType treeType = new IdmTreeType();
treeType.setCode(TREE_TYPE_TEST);
treeType.setDefaultTreeType(false);
treeType.setName(TREE_TYPE_TEST);
treeType = treeTypeService.save(treeType);
// Create synchronization mapping
SysSystemMapping syncSystemMapping = new SysSystemMapping();
syncSystemMapping.setName("default_" + System.currentTimeMillis());
syncSystemMapping.setEntityType(SystemEntityType.TREE);
syncSystemMapping.setTreeType(treeType);
syncSystemMapping.setOperationType(SystemOperationType.SYNCHRONIZATION);
syncSystemMapping.setObjectClass(objectClasses.get(0));
final SysSystemMapping syncMapping = systemMappingService.save(syncSystemMapping);
createMapping(system, syncMapping);
initTreeData();
syncConfigService.find(null).getContent().forEach(config -> {
syncConfigService.delete(config);
});
}
private void initTreeData(){
deleteAllResourceData();
entityManager.persist(this.createNode("1", null));
entityManager.persist(this.createNode("2", "2"));
entityManager.persist(this.createNode("11", "1"));
entityManager.persist(this.createNode("12", "1"));
entityManager.persist(this.createNode("111", "11"));
entityManager.persist(this.createNode("112", "11"));
entityManager.persist(this.createNode("1111", "111"));
entityManager.persist(this.createNode("21", "2"));
entityManager.persist(this.createNode("22", "2"));
entityManager.persist(this.createNode("211", "21"));
entityManager.persist(this.createNode("212", "21"));
entityManager.persist(this.createNode("2111", "211"));
}
private TestTreeResource createNode(String code, String parent){
TestTreeResource node = new TestTreeResource();
node.setCode(code);
node.setName(code);
node.setParent(parent);
node.setId(code);
return node;
}
@Transactional
public void changeOne(){
TestTreeResource one = entityManager.find(TestTreeResource.class, "111");
one.setCode(CHANGED);
entityManager.persist(one);
}
@Transactional
public void removeOne(){
TestTreeResource one = entityManager.find(TestTreeResource.class, "111");
entityManager.remove(one);
}
private void createMapping(SysSystem system, final SysSystemMapping entityHandlingResult) {
SchemaAttributeFilter schemaAttributeFilter = new SchemaAttributeFilter();
schemaAttributeFilter.setSystemId(system.getId());
Page<SysSchemaAttribute> schemaAttributesPage = schemaAttributeService.find(schemaAttributeFilter, null);
schemaAttributesPage.forEach(schemaAttr -> {
if (ATTRIBUTE_NAME.equals(schemaAttr.getName())) {
SysSystemAttributeMapping attributeHandlingName = new SysSystemAttributeMapping();
attributeHandlingName.setUid(true);
attributeHandlingName.setEntityAttribute(false);
attributeHandlingName.setName(schemaAttr.getName());
attributeHandlingName.setSchemaAttribute(schemaAttr);
// For provisioning .. we need create UID
attributeHandlingName.setTransformToResourceScript("if(uid){return uid;}\nreturn entity.getCode();");
attributeHandlingName.setSystemMapping(entityHandlingResult);
schemaAttributeMappingService.save(attributeHandlingName);
} else if ("CODE".equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMapping attributeHandlingName = new SysSystemAttributeMapping();
attributeHandlingName.setIdmPropertyName("code");
attributeHandlingName.setEntityAttribute(true);
attributeHandlingName.setSchemaAttribute(schemaAttr);
attributeHandlingName.setName(schemaAttr.getName());
attributeHandlingName.setSystemMapping(entityHandlingResult);
schemaAttributeMappingService.save(attributeHandlingName);
} else if ("PARENT".equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMapping attributeHandlingName = new SysSystemAttributeMapping();
attributeHandlingName.setIdmPropertyName("parent");
attributeHandlingName.setEntityAttribute(true);
attributeHandlingName.setSchemaAttribute(schemaAttr);
attributeHandlingName.setName(schemaAttr.getName());
attributeHandlingName.setSystemMapping(entityHandlingResult);
schemaAttributeMappingService.save(attributeHandlingName);
} else if ("NAME".equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMapping attributeHandlingName = new SysSystemAttributeMapping();
attributeHandlingName.setIdmPropertyName("name");
attributeHandlingName.setName(schemaAttr.getName());
attributeHandlingName.setEntityAttribute(true);
attributeHandlingName.setSchemaAttribute(schemaAttr);
attributeHandlingName.setSystemMapping(entityHandlingResult);
schemaAttributeMappingService.save(attributeHandlingName);
}
});
}
private DefaultTreeSynchronizationServiceTest getBean() {
return applicationContext.getBean(this.getClass());
}
}
|
package me.foxaice.smartlight.activities.music_mode_settings.presenter;
import me.foxaice.smartlight.activities.music_mode_settings.view.IMusicModeSettingsView;
import me.foxaice.smartlight.fragments.modes.music_mode.model.IMusicInfo;
import me.foxaice.smartlight.preferences.ISharedPreferencesController;
import me.foxaice.smartlight.preferences.SharedPreferencesController;
public class MusicModeSettingsPresenter implements IMusicModeSettingsPresenter {
private IMusicInfo mMusicInfo;
private IMusicModeSettingsView mView;
private ISharedPreferencesController mSharedPreferences;
@Override
public void saveMusicInfoToPreferences() {
if (mSharedPreferences != null && mMusicInfo != null) {
mSharedPreferences.setMusicInfo(mMusicInfo);
}
}
@Override
public void loadMusicInfoFromPreferences() {
mMusicInfo = mSharedPreferences.getMusicInfo();
}
@Override
public void resetMusicInfo() {
onChangeColorMode(IMusicInfo.DefaultValues.COLOR_MODE);
onChangeSoundViewType(IMusicInfo.DefaultValues.VIEW_TYPE);
onChangeMaxFrequencyType(IMusicInfo.DefaultValues.MAX_FREQUENCY_TYPE);
onChangeMaxFrequency(IMusicInfo.DefaultValues.MAX_FREQUENCY);
onChangeMaxVolume(IMusicInfo.DefaultValues.MAX_VOLUME);
onChangeMinVolume(IMusicInfo.DefaultValues.MIN_VOLUME);
}
@Override
public void onChangeColorMode(@IMusicInfo.ColorMode int colorMode) {
mMusicInfo.setColorMode(colorMode);
mView.setColorModeByColorMode(colorMode);
}
@Override
public void onChangeSoundViewType(@IMusicInfo.ViewType int viewType) {
mMusicInfo.setSoundViewType(viewType);
mView.setSoundViewType(viewType);
}
@Override
public void onChangeMaxFrequencyType(@IMusicInfo.MaxFrequencyType int maxFrequencyType) {
mMusicInfo.setMaxFrequencyType(maxFrequencyType);
mView.setMaxFrequencyType(maxFrequencyType);
}
@Override
public void onChangeMaxFrequency(int maxFrequency) {
mMusicInfo.setMaxFrequency(maxFrequency);
mView.setMaxFrequency(maxFrequency);
}
@Override
public void onChangeMaxVolume(int dBSPL) {
mMusicInfo.setMaxVolumeThreshold(dBSPL);
mView.setMaxVolume(dBSPL);
}
@Override
public void onChangeMinVolume(int dBSPL) {
mMusicInfo.setMinVolumeThreshold(dBSPL);
mView.setMinVolume(dBSPL);
}
@Override
public boolean isMusicModeChanged() {
return false;
}
@Override
public int getColorMode() {
return 0;
}
@Override
public int getSoundViewType() {
return 0;
}
@Override
public int getMaxFrequencyType() {
return 0;
}
@Override
public int getMaxFrequency() {
return 0;
}
@Override
public int getMaxVolume() {
return 0;
}
@Override
public int getMinVolume() {
return 0;
}
@Override
public void attach(IMusicModeSettingsView view) {
mView = view;
if (mSharedPreferences == null) {
mSharedPreferences = SharedPreferencesController.getInstance(mView.getContext());
}
}
@Override
public void detach() {
mView = null;
}
}
|
package org.csstudio.opibuilder.editparts;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.csstudio.data.values.ISeverity;
import org.csstudio.data.values.IValue;
import org.csstudio.opibuilder.OPIBuilderPlugin;
import org.csstudio.opibuilder.model.AbstractPVWidgetModel;
import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.opibuilder.model.IPVWidgetModel;
import org.csstudio.opibuilder.properties.AbstractWidgetProperty;
import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler;
import org.csstudio.opibuilder.properties.PVValueProperty;
import org.csstudio.opibuilder.properties.StringProperty;
import org.csstudio.opibuilder.pvmanager.BOYPVFactory;
import org.csstudio.opibuilder.util.AlarmRepresentationScheme;
import org.csstudio.opibuilder.util.ErrorHandlerUtil;
import org.csstudio.opibuilder.util.OPITimer;
import org.csstudio.opibuilder.visualparts.BorderFactory;
import org.csstudio.opibuilder.visualparts.BorderStyle;
import org.csstudio.ui.util.CustomMediaFactory;
import org.csstudio.ui.util.thread.UIBundlingThread;
import org.csstudio.utility.pv.PV;
import org.csstudio.utility.pv.PVListener;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.draw2d.AbstractBorder;
import org.eclipse.draw2d.Border;
import org.eclipse.draw2d.Cursors;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.RGB;
public class PVWidgetEditpartDelegate implements IPVWidgetEditpart{
private interface AlarmSeverity extends ISeverity{
public void copy(ISeverity severity);
}
private final class WidgetPVListener implements PVListener{
private String pvPropID;
public WidgetPVListener(String pvPropID) {
this.pvPropID = pvPropID;
}
public void pvDisconnected(PV pv) {
}
public void pvValueUpdate(PV pv) {
// if(pv == null)
// return;
final AbstractWidgetModel widgetModel = editpart.getWidgetModel();
//write access
if(controlPVPropId != null &&
controlPVPropId.equals(pvPropID) &&
pv.isWriteAllowed() != lastWriteAccess){
lastWriteAccess = pv.isWriteAllowed();
if(lastWriteAccess){
UIBundlingThread.getInstance().addRunnable(
editpart.getViewer().getControl().getDisplay(),new Runnable(){
public void run() {
if(editpart.getFigure().getCursor() == Cursors.NO)
editpart.getFigure().setCursor(savedCursor);
editpart.getFigure().setEnabled(widgetModel.isEnabled());
}
});
}else{
UIBundlingThread.getInstance().addRunnable(
editpart.getViewer().getControl().getDisplay(),new Runnable(){
public void run() {
if(editpart.getFigure().getCursor() != Cursors.NO)
savedCursor = editpart.getFigure().getCursor();
editpart.getFigure().setEnabled(false);
editpart.getFigure().setCursor(Cursors.NO);
}
});
}
}
if(ignoreOldPVValue){
widgetModel.getPVMap().get(widgetModel.
getProperty(pvPropID)).setPropertyValue_IgnoreOldValue(pv.getValue());
}else
widgetModel.getPVMap().get(widgetModel.
getProperty(pvPropID)).setPropertyValue(pv.getValue());
}
}
//invisible border for no_alarm state, this can prevent the widget from resizing
//when alarm turn back to no_alarm state/
private static final AbstractBorder BORDER_NO_ALARM = new AbstractBorder() {
public Insets getInsets(IFigure figure) {
return new Insets(2);
}
public void paint(IFigure figure, Graphics graphics, Insets insets) {
}
};
private int updateSuppressTime = 1000;
private String controlPVPropId = null;
private String controlPVValuePropId = null;
/**
* In most cases, old pv value in the valueChange() method of {@link IWidgetPropertyChangeHandler}
* is not useful. Ignore the old pv value will help to reduce memory usage.
*/
private boolean ignoreOldPVValue =true;
private boolean isBackColorrAlarmSensitive;
private boolean isBorderAlarmSensitive;
private boolean isForeColorAlarmSensitive;
private AlarmSeverity alarmSeverity = new AlarmSeverity(){
private static final long serialVersionUID = 1L;
boolean isInvalid = false;
boolean isMajor = false;
boolean isMinor = false;
boolean isOK = true;
public void copy(ISeverity severity){
isOK = severity.isOK();
isMajor = severity.isMajor();
isMinor = severity.isMinor();
isInvalid = severity.isInvalid();
}
public boolean hasValue() {
return false;
}
public boolean isInvalid() {
return isInvalid;
}
public boolean isMajor() {
return isMajor;
}
public boolean isMinor() {
return isMinor;
}
public boolean isOK() {
return isOK;
}
};
private Map<String, PVListener> pvListenerMap = new HashMap<String, PVListener>();
private Map<String, PV> pvMap = new HashMap<String, PV>();
private PropertyChangeListener[] pvValueListeners;
private AbstractBaseEditPart editpart;
private volatile boolean lastWriteAccess = true;
private Cursor savedCursor;
private Color saveForeColor, saveBackColor;
//the task which will be executed when the updateSuppressTimer due.
protected Runnable timerTask;
//The update from PV will be suppressed for a brief time when writing was performed
protected OPITimer updateSuppressTimer;
private IPVWidgetModel widgetModel;
private ListenerList setPVValueListeners;
/**
* @param editpart the editpart to be delegated.
* It must implemented {@link IPVWidgetEditpart}
*/
public PVWidgetEditpartDelegate(AbstractBaseEditPart editpart) {
this.editpart = editpart;
}
public IPVWidgetModel getWidgetModel() {
if(widgetModel == null)
widgetModel = (IPVWidgetModel) editpart.getWidgetModel();
return widgetModel;
}
public void doActivate(){
if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE){
pvMap.clear();
saveFigureOKStatus(editpart.getFigure());
final Map<StringProperty, PVValueProperty> pvPropertyMap = editpart.getWidgetModel().getPVMap();
for(final StringProperty sp : pvPropertyMap.keySet()){
if(sp.getPropertyValue() == null ||
((String)sp.getPropertyValue()).trim().length() <=0)
continue;
try {
PV pv = BOYPVFactory.createPV((String) sp.getPropertyValue());
pvMap.put(sp.getPropertyID(), pv);
editpart.addToConnectionHandler((String) sp.getPropertyValue(), pv);
PVListener pvListener = new WidgetPVListener(sp.getPropertyID());
pv.addListener(pvListener);
pvListenerMap.put(sp.getPropertyID(), pvListener);
} catch (Exception e) {
OPIBuilderPlugin.getLogger().log(Level.WARNING,
"Unable to connect to PV:" + (String)sp.getPropertyValue(), e); //$NON-NLS-1$
}
}
}
}
/**Start all PVs.
* This should be called as the last step in editpart.activate().
*/
public void startPVs() {
//the pv should be started at the last minute
for(String pvPropId : pvMap.keySet()){
PV pv = pvMap.get(pvPropId);
try {
pv.start();
} catch (Exception e) {
OPIBuilderPlugin.getLogger().log(Level.WARNING,
"Unable to connect to PV:" + pv.getName(), e); //$NON-NLS-1$
}
}
}
public void doDeActivate() {
for(PV pv : pvMap.values())
pv.stop();
for(String pvPropID : pvListenerMap.keySet()){
pvMap.get(pvPropID).removeListener(pvListenerMap.get(pvPropID));
}
pvMap.clear();
pvListenerMap.clear();
}
public PV getControlPV(){
if(controlPVPropId != null)
return pvMap.get(controlPVPropId);
return null;
}
/**Get the PV corresponding to the <code>PV Name</code> property.
* It is same as calling <code>getPV("pv_name")</code>.
* @return the PV corresponding to the <code>PV Name</code> property.
* null if PV Name is not configured for this widget.
*/
public PV getPV(){
return pvMap.get(IPVWidgetModel.PROP_PVNAME);
}
/**Get the pv by PV property id.
* @param pvPropId the PV property id.
* @return the corresponding pv for the pvPropId. null if the pv doesn't exist.
*/
public PV getPV(String pvPropId){
return pvMap.get(pvPropId);
}
/**Get value from one of the attached PVs.
* @param pvPropId the property id of the PV. It is "pv_name" for the main PV.
* @return the {@link IValue} of the PV.
*/
public IValue getPVValue(String pvPropId){
final PV pv = pvMap.get(pvPropId);
if(pv != null){
return pv.getValue();
}
return null;
}
/**
* @return the time needed to suppress reading back from PV after writing.
* No need to suppress if returned value <=0
*/
public int getUpdateSuppressTime(){
return updateSuppressTime;
}
/**Set the time needed to suppress reading back from PV after writing.
* No need to suppress if returned value <=0
* @param updateSuppressTime
*/
public void setUpdateSuppressTime(int updateSuppressTime) {
this.updateSuppressTime = updateSuppressTime;
}
public void initFigure(IFigure figure){
//initialize frequent used variables
isBorderAlarmSensitive = getWidgetModel().isBorderAlarmSensitve();
isBackColorrAlarmSensitive = getWidgetModel().isBackColorAlarmSensitve();
isForeColorAlarmSensitive = getWidgetModel().isForeColorAlarmSensitve();
if(isBorderAlarmSensitive
&& editpart.getWidgetModel().getBorderStyle()== BorderStyle.NONE){
editpart.setFigureBorder(BORDER_NO_ALARM);
}
}
/**
* Initialize the updateSuppressTimer
*/
private synchronized void initUpdateSuppressTimer() {
if(updateSuppressTimer == null)
updateSuppressTimer = new OPITimer();
if(timerTask == null)
timerTask = new Runnable() {
public void run() {
AbstractWidgetProperty pvValueProperty =
editpart.getWidgetModel().getProperty(controlPVValuePropId);
//recover update
if(pvValueListeners != null){
for(PropertyChangeListener listener: pvValueListeners){
pvValueProperty.addPropertyChangeListener(listener);
}
}
//forcefully set PV_Value property again
pvValueProperty.setPropertyValue(
pvValueProperty.getPropertyValue(), true);
}
};
}
/**For PV Control widgets, mark this PV as control PV.
* @param pvPropId the propId of the PV.
*/
public void markAsControlPV(String pvPropId, String pvValuePropId){
controlPVPropId = pvPropId;
controlPVValuePropId = pvValuePropId;
initUpdateSuppressTimer();
}
public boolean isPVControlWidget(){
return controlPVPropId!=null;
}
public void registerBasePropertyChangeHandlers() {
IWidgetPropertyChangeHandler borderHandler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
editpart.setFigureBorder(editpart.calculateBorder());
return true;
}
};
editpart.setPropertyChangeHandler(IPVWidgetModel.PROP_BORDER_ALARMSENSITIVE, borderHandler);
// value
IWidgetPropertyChangeHandler valueHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(final Object oldValue,
final Object newValue,
final IFigure figure) {
if(!isBorderAlarmSensitive && !isBackColorrAlarmSensitive &&
!isForeColorAlarmSensitive)
return false;
ISeverity newSeverity = ((IValue)newValue).getSeverity();
if(newSeverity.isOK() && alarmSeverity.isOK())
return false;
else if(newSeverity.isOK() && !alarmSeverity.isOK()){
alarmSeverity.copy(newSeverity);
restoreFigureToOKStatus(figure);
return true;
}
if(newSeverity.isMajor() && alarmSeverity.isMajor())
return false;
if(newSeverity.isMinor() && alarmSeverity.isMinor())
return false;
if(newSeverity.isInvalid() && alarmSeverity.isInvalid())
return false;
alarmSeverity.copy(newSeverity);
RGB alarmColor;
if(newSeverity.isMajor()){
alarmColor = AlarmRepresentationScheme.getMajorColor();
}else if(newSeverity.isMinor()){
alarmColor = AlarmRepresentationScheme.getMinorColor();
}else{
alarmColor = AlarmRepresentationScheme.getInValidColor();
}
if(isBorderAlarmSensitive){
editpart.setFigureBorder(editpart.calculateBorder());
}
if(isBackColorrAlarmSensitive){
figure.setBackgroundColor(CustomMediaFactory.getInstance().getColor(alarmColor));
}
if(isForeColorAlarmSensitive){
figure.setForegroundColor(CustomMediaFactory.getInstance().getColor(alarmColor));
}
return true;
}
};
editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVVALUE, valueHandler);
class PVNamePropertyChangeHandler implements IWidgetPropertyChangeHandler{
private String pvNamePropID;
public PVNamePropertyChangeHandler(String pvNamePropID) {
this.pvNamePropID = pvNamePropID;
}
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
String newPVName = ((String)newValue).trim();
if(newPVName.length() <= 0)
return false;
PV oldPV = pvMap.get(pvNamePropID);
editpart.removeFromConnectionHandler((String)oldValue);
if(oldPV != null){
oldPV.stop();
oldPV.removeListener(pvListenerMap.get(pvNamePropID));
}
try {
PV newPV = BOYPVFactory.createPV(newPVName);
lastWriteAccess = true;
PVListener pvListener = new WidgetPVListener(pvNamePropID);
newPV.addListener(pvListener);
pvMap.put(pvNamePropID, newPV);
editpart.addToConnectionHandler(newPVName, newPV);
pvListenerMap.put(pvNamePropID, pvListener);
newPV.start();
}
catch (Exception e) {
OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + //$NON-NLS-1$
newPVName, e);
}
return false;
}
}
//PV name
for(StringProperty pvNameProperty : editpart.getWidgetModel().getPVMap().keySet()){
if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE)
editpart.setPropertyChangeHandler(pvNameProperty.getPropertyID(),
new PVNamePropertyChangeHandler(pvNameProperty.getPropertyID()));
}
// //border alarm sensitive
// IWidgetPropertyChangeHandler borderAlarmSentiveHandler = new IWidgetPropertyChangeHandler() {
// public boolean handleChange(Object oldValue, Object newValue, IFigure figure) {
// isBorderAlarmSensitive = widgetModel.isBorderAlarmSensitve();
// if(isBorderAlarmSensitive
// && getWidgetModel().getBorderStyle()== BorderStyle.NONE){
// setAlarmBorder(BORDER_NO_ALARM);
// }else if (!isBorderAlarmSensitive
// && getWidgetModel().getBorderStyle()== BorderStyle.NONE)
// setAlarmBorder(null);
// return false;
// setPropertyChangeHandler(AbstractPVWidgetModel.PROP_BORDER_ALARMSENSITIVE, borderAlarmSentiveHandler);
//// setPropertyChangeHandler(AbstractPVWidgetModel.PROP_BORDER_STYLE, borderAlarmSentiveHandler);
IWidgetPropertyChangeHandler backColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(Object oldValue, Object newValue, IFigure figure) {
isBackColorrAlarmSensitive = (Boolean)newValue;
return false;
}
};
editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_BACKCOLOR_ALARMSENSITIVE, backColorAlarmSensitiveHandler);
IWidgetPropertyChangeHandler foreColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(Object oldValue, Object newValue, IFigure figure) {
isForeColorAlarmSensitive = (Boolean)newValue;
return false;
}
};
editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_FORECOLOR_ALARMSENSITIVE, foreColorAlarmSensitiveHandler);
}
private void restoreFigureToOKStatus(IFigure figure) {
if(isBorderAlarmSensitive)
editpart.setFigureBorder(editpart.calculateBorder());
if(isBackColorrAlarmSensitive)
figure.setBackgroundColor(saveBackColor);
if(isForeColorAlarmSensitive)
figure.setForegroundColor(saveForeColor);
}
private void saveFigureOKStatus(IFigure figure) {
saveForeColor = figure.getForegroundColor();
saveBackColor = figure.getBackgroundColor();
}
/**
* Start the updateSuppressTimer. All property change listeners of PV_Value property will
* temporarily removed until timer is due.
*/
protected synchronized void startUpdateSuppressTimer(){
AbstractWidgetProperty pvValueProperty =
editpart.getWidgetModel().getProperty(controlPVValuePropId);
pvValueListeners = pvValueProperty.getAllPropertyChangeListeners();
pvValueProperty.removeAllPropertyChangeListeners();
updateSuppressTimer.start(timerTask, getUpdateSuppressTime());
}
public Border calculateBorder(){
isBorderAlarmSensitive = getWidgetModel().isBorderAlarmSensitve();
if(!isBorderAlarmSensitive)
return null;
else {
Border alarmBorder;
if(alarmSeverity.isOK()){
if(editpart.getWidgetModel().getBorderStyle()== BorderStyle.NONE)
alarmBorder = BORDER_NO_ALARM;
else
alarmBorder = BorderFactory.createBorder(
editpart.getWidgetModel().getBorderStyle(),
editpart.getWidgetModel().getBorderWidth(),
editpart.getWidgetModel().getBorderColor(),
editpart.getWidgetModel().getName());
}else if(alarmSeverity.isMajor()){
alarmBorder = AlarmRepresentationScheme.getMajorBorder(editpart.getWidgetModel().getBorderStyle());
}else if(alarmSeverity.isMinor()){
alarmBorder = AlarmRepresentationScheme.getMinorBorder(editpart.getWidgetModel().getBorderStyle());
}else{
alarmBorder = AlarmRepresentationScheme.getInvalidBorder(editpart.getWidgetModel().getBorderStyle());
}
return alarmBorder;
}
}
/**Set PV to given value. Should accept Double, Double[], Integer, String, maybe more.
* @param pvPropId
* @param value
*/
public void setPVValue(String pvPropId, Object value){
fireSetPVValue(pvPropId, value);
final PV pv = pvMap.get(pvPropId);
if(pv != null){
try {
if(pvPropId.equals(controlPVPropId) && controlPVValuePropId != null && getUpdateSuppressTime() >0){ //activate suppress timer
synchronized (this) {
if(updateSuppressTimer == null || timerTask == null)
initUpdateSuppressTimer();
if(!updateSuppressTimer.isDue())
updateSuppressTimer.reset();
else
startUpdateSuppressTimer();
}
}
pv.setValue(value);
} catch (final Exception e) {
UIBundlingThread.getInstance().addRunnable(new Runnable(){
public void run() {
String message =
"Failed to write PV:" + pv.getName();
ErrorHandlerUtil.handleError(message, e);
}
});
}
}
}
public void setIgnoreOldPVValue(boolean ignoreOldValue) {
this.ignoreOldPVValue = ignoreOldValue;
}
@Override
public String[] getAllPVNames() {
if(editpart.getWidgetModel().getPVMap().isEmpty())
return new String[]{""}; //$NON-NLS-1$
String[] result = new String[editpart.getWidgetModel().getPVMap().size()];
int i=0;
for(StringProperty sp : editpart.getWidgetModel().getPVMap().keySet()){
result[i++] = (String) sp.getPropertyValue();
}
return result;
}
@Override
public String getPVName() {
return getWidgetModel().getPVName();
}
@Override
public void addSetPVValueListener(ISetPVValueListener listener) {
if(setPVValueListeners == null){
setPVValueListeners = new ListenerList();
}
setPVValueListeners.add(listener);
}
protected void fireSetPVValue(String pvPropId, Object value){
if(setPVValueListeners == null)
return;
for(Object listener: setPVValueListeners.getListeners()){
((ISetPVValueListener)listener).beforeSetPVValue(pvPropId, value);
}
}
}
|
package org.owasp.appsensor.analysis.impl;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.BeforeClass;
import org.junit.Test;
import org.owasp.appsensor.ClientObjectFactory;
import org.owasp.appsensor.DetectionPoint;
import org.owasp.appsensor.Interval;
import org.owasp.appsensor.Response;
import org.owasp.appsensor.ServerObjectFactory;
import org.owasp.appsensor.StatisticalEvent;
import org.owasp.appsensor.Threshold;
import org.owasp.appsensor.User;
import org.owasp.appsensor.configuration.server.ServerConfiguration;
public class ReferenceStatisticalEventAnalysisEngineTest {
private static User bob = new User("bob", "1.2.3.4");
private static DetectionPoint detectionPoint1 = new DetectionPoint();
private static Collection<String> detectionSystems1 = new ArrayList<String>();
private static String detectionSystem1 = "localhostme";
@BeforeClass
public static void doSetup() {
detectionPoint1.setId("IE1");
detectionSystems1.add(detectionSystem1);
}
@Test
public void testAttackCreation() throws Exception {
ServerConfiguration updatedConfiguration = ServerObjectFactory.getConfiguration();
updatedConfiguration.setDetectionPoints(loadMockedDetectionPoints());
ServerObjectFactory.setConfiguration(updatedConfiguration);
assertEquals(0, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(0, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(1, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(0, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(2, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(0, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(3, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(1, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(4, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(1, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(5, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(1, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(6, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(2, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
ClientObjectFactory.getEventManager().addEvent(new StatisticalEvent(bob, detectionPoint1, "localhostme"));
assertEquals(7, ServerObjectFactory.getEventStore().findEvents(bob, detectionPoint1, detectionSystems1).size());
assertEquals(2, ServerObjectFactory.getAttackStore().findAttacks(bob, detectionPoint1, detectionSystems1).size());
}
private Collection<DetectionPoint> loadMockedDetectionPoints() {
final Collection<DetectionPoint> configuredDetectionPoints = new ArrayList<DetectionPoint>();
Interval minutes5 = new Interval(5, Interval.MINUTES);
Interval minutes6 = new Interval(6, Interval.MINUTES);
Interval minutes7 = new Interval(7, Interval.MINUTES);
Interval minutes8 = new Interval(8, Interval.MINUTES);
Interval minutes11 = new Interval(11, Interval.MINUTES);
Interval minutes12 = new Interval(12, Interval.MINUTES);
Interval minutes13 = new Interval(13, Interval.MINUTES);
Interval minutes14 = new Interval(14, Interval.MINUTES);
Interval minutes15 = new Interval(15, Interval.MINUTES);
Interval minutes31 = new Interval(31, Interval.MINUTES);
Interval minutes32 = new Interval(32, Interval.MINUTES);
Interval minutes33 = new Interval(33, Interval.MINUTES);
Interval minutes34 = new Interval(34, Interval.MINUTES);
Interval minutes35 = new Interval(35, Interval.MINUTES);
Threshold events3minutes5 = new Threshold(3, minutes5);
Threshold events12minutes5 = new Threshold(12, minutes5);
Threshold events13minutes6 = new Threshold(13, minutes6);
Threshold events14minutes7 = new Threshold(14, minutes7);
Threshold events15minutes8 = new Threshold(15, minutes8);
Response log = new Response();
log.setAction("log");
Response logout = new Response();
logout.setAction("logout");
Response disableUser = new Response();
disableUser.setAction("disableUser");
Response disableComponentForSpecificUser31 = new Response();
disableComponentForSpecificUser31.setAction("disableComponentForSpecificUser");
disableComponentForSpecificUser31.setInterval(minutes31);
Response disableComponentForSpecificUser32 = new Response();
disableComponentForSpecificUser32.setAction("disableComponentForSpecificUser");
disableComponentForSpecificUser32.setInterval(minutes32);
Response disableComponentForSpecificUser33 = new Response();
disableComponentForSpecificUser33.setAction("disableComponentForSpecificUser");
disableComponentForSpecificUser33.setInterval(minutes33);
Response disableComponentForSpecificUser34 = new Response();
disableComponentForSpecificUser34.setAction("disableComponentForSpecificUser");
disableComponentForSpecificUser34.setInterval(minutes34);
Response disableComponentForSpecificUser35 = new Response();
disableComponentForSpecificUser35.setAction("disableComponentForSpecificUser");
disableComponentForSpecificUser35.setInterval(minutes35);
Response disableComponentForAllUsers11 = new Response();
disableComponentForAllUsers11.setAction("disableComponentForAllUsers");
disableComponentForAllUsers11.setInterval(minutes11);
Response disableComponentForAllUsers12 = new Response();
disableComponentForAllUsers12.setAction("disableComponentForAllUsers");
disableComponentForAllUsers12.setInterval(minutes12);
Response disableComponentForAllUsers13 = new Response();
disableComponentForAllUsers13.setAction("disableComponentForAllUsers");
disableComponentForAllUsers13.setInterval(minutes13);
Response disableComponentForAllUsers14 = new Response();
disableComponentForAllUsers14.setAction("disableComponentForAllUsers");
disableComponentForAllUsers14.setInterval(minutes14);
Response disableComponentForAllUsers15 = new Response();
disableComponentForAllUsers15.setAction("disableComponentForAllUsers");
disableComponentForAllUsers15.setInterval(minutes15);
Collection<Response> point1Responses = new ArrayList<Response>();
point1Responses.add(log);
point1Responses.add(logout);
point1Responses.add(disableUser);
point1Responses.add(disableComponentForSpecificUser31);
point1Responses.add(disableComponentForAllUsers11);
DetectionPoint point1 = new DetectionPoint("IE1", events3minutes5, point1Responses);
Collection<Response> point2Responses = new ArrayList<Response>();
point2Responses.add(log);
point2Responses.add(logout);
point2Responses.add(disableUser);
point2Responses.add(disableComponentForSpecificUser32);
point2Responses.add(disableComponentForAllUsers12);
DetectionPoint point2 = new DetectionPoint("IE2", events12minutes5, point2Responses);
Collection<Response> point3Responses = new ArrayList<Response>();
point3Responses.add(log);
point3Responses.add(logout);
point3Responses.add(disableUser);
point3Responses.add(disableComponentForSpecificUser33);
point3Responses.add(disableComponentForAllUsers13);
DetectionPoint point3 = new DetectionPoint("IE3", events13minutes6, point3Responses);
Collection<Response> point4Responses = new ArrayList<Response>();
point4Responses.add(log);
point4Responses.add(logout);
point4Responses.add(disableUser);
point4Responses.add(disableComponentForSpecificUser34);
point4Responses.add(disableComponentForAllUsers14);
DetectionPoint point4 = new DetectionPoint("IE4", events14minutes7, point4Responses);
Collection<Response> point5Responses = new ArrayList<Response>();
point5Responses.add(log);
point5Responses.add(logout);
point5Responses.add(disableUser);
point5Responses.add(disableComponentForSpecificUser35);
point5Responses.add(disableComponentForAllUsers15);
DetectionPoint point5 = new DetectionPoint("IE5", events15minutes8, point5Responses);
configuredDetectionPoints.add(point1);
configuredDetectionPoints.add(point2);
configuredDetectionPoints.add(point3);
configuredDetectionPoints.add(point4);
configuredDetectionPoints.add(point5);
return configuredDetectionPoints;
}
}
|
package org.ovirt.engine.api.restapi.resource;
import static org.ovirt.engine.api.restapi.resource.BackendVmsResource.SUB_COLLECTIONS;
import static org.ovirt.engine.core.utils.Ticketing.generateOTP;
import java.util.List;
import java.util.Set;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.ovirt.engine.api.common.util.DetailHelper;
import org.ovirt.engine.api.common.util.QueryHelper;
import org.ovirt.engine.api.model.Action;
import org.ovirt.engine.api.model.CdRom;
import org.ovirt.engine.api.model.CdRoms;
import org.ovirt.engine.api.model.Certificate;
import org.ovirt.engine.api.model.CreationStatus;
import org.ovirt.engine.api.model.Display;
import org.ovirt.engine.api.model.Fault;
import org.ovirt.engine.api.model.Statistic;
import org.ovirt.engine.api.model.Statistics;
import org.ovirt.engine.api.model.Template;
import org.ovirt.engine.api.model.Ticket;
import org.ovirt.engine.api.model.VM;
import org.ovirt.engine.api.resource.ActionResource;
import org.ovirt.engine.api.resource.AssignedPermissionsResource;
import org.ovirt.engine.api.resource.AssignedTagsResource;
import org.ovirt.engine.api.resource.CreationResource;
import org.ovirt.engine.api.resource.DevicesResource;
import org.ovirt.engine.api.resource.GraphicsConsolesResource;
import org.ovirt.engine.api.resource.SnapshotsResource;
import org.ovirt.engine.api.resource.StatisticsResource;
import org.ovirt.engine.api.resource.VmApplicationsResource;
import org.ovirt.engine.api.resource.VmDisksResource;
import org.ovirt.engine.api.resource.VmHostDevicesResource;
import org.ovirt.engine.api.resource.VmNicsResource;
import org.ovirt.engine.api.resource.VmNumaNodesResource;
import org.ovirt.engine.api.resource.VmReportedDevicesResource;
import org.ovirt.engine.api.resource.VmResource;
import org.ovirt.engine.api.resource.VmSessionsResource;
import org.ovirt.engine.api.resource.WatchdogsResource;
import org.ovirt.engine.api.resource.externalhostproviders.KatelloErrataResource;
import org.ovirt.engine.api.restapi.logging.Messages;
import org.ovirt.engine.api.restapi.resource.externalhostproviders.BackendVmKatelloErrataResource;
import org.ovirt.engine.api.restapi.types.RngDeviceMapper;
import org.ovirt.engine.api.restapi.types.VmMapper;
import org.ovirt.engine.api.restapi.util.DisplayHelper;
import org.ovirt.engine.api.restapi.util.IconHelper;
import org.ovirt.engine.api.utils.LinkHelper;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.ChangeVMClusterParameters;
import org.ovirt.engine.core.common.action.CloneVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmToServerParameters;
import org.ovirt.engine.core.common.action.MoveVmParameters;
import org.ovirt.engine.core.common.action.RemoveVmFromPoolParameters;
import org.ovirt.engine.core.common.action.RemoveVmParameters;
import org.ovirt.engine.core.common.action.RestoreAllSnapshotsParameters;
import org.ovirt.engine.core.common.action.RunVmOnceParams;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.SetHaMaintenanceParameters;
import org.ovirt.engine.core.common.action.SetVmTicketParameters;
import org.ovirt.engine.core.common.action.ShutdownVmParameters;
import org.ovirt.engine.core.common.action.StopVmParameters;
import org.ovirt.engine.core.common.action.StopVmTypeEnum;
import org.ovirt.engine.core.common.action.TryBackToAllSnapshotsOfVmParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VmManagementParametersBase;
import org.ovirt.engine.core.common.action.VmOperationParameterBase;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.HaMaintenanceMode;
import org.ovirt.engine.core.common.businessentities.InitializationType;
import org.ovirt.engine.core.common.businessentities.SnapshotActionEnum;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VmInit;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.queries.GetPermissionsForObjectParameters;
import org.ovirt.engine.core.common.queries.GetVmTemplateParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.NameQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
public class BackendVmResource extends
AbstractBackendActionableResource<VM, org.ovirt.engine.core.common.businessentities.VM> implements
VmResource {
private static final long DEFAULT_TICKET_EXPIRY = 120 * 60; // 2 hours
private BackendVmsResource parent;
public static final String NEXT_RUN = "next_run";
public BackendVmResource(String id, BackendVmsResource parent) {
super(id, VM.class, org.ovirt.engine.core.common.businessentities.VM.class, SUB_COLLECTIONS);
this.parent = parent;
}
private boolean isNextRunRequested() {
return QueryHelper.getMatrixConstraints(getUriInfo(), NEXT_RUN).containsKey(NEXT_RUN);
}
@Override
public VM get() {
VM vm;
if (isNextRunRequested()) {
org.ovirt.engine.core.common.businessentities.VM entity =
getEntity(org.ovirt.engine.core.common.businessentities.VM.class, VdcQueryType.GetVmNextRunConfiguration,
new IdQueryParameters(guid), id, true);
vm = addLinks(populate(VmMapper.map(entity, null, false), entity));
} else {
vm = performGet(VdcQueryType.GetVmByVmId, new IdQueryParameters(guid));
}
if (vm != null) {
DisplayHelper.adjustDisplayData(this, vm);
removeRestrictedInfo(vm);
}
return vm;
}
private void removeRestrictedInfo(VM vm) {
// Filtered users are not allowed to view host related information
if (isFiltered()) {
vm.setHost(null);
vm.setPlacementPolicy(null);
}
}
@Override
public VM update(VM incoming) {
validateEnums(VM.class, incoming);
validateParameters(incoming);
if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) {
Guid clusterId = lookupClusterId(incoming);
if(!clusterId.toString().equals(get().getCluster().getId())){
performAction(VdcActionType.ChangeVMCluster,
new ChangeVMClusterParameters(clusterId, guid));
}
}
if (!isFiltered()) {
if (incoming.isSetPlacementPolicy()) {
parent.validateAndUpdateHostsInPlacementPolicy(incoming.getPlacementPolicy());
}
} else {
incoming.setPlacementPolicy(null);
}
VM vm = performUpdate(
incoming,
new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class),
VdcActionType.UpdateVm,
new UpdateParametersProvider()
);
if (vm != null) {
DisplayHelper.adjustDisplayData(this, vm);
removeRestrictedInfo(vm);
}
return vm;
}
@Override
public Response remove() {
get();
return performAction(VdcActionType.RemoveVm, new RemoveVmParameters(guid, false));
}
@Override
public Response remove(Action action) {
get();
boolean forceRemove = action != null && action.isSetForce() ? action.isForce() : false;
RemoveVmParameters params = new RemoveVmParameters(guid, forceRemove);
// If detach only is set we do not remove the VM disks
if (action != null && action.isSetVm() && action.getVm().isSetDisks()
&& action.getVm().getDisks().isSetDetachOnly()) {
params.setRemoveDisks(false);
}
return performAction(VdcActionType.RemoveVm, params);
}
private void validateParameters(VM incoming) {
if (incoming.isSetDomain() && !incoming.getDomain().isSetName()) {
throw new WebFaultException(null,
localize(Messages.INCOMPLETE_PARAMS_REASON),
localize(Messages.INCOMPLETE_PARAMS_CONDITIONAL, "Domain", "Domain name"),
Response.Status.BAD_REQUEST);
}
if (!IconHelper.validateIconParameters(incoming)) {
throw new BaseBackendResource.WebFaultException(null,
localize(Messages.INVALID_ICON_PARAMETERS),
Response.Status.BAD_REQUEST);
}
}
protected Guid lookupClusterId(VM vm) {
return vm.getCluster().isSetId() ? asGuid(vm.getCluster().getId())
: getEntity(VDSGroup.class,
VdcQueryType.GetVdsGroupByName,
new NameQueryParameters(vm.getCluster().getName()),
"Cluster: name=" + vm.getCluster().getName()).getId();
}
@Override
public DevicesResource<CdRom, CdRoms> getCdRomsResource() {
return inject(new BackendCdRomsResource(guid,
VdcQueryType.GetVmByVmId,
new IdQueryParameters(guid)));
}
@Override
public WatchdogsResource getWatchdogsResource() {
return inject(
new BackendWatchdogsResource(
true,
guid,
VdcQueryType.GetWatchdog,
new IdQueryParameters(guid)
)
);
}
@Override
public VmDisksResource getDisksResource() {
return inject(new BackendVmDisksResource(guid,
VdcQueryType.GetAllDisksByVmId,
new IdQueryParameters(guid)));
}
@Override
public VmNicsResource getNicsResource() {
return inject(new BackendVmNicsResource(guid));
}
@Override
public SnapshotsResource getSnapshotsResource() {
return inject(new BackendSnapshotsResource(guid));
}
@Override
public AssignedTagsResource getTagsResource() {
return inject(new BackendVmTagsResource(id));
}
@Override
public VmApplicationsResource getApplicationsResource() {
return inject(new BackendVmApplicationsResource(guid));
}
@Override
public AssignedPermissionsResource getPermissionsResource() {
return inject(new BackendAssignedPermissionsResource(guid,
VdcQueryType.GetPermissionsForObject,
new GetPermissionsForObjectParameters(guid),
VM.class,
VdcObjectType.VM));
}
@Override
public CreationResource getCreationSubresource(String ids) {
return inject(new BackendCreationResource(ids));
}
@Override
public ActionResource getActionSubresource(String action, String ids) {
return inject(new BackendActionResource(action, ids));
}
@Override
public StatisticsResource getStatisticsResource() {
EntityIdResolver<Guid> resolver = new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class);
VmStatisticalQuery query = new VmStatisticalQuery(resolver, newModel(id));
return inject(new BackendStatisticsResource<VM, org.ovirt.engine.core.common.businessentities.VM>(entityType, guid, query));
}
@Override
public Response migrate(Action action) {
boolean forceMigration = action.isSetForce() ? action.isForce() : false;
if (!action.isSetHost()) {
return doAction(VdcActionType.MigrateVm,
new MigrateVmParameters(forceMigration, guid, getTargetClusterId(action)),
action);
} else {
return doAction(VdcActionType.MigrateVmToServer,
new MigrateVmToServerParameters(forceMigration, guid, getHostId(action), getTargetClusterId(action)),
action);
}
}
private Guid getTargetClusterId(Action action) {
if (action.isSetCluster() && action.getCluster().isSetId()) {
return asGuid(action.getCluster().getId());
}
// means use the cluster of the provided host
return null;
}
@Override
public Response shutdown(Action action) {
// REVISIT add waitBeforeShutdown Action paramater
// to api schema before next sub-milestone
return doAction(VdcActionType.ShutdownVm,
new ShutdownVmParameters(guid, true),
action);
}
@Override
public Response reboot(Action action) {
return doAction(VdcActionType.RebootVm,
new VmOperationParameterBase(guid),
action);
}
@Override
public Response undoSnapshot(Action action) {
RestoreAllSnapshotsParameters restoreParams = new RestoreAllSnapshotsParameters(guid, SnapshotActionEnum.UNDO);
Response response = doAction(VdcActionType.RestoreAllSnapshots,
restoreParams,
action);
return response;
}
@Override
public Response cloneVm(Action action) {
validateParameters(action, "vm.name");
org.ovirt.engine.core.common.businessentities.VM vm = getEntity(
org.ovirt.engine.core.common.businessentities.VM.class,
VdcQueryType.GetVmByVmId,
new IdQueryParameters(guid), "VM: id=" + guid);
CloneVmParameters cloneVmParameters = new CloneVmParameters(vm, action.getVm().getName());
cloneVmParameters.setMakeCreatorExplicitOwner(isFiltered());
Response response = doAction(VdcActionType.CloneVm,
cloneVmParameters,
action);
return response;
}
@Override
public Response reorderMacAddresses(Action action) {
getEntity(org.ovirt.engine.core.common.businessentities.VM.class,
VdcQueryType.GetVmByVmId,
new IdQueryParameters(guid),
"VM: id=" + guid,
true);
final VmOperationParameterBase params = new VmOperationParameterBase(guid);
final Response response = doAction(
VdcActionType.ReorderVmNics,
params,
action);
return response;
}
@Override
public Response commitSnapshot(Action action) {
RestoreAllSnapshotsParameters restoreParams = new RestoreAllSnapshotsParameters(guid, SnapshotActionEnum.COMMIT);
Response response = doAction(VdcActionType.RestoreAllSnapshots,
restoreParams,
action);
return response;
}
@Override
public Response previewSnapshot(Action action) {
validateParameters(action, "snapshot.id");
TryBackToAllSnapshotsOfVmParameters tryBackParams =
new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId()));
if (action.isSetRestoreMemory()) {
tryBackParams.setRestoreMemory(action.isRestoreMemory());
}
if (action.isSetDisks()) {
tryBackParams.setDisks(getParent().mapDisks(action.getDisks()));
}
Response response = doAction(VdcActionType.TryBackToAllSnapshotsOfVm,
tryBackParams,
action);
return response;
}
@Override
public Response start(Action action) {
RunVmParams params;
VdcActionType actionType;
if (action.isSetVm()) {
VM vm = action.getVm();
validateEnums(VM.class, vm);
actionType = VdcActionType.RunVmOnce;
params = createRunVmOnceParams(vm);
} else {
actionType = VdcActionType.RunVm;
params = new RunVmParams(guid);
}
if (action.isSetPause() && action.isPause()) {
params.setRunAndPause(true);
}
boolean useSysprep = action.isSetUseSysprep() && action.isUseSysprep();
boolean useCloudInit = action.isSetUseCloudInit() && action.isUseCloudInit();
if (useSysprep && useCloudInit) {
Fault fault = new Fault();
fault.setReason(localize(Messages.CANT_USE_SYSPREP_AND_CLOUD_INIT_SIMULTANEOUSLY));
return Response.status(Response.Status.CONFLICT).entity(fault).build();
}
if (useSysprep) {
params.setInitializationType(InitializationType.Sysprep);
}
else if (useCloudInit) {
params.setInitializationType(InitializationType.CloudInit);
}
else {
params.setInitializationType(InitializationType.None);
}
return doAction(actionType, params, action);
}
private RunVmOnceParams createRunVmOnceParams(VM vm) {
RunVmOnceParams params = map(vm, map(map(getEntity(entityType, VdcQueryType.GetVmByVmId, new IdQueryParameters(guid), id, true), new VM()),
new RunVmOnceParams(guid)));
if (vm.isSetPlacementPolicy()) {
Set<Guid> hostsGuidsSet = parent.validateAndUpdateHostsInPlacementPolicy(vm.getPlacementPolicy());
if (hostsGuidsSet.size() > 0) {
// take the arbitrary first host for run destination
params.setDestinationVdsId(hostsGuidsSet.iterator().next());
}
}
if (vm.isSetInitialization()) {
if (vm.getInitialization().isSetCloudInit()) {
params.setInitializationType(InitializationType.CloudInit);
}
params.setVmInit(VmMapper.map(vm.getInitialization(), new VmInit()));
}
return params;
}
@Override
public Response stop(Action action) {
return doAction(VdcActionType.StopVm,
new StopVmParameters(guid, StopVmTypeEnum.NORMAL),
action);
}
@Override
public Response suspend(Action action) {
return doAction(VdcActionType.HibernateVm,
new VmOperationParameterBase(guid),
action);
}
@Override
public Response detach(Action action) {
return doAction(VdcActionType.RemoveVmFromPool,
new RemoveVmFromPoolParameters(guid),
action);
}
@Override
public Response export(Action action) {
validateParameters(action, "storageDomain.id|name");
MoveVmParameters params = new MoveVmParameters(guid, getStorageDomainId(action));
if (action.isSetExclusive() && action.isExclusive()) {
params.setForceOverride(true);
}
if (action.isSetDiscardSnapshots() && action.isDiscardSnapshots()) {
params.setCopyCollapse(true);
}
return doAction(VdcActionType.ExportVm, params, action);
}
@Override
public Response move(Action action) {
validateParameters(action, "storageDomain.id|name");
return doAction(VdcActionType.MoveVm,
new MoveVmParameters(guid, getStorageDomainId(action)),
action);
}
@Override
public Response ticket(Action action) {
final Response response = doAction(VdcActionType.SetVmTicket,
new SetVmTicketParameters(guid,
getTicketValue(action),
getTicketExpiry(action),
deriveGraphicsType()),
action);
final Action actionResponse = (Action) response.getEntity();
if (CreationStatus.FAILED.value().equals(actionResponse.getStatus().getState())) {
actionResponse.getTicket().setValue(null);
actionResponse.getTicket().setExpiry(null);
}
return response;
}
private GraphicsType deriveGraphicsType() {
org.ovirt.engine.core.common.businessentities.VM vm = getEntity(org.ovirt.engine.core.common.businessentities.VM.class,
VdcQueryType.GetVmByVmId, new IdQueryParameters(guid), "GetVmByVmId");
return (vm == null)
? null
: VmMapper.deriveGraphicsType(vm.getGraphicsInfos());
}
protected String getTicketValue(Action action) {
if (!ensureTicket(action).isSetValue()) {
action.getTicket().setValue(generateOTP());
}
return action.getTicket().getValue();
}
protected int getTicketExpiry(Action action) {
if (!ensureTicket(action).isSetExpiry()) {
action.getTicket().setExpiry(DEFAULT_TICKET_EXPIRY);
}
return action.getTicket().getExpiry().intValue();
}
protected Ticket ensureTicket(Action action) {
if (!action.isSetTicket()) {
action.setTicket(new Ticket());
}
return action.getTicket();
}
@Override
public Response logon(Action action) {
final Response response = doAction(VdcActionType.VmLogon,
new VmOperationParameterBase(guid),
action);
return response;
}
@Override
public Response freezeFilesystems(Action action) {
final Response response = doAction(VdcActionType.FreezeVm,
new VmOperationParameterBase(guid),
action);
return response;
}
@Override
public Response thawFilesystems(Action action) {
final Response response = doAction(VdcActionType.ThawVm,
new VmOperationParameterBase(guid),
action);
return response;
}
protected RunVmOnceParams map(VM vm, RunVmOnceParams params) {
return getMapper(VM.class, RunVmOnceParams.class).map(vm, params);
}
@Override
protected VM doPopulate(VM model, org.ovirt.engine.core.common.businessentities.VM entity) {
parent.setConsoleDevice(model);
parent.setVirtioScsiController(model);
parent.setSoundcard(model);
parent.setVmOvfConfiguration(model, entity);
parent.setRngDevice(model);
return model;
}
@Override
protected VM deprecatedPopulate(VM model, org.ovirt.engine.core.common.businessentities.VM entity) {
Set<String> details = DetailHelper.getDetails(httpHeaders, uriInfo);
parent.addInlineDetails(details, model);
if (details.contains("statistics")) {
addStatistics(model, entity, uriInfo);
}
parent.setPayload(model);
parent.setCertificateInfo(model);
MemoryPolicyHelper.setupMemoryBalloon(model, this);
return model;
}
private void addStatistics(VM model, org.ovirt.engine.core.common.businessentities.VM entity, UriInfo ui) {
model.setStatistics(new Statistics());
VmStatisticalQuery query = new VmStatisticalQuery(newModel(model.getId()));
List<Statistic> statistics = query.getStatistics(entity);
for (Statistic statistic : statistics) {
LinkHelper.addLinks(ui, statistic, query.getParentType());
}
model.getStatistics().getStatistics().addAll(statistics);
}
protected class UpdateParametersProvider implements
ParametersProvider<VM, org.ovirt.engine.core.common.businessentities.VM> {
@Override
public VdcActionParametersBase getParameters(VM incoming,
org.ovirt.engine.core.common.businessentities.VM entity) {
VmStatic updated = getMapper(modelType, VmStatic.class).map(incoming,
entity.getStaticData());
updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy()));
VmManagementParametersBase params = new VmManagementParametersBase(updated);
params.setApplyChangesLater(isNextRunRequested());
if (incoming.isSetPayloads()) {
if (incoming.isSetPayloads() && incoming.getPayloads().isSetPayload()) {
params.setVmPayload(parent.getPayload(incoming));
} else {
params.setClearPayload(true);
}
}
if (incoming.isSetMemoryPolicy() && incoming.getMemoryPolicy().isSetBallooning()) {
params.setBalloonEnabled(incoming.getMemoryPolicy().isBallooning());
}
if (incoming.isSetConsole() && incoming.getConsole().isSetEnabled()) {
params.setConsoleEnabled(incoming.getConsole().isEnabled());
}
if (incoming.isSetVirtioScsi()) {
params.setVirtioScsiEnabled(incoming.getVirtioScsi().isEnabled());
}
if (incoming.isSetSoundcardEnabled()) {
params.setSoundDeviceEnabled(incoming.isSoundcardEnabled());
}
if (incoming.isSetRngDevice()) {
params.setUpdateRngDevice(true);
params.setRngDevice(RngDeviceMapper.map(incoming.getRngDevice(), null));
}
DisplayHelper.setGraphicsToParams(incoming.getDisplay(), params);
if (incoming.isSetInstanceType() && (incoming.getInstanceType().isSetId() || incoming.getInstanceType().isSetName())) {
updated.setInstanceTypeId(lookupInstanceTypeId(incoming.getInstanceType()));
} else if (incoming.isSetInstanceType()) {
// this means that the instance type should be unset
updated.setInstanceTypeId(null);
}
IconHelper.setIconToParams(incoming, params);
return params;
}
}
private VDSGroup lookupCluster(Guid id) {
return getEntity(VDSGroup.class, VdcQueryType.GetVdsGroupByVdsGroupId, new IdQueryParameters(id), "GetVdsGroupByVdsGroupId");
}
private Guid lookupInstanceTypeId(Template template) {
return template.isSetId() ? asGuid(template.getId()) : lookupInstanceTypeByName(template).getId();
}
private VmTemplate lookupInstanceTypeByName(Template template) {
return getEntity(VmTemplate.class,
VdcQueryType.GetInstanceType,
new GetVmTemplateParameters(template.getName()),
"GetVmTemplate");
}
@Override
public Response cancelMigration(Action action) {
return doAction(VdcActionType.CancelMigrateVm,
new VmOperationParameterBase(guid), action);
}
public BackendVmsResource getParent() {
return parent;
}
public void setCertificateInfo(VM model) {
VdcQueryReturnValue result =
runQuery(VdcQueryType.GetVdsCertificateSubjectByVmId,
new IdQueryParameters(asGuid(model.getId())));
if (result != null && result.getSucceeded() && result.getReturnValue() != null) {
if (!model.isSetDisplay()) {
model.setDisplay(new Display());
}
model.getDisplay().setCertificate(new Certificate());
model.getDisplay().getCertificate().setSubject(result.getReturnValue().toString());
}
}
@Override
public VmReportedDevicesResource getVmReportedDevicesResource() {
return inject(new BackendVmReportedDevicesResource(guid));
}
@Override
public VmSessionsResource getVmSessionsResource() {
return inject(new BackendVmSessionsResource(guid));
}
@Override
public GraphicsConsolesResource getVmGraphicsConsolesResource() {
return inject(new BackendVmGraphicsConsolesResource(guid));
}
@Override
public Response maintenance(Action action) {
validateParameters(action, "maintenanceEnabled");
org.ovirt.engine.core.common.businessentities.VM entity =
getEntity(org.ovirt.engine.core.common.businessentities.VM.class,
VdcQueryType.GetVmByVmId,
new IdQueryParameters(guid),
id);
if (!entity.isHostedEngine()) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Moving to maintenance mode is currently only available for the VM containing the hosted engine.")
.build());
}
return doAction(VdcActionType.SetHaMaintenance,
new SetHaMaintenanceParameters(entity.getRunOnVds(),
HaMaintenanceMode.GLOBAL, action.isMaintenanceEnabled()),
action);
}
@Override
public VmNumaNodesResource getVirtualNumaNodesResource() {
return inject(new BackendVmNumaNodesResource(guid));
}
@Override
public KatelloErrataResource getKatelloErrataResource() {
return inject(new BackendVmKatelloErrataResource(id));
}
@Override
public VmHostDevicesResource getVmHostDevicesResource() {
return inject(new BackendVmHostDevicesResource(guid));
}
}
|
package com.intellij.codeInsight.daemon.impl;
import com.intellij.codeHighlighting.BackgroundEditorHighlighter;
import com.intellij.codeHighlighting.HighlightingPass;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeInsight.daemon.*;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.intention.impl.FileLevelIntentionComponent;
import com.intellij.codeInsight.intention.impl.IntentionHintComponent;
import com.intellij.codeInspection.ex.GlobalInspectionContextBase;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.ide.PowerSaveMode;
import com.intellij.ide.lightEdit.LightEditUtil;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.application.impl.NonBlockingReadActionImpl;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileEditor.impl.text.AsyncEditorLoader;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.RefreshQueueImpl;
import com.intellij.packageDependencies.DependencyValidationManager;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.*;
import com.intellij.util.concurrency.EdtExecutorService;
import com.intellij.util.io.storage.HeavyProcessLatch;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* This class also controls the auto-reparse and auto-hints.
*/
@State(name = "DaemonCodeAnalyzer", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public final class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzerEx implements PersistentStateComponent<Element>, Disposable {
private static final Logger LOG = Logger.getInstance(DaemonCodeAnalyzerImpl.class);
private static final Key<List<HighlightInfo>> FILE_LEVEL_HIGHLIGHTS = Key.create("FILE_LEVEL_HIGHLIGHTS");
private final Project myProject;
private final DaemonCodeAnalyzerSettings mySettings;
@NotNull private final PsiDocumentManager myPsiDocumentManager;
private DaemonProgressIndicator myUpdateProgress = new DaemonProgressIndicator(); //guarded by this
private final UpdateRunnable myUpdateRunnable;
// use scheduler instead of Alarm because the latter requires ModalityState.current() which is obtainable from EDT only which requires too many invokeLaters
private final ScheduledExecutorService myAlarm = EdtExecutorService.getScheduledExecutorInstance();
@NotNull
private volatile Future<?> myUpdateRunnableFuture = CompletableFuture.completedFuture(null);
private boolean myUpdateByTimerEnabled = true; // guarded by this
private final Collection<VirtualFile> myDisabledHintsFiles = new THashSet<>();
private final Collection<VirtualFile> myDisabledHighlightingFiles = new THashSet<>();
private final FileStatusMap myFileStatusMap;
private DaemonCodeAnalyzerSettings myLastSettings;
private volatile boolean myDisposed; // the only possible transition: false -> true
private volatile boolean myInitialized; // the only possible transition: false -> true
@NonNls private static final String DISABLE_HINTS_TAG = "disable_hints";
@NonNls private static final String FILE_TAG = "file";
@NonNls private static final String URL_ATT = "url";
private final PassExecutorService myPassExecutorService;
public DaemonCodeAnalyzerImpl(@NotNull Project project) {
// DependencyValidationManagerImpl adds scope listener, so, we need to force service creation
DependencyValidationManager.getInstance(project);
myProject = project;
mySettings = DaemonCodeAnalyzerSettings.getInstance();
myPsiDocumentManager = PsiDocumentManager.getInstance(myProject);
myLastSettings = ((DaemonCodeAnalyzerSettingsImpl)mySettings).clone();
myFileStatusMap = new FileStatusMap(project);
myPassExecutorService = new PassExecutorService(project);
Disposer.register(this, myPassExecutorService);
Disposer.register(this, myFileStatusMap);
//noinspection TestOnlyProblems
DaemonProgressIndicator.setDebug(LOG.isDebugEnabled());
assert !myInitialized : "Double Initializing";
Disposer.register(this, new StatusBarUpdater(project));
myInitialized = true;
myDisposed = false;
myFileStatusMap.markAllFilesDirty("DCAI init");
myUpdateRunnable = new UpdateRunnable(myProject);
Disposer.register(this, () -> {
assert myInitialized : "Disposing not initialized component";
assert !myDisposed : "Double dispose";
myUpdateRunnable.clearFieldsOnDispose();
stopProcess(false, "Dispose "+myProject);
myDisposed = true;
myLastSettings = null;
});
}
@Override
public synchronized void dispose() {
clearReferences();
}
private synchronized void clearReferences() {
myUpdateProgress = new DaemonProgressIndicator(); // leak of highlight session via user data
myUpdateRunnableFuture.cancel(true);
}
@NotNull
@TestOnly
public static List<HighlightInfo> getHighlights(@NotNull Document document, @Nullable HighlightSeverity minSeverity, @NotNull Project project) {
List<HighlightInfo> infos = new ArrayList<>();
processHighlights(document, project, minSeverity, 0, document.getTextLength(), Processors.cancelableCollectProcessor(infos));
return infos;
}
@Override
@NotNull
@TestOnly
public List<HighlightInfo> getFileLevelHighlights(@NotNull Project project, @NotNull PsiFile file) {
VirtualFile vFile = file.getViewProvider().getVirtualFile();
return Arrays.stream(FileEditorManager.getInstance(project).getEditors(vFile))
.map(fileEditor -> fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS))
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
@Override
public void cleanFileLevelHighlights(@NotNull Project project, final int group, PsiFile psiFile) {
if (psiFile == null) return;
FileViewProvider provider = psiFile.getViewProvider();
VirtualFile vFile = provider.getVirtualFile();
final FileEditorManager manager = FileEditorManager.getInstance(project);
for (FileEditor fileEditor : manager.getEditors(vFile)) {
final List<HighlightInfo> infos = fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS);
if (infos == null) continue;
List<HighlightInfo> infosToRemove = new ArrayList<>();
for (HighlightInfo info : infos) {
if (info.getGroup() == group) {
manager.removeTopComponent(fileEditor, info.fileLevelComponent);
infosToRemove.add(info);
}
}
infos.removeAll(infosToRemove);
}
}
@Override
public void addFileLevelHighlight(@NotNull final Project project,
final int group,
@NotNull final HighlightInfo info,
@NotNull final PsiFile psiFile) {
VirtualFile vFile = psiFile.getViewProvider().getVirtualFile();
final FileEditorManager manager = FileEditorManager.getInstance(project);
for (FileEditor fileEditor : manager.getEditors(vFile)) {
if (fileEditor instanceof TextEditor) {
FileLevelIntentionComponent component = new FileLevelIntentionComponent(info.getDescription(), info.getSeverity(),
info.getGutterIconRenderer(), info.quickFixActionRanges,
project, psiFile, ((TextEditor)fileEditor).getEditor(), info.getToolTip());
manager.addTopComponent(fileEditor, component);
List<HighlightInfo> fileLevelInfos = fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS);
if (fileLevelInfos == null) {
fileLevelInfos = new ArrayList<>();
fileEditor.putUserData(FILE_LEVEL_HIGHLIGHTS, fileLevelInfos);
}
info.fileLevelComponent = component;
info.setGroup(group);
fileLevelInfos.add(info);
}
}
}
@Override
@NotNull
public List<HighlightInfo> runMainPasses(@NotNull PsiFile psiFile,
@NotNull Document document,
@NotNull final ProgressIndicator progress) {
if (ApplicationManager.getApplication().isDispatchThread()) {
throw new IllegalStateException("Must not run highlighting from under EDT");
}
if (!ApplicationManager.getApplication().isReadAccessAllowed()) {
throw new IllegalStateException("Must run highlighting from under read action");
}
GlobalInspectionContextBase.assertUnderDaemonProgress();
// clear status maps to run passes from scratch so that refCountHolder won't conflict and try to restart itself on partially filled maps
myFileStatusMap.markAllFilesDirty("prepare to run main passes");
stopProcess(false, "disable background daemon");
myPassExecutorService.cancelAll(true);
final List<HighlightInfo> result;
try {
result = new ArrayList<>();
final VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile != null && !virtualFile.getFileType().isBinary()) {
List<TextEditorHighlightingPass> passes =
TextEditorHighlightingPassRegistrarEx.getInstanceEx(myProject).instantiateMainPasses(psiFile, document,
HighlightInfoProcessor.getEmpty());
passes.sort((o1, o2) -> {
if (o1 instanceof GeneralHighlightingPass) return -1;
if (o2 instanceof GeneralHighlightingPass) return 1;
return 0;
});
try {
for (TextEditorHighlightingPass pass : passes) {
pass.doCollectInformation(progress);
result.addAll(pass.getInfos());
}
}
catch (ProcessCanceledException e) {
LOG.debug("Canceled: " + progress);
throw e;
}
}
}
finally {
stopProcess(true, "re-enable background daemon after main passes run");
}
return result;
}
private volatile boolean mustWaitForSmartMode = true;
@TestOnly
public void mustWaitForSmartMode(final boolean mustWait, @NotNull Disposable parent) {
final boolean old = mustWaitForSmartMode;
mustWaitForSmartMode = mustWait;
Disposer.register(parent, () -> mustWaitForSmartMode = old);
}
@TestOnly
public void runPasses(@NotNull PsiFile file,
@NotNull Document document,
@NotNull List<? extends TextEditor> textEditors,
int @NotNull [] toIgnore,
boolean canChangeDocument,
@Nullable final Runnable callbackWhileWaiting) throws ProcessCanceledException {
assert myInitialized;
assert !myDisposed;
Application application = ApplicationManager.getApplication();
application.assertIsDispatchThread();
if (application.isWriteAccessAllowed()) {
throw new AssertionError("Must not start highlighting from within write action, or deadlock is imminent");
}
DaemonProgressIndicator.setDebug(!ApplicationInfoImpl.isInStressTest());
((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
// pump first so that queued event do not interfere
UIUtil.dispatchAllInvocationEvents();
// refresh will fire write actions interfering with highlighting
while (RefreshQueueImpl.isRefreshInProgress() || HeavyProcessLatch.INSTANCE.isRunning()) {
UIUtil.dispatchAllInvocationEvents();
}
long dstart = System.currentTimeMillis();
while (mustWaitForSmartMode && DumbService.getInstance(myProject).isDumb()) {
if (System.currentTimeMillis() > dstart + 100000) {
throw new IllegalStateException("Timeout waiting for smart mode. If you absolutely want to be dumb, please use DaemonCodeAnalyzerImpl.mustWaitForSmartMode(false).");
}
UIUtil.dispatchAllInvocationEvents();
}
UIUtil.dispatchAllInvocationEvents();
FileStatusMap fileStatusMap = getFileStatusMap();
NonBlockingReadActionImpl.waitForAsyncTaskCompletion(); // wait for async editor loading
Map<FileEditor, HighlightingPass[]> map = new HashMap<>();
for (TextEditor textEditor : textEditors) {
TextEditorBackgroundHighlighter highlighter = (TextEditorBackgroundHighlighter)textEditor.getBackgroundHighlighter();
if (highlighter == null) {
Editor editor = textEditor.getEditor();
throw new RuntimeException("Null highlighter from " + textEditor + "; loaded: " + AsyncEditorLoader.isEditorLoaded(editor));
}
final List<TextEditorHighlightingPass> passes = highlighter.getPasses(toIgnore);
HighlightingPass[] array = passes.toArray(HighlightingPass.EMPTY_ARRAY);
assert array.length != 0 : "Highlighting is disabled for the file " + file;
map.put(textEditor, array);
}
for (int ignoreId : toIgnore) {
fileStatusMap.markFileUpToDate(document, ignoreId);
}
myUpdateRunnableFuture.cancel(false);
// previous passes can be canceled but still in flight. wait for them to avoid interference
myPassExecutorService.cancelAll(false);
fileStatusMap.allowDirt(canChangeDocument);
final DaemonProgressIndicator progress = createUpdateProgress(map.keySet());
myPassExecutorService.submitPasses(map, progress);
try {
long start = System.currentTimeMillis();
while (progress.isRunning() && System.currentTimeMillis() < start + 10*60*1000) {
progress.checkCanceled();
if (callbackWhileWaiting != null) {
callbackWhileWaiting.run();
}
waitInOtherThread(50, canChangeDocument);
UIUtil.dispatchAllInvocationEvents();
Throwable savedException = PassExecutorService.getSavedException(progress);
if (savedException != null) throw savedException;
}
if (progress.isRunning() && !progress.isCanceled()) {
throw new RuntimeException("Highlighting still running after " +(System.currentTimeMillis()-start)/1000 + " seconds." +
" Still submitted passes: "+myPassExecutorService.getAllSubmittedPasses()+
" ForkJoinPool.commonPool(): "+ForkJoinPool.commonPool()+"\n"+
", ForkJoinPool.commonPool() active thread count: "+ ForkJoinPool.commonPool().getActiveThreadCount()+
", ForkJoinPool.commonPool() has queued submissions: "+ ForkJoinPool.commonPool().hasQueuedSubmissions()+
"\n"+ ThreadDumper.dumpThreadsToString());
}
HighlightingSessionImpl session = (HighlightingSessionImpl)HighlightingSessionImpl.getOrCreateHighlightingSession(file, progress, null);
if (!waitInOtherThread(60000, canChangeDocument)) {
throw new TimeoutException("Unable to complete in 60s. Thread dump:\n"+ThreadDumper.dumpThreadsToString());
}
session.waitForHighlightInfosApplied();
UIUtil.dispatchAllInvocationEvents();
UIUtil.dispatchAllInvocationEvents();
assert progress.isCanceled() && progress.isDisposed();
}
catch (Throwable e) {
if (e instanceof ExecutionException) e = e.getCause();
if (progress.isCanceled() && progress.isRunning()) {
e.addSuppressed(new RuntimeException("Daemon progress was canceled unexpectedly: " + progress));
}
ExceptionUtil.rethrow(e);
}
finally {
DaemonProgressIndicator.setDebug(false);
fileStatusMap.allowDirt(true);
progress.cancel();
waitForTermination();
}
}
@TestOnly
private boolean waitInOtherThread(int millis, boolean canChangeDocument) throws Throwable {
Disposable disposable = Disposer.newDisposable();
// last hope protection against PsiModificationTrackerImpl.incCounter() craziness (yes, Kotlin)
myProject.getMessageBus().connect(disposable).subscribe(PsiModificationTracker.TOPIC,
() -> {
throw new IllegalStateException("You must not perform PSI modifications from inside highlighting");
});
if (!canChangeDocument) {
myProject.getMessageBus().connect(disposable).subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, new DaemonListener() {
@Override
public void daemonCancelEventOccurred(@NotNull String reason) {
throw new IllegalStateException("You must not cancel daemon inside highlighting test: "+reason);
}
});
}
try {
Future<Boolean> future = ApplicationManager.getApplication().executeOnPooledThread(() -> {
try {
return myPassExecutorService.waitFor(millis);
}
catch (Throwable e) {
throw new RuntimeException(e);
}
});
return future.get();
}
finally {
Disposer.dispose(disposable);
}
}
@TestOnly
public void prepareForTest() {
setUpdateByTimerEnabled(false);
waitForTermination();
clearReferences();
}
@TestOnly
public void cleanupAfterTest() {
if (myProject.isOpen()) {
prepareForTest();
}
}
@TestOnly
public void waitForTermination() {
myPassExecutorService.cancelAll(true);
}
@Override
public void settingsChanged() {
DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance();
if (settings.isCodeHighlightingChanged(myLastSettings)) {
restart();
}
myLastSettings = ((DaemonCodeAnalyzerSettingsImpl)settings).clone();
}
@Override
public synchronized void setUpdateByTimerEnabled(boolean value) {
myUpdateByTimerEnabled = value;
stopProcess(value, "Update by timer change");
}
private final AtomicInteger myDisableCount = new AtomicInteger();
@Override
public void disableUpdateByTimer(@NotNull Disposable parentDisposable) {
setUpdateByTimerEnabled(false);
myDisableCount.incrementAndGet();
ApplicationManager.getApplication().assertIsDispatchThread();
Disposer.register(parentDisposable, () -> {
if (myDisableCount.decrementAndGet() == 0) {
setUpdateByTimerEnabled(true);
}
});
}
synchronized boolean isUpdateByTimerEnabled() {
return myUpdateByTimerEnabled;
}
@Override
public void setImportHintsEnabled(@NotNull PsiFile file, boolean value) {
VirtualFile vFile = file.getVirtualFile();
if (value) {
myDisabledHintsFiles.remove(vFile);
stopProcess(true, "Import hints change");
}
else {
myDisabledHintsFiles.add(vFile);
HintManager.getInstance().hideAllHints();
}
}
@Override
public void resetImportHintsEnabledForProject() {
myDisabledHintsFiles.clear();
}
@Override
public void setHighlightingEnabled(@NotNull PsiFile file, boolean value) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
if (value) {
myDisabledHighlightingFiles.remove(virtualFile);
}
else {
myDisabledHighlightingFiles.add(virtualFile);
}
}
@Override
public boolean isHighlightingAvailable(@Nullable PsiFile file) {
if (file == null || !file.isPhysical()) return false;
if (myDisabledHighlightingFiles.contains(PsiUtilCore.getVirtualFile(file))) return false;
if (file instanceof PsiCompiledElement) return false;
final FileType fileType = file.getFileType();
// To enable T.O.D.O. highlighting
return !fileType.isBinary();
}
@Override
public boolean isImportHintsEnabled(@NotNull PsiFile file) {
return isAutohintsAvailable(file) && !myDisabledHintsFiles.contains(file.getVirtualFile());
}
@Override
public boolean isAutohintsAvailable(PsiFile file) {
return isHighlightingAvailable(file) && !(file instanceof PsiCompiledElement);
}
@Override
public void restart() {
doRestart();
}
// return true if the progress was really canceled
boolean doRestart() {
myFileStatusMap.markAllFilesDirty("Global restart");
return stopProcess(true, "Global restart");
}
@Override
public void restart(@NotNull PsiFile file) {
Document document = myPsiDocumentManager.getCachedDocument(file);
if (document == null) return;
String reason = "Psi file restart: " + file.getName();
myFileStatusMap.markFileScopeDirty(document, new TextRange(0, document.getTextLength()), file.getTextLength(), reason);
stopProcess(true, reason);
}
@NotNull
public List<TextEditorHighlightingPass> getPassesToShowProgressFor(Document document) {
List<TextEditorHighlightingPass> allPasses = myPassExecutorService.getAllSubmittedPasses();
List<TextEditorHighlightingPass> result = new ArrayList<>(allPasses.size());
for (TextEditorHighlightingPass pass : allPasses) {
if (pass.getDocument() == document || pass.getDocument() == null) {
result.add(pass);
}
}
return result;
}
boolean isAllAnalysisFinished(@NotNull PsiFile file) {
if (myDisposed) return false;
Document document = myPsiDocumentManager.getCachedDocument(file);
return document != null &&
document.getModificationStamp() == file.getViewProvider().getModificationStamp() &&
myFileStatusMap.allDirtyScopesAreNull(document);
}
@Override
public boolean isErrorAnalyzingFinished(@NotNull PsiFile file) {
if (myDisposed) return false;
Document document = myPsiDocumentManager.getCachedDocument(file);
return document != null &&
document.getModificationStamp() == file.getViewProvider().getModificationStamp() &&
myFileStatusMap.getFileDirtyScope(document, Pass.UPDATE_ALL) == null;
}
@Override
@NotNull
public FileStatusMap getFileStatusMap() {
return myFileStatusMap;
}
public synchronized boolean isRunning() {
return !myUpdateProgress.isCanceled();
}
@TestOnly
public boolean isRunningOrPending() {
ApplicationManager.getApplication().assertIsDispatchThread();
return isRunning() || !myUpdateRunnableFuture.isDone() || GeneralHighlightingPass.isRestartPending();
}
// return true if the progress really was canceled
synchronized boolean stopProcess(boolean toRestartAlarm, @NotNull @NonNls String reason) {
boolean canceled = cancelUpdateProgress(toRestartAlarm, reason);
// optimisation: this check is to avoid too many re-schedules in case of thousands of events spikes
boolean restart = toRestartAlarm && !myDisposed && myInitialized;
if (restart && myUpdateRunnableFuture.isDone()) {
myUpdateRunnableFuture = myAlarm.schedule(myUpdateRunnable, mySettings.getAutoReparseDelay(), TimeUnit.MILLISECONDS);
}
return canceled;
}
// return true if the progress really was canceled
private synchronized boolean cancelUpdateProgress(boolean toRestartAlarm, @NotNull @NonNls String reason) {
DaemonProgressIndicator updateProgress = myUpdateProgress;
if (myDisposed) return false;
boolean wasCanceled = updateProgress.isCanceled();
if (!wasCanceled) {
PassExecutorService.log(updateProgress, null, "Cancel", reason, toRestartAlarm);
updateProgress.cancel();
myPassExecutorService.cancelAll(false);
return true;
}
return false;
}
static boolean processHighlightsNearOffset(@NotNull Document document,
@NotNull Project project,
@NotNull final HighlightSeverity minSeverity,
final int offset,
final boolean includeFixRange,
@NotNull final Processor<? super HighlightInfo> processor) {
return processHighlights(document, project, null, 0, document.getTextLength(), info -> {
if (!isOffsetInsideHighlightInfo(offset, info, includeFixRange)) return true;
int compare = info.getSeverity().compareTo(minSeverity);
return compare < 0 || processor.process(info);
});
}
@Nullable
public HighlightInfo findHighlightByOffset(@NotNull Document document, final int offset, final boolean includeFixRange) {
return findHighlightByOffset(document, offset, includeFixRange, HighlightSeverity.INFORMATION);
}
@Nullable
HighlightInfo findHighlightByOffset(@NotNull Document document,
final int offset,
final boolean includeFixRange,
@NotNull HighlightSeverity minSeverity) {
final List<HighlightInfo> foundInfoList = new SmartList<>();
processHighlightsNearOffset(document, myProject, minSeverity, offset, includeFixRange,
info -> {
if (info.getSeverity() == HighlightInfoType.ELEMENT_UNDER_CARET_SEVERITY || info.type == HighlightInfoType.TODO) {
return true;
}
if (!foundInfoList.isEmpty()) {
HighlightInfo foundInfo = foundInfoList.get(0);
int compare = foundInfo.getSeverity().compareTo(info.getSeverity());
if (compare < 0) {
foundInfoList.clear();
}
else if (compare > 0) {
return true;
}
}
foundInfoList.add(info);
return true;
});
if (foundInfoList.isEmpty()) return null;
if (foundInfoList.size() == 1) return foundInfoList.get(0);
return HighlightInfoComposite.create(foundInfoList);
}
private static boolean isOffsetInsideHighlightInfo(int offset, @NotNull HighlightInfo info, boolean includeFixRange) {
RangeHighlighterEx highlighter = info.getHighlighter();
if (highlighter == null || !highlighter.isValid()) return false;
int startOffset = highlighter.getStartOffset();
int endOffset = highlighter.getEndOffset();
if (startOffset <= offset && offset <= endOffset) {
return true;
}
if (!includeFixRange) return false;
RangeMarker fixMarker = info.fixMarker;
if (fixMarker != null) { // null means its range is the same as highlighter
if (!fixMarker.isValid()) return false;
startOffset = fixMarker.getStartOffset();
endOffset = fixMarker.getEndOffset();
return startOffset <= offset && offset <= endOffset;
}
return false;
}
@NotNull
public static List<LineMarkerInfo<?>> getLineMarkers(@NotNull Document document, @NotNull Project project) {
ApplicationManager.getApplication().assertIsDispatchThread();
List<LineMarkerInfo<?>> result = new ArrayList<>();
LineMarkersUtil.processLineMarkers(project, document, new TextRange(0, document.getTextLength()), -1,
new CommonProcessors.CollectProcessor<>(result));
return result;
}
@Nullable
public IntentionHintComponent getLastIntentionHint() {
return ((IntentionsUIImpl)IntentionsUI.getInstance(myProject)).getLastIntentionHint();
}
@NotNull
@Override
public Element getState() {
Element state = new Element("state");
if (myDisabledHintsFiles.isEmpty()) {
return state;
}
List<String> array = new SmartList<>();
for (VirtualFile file : myDisabledHintsFiles) {
if (file.isValid()) {
array.add(file.getUrl());
}
}
if (!array.isEmpty()) {
Collections.sort(array);
Element disableHintsElement = new Element(DISABLE_HINTS_TAG);
state.addContent(disableHintsElement);
for (String url : array) {
disableHintsElement.addContent(new Element(FILE_TAG).setAttribute(URL_ATT, url));
}
}
return state;
}
@Override
public void loadState(@NotNull Element state) {
myDisabledHintsFiles.clear();
Element element = state.getChild(DISABLE_HINTS_TAG);
if (element != null) {
for (Element e : element.getChildren(FILE_TAG)) {
String url = e.getAttributeValue(URL_ATT);
if (url != null) {
VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
if (file != null) {
myDisabledHintsFiles.add(file);
}
}
}
}
}
// made this class static and fields cleareable to avoid leaks when this object stuck in invokeLater queue
private static class UpdateRunnable implements Runnable {
private Project myProject;
private UpdateRunnable(@NotNull Project project) {
myProject = project;
}
@Override
public void run() {
ApplicationManager.getApplication().assertIsDispatchThread();
Project project = myProject;
DaemonCodeAnalyzerImpl dca;
if (project == null ||
!project.isInitialized() ||
project.isDisposed() ||
PowerSaveMode.isEnabled() ||
LightEditUtil.isLightEditProject(project) ||
(dca = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project)).myDisposed) {
return;
}
final Collection<FileEditor> activeEditors = dca.getSelectedEditors();
boolean updateByTimerEnabled = dca.isUpdateByTimerEnabled();
PassExecutorService.log(dca.getUpdateProgress(), null, "Update Runnable. myUpdateByTimerEnabled:",
updateByTimerEnabled, " something disposed:",
PowerSaveMode.isEnabled() || !myProject.isInitialized(), " activeEditors:",
activeEditors);
if (!updateByTimerEnabled) return;
if (activeEditors.isEmpty()) return;
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
// makes no sense to start from within write action, will cancel anyway
// we'll restart when the write action finish
return;
}
if (dca.myPsiDocumentManager.hasUncommitedDocuments()) {
// restart when everything committed
dca.myPsiDocumentManager.performLaterWhenAllCommitted(this);
return;
}
if (RefResolveService.ENABLED &&
!RefResolveService.getInstance(myProject).isUpToDate() &&
RefResolveService.getInstance(myProject).getQueueSize() == 1) {
return; // if the user have just typed in something, wait until the file is re-resolved
// (or else it will blink like crazy since unused symbols calculation depends on resolve service)
}
Map<FileEditor, HighlightingPass[]> passes = new THashMap<>(activeEditors.size());
for (FileEditor fileEditor : activeEditors) {
BackgroundEditorHighlighter highlighter = fileEditor.getBackgroundHighlighter();
if (highlighter != null) {
HighlightingPass[] highlightingPasses = highlighter.createPassesForEditor();
passes.put(fileEditor, highlightingPasses);
}
}
// wait for heavy processing to stop, re-schedule daemon but not too soon
if (HeavyProcessLatch.INSTANCE.isRunning()) {
boolean hasPasses = false;
for (Map.Entry<FileEditor, HighlightingPass[]> entry : passes.entrySet()) {
HighlightingPass[] filtered = Arrays.stream(entry.getValue()).filter(DumbService::isDumbAware).toArray(HighlightingPass[]::new);
entry.setValue(filtered);
hasPasses |= filtered.length != 0;
}
if (!hasPasses) {
HeavyProcessLatch.INSTANCE.executeOutOfHeavyProcess(() ->
dca.stopProcess(true, "re-scheduled to execute after heavy processing finished"));
return;
}
}
// cancel all after calling createPasses() since there are perverts {@link com.intellij.util.xml.ui.DomUIFactoryImpl} who are changing PSI there
dca.cancelUpdateProgress(true, "Cancel by alarm");
dca.myUpdateRunnableFuture.cancel(false);
DaemonProgressIndicator progress = dca.createUpdateProgress(passes.keySet());
dca.myPassExecutorService.submitPasses(passes, progress);
}
private void clearFieldsOnDispose() {
myProject = null;
}
}
@NotNull
private synchronized DaemonProgressIndicator createUpdateProgress(@NotNull Collection<FileEditor> fileEditors) {
DaemonProgressIndicator old = myUpdateProgress;
if (!old.isCanceled()) {
old.cancel();
}
DaemonProgressIndicator progress = new MyDaemonProgressIndicator(myProject, fileEditors);
progress.setModalityProgress(null);
progress.start();
myProject.getMessageBus().syncPublisher(DAEMON_EVENT_TOPIC).daemonStarting(fileEditors);
myUpdateProgress = progress;
return progress;
}
private static class MyDaemonProgressIndicator extends DaemonProgressIndicator {
private final Project myProject;
private Collection<FileEditor> myFileEditors;
MyDaemonProgressIndicator(@NotNull Project project, @NotNull Collection<FileEditor> fileEditors) {
myFileEditors = fileEditors;
myProject = project;
}
@Override
public void stopIfRunning() {
super.stopIfRunning();
myProject.getMessageBus().syncPublisher(DAEMON_EVENT_TOPIC).daemonFinished(myFileEditors);
myFileEditors = null;
HighlightingSessionImpl.clearProgressIndicator(this);
}
}
@Override
public void autoImportReferenceAtCursor(@NotNull Editor editor, @NotNull PsiFile file) {
for (ReferenceImporter importer : ReferenceImporter.EP_NAME.getExtensionList()) {
if (importer.autoImportReferenceAtCursor(editor, file)) break;
}
}
@TestOnly
@NotNull
public synchronized DaemonProgressIndicator getUpdateProgress() {
return myUpdateProgress;
}
@NotNull
private Collection<FileEditor> getSelectedEditors() {
Application app = ApplicationManager.getApplication();
app.assertIsDispatchThread();
// editors in modal context
EditorTracker editorTracker = myProject.getServiceIfCreated(EditorTracker.class);
List<Editor> editors = editorTracker == null ? Collections.emptyList() : editorTracker.getActiveEditors();
Collection<FileEditor> activeTextEditors;
if (editors.isEmpty()) {
activeTextEditors = Collections.emptyList();
}
else {
activeTextEditors = new THashSet<>(editors.size());
for (Editor editor : editors) {
if (editor.isDisposed()) continue;
TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
activeTextEditors.add(textEditor);
}
}
if (app.getCurrentModalityState() != ModalityState.NON_MODAL) {
return activeTextEditors;
}
Collection<FileEditor> result = new THashSet<>();
Collection<VirtualFile> files = new THashSet<>(activeTextEditors.size());
if (!app.isUnitTestMode()) {
// editors in tabs
FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(myProject);
for (FileEditor tabEditor : fileEditorManager.getSelectedEditors()) {
if (!tabEditor.isValid()) continue;
VirtualFile file = fileEditorManager.getFile(tabEditor);
if (file != null) {
files.add(file);
}
result.add(tabEditor);
}
}
// do not duplicate documents
if (!activeTextEditors.isEmpty()) {
FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(myProject);
for (FileEditor fileEditor : activeTextEditors) {
VirtualFile file = fileEditorManager.getFile(fileEditor);
if (file != null && files.contains(file)) {
continue;
}
result.add(fileEditor);
}
}
return result;
}
}
|
package org.eclipse.emf.emfstore.internal.client.configuration;
import java.io.File;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPoint;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPointException;
import org.eclipse.emf.emfstore.internal.client.model.util.DefaultWorkspaceLocationProvider;
import org.eclipse.emf.emfstore.internal.common.model.util.ModelUtil;
import org.eclipse.emf.emfstore.server.ESLocationProvider;
/**
* Contains configuration options and information about the workspace related files
* used by the client.
*
* @author emueller
* @author ovonwesen
* @author mkoegel
*/
public class FileInfo {
/**
* Prefix used for project spaces.
*/
public static final String PROJECT_SPACE_DIR_PREFIX = "ps-";
private static ESLocationProvider locationProvider;
private static final String PLUGIN_BASEDIR = "pluginData";
private static final String ERROR_DIAGNOSIS_DIR_NAME = "errorLog";
private static final String MODEL_VERSION_FILENAME = "modelReleaseNumber";
/**
* Returns the registered {@link ESLocationProvider} or if not existent, the
* {@link DefaultWorkspaceLocationProvider}.
*
* @return workspace location provider
*/
public ESLocationProvider getLocationProvider() {
if (locationProvider == null) {
try {
// TODO EXPT PRIO
locationProvider = new ESExtensionPoint("org.eclipse.emf.emfstore.client.workspaceLocationProvider")
.setThrowException(true).getClass("providerClass", ESLocationProvider.class);
} catch (final ESExtensionPointException e) {
ModelUtil.logInfo(e.getMessage());
final String message = "Error while instantiating location provider or none configured, switching to default location!";
ModelUtil.logInfo(message);
}
if (locationProvider == null) {
locationProvider = new DefaultWorkspaceLocationProvider();
}
}
return locationProvider;
}
/**
* Gets the Workspace directory with an pending {@link File#separatorChar} at the end.
*
* @return the workspace directory path string
*/
public String getWorkspaceDirectory() {
final String workspaceDirectory = getLocationProvider().getWorkspaceDirectory();
final File workspace = new File(workspaceDirectory);
if (!workspace.exists()) {
workspace.mkdirs();
}
if (!workspaceDirectory.endsWith(File.separator)) {
return workspaceDirectory + File.separatorChar;
}
return workspaceDirectory;
}
/**
* Return the path of the plugin data directory inside the EMFStore
* workspace (trailing file separator included).
*
* @return the plugin data directory absolute path as string
*/
public String getPluginDataBaseDirectory() {
return getWorkspaceDirectory() + PLUGIN_BASEDIR + File.separatorChar;
}
/**
* Get the Workspace file path.
*
* @return the workspace file path string
*/
public String getWorkspacePath() {
return getWorkspaceDirectory() + "workspace.ucw";
}
/**
* Returns the directory that is used for error logging.<br/>
* If the directory does not exist it will be created. Upon exit of the JVM it will be deleted.
*
* @return the path to the error log directory
*/
public String getErrorLogDirectory() {
final String workspaceDirectory = getWorkspaceDirectory();
final File errorDiagnosisDir = new File(StringUtils.join(
Arrays.asList(workspaceDirectory, ERROR_DIAGNOSIS_DIR_NAME),
File.separatorChar));
if (!errorDiagnosisDir.exists()) {
errorDiagnosisDir.mkdir();
errorDiagnosisDir.deleteOnExit();
}
return errorDiagnosisDir.getAbsolutePath();
}
/**
* Return the name of the model release number file. This file identifies
* the release number of the model in the workspace.
*
* @return the file name
*/
public String getModelReleaseNumberFileName() {
return getWorkspaceDirectory() + MODEL_VERSION_FILENAME;
}
/**
* Return the prefix of the project space directory.
*
* @return the prefix
*/
public String getProjectSpaceDirectoryPrefix() {
return PROJECT_SPACE_DIR_PREFIX;
}
}
|
package com.intellij.refactoring.copy;
import com.intellij.CommonBundle;
import com.intellij.ide.CopyPasteDelegator;
import com.intellij.ide.scratch.ScratchFileService;
import com.intellij.ide.util.EditorHelper;
import com.intellij.ide.util.PlatformPackageUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingRegistry;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class CopyFilesOrDirectoriesHandler extends CopyHandlerDelegateBase {
private static final Logger LOG = Logger.getInstance("com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler");
@Override
public boolean canCopy(PsiElement[] elements, boolean fromUpdate) {
Set<String> names = new HashSet<>();
for (PsiElement element : elements) {
if (!(element instanceof PsiDirectory || element instanceof PsiFile)) return false;
if (!element.isValid()) return false;
if (element instanceof PsiCompiledFile) return false;
String name = ((PsiFileSystemItem) element).getName();
if (names.contains(name)) {
return false;
}
names.add(name);
}
if (fromUpdate) return elements.length > 0;
PsiElement[] filteredElements = PsiTreeUtil.filterAncestors(elements);
return filteredElements.length == elements.length;
}
@Override
public void doCopy(final PsiElement[] elements, PsiDirectory defaultTargetDirectory) {
if (defaultTargetDirectory == null) {
defaultTargetDirectory = getCommonParentDirectory(elements);
}
Project project = defaultTargetDirectory != null ? defaultTargetDirectory.getProject() : elements [0].getProject();
if (defaultTargetDirectory != null) {
defaultTargetDirectory = resolveDirectory(defaultTargetDirectory);
if (defaultTargetDirectory == null) return;
}
defaultTargetDirectory = tryNotNullizeDirectory(project, defaultTargetDirectory);
copyAsFiles(elements, defaultTargetDirectory, project);
}
@Nullable
private static PsiDirectory tryNotNullizeDirectory(@NotNull Project project, @Nullable PsiDirectory defaultTargetDirectory) {
if (defaultTargetDirectory == null || ScratchFileService.isInScratchRoot(defaultTargetDirectory.getVirtualFile())) {
VirtualFile root = ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
if (root == null) root = project.getBaseDir();
if (root == null) root = VfsUtil.getUserHomeDir();
defaultTargetDirectory = root != null ? PsiManager.getInstance(project).findDirectory(root) : null;
if (defaultTargetDirectory == null) {
LOG.warn("No directory found for project: " + project.getName() +", root: " + root);
}
}
return defaultTargetDirectory;
}
public static void copyAsFiles(PsiElement[] elements, @Nullable PsiDirectory defaultTargetDirectory, Project project) {
doCopyAsFiles(elements, defaultTargetDirectory, project);
}
private static void doCopyAsFiles(PsiElement[] elements, @Nullable PsiDirectory defaultTargetDirectory, Project project) {
PsiDirectory targetDirectory;
String newName;
boolean openInEditor;
VirtualFile[] files = Arrays.stream(elements).map(el -> ((PsiFileSystemItem)el).getVirtualFile()).toArray(VirtualFile[]::new);
if (ApplicationManager.getApplication().isUnitTestMode()) {
targetDirectory = defaultTargetDirectory;
newName = null;
openInEditor = true;
}
else {
CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(elements, defaultTargetDirectory, project, false);
if (dialog.showAndGet()) {
newName = elements.length == 1 ? dialog.getNewName() : null;
targetDirectory = dialog.getTargetDirectory();
openInEditor = dialog.openInEditor();
}
else {
return;
}
}
if (targetDirectory != null) {
PsiManager manager = PsiManager.getInstance(project);
try {
for (VirtualFile file : files) {
if (file.isDirectory()) {
PsiFileSystemItem psiElement = manager.findDirectory(file);
MoveFilesOrDirectoriesUtil.checkIfMoveIntoSelf(psiElement, targetDirectory);
}
}
}
catch (IncorrectOperationException e) {
CommonRefactoringUtil.showErrorHint(project, null, e.getMessage(), CommonBundle.getErrorTitle(), null);
return;
}
CommandProcessor.getInstance().executeCommand(project, () -> copyImpl(files, newName, targetDirectory, false, openInEditor),
RefactoringBundle.message("copy.handler.copy.files.directories"), null);
}
}
@Override
public void doClone(final PsiElement element) {
doCloneFile(element);
}
public static void doCloneFile(PsiElement element) {
PsiDirectory targetDirectory;
if (element instanceof PsiDirectory) {
targetDirectory = ((PsiDirectory)element).getParentDirectory();
}
else {
targetDirectory = PlatformPackageUtil.getDirectory(element);
}
targetDirectory = tryNotNullizeDirectory(element.getProject(), targetDirectory);
if (targetDirectory == null) return;
PsiElement[] elements = {element};
VirtualFile file = ((PsiFileSystemItem)element).getVirtualFile();
CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(elements, null, element.getProject(), true);
if (dialog.showAndGet()) {
String newName = dialog.getNewName();
copyImpl(new VirtualFile[] {file}, newName, targetDirectory, true, true);
}
}
@Nullable
private static PsiDirectory getCommonParentDirectory(PsiElement[] elements){
PsiDirectory result = null;
for (PsiElement element : elements) {
PsiDirectory directory;
if (element instanceof PsiDirectory) {
directory = (PsiDirectory)element;
directory = directory.getParentDirectory();
}
else if (element instanceof PsiFile) {
directory = PlatformPackageUtil.getDirectory(element);
}
else {
throw new IllegalArgumentException("unexpected element " + element);
}
if (directory == null) continue;
if (result == null) {
result = directory;
}
else {
if (PsiTreeUtil.isAncestor(directory, result, true)) {
result = directory;
}
}
}
return result;
}
/**
* @param files
* @param newName can be not null only if elements.length == 1
* @param targetDirectory
* @param openInEditor
*/
private static void copyImpl(@NotNull final VirtualFile[] files,
@Nullable final String newName,
@NotNull final PsiDirectory targetDirectory,
final boolean doClone,
final boolean openInEditor) {
if (doClone && files.length != 1) {
throw new IllegalArgumentException("invalid number of elements to clone:" + files.length);
}
if (newName != null && files.length != 1) {
throw new IllegalArgumentException("no new name should be set; number of elements is: " + files.length);
}
final Project project = targetDirectory.getProject();
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, Collections.singleton(targetDirectory), true)) {
return;
}
String title = RefactoringBundle.message(doClone ? "copy,handler.clone.files.directories" : "copy.handler.copy.files.directories");
try {
PsiFile firstFile = null;
final int[] choice = files.length > 1 || files[0].isDirectory() ? new int[]{-1} : null;
PsiManager manager = PsiManager.getInstance(project);
for (VirtualFile file : files) {
PsiElement psiElement = file.isDirectory() ? manager.findDirectory(file) : manager.findFile(file);
if (psiElement == null) {
LOG.info("invalid file: " + file.getExtension());
continue;
}
PsiFile f = copyToDirectory((PsiFileSystemItem)psiElement, newName, targetDirectory, choice, title);
if (firstFile == null) {
firstFile = f;
}
}
if (firstFile != null && openInEditor) {
CopyHandler.updateSelectionInActiveProjectView(firstFile, project, doClone);
if (!(firstFile instanceof PsiBinaryFile)) {
EditorHelper.openInEditor(firstFile);
ToolWindowManager.getInstance(project).activateEditorComponent();
}
}
}
catch (final IncorrectOperationException | IOException ex) {
Messages.showErrorDialog(project, ex.getMessage(), RefactoringBundle.message("error.title"));
}
}
/**
* @param elementToCopy PsiFile or PsiDirectory
* @param newName can be not null only if elements.length == 1
* @return first copied PsiFile (recursively); null if no PsiFiles copied
*/
@Nullable
public static PsiFile copyToDirectory(@NotNull PsiFileSystemItem elementToCopy,
@Nullable String newName,
@NotNull PsiDirectory targetDirectory) throws IncorrectOperationException, IOException {
return copyToDirectory(elementToCopy, newName, targetDirectory, null, null);
}
/**
* @param elementToCopy PsiFile or PsiDirectory
* @param newName can be not null only if elements.length == 1
* @param choice a horrible way to pass/keep user preference
* @return first copied PsiFile (recursively); null if no PsiFiles copied
*/
@Nullable
public static PsiFile copyToDirectory(@NotNull PsiFileSystemItem elementToCopy,
@Nullable String newName,
@NotNull PsiDirectory targetDirectory,
@Nullable int[] choice,
@Nullable String title) throws IncorrectOperationException, IOException {
if (elementToCopy instanceof PsiFile) {
PsiFile file = (PsiFile)elementToCopy;
String name = newName == null ? file.getName() : newName;
if (checkFileExist(targetDirectory, choice, file, name, "Copy")) return null;
return WriteCommandAction.writeCommandAction(targetDirectory.getProject()).withName(title)
.compute(() -> targetDirectory.copyFileFrom(name, file));
}
else if (elementToCopy instanceof PsiDirectory) {
PsiDirectory directory = (PsiDirectory)elementToCopy;
if (directory.equals(targetDirectory)) {
return null;
}
if (newName == null) newName = directory.getName();
final PsiDirectory existing = targetDirectory.findSubdirectory(newName);
final PsiDirectory subdirectory;
if (existing == null) {
String finalNewName = newName;
subdirectory = WriteCommandAction.writeCommandAction(targetDirectory.getProject()).withName(title)
.compute(() -> targetDirectory.createSubdirectory(finalNewName));
}
else {
subdirectory = existing;
}
EncodingRegistry.doActionAndRestoreEncoding(directory.getVirtualFile(),
(ThrowableComputable<VirtualFile, IOException>)() -> subdirectory.getVirtualFile());
PsiFile firstFile = null;
Project project = directory.getProject();
PsiManager manager = PsiManager.getInstance(project);
VirtualFile[] children = directory.getVirtualFile().getChildren();
for (VirtualFile file : children) {
PsiFileSystemItem item = file.isDirectory() ? manager.findDirectory(file) : manager.findFile(file);
if (item == null) {
LOG.info("Invalidated item: " + file.getExtension());
continue;
}
PsiFile f = copyToDirectory(item, item.getName(), subdirectory, choice, title);
if (firstFile == null) {
firstFile = f;
}
}
return firstFile;
}
else {
throw new IllegalArgumentException("unexpected elementToCopy: " + elementToCopy);
}
}
public static boolean checkFileExist(@Nullable PsiDirectory targetDirectory, int[] choice, PsiFile file, String name, String title) {
if (targetDirectory == null) return false;
final PsiFile existing = targetDirectory.findFile(name);
if (existing != null && !existing.equals(file)) {
int selection;
if (choice == null || choice[0] == -1) {
String message = String.format("File '%s' already exists in directory '%s'", name, targetDirectory.getVirtualFile().getPath());
String[] options = choice == null ? new String[]{"Overwrite", "Skip"}
: new String[]{"Overwrite", "Skip", "Overwrite for all", "Skip for all"};
selection = Messages.showDialog(message, title, options, 0, Messages.getQuestionIcon());
}
else {
selection = choice[0];
}
if (choice != null && selection > 1) {
choice[0] = selection % 2;
selection = choice[0];
}
if (selection == 0 && file != existing) {
WriteCommandAction.writeCommandAction(targetDirectory.getProject())
.withName(title)
.run(() -> existing.delete());
}
else {
return true;
}
}
return false;
}
@Nullable
protected static PsiDirectory resolveDirectory(@NotNull PsiDirectory defaultTargetDirectory) {
final Project project = defaultTargetDirectory.getProject();
final Boolean showDirsChooser = defaultTargetDirectory.getCopyableUserData(CopyPasteDelegator.SHOW_CHOOSER_KEY);
if (showDirsChooser != null && showDirsChooser.booleanValue()) {
final PsiDirectoryContainer directoryContainer =
PsiDirectoryFactory.getInstance(project).getDirectoryContainer(defaultTargetDirectory);
if (directoryContainer == null) {
return defaultTargetDirectory;
}
return MoveFilesOrDirectoriesUtil.resolveToDirectory(project, directoryContainer);
}
return defaultTargetDirectory;
}
}
|
package uk.nhs.careconnect.ri.database.entity.graphDefinition;
import org.hl7.fhir.dstu3.model.ResourceType;
import uk.nhs.careconnect.ri.database.entity.BaseResource;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name="GraphDefinitionLinkTarget", uniqueConstraints= @UniqueConstraint(name="PK_GRAPH_TARGET_LINK", columnNames={"GRAPH_LINK_TARGET_ID"})
,indexes = {}
)
public class GraphDefinitionLinkTarget extends BaseResource {
public GraphDefinitionLinkTarget() {
}
private static final int MAX_DESC_LENGTH = 4096;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name= "GRAPH_LINK_TARGET_ID")
private Long graphDefinitionLinkTarget;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name = "GRAPH_LINK_ID",foreignKey= @ForeignKey(name="FK_GRAPH_LINK_TARGET_ITEM_ID"))
private GraphDefinitionLink graphDefinitionLink;
@Column(name="RESOURCE_TYPE")
String type;
@Column(name= "PARAMS")
private String params;
@Column(name = "PROFILE")
private String profile;
@Column(name="DESCRIPTION",length = MAX_DESC_LENGTH,nullable = true)
private String description;
@OneToMany(mappedBy="graphDefinitionLinkTarget", targetEntity=GraphDefinitionLink.class)
//@OrderBy(value = "linkId ASC")
private Set<GraphDefinitionLink> links = new HashSet<>();
@OneToMany(mappedBy="graphDefinitionLinkTarget", targetEntity=GraphDefinitionLinkTargetCompartment.class)
private Set<GraphDefinitionLinkTargetCompartment> compartments = new HashSet<>();
public static int getMaxDescLength() {
return MAX_DESC_LENGTH;
}
@Override
public Long getId() {
return null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getGraphDefinitionLinkTarget() {
return graphDefinitionLinkTarget;
}
public void setGraphDefinitionLinkTarget(Long graphDefinitionLinkTarget) {
this.graphDefinitionLinkTarget = graphDefinitionLinkTarget;
}
public GraphDefinitionLink getGraphDefinitionLink() {
return graphDefinitionLink;
}
public void setGraphDefinitionLink(GraphDefinitionLink graphDefinitionLink) {
this.graphDefinitionLink = graphDefinitionLink;
}
public Set<GraphDefinitionLink> getLinks() {
return links;
}
public void setLinks(Set<GraphDefinitionLink> links) {
this.links = links;
}
public Set<GraphDefinitionLinkTargetCompartment> getCompartments() {
return compartments;
}
public void setCompartments(Set<GraphDefinitionLinkTargetCompartment> compartments) {
this.compartments = compartments;
}
}
|
package uk.nhs.careconnect.ri.entity.practitioner;
import org.apache.commons.collections4.Transformer;
import uk.nhs.careconnect.ri.model.practitioner.PractitionerDetails;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PractitionerEntityToObjectTransformer implements Transformer<PractitionerEntity, PractitionerDetails> {
@Override
public PractitionerDetails transform(final PractitionerEntity practitionerEntity) {
PractitionerDetails practitioner = new PractitionerDetails();
List<String> roleIds = Arrays.asList(practitionerEntity.getRoleIds().split("\\|"))
.stream()
.filter(roleId -> !roleId.isEmpty())
.collect(Collectors.toList());
practitioner.setId(practitionerEntity.getId());
practitioner.setUserId(practitionerEntity.getUserId());
practitioner.setRoleIds(roleIds);
practitioner.setNameFamily(practitionerEntity.getNameFamily());
practitioner.setNameGiven(practitionerEntity.getNameGiven());
practitioner.setNamePrefix(practitionerEntity.getNamePrefix());
practitioner.setGender(practitionerEntity.getGender());
practitioner.setOrganizationId(practitionerEntity.getOrganizationId());
practitioner.setRoleCode(practitionerEntity.getRoleCode());
practitioner.setRoleDisplay(practitionerEntity.getRoleDisplay());
practitioner.setComCode(practitionerEntity.getComCode());
practitioner.setComDisplay(practitionerEntity.getComDisplay());
practitioner.setLastUpdated(practitionerEntity.getLastUpdated());
return practitioner;
}
}
|
package com.intellij.testFramework.propertyBased;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.IntentionActionDelegate;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.QuickFixWrapper;
import com.intellij.codeInspection.ex.ToolsImpl;
import com.intellij.history.Label;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryException;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.RunAll;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import com.intellij.util.containers.SoftFactoryMap;
import com.intellij.util.containers.TreeTraversal;
import com.intellij.util.ui.UIUtil;
import gnu.trove.TObjectLongHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jetCheck.GenerationEnvironment;
import org.jetbrains.jetCheck.Generator;
import org.jetbrains.jetCheck.ImperativeCommand;
import org.jetbrains.jetCheck.PropertyChecker;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* @author peter
*/
public final class MadTestingUtil {
private static final Logger LOG = Logger.getInstance(MadTestingUtil.class);
private static final boolean USE_ROULETTE_WHEEL = true;
public static void restrictChangesToDocument(Document document, Runnable r) {
letSaveAllDocumentsPassIfAny();
watchDocumentChanges(r::run, event -> {
Document changed = event.getDocument();
if (changed != document) {
VirtualFile file = FileDocumentManager.getInstance().getFile(changed);
if (file != null && file.isInLocalFileSystem()) {
throw new AssertionError("Unexpected document change: " + changed);
}
}
});
}
//for possible com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl.saveAllDocumentsLater
private static void letSaveAllDocumentsPassIfAny() {
UIUtil.dispatchAllInvocationEvents();
}
public static void prohibitDocumentChanges(Runnable r) {
letSaveAllDocumentsPassIfAny();
watchDocumentChanges(r::run, event -> {
Document changed = event.getDocument();
VirtualFile file = FileDocumentManager.getInstance().getFile(changed);
if (file != null && file.isInLocalFileSystem()) {
throw new AssertionError("Unexpected document change: " + changed);
}
});
}
private static <E extends Throwable> void watchDocumentChanges(ThrowableRunnable<E> r, Consumer<? super DocumentEvent> eventHandler) throws E {
Disposable disposable = Disposer.newDisposable();
EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new DocumentListener() {
@Override
public void documentChanged(@NotNull DocumentEvent event) {
eventHandler.accept(event);
}
}, disposable);
try {
r.run();
} finally {
Disposer.dispose(disposable);
}
}
public static void changeAndRevert(Project project, Runnable r) {
Label label = LocalHistory.getInstance().putUserLabel(project, "changeAndRevert");
boolean failed = false;
try {
r.run();
}
catch (Throwable e) {
failed = true;
throw e;
}
finally {
restoreEverything(label, failed, project);
}
}
private static void restoreEverything(Label label, boolean failed, Project project) {
try {
WriteAction.run(() -> {
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
new RunAll(
() -> PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(),
() -> FileEditorManagerEx.getInstanceEx(project).closeAllFiles(),
() -> FileDocumentManager.getInstance().saveAllDocuments(),
() -> revertVfs(label, project),
() -> documentManager.commitAllDocuments(),
() -> UsefulTestCase.assertEmpty(documentManager.getUncommittedDocuments()),
() -> UsefulTestCase.assertEmpty(FileDocumentManager.getInstance().getUnsavedDocuments())
).run();
});
}
catch (Throwable e) {
if (failed) {
LOG.info("Exceptions while restoring state", e);
} else {
throw e;
}
}
}
private static void revertVfs(Label label, Project project) throws LocalHistoryException {
watchDocumentChanges(() -> label.revert(project, PlatformTestUtil.getOrCreateProjectBaseDir(project)),
__ -> {
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
if (documentManager.getUncommittedDocuments().length > 3) {
documentManager.commitAllDocuments();
}
});
}
/**
* Enables all inspections in the test project profile except for "HighlightVisitorInternal" and other passed inspections.<p>
*
* "HighlightVisitorInternal" inspection has error-level by default and highlights the first token from erroneous range,
* which is not very stable and also masks other warning-level inspections available on the same token.
*
* @param except short names of inspections to disable
*/
public static void enableAllInspections(@NotNull Project project, String... except) {
InspectionProfileImpl.INIT_INSPECTIONS = true;
InspectionProfileImpl profile = new InspectionProfileImpl("allEnabled");
profile.enableAllTools(project);
disableInspection(project, profile, "HighlightVisitorInternal");
for (String shortId : except) {
disableInspection(project, profile, shortId);
}
// instantiate all tools to avoid extension loading in inconvenient moment
profile.getAllEnabledInspectionTools(project).forEach(state -> state.getTool().getTool());
ProjectInspectionProfileManager manager = (ProjectInspectionProfileManager)InspectionProjectProfileManager.getInstance(project);
manager.addProfile(profile);
InspectionProfileImpl prev = manager.getCurrentProfile();
manager.setCurrentProfile(profile);
Disposer.register(((ProjectEx)project).getEarlyDisposable(), () -> {
InspectionProfileImpl.INIT_INSPECTIONS = false;
manager.setCurrentProfile(prev);
manager.deleteProfile(profile);
});
}
private static void disableInspection(Project project, InspectionProfileImpl profile, String shortId) {
ToolsImpl tools = profile.getToolsOrNull(shortId, project);
if (tools != null) {
tools.setEnabled(false);
}
}
private static Generator<File> randomFiles(String rootPath, FileFilter fileFilter) {
return randomFiles(rootPath, fileFilter, USE_ROULETTE_WHEEL);
}
private static Generator<File> randomFiles(String rootPath,
FileFilter fileFilter,
boolean useRouletteWheel) {
FileFilter interestingIdeaFiles = child -> {
String name = child.getName();
if (name.startsWith(".")) return false;
if (child.isDirectory()) {
return shouldGoInsiderDir(name);
}
return !FileTypeManager.getInstance().getFileTypeByFileName(name).isBinary() &&
fileFilter.accept(child) &&
child.length() < 500_000;
};
File root = new File(rootPath);
Function<GenerationEnvironment, File> generator =
useRouletteWheel ? new RouletteWheelFileGenerator(root, interestingIdeaFiles) : new FileGenerator(root, interestingIdeaFiles);
return Generator.from(generator)
.suchThat(new Predicate<>() {
@Override
public boolean test(File file) {
return file != null;
}
@Override
public String toString() {
return "can find a file under " + rootPath + " satisfying given filters";
}
})
.noShrink();
}
/**
* Finds files under {@code rootPath} (e.g. test data root) satisfying {@code fileFilter condition} (e.g. correct extension) and uses {@code actions} to generate actions on those files (e.g. invoke completion/intentions or random editing).
* Almost: the files with same paths and contents are created inside the test project, then the actions are executed on them.
* Note that the test project contains only one file at each moment, so it's best to test actions that don't require much environment.
*/
@NotNull
public static Supplier<MadTestingAction> actionsOnFileContents(CodeInsightTestFixture fixture, String rootPath,
FileFilter fileFilter,
Function<? super PsiFile, ? extends Generator<? extends MadTestingAction>> actions) {
return performOnFileContents(fixture, rootPath, fileFilter, (env, vFile) ->
env.executeCommands(Generator.from(data -> data.generate(actions.apply(fixture.getPsiManager().findFile(vFile))))));
}
/**
* Finds files under {@code rootPath} (e.g. test data root) satisfying {@code fileFilter condition} (e.g. correct extension) and invokes {@code action} on those files.
* Almost: the files with same paths and contents are created inside the test project, then the actions are executed on them.
* Note that the test project contains only one file at each moment, so it's best to test actions that don't require much environment.
*/
@NotNull
public static Supplier<MadTestingAction> performOnFileContents(CodeInsightTestFixture fixture,
String rootPath,
FileFilter fileFilter,
BiConsumer<? super ImperativeCommand.Environment, ? super VirtualFile> action) {
Generator<File> randomFiles = randomFiles(rootPath, fileFilter);
return () -> env -> new RunAll(
() -> {
File ioFile = env.generateValue(randomFiles, "Working with %s");
VirtualFile vFile = copyFileToProject(ioFile, fixture, rootPath);
PsiFile psiFile = fixture.getPsiManager().findFile(vFile);
if (psiFile instanceof PsiBinaryFile || psiFile instanceof PsiPlainTextFile) {
//noinspection UseOfSystemOutOrSystemErr
System.err.println("Can't check " + vFile + " due to incorrect file type: " + psiFile + " of " + psiFile.getClass());
return;
}
action.accept(env, vFile);
},
() -> WriteAction.run(() -> {
for (VirtualFile file : Objects.requireNonNull(fixture.getTempDirFixture().getFile("")).getChildren()) {
file.delete(fixture);
}
}),
() -> PsiDocumentManager.getInstance(fixture.getProject()).commitAllDocuments(),
() -> UIUtil.dispatchAllInvocationEvents()
).run();
}
private static boolean shouldGoInsiderDir(@NotNull String name) {
return !name.equals("gen") &&
!name.equals("reports") && // no idea what this is
!name.equals("android") && // no 'android' repo on agents in some builds
!containsBinariesOnly(name) &&
!name.endsWith("system") && !name.endsWith("config"); // temporary stuff from tests or debug IDE
}
private static boolean containsBinariesOnly(@NotNull String name) {
return name.equals("jdk") ||
name.equals("jre") ||
name.equals("lib") ||
name.equals("bin") ||
name.equals("out");
}
@NotNull
private static VirtualFile copyFileToProject(File ioFile, CodeInsightTestFixture fixture, String rootPath) {
try {
String path = FileUtil.getRelativePath(FileUtil.toCanonicalPath(rootPath), FileUtil.toSystemIndependentName(ioFile.getPath()), '/');
assert path != null;
Matcher rootPackageMatcher = Pattern.compile("/com/|/org/|/onair/").matcher(path);
if (rootPackageMatcher.find()) {
path = path.substring(rootPackageMatcher.start() + 1);
}
VirtualFile existing = fixture.getTempDirFixture().getFile(path);
if (existing != null) {
WriteAction.run(() -> existing.delete(fixture));
}
return fixture.addFileToProject(path, FileUtil.loadFile(ioFile)).getVirtualFile();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Generates actions checking that incremental reparse produces the same PSI as full reparse. This check makes sense
* in languages employing {@link com.intellij.psi.tree.ILazyParseableElementTypeBase}.
*/
@NotNull
public static Generator<MadTestingAction> randomEditsWithReparseChecks(@NotNull PsiFile file) {
return Generator.sampledFrom(
new InsertString(file),
new DeleteRange(file),
new CommitDocumentAction(file),
new CheckPsiTextConsistency(file)
);
}
/**
* @param skipCondition should return {@code true} if particular accessor method should be ignored
* @return function returning generator of actions checking that
* read accessors on all PSI elements in the file don't throw exceptions when invoked.
*/
@NotNull
public static Function<PsiFile, Generator<? extends MadTestingAction>> randomEditsWithPsiAccessorChecks(@NotNull Condition<? super Method> skipCondition) {
return file -> Generator.sampledFrom(
new InsertString(file),
new DeleteRange(file),
new CommitDocumentAction(file),
new CheckPsiReadAccessors(file, skipCondition),
new ResolveAllReferences(file)
);
}
public static boolean isAfterError(PsiFile file, int offset) {
return SyntaxTraverser.psiTraverser(file).filter(PsiErrorElement.class).find(e -> e.getTextRange().getStartOffset() <= offset) != null;
}
public static boolean containsErrorElements(FileViewProvider viewProvider) {
return ContainerUtil.exists(viewProvider.getAllFiles(), file -> SyntaxTraverser.psiTraverser(file).filter(PsiErrorElement.class).isNotEmpty());
}
@NotNull
public static String getPositionDescription(int offset, Document document) {
int line = document.getLineNumber(offset);
int start = document.getLineStartOffset(line);
int end = document.getLineEndOffset(line);
int column = offset - start;
String prefix = document.getText(new TextRange(start, offset)).trim();
if (prefix.length() > 30) {
prefix = "..." + prefix.substring(prefix.length() - 30);
}
String suffix = StringUtil.shortenTextWithEllipsis(document.getText(new TextRange(offset, end)), 30, 0);
String text = prefix + "|" + suffix;
return offset + "(" + (line + 1) + ":" + (column + 1) + ") [" + text + "]";
}
@NotNull
static String getIntentionDescription(IntentionAction action) {
return getIntentionDescription(action.getText(), action);
}
@NotNull
static String getIntentionDescription(String intentionName, IntentionAction action) {
IntentionAction actual = IntentionActionDelegate.unwrap(action);
String family = actual.getFamilyName();
Class<?> aClass = actual.getClass();
if (actual instanceof QuickFixWrapper) {
LocalQuickFix fix = ((QuickFixWrapper)actual).getFix();
family = fix.getFamilyName();
aClass = fix.getClass();
}
return "'" + intentionName + "' (family: '" + family + "'; class: '" + aClass.getName() + "')";
}
public static void testFileGenerator(File root, FileFilter filter, int iterationCount, PrintStream out) {
/* Typical output:
Roulette wheel generator:
#10000: sum = 5281 [1: 3770 | 2: 767 | 3: 272 | 4..5: 232 | 6..10: 146 | 11..20: 67 | 21..30: 12 | 31..50: 12 | 51..100: 3 | 101..200: 0 | 201+: 0]
Plain generator:
#10000: sum = 2504 [1: 1478 | 2: 391 | 3: 159 | 4..5: 155 | 6..10: 156 | 11..20: 103 | 21..30: 22 | 31..50: 8 | 51..100: 22 | 101..200: 9 | 201+: 1]
*/
for (boolean roulette : new boolean[]{true, false}) {
out.println("Testing " + (roulette ? "roulette" : "plain") + " generator");
TObjectLongHashMap<String> fileMap = new TObjectLongHashMap<>();
Generator<File> generator = randomFiles(root.getPath(), filter, roulette);
MadTestingAction action = env -> {
long lastTime = System.nanoTime(), startTime = lastTime;
for (int iteration = 1; iteration <= iterationCount; iteration++) {
File file = env.generateValue(generator, null);
assert filter.accept(file);
if (!fileMap.containsKey(file.getPath())) {
fileMap.put(file.getPath(), 1);
}
else {
fileMap.increment(file.getPath());
}
long curTime = System.nanoTime();
if (iteration <= 10) {
out.print("#" + iteration + " = " + (curTime - lastTime) / 1_000_000 + "ms");
if (iteration == 10) {
out.println();
} else {
out.print("; ");
}
lastTime = curTime;
}
if (iteration == iterationCount || curTime - lastTime > TimeUnit.SECONDS.toNanos(5)) {
lastTime = curTime;
out.println(getHistogramReport(fileMap, iteration));
}
}
out.println("Total time: " + (System.nanoTime() - startTime) / 1_000_000 + "ms");
};
PropertyChecker.customized().withIterationCount(1).checkScenarios(() -> action);
}
}
@NotNull
private static String getHistogramReport(TObjectLongHashMap<String> fileMap, int iteration) {
long[] stops = {1, 2, 3, 5, 10, 20, 30, 50, 100, 200, Long.MAX_VALUE};
int[] histogram = new int[stops.length];
fileMap.forEachValue(count -> {
int pos = Arrays.binarySearch(stops, count);
if (pos < 0) {
pos = -pos - 1;
}
histogram[pos]++;
return true;
});
StringBuilder report = new StringBuilder();
for (int i = 0; i < stops.length; i++) {
String range = i == 0 || stops[i - 1] == stops[i] - 1 ? String.valueOf(stops[i]) :
(stops[i - 1] + 1) + (stops[i] == Long.MAX_VALUE ? "+" : ".."+stops[i]);
report.append(String.format(Locale.ENGLISH, "%s: %-5d| ", range, histogram[i]));
}
return String.format(Locale.ENGLISH, "#%-5d: sum = %5d [%s]", iteration,
Arrays.stream(histogram).sum(), report.toString().replaceFirst("[\\s|]+$", ""));
}
private static final class FileGenerator implements Function<GenerationEnvironment, File> {
private static final com.intellij.util.Function<File, JBIterable<File>> FS_TRAVERSAL =
TreeTraversal.PRE_ORDER_DFS.traversal((File f) -> f.isDirectory() ? Arrays.asList(Objects.requireNonNull(f.listFiles())) : Collections.emptyList());
private final File myRoot;
private final FileFilter myFilter;
private FileGenerator(File root, FileFilter filter) {
myRoot = root;
myFilter = filter;
}
@Override
public File apply(GenerationEnvironment data) {
return generateRandomFile(data, myRoot, new HashSet<>());
}
@Nullable
private File generateRandomFile(GenerationEnvironment data, File file, Set<? super File> exhausted) {
while (true) {
File[] children = file.listFiles(f -> !exhausted.contains(f) && containsAtLeastOneFileDeep(f) && myFilter.accept(f));
if (children == null) {
return file;
}
if (children.length == 0) {
exhausted.add(file);
return null;
}
List<File> toChoose = preferDirs(data, children);
toChoose.sort(Comparator.comparing(File::getName));
File chosen = data.generate(Generator.sampledFrom(toChoose));
File generated = generateRandomFile(data, chosen, exhausted);
if (generated != null) {
return generated;
}
}
}
private static boolean containsAtLeastOneFileDeep(File root) {
return FS_TRAVERSAL.fun(root).find(f -> f.isFile()) != null;
}
private static List<File> preferDirs(GenerationEnvironment data, File[] children) {
List<File> files = new ArrayList<>();
List<File> dirs = new ArrayList<>();
for (File child : children) {
(child.isDirectory() ? dirs : files).add(child);
}
if (files.isEmpty() || dirs.isEmpty()) {
return Arrays.asList(children);
}
int ratio = Math.max(100, dirs.size() / files.size());
return data.generate(Generator.integers(0, ratio - 1)) != 0 ? dirs : files;
}
}
private static final class RouletteWheelFileGenerator implements Function<GenerationEnvironment, File> {
private final File myRoot;
private final FileFilter myFilter;
private static final File[] EMPTY_DIRECTORY = new File[0];
private final SoftFactoryMap<File, File[]> myChildrenCache = new SoftFactoryMap<>() {
@Override
protected File[] create(File f) {
File[] files = f.listFiles(child -> myFilter.accept(child) && (child.isFile() || FileGenerator.containsAtLeastOneFileDeep(child)));
return files != null && files.length == 0 ? EMPTY_DIRECTORY : files;
}
};
private RouletteWheelFileGenerator(File root, FileFilter filter) {
myRoot = root;
myFilter = filter;
}
@Override
public File apply(GenerationEnvironment data) {
return generateRandomFile(data, myRoot, new HashSet<>());
}
@Nullable
private File generateRandomFile(GenerationEnvironment data, File file, Set<File> exhausted) {
File[] children = myChildrenCache.get(file);
if (children == null) {
return file;
}
if (children == EMPTY_DIRECTORY) {
return null;
}
Arrays.sort(children, Comparator.comparing(File::getName));
while (true) {
int[] weights = Arrays.stream(children).mapToInt(child -> estimateWeight(child, exhausted)).toArray();
int index;
try {
index = spin(data, weights);
}
catch (RuntimeException e) {
if ("org.jetbrains.jetCheck.CannotRestoreValue".equals(e.getClass().getName())) {
throw new RuntimeException("Directory structure changed in " + file + " or its direct children?", e);
}
throw e;
}
if (index == -1) return null;
File chosen = children[index];
File generated = generateRandomFile(data, chosen, exhausted);
if (generated != null) {
return generated;
}
exhausted.add(chosen);
}
}
private static int spin(@NotNull GenerationEnvironment data, int @NotNull [] weights) {
int totalWeight = Arrays.stream(weights).sum();
if (totalWeight == 0) return -1;
int value = data.generate(Generator.integers(0, totalWeight));
for (int i = 0; i < weights.length; i++) {
value -= weights[i];
if (value < 0) {
return i;
}
}
return -1;
}
private int estimateWeight(File file, @NotNull Set<File> exhausted) {
if (exhausted.contains(file)) return 0;
File[] children = myChildrenCache.get(file);
if (children == null) return 1;
return Stream.of(children).mapToInt(f -> exhausted.contains(f) ? 0 : f.isDirectory() ? 5 : 1).sum();
}
}
}
|
package com.intellij.openapi.vcs.ui;
import com.intellij.ui.ErrorLabel;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.panels.OpaquePanel;
import com.intellij.ui.popup.list.IconListPopupRenderer;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.ui.popup.list.PopupListElementRenderer;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
public class PopupListElementRendererWithIcon extends PopupListElementRenderer<Object> implements IconListPopupRenderer {
protected IconComponent myIconLabel;
public PopupListElementRendererWithIcon(ListPopupImpl aPopup) {
super(aPopup);
}
@Override
public boolean isIconAt(@NotNull Point point) {
JList list = myPopup.getList();
int index = myPopup.getList().locationToIndex(point);
Rectangle bounds = myPopup.getList().getCellBounds(index, index);
Component renderer = getListCellRendererComponent(list, list.getSelectedValue(), index, true, true);
renderer.setBounds(bounds);
renderer.doLayout();
point.translate(-bounds.x, -bounds.y);
return SwingUtilities.getDeepestComponentAt(renderer, point.x, point.y) instanceof IconComponent;
}
@Override
protected void customizeComponent(JList<?> list, Object value, boolean isSelected) {
super.customizeComponent(list, value, isSelected);
myTextLabel.setIcon(null);
myTextLabel.setDisabledIcon(null);
myIconLabel.setIcon(isSelected ? IconUtil.wrapToSelectionAwareIcon(myDescriptor.getSelectedIconFor(value)) : myDescriptor.getIconFor(value));
}
@Override
protected JComponent createItemComponent() {
myTextLabel = new ErrorLabel();
myTextLabel.setOpaque(true);
myTextLabel.setBorder(JBUI.Borders.empty(1));
myIconLabel = new IconComponent();
JPanel panel = new OpaquePanel(new BorderLayout(), JBColor.WHITE);
panel.add(myIconLabel, BorderLayout.WEST);
panel.add(myTextLabel, BorderLayout.CENTER);
return layoutComponent(panel);
}
public static class IconComponent extends JLabel {
}
}
|
package com.vectrace.MercurialEclipse.synchronize.cs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Observer;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.mapping.ResourceTraversal;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.team.core.diff.IDiffChangeEvent;
import org.eclipse.team.core.mapping.ISynchronizationContext;
import org.eclipse.team.internal.core.subscribers.BatchingChangeSetManager;
import org.eclipse.team.internal.core.subscribers.IChangeSetChangeListener;
import org.eclipse.team.internal.core.subscribers.BatchingChangeSetManager.CollectorChangeEvent;
import org.eclipse.team.internal.ui.Utils;
import org.eclipse.team.internal.ui.synchronize.ChangeSetCapability;
import org.eclipse.team.internal.ui.synchronize.IChangeSetProvider;
import org.eclipse.team.ui.mapping.SynchronizationContentProvider;
import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration;
import org.eclipse.team.ui.synchronize.ISynchronizeParticipant;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.navigator.ICommonContentExtensionSite;
import org.eclipse.ui.navigator.INavigatorContentExtension;
import org.eclipse.ui.navigator.INavigatorContentService;
import org.eclipse.ui.navigator.INavigatorSorterService;
import com.vectrace.MercurialEclipse.MercurialEclipsePlugin;
import com.vectrace.MercurialEclipse.model.ChangeSet;
import com.vectrace.MercurialEclipse.model.FileFromChangeSet;
import com.vectrace.MercurialEclipse.model.HgRoot;
import com.vectrace.MercurialEclipse.model.IHgRepositoryLocation;
import com.vectrace.MercurialEclipse.model.PathFromChangeSet;
import com.vectrace.MercurialEclipse.model.UncommittedChangeSet;
import com.vectrace.MercurialEclipse.model.WorkingChangeSet;
import com.vectrace.MercurialEclipse.model.ChangeSet.Direction;
import com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants;
import com.vectrace.MercurialEclipse.synchronize.HgDragAdapterAssistant;
import com.vectrace.MercurialEclipse.synchronize.HgSubscriberMergeContext;
import com.vectrace.MercurialEclipse.synchronize.MercurialSynchronizeParticipant;
import com.vectrace.MercurialEclipse.synchronize.MercurialSynchronizeSubscriber;
import com.vectrace.MercurialEclipse.synchronize.PresentationMode;
import com.vectrace.MercurialEclipse.team.cache.MercurialStatusCache;
import com.vectrace.MercurialEclipse.utils.ResourceUtils;
@SuppressWarnings("restriction")
public class HgChangeSetContentProvider extends SynchronizationContentProvider {
public static final String ID = "com.vectrace.MercurialEclipse.changeSetContent";
private static final MercurialStatusCache STATUS_CACHE = MercurialStatusCache.getInstance();
private final class UcommittedSetListener implements IPropertyChangeListener {
public void propertyChange(PropertyChangeEvent event) {
Object input = getTreeViewer().getInput();
if (input instanceof HgChangeSetModelProvider) {
Utils.asyncExec(new Runnable() {
public void run() {
TreeViewer treeViewer = getTreeViewer();
treeViewer.getTree().setRedraw(false);
treeViewer.refresh(uncommitted, true);
if (uncommitted instanceof ChangesetGroup) {
for (ChangeSet cs : ((ChangesetGroup) uncommitted).getChangesets()) {
treeViewer.refresh(cs, true);
}
}
treeViewer.getTree().setRedraw(true);
}
}, getTreeViewer());
}
}
}
private final class PreferenceListener implements IPropertyChangeListener {
public void propertyChange(PropertyChangeEvent event) {
Object input = getTreeViewer().getInput();
String property = event.getProperty();
final boolean bLocal = property
.equals(MercurialPreferenceConstants.PREF_SYNC_ENABLE_LOCAL_CHANGESETS);
if ((property.equals(PresentationMode.PREFERENCE_KEY) || bLocal
|| property.equals(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS))
&& input instanceof HgChangeSetModelProvider) {
Utils.asyncExec(new Runnable() {
public void run() {
TreeViewer treeViewer = getTreeViewer();
if (bLocal) {
recreateUncommittedEntry(treeViewer);
} else {
treeViewer.getTree().setRedraw(false);
treeViewer.refresh(uncommitted, true);
for(RepositoryChangesetGroup sg : projectGroup) {
treeViewer.refresh(sg.getOutgoing(), true);
treeViewer.refresh(sg.getIncoming(), true);
}
treeViewer.getTree().setRedraw(true);
treeViewer.refresh();
}
}
}, getTreeViewer());
}
}
}
private final class CollectorListener implements IChangeSetChangeListener, BatchingChangeSetManager.IChangeSetCollectorChangeListener {
public void setAdded(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) {
ChangeSet set = (ChangeSet)cs;
if (isVisibleInMode(set)) {
final ChangesetGroup toRefresh = findChangeSetInProjects(cs);
if(toRefresh != null) {
boolean added = toRefresh.getChangesets().add(set);
if (added) {
Utils.asyncExec(new Runnable() {
public void run() {
getTreeViewer().refresh(toRefresh, true);
getTreeViewer().refresh();
}
}, getTreeViewer());
}
}
}
}
public void setRemoved(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) {
ChangeSet set = (ChangeSet)cs;
if (isVisibleInMode(set)) {
final ChangesetGroup toRefresh = findChangeSetInProjects(cs);
boolean removed = toRefresh.getChangesets().remove(set);
if(removed) {
Utils.asyncExec(new Runnable() {
public void run() {
getTreeViewer().refresh(toRefresh, true);
}
}, getTreeViewer());
}
}
}
private ChangesetGroup findChangeSetInProjects(final org.eclipse.team.internal.core.subscribers.ChangeSet cs) {
ChangeSet set = (ChangeSet) cs;
for (RepositoryChangesetGroup sg : projectGroup) {
if (set.getRepository().equals(sg.getLocation())) {
if (set.getDirection() == Direction.INCOMING) {
return sg.getIncoming();
}
if (set.getDirection() == Direction.OUTGOING) {
return sg.getOutgoing();
}
}
}
return null;
}
public void defaultSetChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet previousDefault, final org.eclipse.team.internal.core.subscribers.ChangeSet set) {
// user has requested a manual refresh: simply refresh root elements
getRootElements();
}
public void nameChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet set) {
// ignored
}
public void resourcesChanged(final org.eclipse.team.internal.core.subscribers.ChangeSet set, final IPath[] paths) {
// ignored
}
public void changeSetChanges(final CollectorChangeEvent event, IProgressMonitor monitor) {
// ignored
}
}
private HgChangesetsCollector csCollector;
private boolean collectorInitialized;
private final IChangeSetChangeListener collectorListener;
private final IPropertyChangeListener uncommittedSetListener;
private final IPropertyChangeListener preferenceListener;
private final List<RepositoryChangesetGroup> projectGroup;
private WorkbenchContentProvider provider;
boolean initialized;
private IUncommitted uncommitted;
public HgChangeSetContentProvider() {
super();
projectGroup = new ArrayList<RepositoryChangesetGroup>();
collectorListener = new CollectorListener();
uncommittedSetListener = new UcommittedSetListener();
preferenceListener = new PreferenceListener();
MercurialEclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(preferenceListener);
uncommitted = makeUncommittedEntry();
}
private IUncommitted makeUncommittedEntry() {
if (MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean(
MercurialPreferenceConstants.PREF_SYNC_ENABLE_LOCAL_CHANGESETS)) {
return new UncommittedChangesetGroup();
}
return new UncommittedChangeSet();
}
@Override
protected String getModelProviderId() {
return HgChangeSetModelProvider.ID;
}
private boolean isOutgoingVisible(){
return getConfiguration().getMode() != ISynchronizePageConfiguration.INCOMING_MODE;
}
private boolean isIncomingVisible(){
return getConfiguration().getMode() != ISynchronizePageConfiguration.OUTGOING_MODE;
}
private boolean isEnabled() {
final Object input = getViewer().getInput();
return input instanceof HgChangeSetModelProvider;
}
@Override
public Object[] getChildren(Object parent) {
return getElements(parent);
}
@Override
public Object[] getElements(Object parent) {
if (parent instanceof ISynchronizationContext) {
// Do not show change sets when all models are visible because
// model providers that override the resource content may cause
// problems for the change set content provider
return new Object[0];
}
if(isEnabled()){
if(!((HgChangeSetModelProvider) getViewer().getInput()).isParticipantCreated()){
initCollector();
// on startup, do not start to show anything for the first time:
// show "reminder" page which allows user to choose synchronize or not
// return new Object[0];
// TODO right now it doesn't make sense to show "reminder page" as we
// connect to the remote servers automatically as soon as the sync view
// shows up.
}
}
if (parent == getModelProvider()) {
return getRootElements();
} else if (parent instanceof ChangesetGroup) {
ChangesetGroup group = (ChangesetGroup) parent;
Direction direction = group.getDirection();
if (isOutgoing(direction)) {
if (isOutgoingVisible()) {
return group.getChangesets().toArray();
}
return new Object[] {new FilteredPlaceholder()};
}
if(direction == Direction.INCOMING){
if (isIncomingVisible()) {
return group.getChangesets().toArray();
}
return new Object[] {new FilteredPlaceholder()};
}
if(direction == Direction.LOCAL){
return group.getChangesets().toArray();
}
} else if (parent instanceof RepositoryChangesetGroup) {
// added groups to view
boolean showEmpty = MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS);
// showEmpty = true;
RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) parent;
ArrayList<Object> groups =new ArrayList<Object>();
if(supergroup.getIncoming().getChangesets().size() > 0) {
groups.add(supergroup.getIncoming());
} else if(showEmpty) {
groups.add(supergroup.getIncoming());
}
if(supergroup.getOutgoing().getChangesets().size() > 0) {
groups.add(supergroup.getOutgoing());
} else if(showEmpty) {
groups.add(supergroup.getOutgoing());
}
return groups.toArray();
} else if (parent instanceof ChangeSet) {
FileFromChangeSet[] files = ((ChangeSet) parent).getChangesetFiles();
if (files.length != 0) {
switch (PresentationMode.get()) {
case FLAT:
return files;
case TREE:
return collectTree(parent, files);
case COMPRESSED_TREE:
return collectCompressedTree(parent, files);
}
}
} else if (parent instanceof PathFromChangeSet) {
return ((PathFromChangeSet) parent).getChildren();
}
return new Object[0];
}
private synchronized void initProjects(MercurialSynchronizeSubscriber subscriber) {
Set<IHgRepositoryLocation> repositoryLocations = subscriber.getParticipant().getRepositoryLocation();
for (IHgRepositoryLocation repoLocation : repositoryLocations) {
Set<HgRoot> hgRoots = MercurialEclipsePlugin.getRepoManager().getAllRepoLocationRoots(repoLocation);
String projectName = repoLocation.getLocation();
if(hgRoots.size() == 1) {
projectName = hgRoots.iterator().next().getName();
}
RepositoryChangesetGroup scg = new RepositoryChangesetGroup(projectName, repoLocation);
scg.setIncoming(new ChangesetGroup("Incoming", Direction.INCOMING));
scg.setOutgoing(new ChangesetGroup("Outgoing", Direction.OUTGOING));
ArrayList<IProject> projects = new ArrayList<IProject>();
Map<HgRoot, List<IResource>> byRoot = ResourceUtils.groupByRoot(Arrays.asList(subscriber.getProjects()));
for(HgRoot root : hgRoots) {
projects.addAll((Collection<? extends IProject>) byRoot.get(root));
}
scg.setProjects(projects);
projectGroup.add(scg);
}
}
private Object[] collectTree(Object parent, FileFromChangeSet[] files) {
List<Object> out = new ArrayList<Object>(files.length * 2);
for (FileFromChangeSet file : files) {
IPath path = file.getPath();
if(path == null) {
out.add(Path.EMPTY);
} else {
out.add(path.removeLastSegments(1));
}
out.add(file);
}
return collectTree(parent, out);
}
private Object[] collectTree(Object parent, List<Object> files) {
HashMap<String, List<Object>> map = new HashMap<String, List<Object>>();
List<Object> out = new ArrayList<Object>();
for (Iterator<Object> it = files.iterator(); it.hasNext();) {
IPath path = (IPath) it.next();
FileFromChangeSet file = (FileFromChangeSet) it.next();
if (path == null || 0 == path.segmentCount()) {
out.add(file);
} else {
String seg = path.segment(0);
List<Object> l = map.get(seg);
if (l == null) {
map.put(seg, l = new ArrayList<Object>());
}
l.add(path.removeFirstSegments(1));
l.add(file);
}
}
for (String seg : map.keySet()) {
out.add(new TreePathFromChangeSet(parent, seg, map.get(seg)));
}
return out.toArray(new Object[out.size()]);
}
private Object[] collectCompressedTree(Object parent, FileFromChangeSet[] files) {
HashMap<IPath, List<FileFromChangeSet>> map = new HashMap<IPath, List<FileFromChangeSet>>();
List<Object> out = new ArrayList<Object>();
for (FileFromChangeSet file : files) {
IPath path;
if(file.getPath() == null) {
path = Path.EMPTY;
} else {
path = file.getPath().removeLastSegments(1);
}
List<FileFromChangeSet> l = map.get(path);
if (l == null) {
map.put(path, l = new ArrayList<FileFromChangeSet>());
}
l.add(file);
}
for (IPath path : map.keySet()) {
final List<FileFromChangeSet> data = map.get(path);
if (path.isEmpty()) {
out.addAll(data);
} else {
out.add(new CompressedTreePathFromChangeSet(parent, path.toString(), data));
}
}
return out.toArray(new Object[out.size()]);
}
private void ensureRootsAdded() {
TreeViewer viewer = getTreeViewer();
TreeItem[] children = viewer.getTree().getItems();
if(children.length == 0) {
viewer.add(viewer.getInput(), getRootElements());
}
}
// traverse through elements and add them to the correct group
private Object[] getRootElements() {
initCollector();
List<ChangeSet> result = new ArrayList<ChangeSet>();
Collection<ChangeSet> allSets = getAllSets();
for (ChangeSet set : allSets) {
if (hasChildren(set)) {
result.add(set);
}
}
boolean showOutgoing = isOutgoingVisible();
boolean showIncoming = isIncomingVisible();
for (ChangeSet set : result) {
for (RepositoryChangesetGroup group : projectGroup) {
if (set.getRepository().equals(group.getLocation())) {
Direction direction = set.getDirection();
if (showOutgoing && (isOutgoing(direction))) {
group.getOutgoing().getChangesets().add(set);
}
if (showIncoming && direction == Direction.INCOMING) {
group.getIncoming().getChangesets().add(set);
}
}
}
}
List<Object> itemsToShow = new ArrayList<Object>();
itemsToShow.add(uncommitted);
for(RepositoryChangesetGroup group : projectGroup) {
// if(group.getIncoming().getChangesets().size() > 0 || group.getOutgoing().getChangesets().size() > 0) {
itemsToShow.add(group);
}
return itemsToShow.toArray();
}
private synchronized void initCollector() {
if (!collectorInitialized) {
initializeChangeSets(getChangeSetCapability());
collectorInitialized = true;
}
}
@Override
protected ResourceTraversal[] getTraversals(
ISynchronizationContext context, Object object) {
if (object instanceof ChangeSet) {
ChangeSet set = (ChangeSet) object;
IResource[] resources = set.getResources();
return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) };
}
if(object instanceof IResource){
IResource[] resources = new IResource[]{(IResource) object};
return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) };
}
if(object instanceof ChangesetGroup){
ChangesetGroup group = (ChangesetGroup) object;
Set<ChangeSet> changesets = group.getChangesets();
Set<IFile> all = new HashSet<IFile>();
for (ChangeSet changeSet : changesets) {
all.addAll(changeSet.getFiles());
}
IResource[] resources = all.toArray(new IResource[0]);
return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) };
}
if(object instanceof RepositoryChangesetGroup){
RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) object;
Set<IFile> all = new HashSet<IFile>();
Set<ChangeSet> changesets = supergroup.getIncoming().getChangesets();
for (ChangeSet changeSet : changesets) {
all.addAll(changeSet.getFiles());
}
changesets = supergroup.getOutgoing().getChangesets();
for (ChangeSet changeSet : changesets) {
all.addAll(changeSet.getFiles());
}
IResource[] resources = all.toArray(new IResource[0]);
return new ResourceTraversal[] { new ResourceTraversal(resources, IResource.DEPTH_ZERO, IResource.NONE) };
}
return new ResourceTraversal[0];
}
/**
* @see org.eclipse.team.ui.mapping.SynchronizationContentProvider#hasChildrenInContext(org.eclipse.team.core.mapping.ISynchronizationContext,
* java.lang.Object)
*/
@Override
protected boolean hasChildrenInContext(ISynchronizationContext context, Object element) {
if (element instanceof ChangeSet) {
return hasChildren((ChangeSet) element);
} else if (element instanceof ChangesetGroup) {
ChangesetGroup group = (ChangesetGroup) element;
Direction direction = group.getDirection();
if (isOutgoingVisible() && isOutgoing(direction)) {
return true;
}
if(isIncomingVisible() && direction == Direction.INCOMING){
return true;
}
} else if (element instanceof RepositoryChangesetGroup) {
boolean showEmptyGroups = MercurialEclipsePlugin.getDefault().getPreferenceStore().getBoolean(MercurialPreferenceConstants.PREF_SYNC_SHOW_EMPTY_GROUPS);
RepositoryChangesetGroup supergroup = (RepositoryChangesetGroup) element;
if (isOutgoingVisible() && (showEmptyGroups || supergroup.getOutgoing().getChangesets().size() > 0)) {
return true;
}
if (isIncomingVisible() && (showEmptyGroups || supergroup.getIncoming().getChangesets().size() > 0)) {
return true;
}
} else if (element instanceof PathFromChangeSet) {
return true;
}
return false;
}
private boolean isVisibleInMode(ChangeSet cs) {
int mode = getConfiguration().getMode();
if (cs != null) {
switch (mode) {
case ISynchronizePageConfiguration.BOTH_MODE:
return true;
case ISynchronizePageConfiguration.CONFLICTING_MODE:
return containsConflicts(cs);
case ISynchronizePageConfiguration.INCOMING_MODE:
return cs.getDirection() == Direction.INCOMING;
case ISynchronizePageConfiguration.OUTGOING_MODE:
return hasConflicts(cs) || isOutgoing(cs.getDirection());
default:
break;
}
}
return true;
}
private static boolean isOutgoing(Direction direction) {
return direction == Direction.OUTGOING || direction == Direction.LOCAL;
}
private static boolean hasConflicts(ChangeSet cs) {
// Conflict mode not meaningful in a DVCS
return false;
}
private static boolean containsConflicts(ChangeSet cs) {
// Conflict mode not meaningful in a DVCS
return false;
}
private boolean hasChildren(ChangeSet changeset) {
return isVisibleInMode(changeset)
&& (!changeset.getFiles().isEmpty() || changeset.getChangesetFiles().length > 0);
}
/**
* Return all the change sets (incoming and outgoing). This
* list must not include the unassigned set.
* @return all the change sets (incoming and outgoing)
*/
private Collection<ChangeSet> getAllSets() {
if (csCollector != null) {
return csCollector.getChangeSets();
}
return new HashSet<ChangeSet>();
}
@Override
public void init(ICommonContentExtensionSite site) {
super.init(site);
HgChangeSetSorter sorter = getSorter();
if (sorter != null) {
sorter.setConfiguration(getConfiguration());
}
MercurialSynchronizeParticipant participant = (MercurialSynchronizeParticipant) getConfiguration().getParticipant();
getExtensionSite().getService().getDnDService().bindDragAssistant(new HgDragAdapterAssistant());
uncommitted.setContext((HgSubscriberMergeContext) participant.getContext());
}
private HgChangeSetSorter getSorter() {
INavigatorContentService contentService = getExtensionSite().getService();
INavigatorSorterService sortingService = contentService.getSorterService();
INavigatorContentExtension extension = getExtensionSite().getExtension();
if (extension != null) {
ViewerSorter sorter = sortingService.findSorter(extension.getDescriptor(), getModelProvider(), null, null); // incoming, incoming
if (sorter instanceof HgChangeSetSorter) {
return (HgChangeSetSorter) sorter;
}
}
return null;
}
private void initializeChangeSets(ChangeSetCapability csc) {
if (csc.supportsCheckedInChangeSets()) {
csCollector = ((HgChangeSetCapability) csc).createSyncInfoSetChangeSetCollector(getConfiguration());
csCollector.addListener(collectorListener);
initializeUncommittedEntry(csCollector.getSubscriber().getProjects());
initProjects(csCollector.getSubscriber());
}
}
private void initializeUncommittedEntry(IProject[] projects) {
uncommitted.setProjects(projects);
uncommitted.addListener(uncommittedSetListener);
STATUS_CACHE.addObserver(uncommitted);
}
@Override
public void dispose() {
if (csCollector != null) {
csCollector.removeListener(collectorListener);
csCollector.dispose();
}
MercurialEclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(preferenceListener);
disposeUncommittedEntry();
super.dispose();
}
private void disposeUncommittedEntry() {
uncommitted.removeListener(uncommittedSetListener);
STATUS_CACHE.deleteObserver(uncommitted);
uncommitted.dispose();
for(RepositoryChangesetGroup sg : projectGroup) {
sg.getOutgoing().getChangesets().clear();
sg.getIncoming().getChangesets().clear();
}
projectGroup.clear();
// initialized=false;
super.dispose();
}
protected void recreateUncommittedEntry(TreeViewer tree) {
IProject[] projects = uncommitted.getProjects();
HgSubscriberMergeContext ctx = uncommitted.getContext();
disposeUncommittedEntry();
uncommitted = makeUncommittedEntry();
uncommitted.setContext(ctx);
if (collectorInitialized) {
initializeUncommittedEntry(projects);
}
tree.refresh();
}
@Override
public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) {
Utils.asyncExec(new Runnable() {
public void run() {
ensureRootsAdded();
}
}, getTreeViewer());
if (csCollector != null) {
csCollector.handleChange(event);
}
// no other updates here, as it simply doesn't fit into the changeset concept.
}
private ChangeSetCapability getChangeSetCapability() {
ISynchronizeParticipant participant = getConfiguration().getParticipant();
if (participant instanceof IChangeSetProvider) {
IChangeSetProvider csProvider = (IChangeSetProvider) participant;
return csProvider.getChangeSetCapability();
}
return null;
}
private TreeViewer getTreeViewer() {
return (TreeViewer) getViewer();
}
@Override
protected ITreeContentProvider getDelegateContentProvider() {
if (provider == null) {
provider = new WorkbenchContentProvider();
}
return provider;
}
@Override
protected Object getModelRoot() {
return ResourcesPlugin.getWorkspace().getRoot();
}
/**
*
* @param file may be null
* @return may return null, if the given file is null, not selected or is not contained
* in any selected changesets
*/
public ChangeSet getParentOfSelection(FileFromChangeSet file){
TreeItem[] selection = getTreeViewer().getTree().getSelection();
for (TreeItem treeItem : selection) {
if(treeItem.getData() != file){
continue;
}
TreeItem parentItem = treeItem.getParentItem();
while (parentItem != null && !(parentItem.getData() instanceof ChangeSet)) {
parentItem = parentItem.getParentItem();
}
if (parentItem != null) {
return (ChangeSet) parentItem.getData();
}
}
return null;
}
/**
* @param changeset may be null
* @return may return null
*/
public ChangesetGroup getParentGroup(ChangeSet changeset){
if(changeset == null || changeset instanceof WorkingChangeSet){
return null;
}
assert false; // TODO: implement for mult-repo sync
return null;
// if(changeset.getDirection() == Direction.INCOMING){
// return incoming;
// return outgoing;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("HgChangeSetContentProvider [collectorInitialized=");
builder.append(collectorInitialized);
builder.append(", ");
if (csCollector != null) {
builder.append("csCollector=");
builder.append(csCollector);
builder.append(", ");
}
if (provider != null) {
builder.append("provider=");
builder.append(provider);
builder.append(", ");
}
builder.append("]");
return builder.toString();
}
public IUncommitted getUncommittedEntry() {
return uncommitted;
}
private class CompressedTreePathFromChangeSet extends PathFromChangeSet {
protected final List<FileFromChangeSet> data;
public CompressedTreePathFromChangeSet(Object prnt, String seg, List<FileFromChangeSet> data) {
super(prnt, seg);
this.data = data;
if (data != null && data.size() > 0) {
IFile file = data.get(0).getFile();
this.resource = file != null? file.getParent() : null;
}
}
@Override
public Object[] getChildren() {
return data.toArray(new FileFromChangeSet[data.size()]);
}
@Override
public Set<FileFromChangeSet> getFiles() {
return new LinkedHashSet<FileFromChangeSet>(data);
}
}
private class TreePathFromChangeSet extends PathFromChangeSet {
protected final List<Object> data;
public TreePathFromChangeSet(Object prnt, String seg, List<Object> data) {
super(prnt, seg);
this.data = data;
this.resource = getResource();
}
@Override
public Object[] getChildren() {
return collectTree(HgChangeSetContentProvider.this, data);
}
private IResource getResource() {
IResource result = null;
if (data.size() > 1) {
// first object must be an IPath
Object o1 = data.get(0);
// and second must be FileFromChangeSet
Object o2 = data.get(1);
if (o1 instanceof IPath && o2 instanceof FileFromChangeSet) {
FileFromChangeSet fcs = (FileFromChangeSet) o2;
IResource childResource = ResourceUtils.getResource(fcs);
if(childResource != null) {
IPath folderPath = ResourceUtils.getPath(childResource).removeLastSegments(
((IPath) o1).segmentCount() + 1);
return ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(
folderPath);
}
}
}
return result;
}
@Override
public Set<FileFromChangeSet> getFiles() {
Set<FileFromChangeSet> files = new LinkedHashSet<FileFromChangeSet>();
for (Object o : data) {
if(o instanceof FileFromChangeSet) {
files.add((FileFromChangeSet) o);
}
}
return files;
}
}
protected static class FilteredPlaceholder
{
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "<Filtered>";
}
}
public interface IUncommitted extends Observer
{
void setProjects(IProject[] projects);
IProject[] getProjects();
void dispose();
void removeListener(IPropertyChangeListener listener);
void addListener(IPropertyChangeListener listener);
void setContext(HgSubscriberMergeContext context);
HgSubscriberMergeContext getContext();
}
}
|
package org.yakindu.sct.domain.extension;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.osgi.framework.Bundle;
import org.yakindu.sct.model.sgraph.SGraphPackage;
import org.yakindu.sct.model.sgraph.Statechart;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author andreas muelder - Initial contribution and API
*
*/
public class DomainRegistry {
private static final String EXTENSION_POINT = "org.yakindu.sct.domain";
private static final String DOMAIN_ID = "domainID";
private static final String DESCRIPTION = "description";
private static final String IMAGE = "image";
private static final String NAME = "name";
private static final String MODULE_PROVIDER = "domainModuleProvider";
private DomainRegistry() {
}
private static List<DomainDescriptor> descriptors = null;
public static final class DomainDescriptor {
private final IConfigurationElement configElement;
private Image image;
private IDomainInjectorProvider injectorProvider;
DomainDescriptor(IConfigurationElement configElement) {
this.configElement = configElement;
}
public String getDomainID() {
return configElement.getAttribute(DOMAIN_ID);
}
public String getName() {
return configElement.getAttribute(NAME);
}
public String getDescription() {
return configElement.getAttribute(DESCRIPTION);
}
public IDomainInjectorProvider getDomainInjectorProvider() {
if (injectorProvider == null) {
try {
injectorProvider = (IDomainInjectorProvider) configElement
.createExecutableExtension(MODULE_PROVIDER);
} catch (CoreException e) {
e.printStackTrace();
}
}
return injectorProvider;
}
public Image getImage() {
if (image != null)
return image;
String path = configElement.getAttribute(IMAGE);
if (path == null)
return null;
Bundle extensionBundle = Platform.getBundle(configElement.getContributor().getName());
URL entry = extensionBundle.getEntry(path);
ImageDescriptor descriptor = ImageDescriptor.createFromURL(entry);
image = descriptor.createImage();
return image;
}
public IConfigurationElement getConfigElement() {
return configElement;
}
public void setImage(Image image) {
this.image = image;
}
}
public static List<DomainDescriptor> getDomainDescriptors() {
if (descriptors == null) {
descriptors = new ArrayList<DomainDescriptor>();
IConfigurationElement[] configurationElements = Platform.getExtensionRegistry()
.getConfigurationElementsFor(EXTENSION_POINT);
for (IConfigurationElement iConfigurationElement : configurationElements) {
descriptors.add(new DomainDescriptor(iConfigurationElement));
}
}
return descriptors;
}
public static DomainDescriptor getDomainDescriptor(final String id) {
final String defaultDomainID = SGraphPackage.Literals.STATECHART__DOMAIN_ID.getDefaultValueLiteral();
try {
return Iterables.find(getDomainDescriptors(), new Predicate<DomainDescriptor>() {
@Override
public boolean apply(DomainDescriptor input) {
return input.getDomainID().equals(id != null ? id : defaultDomainID);
}
});
} catch (NoSuchElementException e) {
if (defaultDomainID.equals(id)) {
throw new IllegalArgumentException("No default domain found!");
}
System.err.println("Could not find domain descriptor for id " + id + " - > using default domain");
return getDomainDescriptor(defaultDomainID);
}
}
public static DomainDescriptor getDomainDescriptor(EObject object) {
EObject rootContainer = EcoreUtil.getRootContainer(object);
Assert.isTrue(rootContainer instanceof Statechart);
return getDomainDescriptor(((Statechart) rootContainer).getDomainID());
}
}
|
package org.lockss.plugin.palgrave;
import java.util.regex.Pattern;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.daemon.ConfigParamDescr;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.ArticleFiles;
import org.lockss.plugin.AuUtil;
import org.lockss.plugin.CachedUrl;
import org.lockss.plugin.CachedUrlSetNode;
import org.lockss.plugin.PluginTestUtil;
import org.lockss.plugin.SubTreeArticleIterator;
import org.lockss.plugin.UrlCacher;
import org.lockss.plugin.simulated.SimulatedArchivalUnit;
import org.lockss.plugin.simulated.SimulatedContentGenerator;
import org.lockss.test.ArticleIteratorTestCase;
import org.lockss.util.ListUtil;
import java.util.Iterator;
import org.lockss.util.Constants;
public class TestPalgraveBookArticleIteratorFactory extends ArticleIteratorTestCase {
private SimulatedArchivalUnit sau; // Simulated AU to generate content
private static final String PLUGIN_NAME = "org.lockss.plugin.palgrave.ClockssPalgraveBookPlugin";
private static final String BASE_URL = "http:
private static final String BOOK_ISBN = "9781137024497";
private static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
private static final String BOOK_ISBN_KEY = "book_isbn";
private static final int DEFAULT_FILESIZE = 3000;
private final String EXPECTED_PDF_LANDING_PAGE = "http:
private final String EXPECTED_PDF_URL = "http:
private final String EXPECTED_FULL_TEXT_URL = EXPECTED_PDF_URL;
@Override
public void setUp() throws Exception {
super.setUp();
String tempDirPath = setUpDiskSpace();
au = createAu();
sau = PluginTestUtil.createAndStartSimAu(simAuConfig(tempDirPath));
}
@Override
public void tearDown() throws Exception {
sau.deleteContentTree();
super.tearDown();
}
protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException {
return
PluginTestUtil.createAndStartAu(PLUGIN_NAME, palgraveBookAuConfig());
}
// Set configuration attributes to create plugin AU (archival unit)
Configuration palgraveBookAuConfig() {
Configuration conf = ConfigManager.newConfiguration();
conf.put(BASE_URL_KEY, BASE_URL);
conf.put(BOOK_ISBN_KEY, BOOK_ISBN);
return conf;
}
Configuration simAuConfig(String rootPath) {
Configuration conf = ConfigManager.newConfiguration();
conf.put("root", rootPath);
conf.put("base_url", BASE_URL);
conf.put("depth", "1");
conf.put("branch", "4");
conf.put("numFiles", "7");
conf.put("fileTypes",
"" + ( SimulatedContentGenerator.FILE_TYPE_HTML
| SimulatedContentGenerator.FILE_TYPE_PDF));
conf.put("binFileSize", "" + DEFAULT_FILESIZE);
return conf;
}
public void testRoots() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
assertEquals(ListUtil.list(BASE_URL + "pc/"), getRootUrls(artIter));
}
public void testUrlsWithPrefixes() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
Pattern pat = getPattern(artIter);
// PATTERN_TEMPLATE = "\"%spc/.+/browse/inside/(download|epub)?/[0-9]+\\.(html|pdf|epub)$\", base_url";
assertNotMatchesRE(pat, "http:
assertMatchesRE(pat, "http:
assertMatchesRE(pat, "http:
assertMatchesRE(pat, "http:
}
public void testCreateArticleFiles() throws Exception {
PluginTestUtil.crawlSimAu(sau);
// create urls to store in UrlCacher
String[] urls = { BASE_URL + "pc/doifinder/10.1057/9781137024497",
BASE_URL + "pc/busman2013/browse/inside/download/9781137024497.pdf" };
// get cached url content type and properties from simulated contents
// for UrclCacher.storeContent()
CachedUrl cuPdf = null;
CachedUrl cuHtml = null;
for (CachedUrl cu : AuUtil.getCuIterable(sau)) {
if (cuPdf == null
&& cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_PDF)) {
//log.info("pdf contenttype: " + cu.getContentType());
cuPdf = cu;
} else if (cuHtml == null
&& cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_HTML)) {
//log.info("html contenttype: " + cu.getContentType());
cuHtml = cu;
}
if (cuPdf != null && cuHtml != null) {
break;
}
}
// store content using cached url content type and properties
UrlCacher uc;
for (String url : urls) {
uc = au.makeUrlCacher(url);
if(url.contains("pdf")){
uc.storeContent(cuPdf.getUnfilteredInputStream(), cuPdf.getProperties());
} else if (url.contains("html")) {
uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties());
}
}
// get article iterator, get article files and the appropriate urls according
// to their roles.
String [] expectedUrls = { EXPECTED_FULL_TEXT_URL,
EXPECTED_PDF_URL,
//EXPECTED_PDF_LANDING_PAGE
};
SubTreeArticleIterator artIter = createSubTreeIter();
// for (SubTreeArticleIterator artIter = createSubTreeIter(); artIter.hasNext(); ) {
ArticleFiles af = artIter.next();
String[] actualUrls = { af.getFullTextUrl(),
af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF),
//af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE)
};
//log.info("actualUrls: " + actualUrls.length);
for (int i = 0;i< actualUrls.length; i++) {
//log.info("e_url: " + expectedUrls[i]);
//log.info("url: " + actualUrls[i]);
assertEquals(expectedUrls[i], actualUrls[i]);
}
}
}
|
// RMG - Reaction Mechanism Generator
// RMG Team ([email protected])
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxnSys;
import java.io.*;
import jing.rxnSys.ReactionSystem;
import jing.rxn.*;
import jing.chem.*;
import java.util.*;
import jing.mathTool.UncertainDouble;
import jing.param.*;
import jing.chemUtil.*;
import jing.chemParser.*;
//## package jing::rxnSys
// jing\rxnSys\ReactionModelGenerator.java
//## class ReactionModelGenerator
public class ReactionModelGenerator {
protected LinkedList timeStep; //## attribute timeStep
protected ReactionModel reactionModel; //gmagoon 9/24/07
protected String workingDirectory; //## attribute workingDirectory
// protected ReactionSystem reactionSystem;
protected LinkedList reactionSystemList; //10/24/07 gmagoon: changed from reactionSystem to reactionSystemList
protected int paraInfor;//svp
protected boolean error;//svp
protected boolean sensitivity;//svp
protected LinkedList species;//svp
// protected InitialStatus initialStatus;//svp
protected LinkedList initialStatusList; //10/23/07 gmagoon: changed from initialStatus to initialStatusList
protected double rtol;//svp
protected static double atol;
protected PrimaryKineticLibrary primaryKineticLibrary;//9/24/07 gmagoon
protected ReactionLibrary ReactionLibrary;
protected ReactionModelEnlarger reactionModelEnlarger;//9/24/07 gmagoon
protected LinkedHashSet speciesSeed;//9/24/07 gmagoon;
protected ReactionGenerator reactionGenerator;//9/24/07 gmagoon
protected LibraryReactionGenerator lrg;// = new LibraryReactionGenerator();//9/24/07 gmagoon: moved from ReactionSystem.java;10/4/07 gmagoon: postponed initialization of lrg til later
//10/23/07 gmagoon: added additional variables
protected LinkedList tempList;
protected LinkedList presList;
protected LinkedList validList;//10/24/07 gmagoon: added
//10/25/07 gmagoon: moved variables from modelGeneration()
protected LinkedList initList = new LinkedList();
protected LinkedList beginList = new LinkedList();
protected LinkedList endList = new LinkedList();
protected LinkedList lastTList = new LinkedList();
protected LinkedList currentTList = new LinkedList();
protected LinkedList lastPList = new LinkedList();
protected LinkedList currentPList = new LinkedList();
protected LinkedList conditionChangedList = new LinkedList();
protected LinkedList reactionChangedList = new LinkedList();
protected int numConversions;//5/6/08 gmagoon: moved from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
protected String equationOfState;
// 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file
// This temperature is used to select the "best" kinetics from the rxn library
protected static Temperature temp4BestKinetics;
// Added by AJ on July 12, 2010
protected static boolean useDiffusion;
protected SeedMechanism seedMechanism = null;
protected PrimaryThermoLibrary primaryThermoLibrary;
protected PrimaryTransportLibrary primaryTransportLibrary;
protected boolean readrestart = false;
protected boolean writerestart = false;
protected LinkedHashSet restartCoreSpcs = new LinkedHashSet();
protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet();
protected LinkedHashSet restartCoreRxns = new LinkedHashSet();
protected LinkedHashSet restartEdgeRxns = new LinkedHashSet();
// Constructors
private HashSet specs = new HashSet();
//public static native long getCpuTime();
//static {System.loadLibrary("cpuTime");}
public static boolean rerunFame = false;
protected static double tolerance;//can be interpreted as "coreTol" (vs. edgeTol)
protected static double termTol;
protected static double edgeTol;
protected static int minSpeciesForPruning;
protected static int maxEdgeSpeciesAfterPruning;
public int limitingReactantID = 1;
public int numberOfEquivalenceRatios = 0;
//## operation ReactionModelGenerator()
public ReactionModelGenerator() {
workingDirectory = System.getProperty("RMG.workingDirectory");
}
//## operation initializeReactionSystem()
//10/24/07 gmagoon: changed name to initializeReactionSystems
public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
setPrimaryKineticLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader, true);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader, true);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
line = readMaxAtomTypes(line,reader);
// if (line.startsWith("MaxCarbonNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
// int maxCNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxCarbonNumber(maxCNum);
// System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxOxygenNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
// int maxONum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxOxygenNumber(maxONum);
// System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxRadicalNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
// int maxRadNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxRadicalNumber(maxRadNum);
// System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxSulfurNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
// int maxSNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSulfurNumber(maxSNum);
// System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxSiliconNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
// int maxSiNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSiliconNumber(maxSiNum);
// System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxHeavyAtom")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
// int maxHANum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxHeavyAtomNumber(maxHANum);
// System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
// line = ChemParser.readMeaningfulLine(reader);
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader, true);
/*
* MRH 17-May-2010:
* Added primary transport library field
*/
if (line.toLowerCase().startsWith("primarytransportlibrary")) {
readAndMakePTransL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryTransportLibrary field.");
line = ChemParser.readMeaningfulLine(reader, true);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
readRestartReactions();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
createTModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String t = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// tempList = new LinkedList();
// //read first temperature
// double t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
// Global.lowTemperature = (Temperature)temp.clone();
// Global.highTemperature = (Temperature)temp.clone();
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
// if(temp.getK() < Global.lowTemperature.getK())
// Global.lowTemperature = (Temperature)temp.clone();
// if(temp.getK() > Global.highTemperature.getK())
// Global.highTemperature = (Temperature)temp.clone();
// // Global.temperature = new Temperature(t,unit);
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
// else {
// throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PressureModel:")) {
createPModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String p = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// presList = new LinkedList();
// //read first pressure
// double p = Double.parseDouble(st.nextToken());
// Pressure pres = new Pressure(p, unit);
// Global.lowPressure = (Pressure)pres.clone();
// Global.highPressure = (Pressure)pres.clone();
// presList.add(new ConstantPM(p, unit));
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// p = Double.parseDouble(st.nextToken());
// presList.add(new ConstantPM(p, unit));
// pres = new Pressure(p, unit);
// if(pres.getBar() < Global.lowPressure.getBar())
// Global.lowPressure = (Pressure)pres.clone();
// if(pres.getBar() > Global.lowPressure.getBar())
// Global.highPressure = (Pressure)pres.clone();
// //Global.pressure = new Pressure(p, unit);
// //10/23/07 gmagoon: commenting out; further updates needed to get this to work
// //else if (modelType.equals("Curved")) {
// // // add reading curved pressure function here
// // pressureModel = new CurvedPM(new LinkedList());
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Diffusion effects
// If 'Diffusion' is 'on' then override the settings made by the solvation flag and sets solvation 'on'
if (line.startsWith("Diffusion:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String diffusionOnOff = st.nextToken().toLowerCase();
if (diffusionOnOff.equals("on")) {
//Species.useSolvation = true;
setUseDiffusion(true);
} else if (diffusionOnOff.equals("off")) {
setUseDiffusion(false);
}
else throw new InvalidSymbolException("condition.txt: Unknown diffusion flag: " + diffusionOnOff);
line = ChemParser.readMeaningfulLine(reader,true);//read in reactants or thermo line
}
/* AJ 12JULY2010:
* Right now we do not want RMG to throw an exception if it cannot find a diffusion flag
*/
//else throw new InvalidSymbolException("condition.txt: Cannot find diffusion flag.");
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
if(st.hasMoreTokens()){//override the default qmprogram ("both") if there are more; current options: "gaussian03" and "mopac" and of course, "both"
QMTP.qmprogram = st.nextToken().toLowerCase();
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader, true);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
/*
* 7/Apr/2010: MRH
* Neither of these variables are utilized
*/
// LinkedHashMap speciesStatus = new LinkedHashMap();
// int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
speciesSet = populateInitialStatusListWithReactiveSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken();
// //if (restart) name += "("+speciesnum+")";
// // 24Jun2009: MRH
// // Check if the species name begins with a number.
// // If so, terminate the program and inform the user to choose
// // a different name. This is implemented so that the chem.inp
// // file generated will be valid when run in Chemkin
// try {
// int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
// System.out.println("\nA species name should not begin with a number." +
// " Please rename species: " + name + "\n");
// System.exit(0);
// } catch (NumberFormatException e) {
// // We're good
// speciesnum ++;
// if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// String conc = st.nextToken();
// double concentration = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// concentration /= 1000;
// unit = "mol/cm3";
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// concentration /= 1000000;
// unit = "mol/cm3";
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// concentration /= 6.022e23;
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Species Concentration in condition.txt!");
// //GJB to allow "unreactive" species that only follow user-defined library reactions.
// // They will not react according to RMG reaction families
// boolean IsReactive = true;
// boolean IsConstantConcentration = false;
// while (st.hasMoreTokens()) {
// String reactive = st.nextToken().trim();
// if (reactive.equalsIgnoreCase("unreactive"))
// IsReactive = false;
// if (reactive.equalsIgnoreCase("constantconcentration"))
// IsConstantConcentration=true;
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
// //System.out.println(name);
// Species species = Species.make(name,cg);
// species.setReactivity(IsReactive); // GJB
// species.setConstantConcentration(IsConstantConcentration);
// speciesSet.put(name, species);
// getSpeciesSeed().add(species);
// double flux = 0;
// int species_type = 1; // reacted species
// SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
// speciesStatus.put(species, ss);
// line = ChemParser.readMeaningfulLine(reader);
// ReactionTime initial = new ReactionTime(0,"S");
// //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
// initialStatusList = new LinkedList();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// LinkedHashMap speStat = new LinkedHashMap();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
// SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
// speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
// initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("InertGas:")) {
populateInitialStatusListWithInertSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken().trim();
// String conc = st.nextToken();
// double inertConc = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// inertConc /= 1000;
// unit = "mol/cm3";
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// inertConc /= 1000000;
// unit = "mol/cm3";
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// inertConc /= 6.022e23;
// unit = "mol/cm3";
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
// //SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
// line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
if (readrestart) if (PDepNetwork.generateNetworks) readPDepNetworks();
// include species (optional)
/*
*
* MRH 3-APR-2010:
* This if statement is no longer necessary and was causing an error
* when the PressureDependence field was set to "off"
*/
// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
// line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader, true);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader, true);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant in 'Goal Conversion' field of input file : " + name);
setLimitingReactantID(spe.getID());
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader, true);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
if (temp.startsWith("AUTOPRUNE")){//for the AUTOPRUNE case, read in additional lines for termTol and edgeTol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TerminationTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
termTol = Double.parseDouble(st.nextToken());
}
else {
System.out.println("Cannot find TerminationTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PruningTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
edgeTol = Double.parseDouble(st.nextToken());
}
else {
System.out.println("Cannot find PruningTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MinSpeciesForPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
minSpeciesForPruning = Integer.parseInt(st.nextToken());
}
else {
System.out.println("Cannot find MinSpeciesForPruning in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MaxEdgeSpeciesAfterPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
maxEdgeSpeciesAfterPruning = Integer.parseInt(st.nextToken());
}
else {
System.out.println("Cannot find MaxEdgeSpeciesAfterPruning in condition.txt");
System.exit(0);
}
//print header for pruning log (based on restart format)
BufferedWriter bw = null;
try {
File f = new File("Pruning/edgeReactions.txt");
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
else if (temp.startsWith("AUTO")){//in the non-autoprune case (i.e. original AUTO functionality), we set the new parameters to values that should reproduce original functionality
termTol = tolerance;
edgeTol = 0;
minSpeciesForPruning = 999999;//arbitrary high number (actually, the value here should not matter, since pruning should not be done)
maxEdgeSpeciesAfterPruning = 999999;
}
// read in atol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader, true);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!");
// read in reaction model enlarger
/* Read in the Primary Kinetic Library
* The user can specify as many PKLs,
* including none, as they like.
*/
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PrimaryKineticLibrary:")) {
readAndMakePKL(reader);
} else throw new InvalidSymbolException("condition.txt: can't find PrimaryKineticLibrary");
// Reaction Library
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactionLibrary:")) {
readAndMakeReactionLibrary(reader);
} else throw new InvalidSymbolException("condition.txt: can't find ReactionLibrary");
/*
* Added by MRH 12-Jun-2009
*
* The SeedMechanism acts almost exactly as the old
* PrimaryKineticLibrary did. Whatever is in the SeedMechanism
* will be placed in the core at the beginning of the simulation.
* The user can specify as many seed mechanisms as they like, with
* the priority (in the case of duplicates) given to the first
* instance. There is no on/off flag.
*/
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SeedMechanism:")) {
line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("GenerateReactions: ");
String generateStr = tempString[tempString.length-1].trim();
boolean generate = true;
if (generateStr.equalsIgnoreCase("yes") ||
generateStr.equalsIgnoreCase("on") ||
generateStr.equalsIgnoreCase("true")){
generate = true;
System.out.println("Will generate cross-reactions between species in seed mechanism " + name);
} else if(generateStr.equalsIgnoreCase("no") ||
generateStr.equalsIgnoreCase("off") ||
generateStr.equalsIgnoreCase("false")) {
generate = false;
System.out.println("Will NOT initially generate cross-reactions between species in seed mechanism "+ name);
System.out.println("This may have unintended consequences");
}
else {
System.err.println("Input file invalid");
System.err.println("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name);
System.exit(0);
}
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (getSeedMechanism() == null)
setSeedMechanism(new SeedMechanism(name, path, generate, false));
else
getSeedMechanism().appendSeedMechanism(name, path, generate, false);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (getSeedMechanism() != null) System.out.println("Seed Mechanisms in use: " + getSeedMechanism().getName());
else setSeedMechanism(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate SeedMechanism field");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ChemkinUnits")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Verbose:")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken();
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
ArrheniusKinetics.setVerbose(false);
} else if (OnOff.equals("on")) {
ArrheniusKinetics.setVerbose(true);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
/*
* MRH 3MAR2010:
* Adding user option regarding chemkin file
*
* New field: If user would like the empty SMILES string
* printed with each species in the thermochemistry portion
* of the generated chem.inp file
*/
if (line.toUpperCase().startsWith("SMILES")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "SMILES:"
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
Chemkin.setSMILES(false);
} else if (OnOff.equals("on")) {
Chemkin.setSMILES(true);
/*
* MRH 9MAR2010:
* MRH decided not to generate an InChI for every new species
* during an RMG simulation (especially since it is not used
* for anything). Instead, they will only be generated in the
* post-processing, if the user asked for InChIs.
*/
//Species.useInChI = true;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("A")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "A:"
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
ArrheniusKinetics.setAUnits(units);
else {
System.err.println("Units for A were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units A field.");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Ea")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "Ea:"
String units = st.nextToken();
if (units.equals("kcal/mol") || units.equals("cal/mol") ||
units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins"))
ArrheniusKinetics.setEaUnits(units);
else {
System.err.println("Units for Ea were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units Ea field.");
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate ChemkinUnits field.");
in.close();
// LinkedList temperatureArray = new LinkedList();
// LinkedList pressureArray = new LinkedList();
// Iterator iterIS = initialStatusList.iterator();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// InitialStatus is = (InitialStatus)iterIS.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));
// pressureArray.add(pm.getPressure(is.getTime()));
// PDepNetwork.setTemperatureArray(temperatureArray);
// PDepNetwork.setPressureArray(pressureArray);
//10/4/07 gmagoon: moved to modelGeneration()
//ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator
// setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added
/*
* MRH 12-Jun-2009
* A TemplateReactionGenerator now requires a Temperature be passed to it.
* This allows RMG to determine the "best" kinetic parameters to use
* in the mechanism generation. For now, I choose to pass the first
* temperature in the list of temperatures. RMG only outputs one mechanism,
* even for multiple temperature/pressure systems, so we can only have one
* set of kinetics.
*/
Temperature t = new Temperature(300,"K");
for (Iterator iter = tempList.iterator(); iter.hasNext();) {
TemperatureModel tm = (TemperatureModel)iter.next();
t = tm.getTemperature(new ReactionTime(0,"sec"));
setTemp4BestKinetics(t);
break;
}
setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary kinetic library files!"
lrg = new LibraryReactionGenerator(ReactionLibrary);//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator
//10/24/07 gmagoon: updated to use multiple reactionSystem variables
reactionSystemList = new LinkedList();
// LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
Iterator iter3 = initialStatusList.iterator();
Iterator iter4 = dynamicSimulatorList.iterator();
int i = 0;//10/30/07 gmagoon: added
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
//InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop"
//DynamicSimulator ds = (DynamicSimulator)iter4.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
for (int numConcList=0; numConcList<initialStatusList.size()/tempList.size()/presList.size(); ++numConcList) {
// InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop""
InitialStatus is = (InitialStatus)initialStatusList.get(i); DynamicSimulator ds = (DynamicSimulator)iter4.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg;
//11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT
// TerminationTester termTestCopy;
// if (finishController.getTerminationTester() instanceof ConversionTT){
// ConversionTT termTest = (ConversionTT)finishController.getTerminationTester();
// LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone());
// termTestCopy = new ConversionTT(spcCopy);
// else{
// termTestCopy = finishController.getTerminationTester();
FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable"
// FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester());
reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryKineticLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState));
i++;//10/30/07 gmagoon: added
System.out.println("Created reaction system "+i+"\n");
System.out.println((initialStatusList.get(i-1)).toString() + "\n");
}
}
}
// PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
}
catch (IOException e) {
System.err.println("Error reading reaction system initialization file.");
throw new IOException("Input file error: " + e.getMessage());
}
}
public void setReactionModel(ReactionModel p_ReactionModel) {
reactionModel = p_ReactionModel;
}
public void modelGeneration() {
//long begin_t = System.currentTimeMillis();
try{
ChemGraph.readForbiddenStructure();
setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel
// setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems
// setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem
// initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
initializeReactionSystems();
}
catch (IOException e) {
System.err.println(e.getMessage());
System.exit(0);
}
catch (InvalidSymbolException e) {
System.err.println(e.getMessage());
System.exit(0);
}
//10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called
validList = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
validList.add(false);
}
initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
//10/24/07 gmagoon: changed to use reactionSystemList
// LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class
// LinkedList beginList = new LinkedList();
// LinkedList endList = new LinkedList();
// LinkedList lastTList = new LinkedList();
// LinkedList currentTList = new LinkedList();
// LinkedList lastPList = new LinkedList();
// LinkedList currentPList = new LinkedList();
// LinkedList conditionChangedList = new LinkedList();
// LinkedList reactionChangedList = new LinkedList();
//5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester)
boolean intermediateSteps = true;
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (timeStep == null){
intermediateSteps = false;
}
}
else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length
intermediateSteps=false;
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
if (!readrestart) rs.initializePDepNetwork();
}
ReactionTime init = rs.getInitialReactionTime();
initList.add(init);
ReactionTime begin = init;
beginList.add(begin);
ReactionTime end;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
end = (ReactionTime)timeStep.get(0);
}
else{
end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime;
}
//end = (ReactionTime)timeStep.get(0);
endList.add(end);
}
else{
end = new ReactionTime(1e6,"sec");
endList.add(end);
}
// int iterationNumber = 1;
lastTList.add(rs.getTemperature(init));
currentTList.add(rs.getTemperature(init));
lastPList.add(rs.getPressure(init));
currentPList.add(rs.getPressure(init));
conditionChangedList.add(false);
reactionChangedList.add(false);//10/31/07 gmagoon: added
//Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus());
}
int iterationNumber = 1;
LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated
//validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel
//10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively
boolean allTerminated = true;
boolean allValid = true;
// IF RESTART IS TURNED ON
// Update the systemSnapshot for each ReactionSystem in the reactionSystemList
if (readrestart) {
for (Integer i=0; i<reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
InitialStatus is = rs.getInitialStatus();
putRestartSpeciesInInitialStatus(is,i);
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1));
Chemkin.writeChemkinInputFile(rs);
boolean terminated = rs.isReactionTerminated();
terminatedList.add(terminated);
if(!terminated)
allTerminated = false;
boolean valid = rs.isModelValid();
//validList.add(valid);
validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel
if(!valid)
allValid = false;
reactionChangedList.set(i,false);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
//System.exit(0);
printModelSize();
StringBuilder print_info = Global.diagnosticInfo;
print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n");
print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac");
print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n");
double solverMin = 0;
double vTester = 0;
/*if (!restart){
writeRestartFile();
writeCoreReactions();
writeAllReactions();
}*/
//System.exit(0);
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
System.out.println("Species dictionary size: "+dictionary.size());
double tAtInitialization = Global.tAtInitialization;
//10/24/07: changed to use allTerminated and allValid
// step 2: iteratively grow reaction system
while (!allTerminated || !allValid) {
while (!allValid) {
//writeCoreSpecies();
double pt = System.currentTimeMillis();
// Grab all species from primary kinetics / reaction libraries
// WE CANNOT PRUNE THESE SPECIES
HashMap unprunableSpecies = new HashMap();
if (getPrimaryKineticLibrary() != null) {
unprunableSpecies.putAll(getPrimaryKineticLibrary().speciesSet);
}
if (getReactionLibrary() != null) {
unprunableSpecies.putAll(getReactionLibrary().getDictionary());
}
//prune the reaction model (this will only do something in the AUTO case)
pruneReactionModel(unprunableSpecies);
garbageCollect();
//System.out.println("After pruning:");
//printModelSize();
// ENLARGE THE MODEL!!! (this is where the good stuff happens)
enlargeReactionModel();
double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60;
//PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet());
//10/24/07 gmagoon: changed to use reactionSystemList
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.initializePDepNetwork();
}
//reactionSystem.initializePDepNetwork();
}
pt = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.resetSystemSnapshot();
}
//reactionSystem.resetSystemSnapshot();
double resetSystem = (System.currentTimeMillis() - pt)/1000/60;
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
//reactionChanged = true;
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i,true);
// begin = init;
beginList.set(i, (ReactionTime)initList.get(i));
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
endList.set(i,(ReactionTime)timeStep.get(0));
}
else{
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
}
// endList.set(i, (ReactionTime)timeStep.get(0));
//end = (ReactionTime)timeStep.get(0);
}
else
endList.set(i, new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
// iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
}
iterationNumber = 1;
double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1));
//end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
for (Integer i = 0; i<reactionSystemList.size();i++) {
// we over-write the chemkin file each time, so only the LAST reaction system is saved
// i.e. if you are using RATE for pdep, only the LAST pressure is used.
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(rs);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
double chemkint = (System.currentTimeMillis()-startTime)/1000/60;
if (writerestart) {
/*
* Rename current restart files:
* In the event RMG fails while writing the restart files,
* user won't lose any information
*/
String[] restartFiles = {"Restart/coreReactions.txt", "Restart/coreSpecies.txt",
"Restart/edgeReactions.txt", "Restart/edgeSpecies.txt",
"Restart/pdepnetworks.txt", "Restart/pdepreactions.txt"};
writeBackupRestartFiles(restartFiles);
writeCoreSpecies();
writeCoreReactions();
writeEdgeSpecies();
writeEdgeReactions();
if (PDepNetwork.generateNetworks == true) writePDepNetworks();
/*
* Remove backup restart files from Restart folder
*/
removeBackupRestartFiles(restartFiles);
}
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(getLimitingReactantID());
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getFullName() + " is:");
System.out.println(conv);
}
System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis()-tAtInitialization)/1000/60) + " minutes.");
printModelSize();
printMemoryUsed();
startTime = System.currentTimeMillis();
double mU = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
double gc = (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: updating to use reactionSystemList
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
if(!valid)
allValid = false;
validList.set(i,valid);
//valid = reactionSystem.isModelValid();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
writeDiagnosticInfo();
writeEnlargerInfo();
double restart2 = (System.currentTimeMillis()-startTime)/1000/60;
int allSpecies, allReactions;
allSpecies = SpeciesDictionary.getInstance().size();
print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n");
}
//5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps
double startTime = System.currentTimeMillis();
if(intermediateSteps){
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i, false);
//reactionChanged = false;
Temperature currentT = (Temperature)currentTList.get(i);
Pressure currentP = (Pressure)currentPList.get(i);
lastTList.set(i,(Temperature)currentT.clone()) ;
lastPList.set(i,(Pressure)currentP.clone());
//lastT = (Temperature)currentT.clone();
//lastP = (Pressure)currentP.clone();
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time);
// begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber < timeStep.size()){
endList.set(i,(ReactionTime)timeStep.get(iterationNumber));
//end = (ReactionTime)timeStep.get(iterationNumber);
}
else
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else
endList.set(i,new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
}
iterationNumber++;
startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps
//double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1));
// end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
validList.set(i,valid);
if(!valid)
allValid = false;
}
}//5/6/08 gmagoon: end of block for intermediateSteps
allTerminated = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean terminated = rs.isReactionTerminated();
terminatedList.set(i,terminated);
if(!terminated){
allTerminated = false;
System.out.println("Reaction System "+(i+1)+" has not reached its termination criterion");
if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) {
System.out.println("although it seems to be valid (complete), so it was not interrupted for being invalid.");
System.out.println("This probably means there was an error with the ODE solver, and we risk entering an endless loop.");
System.out.println("Stopping.");
throw new Error();
}
}
}
// //10/24/07 gmagoon: changed to use reactionSystemList
// allTerminated = true;
// allValid = true;
// for (Integer i = 0; i<reactionSystemList.size();i++) {
// ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
// boolean terminated = rs.isReactionTerminated();
// terminatedList.set(i,terminated);
// if(!terminated)
// allTerminated = false;
// boolean valid = rs.isModelValid();
// validList.set(i,valid);
// if(!valid)
// allValid = false;
// //terminated = reactionSystem.isReactionTerminated();
// //valid = reactionSystem.isModelValid();
//10/24/07 gmagoon: changed to use reactionSystemList, allValid
if (allValid) {
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this reaction time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(getLimitingReactantID());
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getFullName() + " is:");
System.out.println(conv);
}
//System.out.println("At this time: " + end.toString());
//Species spe = SpeciesDictionary.getSpeciesFromID(1);
//double conv = reactionSystem.getPresentConversion(spe);
//System.out.print("current conversion = ");
//System.out.println(conv);
printMemoryUsed();
printModelSize();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing
}
//System.out.println("Performing model reduction");
if (paraInfor != 0){
System.out.println("Model Generation performed. Now generating sensitivity data.");
//10/24/07 gmagoon: updated to use reactionSystemList
LinkedList dynamicSimulator2List = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
//6/25/08 gmagoon: updated to pass index i
//6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here);
dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i));
//DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus);
((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length);
//dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length);
rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i));
//reactionSystem.setDynamicSimulator(dynamicSimulator2);
int numSteps = rs.systemSnapshot.size() -1;
rs.resetSystemSnapshot();
beginList.set(i, (ReactionTime)initList.get(i));
//begin = init;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else{
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i, end.add(end));
//end = end.add(end);
}
terminatedList.set(i, false);
//terminated = false;
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
rs.solveReactionSystemwithSEN(begin, end, true, false, false);
//reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false);
}
}
// All of the reaction systems are the same, so just write the chemkin
// file for the first reaction system
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(0);
Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus());
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
System.out.println("Model Generation Completed");
return;
}
//9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey
//this is based off of writeChemkinFile in ChemkinInputFile.java
private void writeInChIs(ReactionModel p_reactionModel) {
StringBuilder result=new StringBuilder();
for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) {
Species species = (Species) iter.next();
result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n");
}
String file = "inchiDictionary.txt";
try {
FileWriter fw = new FileWriter(file);
fw.write(result.toString());
fw.close();
}
catch (Exception e) {
System.out.println("Error in writing InChI file inchiDictionary.txt!");
System.out.println(e.getMessage());
System.exit(0);
}
}
//9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java
private void writeDictionary(ReactionModel rm){
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
//Write core species to RMG_Dictionary.txt
String coreSpecies ="";
Iterator iter = cerm.getSpecies();
if (Species.useInChI) {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
} else {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
}
try{
File rmgDictionary = new File("RMG_Dictionary.txt");
FileWriter fw = new FileWriter(rmgDictionary);
fw.write(coreSpecies);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Dictionary.txt");
System.exit(0);
}
// If we have solvation on, then every time we write the dictionary, also write the solvation properties
if (Species.useSolvation) {
writeSolvationProperties(rm);
}
}
private void writeSolvationProperties(ReactionModel rm){
//Write core species to RMG_Solvation_Properties.txt
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
StringBuilder result = new StringBuilder();
result.append("ChemkinName\tChemicalFormula\tMolecularWeight\tRadius\tDiffusivity\tAbrahamS\tAbrahamB\tAbrahamE\tAbrahamL\tAbrahamA\tAbrahamV\tChemkinName\n\n");
Iterator iter = cerm.getSpecies();
while (iter.hasNext()){
Species spe = (Species)iter.next();
result.append(spe.getChemkinName() + "\t");
result.append(spe.getChemGraph().getChemicalFormula()+ "\t");
result.append(spe.getMolecularWeight() + "\t");
result.append(spe.getChemGraph().getRadius()+ "\t");
result.append(spe.getChemGraph().getDiffusivity()+ "\t");
result.append(spe.getChemGraph().getAbramData().toString()+ "\t");
result.append(spe.getChemkinName() + "\n");
}
try{
File rmgSolvationProperties = new File("RMG_Solvation_Properties.txt");
FileWriter fw = new FileWriter(rmgSolvationProperties);
fw.write(result.toString() );
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Solvation_Properties.txt");
System.exit(0);
}
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseRestartFiles method
*/
// private void parseRestartFiles() {
// parseAllSpecies();
// parseCoreSpecies();
// parseEdgeSpecies();
// parseAllReactions();
// parseCoreReactions();
/*
* MRH 23MAR2010:
* Commenting out deprecated parseEdgeReactions method
*/
// private void parseEdgeReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File coreReactions = new File("Restart/edgeReactions.txt");
// FileReader fr = new FileReader(coreReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// while (line != null){
// Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1);
// boolean added = reactionSet.add(reaction);
// if (!added){
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// if (!found){
// System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added");
// System.exit(0);
// else found = false;
// //Reaction reverse = reaction.getReverseReaction();
// //if (reverse != null) reactionSet.add(reverse);
// line = ChemParser.readMeaningfulLine(reader);
// ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
// catch (IOException e){
// System.out.println("Could not read the corespecies restart file");
// System.exit(0);
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public void parseCoreReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// int i=1;
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File coreReactions = new File("Restart/coreReactions.txt");
// FileReader fr = new FileReader(coreReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// while (line != null){
// Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel));
// boolean added = reactionSet.add(reaction);
// if (!added){
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// if (!found){
// System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
// //System.exit(0);
// else found = false;
// Reaction reverse = reaction.getReverseReaction();
// if (reverse != null) {
// reactionSet.add(reverse);
// //System.out.println(2 + "\t " + line);
// //else System.out.println(1 + "\t" + line);
// line = ChemParser.readMeaningfulLine(reader);
// i=i+1;
// ((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet);
// catch (IOException e){
// System.out.println("Could not read the coreReactions restart file");
// System.exit(0);
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// private void parseAllReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// int i=1;
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File allReactions = new File("Restart/allReactions.txt");
// FileReader fr = new FileReader(allReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// OuterLoop:
// while (line != null){
// Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel()));
// if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){
// boolean added = reactionSet.add(reaction);
// if (!added){
// found = false;
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// if (!found){
// Iterator iter = reactionSet.iterator();
// while (iter.hasNext()){
// Reaction reacTemp = (Reaction)iter.next();
// if (reacTemp.equals(reaction)){
// reactionSet.remove(reacTemp);
// reactionSet.add(reaction);
// break;
// //System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
// //System.exit(0);
// //else found = false;
// /*Reaction reverse = reaction.getReverseReaction();
// if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) {
// reactionSet.add(reverse);
// //System.out.println(2 + "\t " + line);
// }*/
// //else System.out.println(1 + "\t" + line);
// i=i+1;
// line = ChemParser.readMeaningfulLine(reader);
// ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
// catch (IOException e){
// System.out.println("Could not read the corespecies restart file");
// System.exit(0);
private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) {
Structure reactionStructure = p_Reaction.getStructure();
//Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList());
boolean found = false;
if (rOrP.equals("reactants")){
Iterator originalreactants = reactionStructure.getReactants();
HashSet tempHashSet = new HashSet();
while(originalreactants.hasNext()){
tempHashSet.add(originalreactants.next());
}
Iterator reactants = tempHashSet.iterator();
while(reactants.hasNext() && !found){
ChemGraph reactant = (ChemGraph)reactants.next();
if (reactant.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeReactants(reactant);
reactionStructure.addReactants(newChemGraph);
reactant = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
else{
Iterator originalproducts = reactionStructure.getProducts();
HashSet tempHashSet = new HashSet();
while(originalproducts.hasNext()){
tempHashSet.add(originalproducts.next());
}
Iterator products = tempHashSet.iterator();
while(products.hasNext() && !found){
ChemGraph product = (ChemGraph)products.next();
if (product.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeProducts(product);
reactionStructure.addProducts(newChemGraph);
product = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
return found;
}
public void parseCoreSpecies() {
// String restartFileContent ="";
//int speciesCount = 0;
//boolean added;
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File coreSpecies = new File ("Restart/coreSpecies.txt");
FileReader fr = new FileReader(coreSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader, true);
//HashSet speciesSet = new HashSet();
// if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway
// //ReactionSystem reactionSystem = new ReactionSystem();
setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
System.out.println("There was no species with ID "+ID +" in the species dictionary");
((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
public static void garbageCollect(){
System.gc();
}
public static void printMemoryUsed(){
garbageCollect();
Runtime rT = Runtime.getRuntime();
long uM, tM, fM;
tM = rT.totalMemory();
fM = rT.freeMemory();
uM = tM - fM;
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(uM);
System.out.print("Free memory: ");
System.out.println(fM);
}
private HashSet readIncludeSpecies(String fileName) {
HashSet speciesSet = new HashSet();
try {
File includeSpecies = new File (fileName);
FileReader fr = new FileReader(includeSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken().trim();
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.out.println("Included species file "+fileName+" contains a forbidden structure.");
System.exit(0);
}
Species species = Species.make(name,cg);
//speciesSet.put(name, species);
speciesSet.add(species);
line = ChemParser.readMeaningfulLine(reader, true);
System.out.println(line);
}
}
catch (IOException e){
System.out.println("Could not read the included species file" + fileName);
System.exit(0);
}
return speciesSet;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public LinkedHashSet parseAllSpecies() {
// // String restartFileContent ="";
// int speciesCount = 0;
// LinkedHashSet speciesSet = new LinkedHashSet();
// boolean added;
// try{
// long initialTime = System.currentTimeMillis();
// File coreSpecies = new File ("allSpecies.txt");
// BufferedReader reader = new BufferedReader(new FileReader(coreSpecies));
// String line = ChemParser.readMeaningfulLine(reader);
// int i=0;
// while (line!=null) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken().trim();
// int ID = getID(name);
// name = getName(name);
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// System.exit(0);
// Species species;
// if (ID == 0)
// species = Species.make(name,cg);
// else
// species = Species.make(name,cg,ID);
// speciesSet.add(species);
// double flux = 0;
// int species_type = 1;
// line = ChemParser.readMeaningfulLine(reader);
// System.out.println(line);
// catch (IOException e){
// System.out.println("Could not read the allSpecies restart file");
// System.exit(0);
// return speciesSet;
private String getName(String name) {
//int id;
String number = "";
int index=0;
if (!name.endsWith(")")) return name;
else {
char [] nameChars = name.toCharArray();
String temp = String.copyValueOf(nameChars);
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') {
index=i;
i=0;
}
else i = i-1;
}
}
number = name.substring(0,index);
return number;
}
private int getID(String name) {
int id;
String number = "";
if (!name.endsWith(")")) return 0;
else {
char [] nameChars = name.toCharArray();
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') i=0;
else{
number = name.charAt(i)+number;
i = i-1;
}
}
}
id = Integer.parseInt(number);
return id;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// private void parseEdgeSpecies() {
// // String restartFileContent ="";
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// try{
// File edgeSpecies = new File ("Restart/edgeSpecies.txt");
// FileReader fr = new FileReader(edgeSpecies);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// //HashSet speciesSet = new HashSet();
// while (line!=null) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// int ID = Integer.parseInt(index);
// Species spe = dictionary.getSpeciesFromID(ID);
// if (spe == null)
// System.out.println("There was no species with ID "+ID +" in the species dictionary");
// //reactionSystem.reactionModel = new CoreEdgeReactionModel();
// ((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe);
// line = ChemParser.readMeaningfulLine(reader);
// catch (IOException e){
// System.out.println("Could not read the edgepecies restart file");
// System.exit(0);
/*private int calculateAllReactionsinReactionTemplate() {
int totalnum = 0;
TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator;
Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate();
while (iter.hasNext()){
ReactionTemplate rt = (ReactionTemplate)iter.next();
totalnum += rt.getNumberOfReactions();
}
return totalnum;
}*/
private void writeEnlargerInfo() {
try {
File diagnosis = new File("enlarger.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.enlargerInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write enlarger file");
System.exit(0);
}
}
private void writeDiagnosticInfo() {
try {
File diagnosis = new File("diagnosis.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.diagnosticInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write diagnosis file");
System.exit(0);
}
}
//10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified
//Is still incomplete.
public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) {
//writeCoreSpecies(p_rs);
//writeCoreReactions(p_rs, p_time);
//writeEdgeSpecies();
//writeAllReactions(p_rs, p_time);
//writeEdgeReactions(p_rs, p_time);
//String restartFileName;
//String restartFileContent="";
}
/*
* MRH 25MAR2010
* This method is no longer used
*/
/*Only write the forward reactions in the model core.
The reverse reactions are generated from the forward reactions.*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent =new StringBuilder();
// int reactionCount = 1;
// try{
// File coreSpecies = new File ("Restart/edgeReactions.txt");
// FileWriter fw = new FileWriter(coreSpecies);
// for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// //if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// reactionCount = reactionCount + 1;
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// catch (IOException e){
// System.out.println("Could not write the restart edgereactions file");
// System.exit(0);
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent = new StringBuilder();
// int reactionCount = 1;
// try{
// File allReactions = new File ("Restart/allReactions.txt");
// FileWriter fw = new FileWriter(allReactions);
// for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// //if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// catch (IOException e){
// System.out.println("Could not write the restart edgereactions file");
// System.exit(0);
private void writeEdgeSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt"));
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getFullName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writePrunedEdgeSpecies(Species species) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Pruning/edgeSpecies.txt", true));
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent = new StringBuilder();
// int reactionCount = 0;
// try{
// File coreSpecies = new File ("Restart/coreReactions.txt");
// FileWriter fw = new FileWriter(coreSpecies);
// for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// reactionCount = reactionCount + 1;
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// catch (IOException e){
// System.out.println("Could not write the restart corereactions file");
// System.exit(0);
private void writeCoreSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt"));
for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getFullName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeCoreReactions() {
BufferedWriter bw_rxns = null;
BufferedWriter bw_pdeprxns = null;
try {
bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt"));
bw_pdeprxns = new BufferedWriter(new FileWriter("Restart/pdepreactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
String AUnits = ArrheniusKinetics.getAUnits();
bw_rxns.write("UnitsOfEa: " + EaUnits);
bw_rxns.newLine();
bw_pdeprxns.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_pdeprxns.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet allcoreRxns = cerm.core.reaction;
for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
if (reaction instanceof TROEReaction) {
TROEReaction troeRxn = (TROEReaction) reaction;
bw_pdeprxns.write(troeRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else if (reaction instanceof LindemannReaction) {
LindemannReaction lindeRxn = (LindemannReaction) reaction;
bw_pdeprxns.write(lindeRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else if (reaction instanceof ThirdBodyReaction) {
ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction;
bw_pdeprxns.write(tbRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw_rxns.write(reaction.toRestartString(new Temperature(298,"K"),false));
bw_rxns.newLine();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw_rxns != null) {
bw_rxns.flush();
bw_rxns.close();
}
if (bw_pdeprxns != null) {
bw_pdeprxns.flush();
bw_pdeprxns.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeEdgeReactions() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet alledgeRxns = cerm.edge.reaction;
for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw.write(reaction.toRestartString(new Temperature(298,"K"),false));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
//bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K"),false));
bw.newLine();
} else
System.out.println("Could not determine forward direction for following rxn: " + reaction.toString());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
//gmagoon 4/5/10: based on Mike's writeEdgeReactions
private void writePrunedEdgeReaction(Reaction reaction) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
if (reaction.isForward()) {
bw.write(reaction.toChemkinString(new Temperature(298,"K")));
// bw.write(reaction.toRestartString(new Temperature(298,"K")));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
//bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K")));
bw.newLine();
} else
System.out.println("Could not determine forward direction for following rxn: " + reaction.toString());
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writePDepNetworks() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt"));
int numFameTemps = PDepRateConstant.getTemperatures().length;
int numFamePress = PDepRateConstant.getPressures().length;
int numChebyTemps = ChebyshevPolynomials.getNT();
int numChebyPress = ChebyshevPolynomials.getNP();
int numPlog = PDepArrheniusKinetics.getNumPressures();
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
bw.write("NumberOfFameTemps: " + numFameTemps);
bw.newLine();
bw.write("NumberOfFamePress: " + numFamePress);
bw.newLine();
bw.write("NumberOfChebyTemps: " + numChebyTemps);
bw.newLine();
bw.write("NumberOfChebyPress: " + numChebyPress);
bw.newLine();
bw.write("NumberOfPLogs: " + numPlog);
bw.newLine();
bw.newLine();
LinkedList allNets = PDepNetwork.getNetworks();
for(Iterator iter=allNets.iterator(); iter.hasNext();){
PDepNetwork pdepnet = (PDepNetwork) iter.next();
bw.write("PDepNetwork #" + pdepnet.getID());
bw.newLine();
// Write netReactionList
LinkedList netRxns = pdepnet.getNetReactions();
bw.write("netReactionList:");
bw.newLine();
for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
// Write nonincludedReactionList
LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions();
bw.write("nonIncludedReactionList:");
bw.newLine();
for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
// Not all nonIncludedReactions are reversible
if (currentPDepReverseRxn != null) {
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
}
// Write pathReactionList
LinkedList pathRxns = pdepnet.getPathReactions();
bw.write("pathReactionList:");
bw.newLine();
for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toRestartString(new Temperature(298,"K")));
bw.newLine();
}
bw.newLine();
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps,
int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) {
StringBuilder sb = new StringBuilder();
// Write the rate coefficients
double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants();
for (int i=0; i<numFameTemps; i++) {
for (int j=0; j<numFamePress; j++) {
sb.append(rateConstants[i][j] + "\t");
}
sb.append("\n");
}
sb.append("\n");
// If chebyshev polynomials are present, write them
if (numChebyTemps != 0) {
ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev();
for (int i=0; i<numChebyTemps; i++) {
for (int j=0; j<numChebyPress; j++) {
sb.append(chebyPolys.getAlpha(i,j) + "\t");
}
sb.append("\n");
}
sb.append("\n");
}
// If plog parameters are present, write them
else if (numPlog != 0) {
PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics();
for (int i=0; i<numPlog; i++) {
double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K"));
sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n");
}
sb.append("\n");
}
return sb.toString();
}
public LinkedList getTimeStep() {
return timeStep;
}
public static boolean getUseDiffusion() {
return useDiffusion;
}
public void setUseDiffusion(Boolean p_boolean) {
useDiffusion = p_boolean;
}
public void setTimeStep(ReactionTime p_timeStep) {
if (timeStep == null)
timeStep = new LinkedList();
timeStep.add(p_timeStep);
}
public String getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(String p_workingDirectory) {
workingDirectory = p_workingDirectory;
}
//svp
public boolean getError(){
return error;
}
//svp
public boolean getSensitivity(){
return sensitivity;
}
public LinkedList getSpeciesList() {
return species;
}
//gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem
// public ReactionSystem getReactionSystem() {
// return reactionSystem;
//11/2/07 gmagoon: adding accessor method for reactionSystemList
public LinkedList getReactionSystemList(){
return reactionSystemList;
}
//added by gmagoon 9/24/07
// public void setReactionSystem(ReactionSystem p_ReactionSystem) {
// reactionSystem = p_ReactionSystem;
//copied from ReactionSystem.java by gmagoon 9/24/07
public ReactionModel getReactionModel() {
return reactionModel;
}
public void readRestartSpecies() {
System.out.println("Reading in species from Restart folder");
// Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure)
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")");
Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartCoreSpcs.add(species);
/*int species_type = 1; // reacted species
for (int i=0; i<numRxnSystems; i++) {
SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]);
speciesStatus[i].put(species, ss);
}*/
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Read in edge species
try {
FileReader in = new FileReader("Restart/edgeSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Rewrite the species name ... with the exception of the (
String speciesName = splitString1[0];
for (int numTokens=1; numTokens<splitString1.length-1; ++numTokens) {
speciesName += "(" + splitString1[numTokens];
}
// Make the species
Species species = Species.make(speciesName,cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartEdgeSpcs.add(species);
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readRestartReactions() {
// Grab the IDs from the core species
int[] coreSpcsIds = new int[restartCoreSpcs.size()];
int i = 0;
for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) {
Species spcs = (Species)iter.next();
coreSpcsIds[i] = spcs.getID();
++i;
}
System.out.println("Reading reactions from Restart folder");
// Read in core reactions
try {
FileReader in = new FileReader("Restart/coreReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits);
Iterator rxnIter = restartCoreRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics()[0],1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
if (r.hasReverseReaction()) r.generateReverseReaction();
restartCoreRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*
* Read in the pdepreactions.txt file:
* This file contains third-body, lindemann, and troe reactions
* A RMG mechanism would only have these reactions if a user specified
* them in a Seed Mechanism, meaning they are core species &
* reactions.
* Place these reactions in a new Seed Mechanism, using the
* coreSpecies.txt file as the species.txt file.
*/
try {
String path = System.getProperty("user.dir") + "/Restart";
if (getSeedMechanism() == null)
setSeedMechanism(new SeedMechanism("Restart", path, false, true));
else
getSeedMechanism().appendSeedMechanism("Restart", path, false, true);
} catch (IOException e1) {
e1.printStackTrace();
}
restartCoreRxns.addAll(getSeedMechanism().getReactionSet());
// Read in edge reactions
try {
FileReader in = new FileReader("Restart/edgeReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits);
Iterator rxnIter = restartEdgeRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics()[0],1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
r.generateReverseReaction();
restartEdgeRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public LinkedHashMap getRestartSpeciesStatus(int i) {
LinkedHashMap speciesStatus = new LinkedHashMap();
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader, true));
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
double y = 0.0;
double yprime = 0.0;
for (int j=0; j<numRxnSystems; j++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
if (j == i) {
y = Double.parseDouble(st.nextToken());
yprime = Double.parseDouble(st.nextToken());
}
}
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return speciesStatus;
}
public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) {
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
if (is.getSpeciesStatus(species) == null) {
SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0);
is.putSpeciesStatus(ss);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readPDepNetworks() {
LinkedList allNetworks = PDepNetwork.getNetworks();
try {
FileReader in = new FileReader("Restart/pdepnetworks.txt");
BufferedReader reader = new BufferedReader(in);
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
String tempString = st.nextToken();
String EaUnits = st.nextToken();
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numFameTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numFamePs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numChebyTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numChebyPs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numPlogs = Integer.parseInt(st.nextToken());
double[][] rateCoefficients = new double[numFameTs][numFamePs];
double[][] chebyPolys = new double[numChebyTs][numChebyPs];
Kinetics[] plogKinetics = new Kinetics[numPlogs];
String line = ChemParser.readMeaningfulLine(reader, true); // line should be "PDepNetwork
while (line != null) {
line = ChemParser.readMeaningfulLine(reader, true); // line should now be "netReactionList:"
PDepNetwork newNetwork = new PDepNetwork();
LinkedList netRxns = newNetwork.getNetReactions();
LinkedList nonincludeRxns = newNetwork.getNonincludedReactions();
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "nonIncludedReactionList"
// If line is "nonincludedreactionlist", we need to skip over this while loop
if (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
while (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\
/*
* Determine if netReaction is reversible or irreversible
*/
boolean reactionIsReversible = true;
if (reactsANDprods.length == 2)
reactionIsReversible = false;
else
reactsANDprods = line.split("\\<=>");
PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim());
PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim());
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
if (reactionIsReversible) {
PDepReaction reverse = new PDepReaction(Products, Reactants, new PDepRateConstant());
reverse.setPDepRateConstant(null);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
}
else {
PDepReaction reverse = null;
forward.setReverseReaction(reverse);
}
netRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
// This loop ends once line == "nonIncludedReactionList"
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "pathReactionList"
if (!line.toLowerCase().startsWith("pathreactionList")) {
while (!line.toLowerCase().startsWith("pathreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\
/*
* Determine if nonIncludedReaction is reversible or irreversible
*/
boolean reactionIsReversible = true;
if (reactsANDprods.length == 2)
reactionIsReversible = false;
else
reactsANDprods = line.split("\\<=>");
PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim());
PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim());
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
if (reactionIsReversible) {
PDepReaction reverse = new PDepReaction(Products, Reactants, new PDepRateConstant());
reverse.setPDepRateConstant(null);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
}
else {
PDepReaction reverse = null;
forward.setReverseReaction(reverse);
}
nonincludeRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
// This loop ends once line == "pathReactionList"
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "PDepNetwork #_" or null (end of file)
while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) {
st = new StringTokenizer(line);
int direction = Integer.parseInt(st.nextToken());
// First token is the rxn structure: A+B=C+D
// Note: Up to 3 reactants/products allowed
// : Either "=" or "=>" will separate reactants and products
String structure = st.nextToken();
// Separate the reactants from the products
boolean generateReverse = false;
String[] reactsANDprods = structure.split("\\=>");
if (reactsANDprods.length == 1) {
reactsANDprods = structure.split("[=]");
generateReverse = true;
}
SpeciesDictionary sd = SpeciesDictionary.getInstance();
LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]);
LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]);
Structure s = new Structure(r,p);
s.setDirection(direction);
// Next three tokens are the modified Arrhenius parameters
double rxn_A = Double.parseDouble(st.nextToken());
double rxn_n = Double.parseDouble(st.nextToken());
double rxn_E = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
rxn_E = rxn_E / 1000;
else if (EaUnits.equals("J/mol"))
rxn_E = rxn_E / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
rxn_E = rxn_E / 4.184;
else if (EaUnits.equals("Kelvins"))
rxn_E = rxn_E * 1.987;
UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A");
UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A");
UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A");
// The remaining tokens are comments
String comments = "";
if (st.hasMoreTokens()) {
String beginningOfComments = st.nextToken();
int startIndex = line.indexOf(beginningOfComments);
comments = line.substring(startIndex);
}
if (comments.startsWith("!")) comments = comments.substring(1);
// while (st.hasMoreTokens()) {
// comments += st.nextToken();
ArrheniusKinetics[] k = new ArrheniusKinetics[1];
k[0] = new ArrheniusKinetics(uA,un,uE,"",1,"",comments);
Reaction pathRxn = new Reaction();
// if (direction == 1)
// pathRxn = Reaction.makeReaction(s,k,generateReverse);
// else
// pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse);
pathRxn = Reaction.makeReaction(s,k,generateReverse);
PDepIsomer Reactants = new PDepIsomer(r);
PDepIsomer Products = new PDepIsomer(p);
PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn);
newNetwork.addReaction(pdeppathrxn,true);
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
line = ChemParser.readMeaningfulLine(reader, true);
}
newNetwork.setAltered(false);
PDepNetwork.getNetworks().add(newNetwork);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public PDepIsomer parseIsomerFromRestartFile(String p_string) {
SpeciesDictionary sd = SpeciesDictionary.getInstance();
PDepIsomer isomer = null;
if (p_string.contains("+")) {
String[] indivReacts = p_string.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromNameID(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
String[] nameANDincluded = name.split("\\(included =");
Species spc2 = sd.getSpeciesFromNameID(nameANDincluded[0].trim());
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1));
isomer = new PDepIsomer(spc1,spc2,isIncluded);
} else {
String name = p_string.trim();
/*
* Separate the (included =boolean) portion of the string
* from the name of the Isomer
*/
String[] nameANDincluded = name.split("\\(included =");
Species spc = sd.getSpeciesFromNameID(nameANDincluded[0].trim());
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1));
isomer = new PDepIsomer(spc,isIncluded);
}
return isomer;
}
public double[][] parseRateCoeffsFromRestartFile(int numFameTs, int numFamePs, BufferedReader reader) {
double[][] rateCoefficients = new double[numFameTs][numFamePs];
for (int i=0; i<numFameTs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
return rateCoefficients;
}
public PDepRateConstant parsePDepRateConstantFromRestartFile(BufferedReader reader,
int numChebyTs, int numChebyPs, double[][] rateCoefficients,
int numPlogs, String EaUnits) {
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
double chebyPolys[][] = new double[numChebyTs][numChebyPs];
for (int i=0; i<numChebyTs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(numPlogs);
for (int i=0; i<numPlogs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
return pdepk;
}
/**
* MRH 14Jan2010
*
* getSpeciesBySPCName
*
* Input: String name - Name of species, normally chemical formula followed
* by "J"s for radicals, and then (#)
* SpeciesDictionary sd
*
* This method was originally written as a complement to the method readPDepNetworks.
* jdmo found a bug with the readrestart option. The bug was that the method was
* attempting to add a null species to the Isomer list. The null species resulted
* from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the
* chemkinName present in the dictionary was SPC(48).
*
*/
public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) {
String[] nameFromNumber = name.split("\\(");
String newName = "SPC(" + nameFromNumber[1];
return sd.getSpeciesFromChemkinName(newName);
}
/**
* MRH 12-Jun-2009
*
* Function initializes the model's core and edge.
* The initial core species always consists of the species contained
* in the condition.txt file. If seed mechanisms exist, those species
* (and the reactions given in the seed mechanism) are also added to
* the core.
* The initial edge species/reactions are determined by reacting the core
* species by one full iteration.
*/
public void initializeCoreEdgeModel() {
LinkedHashSet allInitialCoreSpecies = new LinkedHashSet();
LinkedHashSet allInitialCoreRxns = new LinkedHashSet();
if (readrestart) {
allInitialCoreSpecies.addAll(restartCoreSpcs);
allInitialCoreRxns.addAll(restartCoreRxns);
}
// Add the species from the condition.txt (input) file
allInitialCoreSpecies.addAll(getSpeciesSeed());
// Add the species from the seed mechanisms, if they exist
if (hasSeedMechanisms()) {
allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet());
allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet());
}
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns);
if (readrestart) {
cerm.addUnreactedSpeciesSet(restartEdgeSpcs);
cerm.addUnreactedReactionSet(restartEdgeRxns);
}
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file and the seed mechanisms as the core
if (!readrestart) {
LinkedHashSet reactionSet_withdup;
LinkedHashSet reactionSet;
// If Seed Mechanism is present and Generate Reaction is set on
if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
reactionSet_withdup = getLibraryReactionGenerator().react(allInitialCoreSpecies);
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies));
// Removing Duplicates instances of reaction if present
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// shamel 6/22/2010 Suppressed output , line is only for debugging
//System.out.println("Current Reaction Set after RModG + LRG and Removing Dups"+reactionSet);
}
else {
reactionSet_withdup = new LinkedHashSet();
//System.out.println("Initial Core Species RModG"+allInitialCoreSpecies);
LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(allInitialCoreSpecies);
if(!tempnewReactionSet.isEmpty()){
System.out.println("Reaction Set Found from Reaction Library "+tempnewReactionSet);
}
// Adds Reactions Found in Library Reaction Generator to Reaction Set
reactionSet_withdup.addAll(getLibraryReactionGenerator().react(allInitialCoreSpecies));
// shamel 6/22/2010 Suppressed output , line is only for debugging
//System.out.println("Current Reaction Set after LRG"+reactionSet_withdup);
// Generates Reaction from the Reaction Generator and adds them to Reaction Set
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec,"All"));
}
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// shamel 6/22/2010 Suppressed output , line is only for debugging
//System.out.println("Current Reaction Set after RModG + LRG and Removing Dups"+reactionSet);
}
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
/*
* 22-SEPT-2010
* ELSE:
* If reading in restart files, at the very least, we should react
* all species present in the input file (speciesSeed) with all of
* the coreSpecies. Before, when the following else statement was
* not present, we would completely skip this step. Thus, RMG would
* come to the first ODE solve, integrate to a very large time, and
* conclude that the model was both valid and terminated, thereby
* not adding any new reactions to the core regardless of the
* conditions stated in the input file.
* EXAMPLE:
* A user runs RMG for iso-octane with Restart turned on. The
* simulation converges and now the user would like to add a small
* amount of 1-butanol to the input file, while reading in from the
* Restart files. What should happen, at the very least, is 1-butanol
* reacts with the other species present in the input file and with
* the already-known coreSpecies. This will, at a minimum, add these
* reactions to the core. Whether the model remains validated and
* terminated depends on the conditions stated in the input file.
* MRH ([email protected])
*/
else {
LinkedHashSet reactionSet_withdup;
LinkedHashSet reactionSet;
/*
* If the user has specified a Seed Mechanism, and that the cross reactions
* should be generated, generate those here
* NOTE: Since the coreSpecies from the Restart files are treated as a Seed
* Mechanism, MRH is inclined to comment out the following lines. Depending
* on how large the Seed Mechanism and/or Restart files are, RMG could get
* "stuck" cross-reacting hundreds of species against each other.
*/
// if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
// reactionSet_withdup = getLibraryReactionGenerator().react(getSeedMechanism().getSpeciesSet());
// reactionSet_withdup.addAll(getReactionGenerator().react(getSeedMechanism().getSpeciesSet()));
// reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
/*
* If not, react the species present in the input file against any
* reaction libraries, and then against all RMG-defined reaction
* families
*/
// else {
reactionSet_withdup = new LinkedHashSet();
LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(speciesSeed);
if (!tempnewReactionSet.isEmpty()) {
System.out.println("Reaction Set Found from Reaction Library "+tempnewReactionSet);
}
// Adds Reactions Found in Library Reaction Generator to Reaction Set
reactionSet_withdup.addAll(tempnewReactionSet);
// Generates Reaction from the Reaction Generator and adds them to Reaction Set
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies,spec,"All"));
}
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
}
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeModelWithPKL() {
initializeCoreEdgeModelWithoutPKL();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet primarySpeciesSet = getPrimaryKineticLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary
LinkedHashSet primaryKineticSet = getPrimaryKineticLibrary().getReactionSet();
cerm.addReactedSpeciesSet(primarySpeciesSet);
cerm.addPrimaryKineticSet(primaryKineticSet);
LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet());
if (reactionModelEnlarger instanceof RateBasedRME)
cerm.addReactionSet(newReactions);
else {
Iterator iter = newReactions.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){
cerm.addReaction(r);
}
}
}
return;
//
}
//9/24/07 gmagoon: moved from ReactionSystem.java
protected void initializeCoreEdgeModelWithoutPKL() {
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed()));
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file as the core
LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed());
reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed()));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
//10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement
//10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
//reactionSystem.setReactionModel(getReactionModel());
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
//
}
//## operation initializeCoreEdgeReactionModel()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeReactionModel() {
System.out.println("\nInitializing core-edge reaction model");
// setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon:moved from initializeReactionSystem; later moved to modelGeneration()
//#[ operation initializeCoreEdgeReactionModel()
// if (hasPrimaryKineticLibrary()) initializeCoreEdgeModelWithPKL();
// else initializeCoreEdgeModelWithoutPKL();
/*
* MRH 12-Jun-2009
*
* I've lumped the initializeCoreEdgeModel w/ and w/o a seed mechanism
* (which used to be the PRL) into one function. Before, RMG would
* complete one iteration (construct the edge species/rxns) before adding
* the seed mechanism to the rxn, thereby possibly estimating kinetic
* parameters for a rxn that exists in a seed mechanism
*/
initializeCoreEdgeModel();
//
}
//9/24/07 gmagoon: copied from ReactionSystem.java
public ReactionGenerator getReactionGenerator() {
return reactionGenerator;
}
//10/4/07 gmagoon: moved from ReactionSystem.java
public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) {
reactionGenerator = p_ReactionGenerator;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//10/24/07 gmagoon: changed to use reactionSystemList
//## operation enlargeReactionModel()
public void enlargeReactionModel() {
//#[ operation enlargeReactionModel()
if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger");
System.out.println("\nEnlarging reaction model");
reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList);
return;
//
}
public void pruneReactionModel(HashMap unprunableSpecies) {
HashMap prunableSpeciesMap = new HashMap();
//check whether all the reaction systems reached target conversion/time
boolean allReachedTarget = true;
for (Integer i = 0; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if (!ds.targetReached) allReachedTarget = false;
}
JDAS ds0 = (JDAS)((ReactionSystem) reactionSystemList.get(0)).getDynamicSimulator(); //get the first reactionSystem dynamic simulator
//prune the reaction model if AUTO is being used, and all reaction systems have reached target time/conversion, and edgeTol is non-zero (and positive, obviously), and if there are a sufficient number of species in the reaction model (edge + core)
if ( JDAS.autoflag &&
allReachedTarget &&
edgeTol>0 &&
(((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber()+reactionModel.getSpeciesNumber())>= minSpeciesForPruning){
int numberToBePruned = ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber() - maxEdgeSpeciesAfterPruning;
//System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, before pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber());
//System.out.println("PDep Pruning DEBUG:\nRMG thinks the following number of species" +
// " needs to be pruned: " + numberToBePruned);
Iterator iter = JDAS.edgeID.keySet().iterator();//determine the maximum edge flux ratio for each edge species
while(iter.hasNext()){
Species spe = (Species)iter.next();
Integer id = (Integer)JDAS.edgeID.get(spe);
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1];
boolean prunable = ds0.prunableSpecies[id-1];
//go through the rest of the reaction systems to see if there are higher max flux ratios
for (Integer i = 1; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1];
if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness
}
//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), add it to the prunableSpeciesMap
if( prunable){
prunableSpeciesMap.put(spe, maxmaxRatio);
}
}
//repeat with the edgeLeakID; if a species appears in both lists, it will be prunable only if it is prunable in both cases, and the sum of maximum edgeFlux + maximum edgeLeakFlux (for each reaction system) will be considered; this will be a conservative overestimate of maximum (edgeFlux+edgeLeakFlux)
iter = JDAS.edgeLeakID.keySet().iterator();
while(iter.hasNext()){
Species spe = (Species)iter.next();
Integer id = (Integer)JDAS.edgeLeakID.get(spe);
//check whether the same species is in edgeID
if(JDAS.edgeID.containsKey(spe)){//the species exists in edgeID
if(prunableSpeciesMap.containsKey(spe)){//the species was determined to be "prunable" based on edgeID
Integer idEdge=(Integer)JDAS.edgeID.get(spe);
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1]+ds0.maxEdgeFluxRatio[idEdge-1];
boolean prunable = ds0.prunableSpecies[id-1];
//go through the rest of the reaction systems to see if there are higher max flux ratios
for (Integer i = 1; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1]+ds.maxEdgeFluxRatio[idEdge-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1]+ds.maxEdgeFluxRatio[idEdge-1];
if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness
}
if( prunable){//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), replace with the newly determined maxmaxRatio
prunableSpeciesMap.remove(spe);
prunableSpeciesMap.put(spe, maxmaxRatio);
}
else{//otherwise, the species is not prunable in both edgeID and edgeLeakID and should be removed from the prunable species map
prunableSpeciesMap.remove(spe);
}
}
}
else{//the species is new
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1];
boolean prunable = ds0.prunableSpecies[id-1];
//go through the rest of the reaction systems to see if there are higher max flux ratios
for (Integer i = 1; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1];
if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness
}
//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), add it to the prunableSpeciesMap
if( prunable){
prunableSpeciesMap.put(spe, maxmaxRatio);
}
}
}
// at this point prunableSpeciesMap includes ALL prunable species, no matter how large their flux
//System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
// " as prunable, before checking against explored (included) species: " + prunableSpeciesMap.size());
// Pressure dependence only: Species that are included in any
// PDepNetwork are not eligible for pruning, so they must be removed
// from the map of prunable species
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
LinkedList speciesToRemove = new LinkedList();
for (iter = prunableSpeciesMap.keySet().iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
if (PDepNetwork.isSpeciesIncludedInAnyNetwork(spec))
speciesToRemove.add(spec);
}
for (iter = speciesToRemove.iterator(); iter.hasNext(); ) {
prunableSpeciesMap.remove(iter.next());
}
}
//System.out.println("PDep Pruning DEBUG:\nRMG now reduced the number of prunable species," +
// " after checking against explored (included) species, to: " + prunableSpeciesMap.size());
// sort the prunableSpecies by maxmaxRatio
// i.e. sort the map by values
List prunableSpeciesList = new LinkedList(prunableSpeciesMap.entrySet());
Collections.sort(prunableSpeciesList, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
List speciesToPrune = new LinkedList();
int belowThreshold = 0;
int lowMaxFlux = 0;
for (Iterator it = prunableSpeciesList.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Species spe = (Species)entry.getKey();
double maxmaxRatio = (Double)entry.getValue();
if (maxmaxRatio < edgeTol)
{
System.out.println("Edge species "+spe.getChemkinName() +" has a maximum flux ratio ("+maxmaxRatio+") lower than edge inclusion threshhold and will be pruned.");
speciesToPrune.add(spe);
++belowThreshold;
}
else if ( numberToBePruned - speciesToPrune.size() > 0 ) {
System.out.println("Edge species "+spe.getChemkinName() +" has a low maximum flux ratio ("+maxmaxRatio+") and will be pruned to reduce the edge size to the maximum ("+maxEdgeSpeciesAfterPruning+").");
speciesToPrune.add(spe);
++lowMaxFlux;
}
else break; // no more to be pruned
}
//System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
// " to be pruned due to max flux ratio lower than threshold: " + belowThreshold);
//System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
// " to be pruned due to low max flux ratio : " + lowMaxFlux);
//now, speciesToPrune has been filled with species that should be pruned from the edge
System.out.println("Pruning...");
//prune species from the edge
//remove species from the edge and from the species dictionary and from edgeID
iter = speciesToPrune.iterator();
while(iter.hasNext()){
Species spe = (Species)iter.next();
writePrunedEdgeSpecies(spe);
((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().remove(spe);
//SpeciesDictionary.getInstance().getSpeciesSet().remove(spe);
if (!unprunableSpecies.containsValue(spe))
SpeciesDictionary.getInstance().remove(spe);
else System.out.println("Pruning Message: Not removing the following species " +
"from the SpeciesDictionary\nas it is present in a Primary Kinetic / Reaction" +
" Library\nThe species will still be removed from the Edge of the " +
"Reaction Mechanism\n" + spe.toString());
JDAS.edgeID.remove(spe);
}
//remove reactions from the edge involving pruned species
iter = ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();
HashSet toRemove = new HashSet();
while(iter.hasNext()){
Reaction reaction = (Reaction)iter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemove.add(reaction);
}
iter = toRemove.iterator();
while(iter.hasNext()){
Reaction reaction = (Reaction)iter.next();
writePrunedEdgeReaction(reaction);
Reaction reverse = reaction.getReverseReaction();
((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reaction);
((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
if ((reaction.isForward() && reaction.getKineticsSource(0).contains("Library")) ||
(reaction.isBackward() && reaction.getReverseReaction().getKineticsSource(0).contains("Library")))
continue;
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove reactions from PDepNetworks in PDep cases
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
iter = PDepNetwork.getNetworks().iterator();
HashSet pdnToRemove = new HashSet();
HashSet toRemovePath;
HashSet toRemoveNet;
HashSet toRemoveNonincluded;
HashSet toRemoveIsomer;
while (iter.hasNext()){
PDepNetwork pdn = (PDepNetwork)iter.next();
//identify path reactions to remove
Iterator rIter = pdn.getPathReactions().iterator();
toRemovePath = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemovePath.add(reaction);
}
//identify net reactions to remove
rIter = pdn.getNetReactions().iterator();
toRemoveNet = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNet.add(reaction);
}
//identify nonincluded reactions to remove
rIter = pdn.getNonincludedReactions().iterator();
toRemoveNonincluded = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNonincluded.add(reaction);
}
//identify isomers to remove
Iterator iIter = pdn.getIsomers().iterator();
toRemoveIsomer = new HashSet();
while(iIter.hasNext()){
PDepIsomer pdi = (PDepIsomer)iIter.next();
Iterator isIter = pdi.getSpeciesListIterator();
while(isIter.hasNext()){
Species spe = (Species)isIter.next();
if (speciesToPrune.contains(spe)&&!toRemove.contains(pdi)) toRemoveIsomer.add(pdi);
}
if(pdi.getSpeciesList().size()==0 && !toRemove.contains(pdi)) toRemoveIsomer.add(pdi);//if the pdi doesn't contain any species, schedule it for removal
}
//remove path reactions
Iterator iterRem = toRemovePath.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromPathReactionList((PDepReaction)reaction);
pdn.removeFromPathReactionList((PDepReaction)reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
if ((reaction.isForward() && reaction.getKineticsSource(0).contains("Library")) ||
(reaction.isBackward() && reaction.getReverseReaction().getKineticsSource(0).contains("Library")))
continue;
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove net reactions
iterRem = toRemoveNet.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromNetReactionList((PDepReaction)reaction);
pdn.removeFromNetReactionList((PDepReaction)reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove nonincluded reactions
iterRem = toRemoveNonincluded.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromNonincludedReactionList((PDepReaction)reaction);
pdn.removeFromNonincludedReactionList((PDepReaction)reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove isomers
iterRem = toRemoveIsomer.iterator();
while(iterRem.hasNext()){
PDepIsomer pdi = (PDepIsomer)iterRem.next();
pdn.removeFromIsomerList(pdi);
}
//remove the entire network if the network has no path or net reactions
if(pdn.getPathReactions().size()==0&&pdn.getNetReactions().size()==0) pdnToRemove.add(pdn);
}
iter = pdnToRemove.iterator();
while (iter.hasNext()){
PDepNetwork pdn = (PDepNetwork)iter.next();
PDepNetwork.getNetworks().remove(pdn);
}
}
}
//System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, after pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber());
return;
}
//determines whether a reaction can be removed; returns true ; cf. categorizeReaction() in CoreEdgeReactionModel
//returns true if the reaction involves reactants or products that are in p_prunableSpecies; otherwise returns false
public boolean reactionPrunableQ(Reaction p_reaction, Collection p_prunableSpecies){
Iterator iter = p_reaction.getReactants();
while (iter.hasNext()) {
Species spe = (Species)iter.next();
if (p_prunableSpecies.contains(spe))
return true;
}
iter = p_reaction.getProducts();
while (iter.hasNext()) {
Species spe = (Species)iter.next();
if (p_prunableSpecies.contains(spe))
return true;
}
return false;
}
public boolean hasPrimaryKineticLibrary() {
if (primaryKineticLibrary == null) return false;
return (primaryKineticLibrary.size() > 0);
}
public boolean hasSeedMechanisms() {
if (getSeedMechanism() == null) return false;
return (seedMechanism.size() > 0);
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public PrimaryKineticLibrary getPrimaryKineticLibrary() {
return primaryKineticLibrary;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public void setPrimaryKineticLibrary(PrimaryKineticLibrary p_PrimaryKineticLibrary) {
primaryKineticLibrary = p_PrimaryKineticLibrary;
}
public ReactionLibrary getReactionLibrary() {
return ReactionLibrary;
}
public void setReactionLibrary(ReactionLibrary p_ReactionLibrary) {
ReactionLibrary = p_ReactionLibrary;
}
//10/4/07 gmagoon: added
public LinkedHashSet getSpeciesSeed() {
return speciesSeed;
}
//10/4/07 gmagoon: added
public void setSpeciesSeed(LinkedHashSet p_speciesSeed) {
speciesSeed = p_speciesSeed;
}
//10/4/07 gmagoon: added
public LibraryReactionGenerator getLibraryReactionGenerator() {
return lrg;
}
//10/4/07 gmagoon: added
public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) {
lrg = p_lrg;
}
public static Temperature getTemp4BestKinetics() {
return temp4BestKinetics;
}
public static void setTemp4BestKinetics(Temperature firstSysTemp) {
temp4BestKinetics = firstSysTemp;
}
public SeedMechanism getSeedMechanism() {
return seedMechanism;
}
public void setSeedMechanism(SeedMechanism p_seedMechanism) {
seedMechanism = p_seedMechanism;
}
public PrimaryThermoLibrary getPrimaryThermoLibrary() {
return primaryThermoLibrary;
}
public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) {
primaryThermoLibrary = p_primaryThermoLibrary;
}
public static double getAtol(){
return atol;
}
public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) {
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true;
return true;
//if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions
else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented
return true;
}
}
else //the case where intermediate conversions are specified
if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed
return true;
}
return false; //return false if none of the above criteria are met
}
public void readAndMakePKL(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setPrimaryKineticLibrary(new PrimaryKineticLibrary(name, path));
Ilib++;
}
else {
getPrimaryKineticLibrary().appendPrimaryKineticLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (Ilib==0) {
setPrimaryKineticLibrary(null);
}
else System.out.println("Primary Kinetic Libraries in use: " + getPrimaryKineticLibrary().getName());
}
public void readAndMakeReactionLibrary(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setReactionLibrary(new ReactionLibrary(name, path));
Ilib++;
}
else {
getReactionLibrary().appendReactionLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (Ilib==0) {
setReactionLibrary(null);
}
else System.out.println("Reaction Libraries in use: " + getReactionLibrary().getName());
}
public void readAndMakePTL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
++numPTLs;
}
else {
getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (numPTLs == 0) setPrimaryThermoLibrary(null);
}
public void readExtraForbiddenStructures(BufferedReader reader) throws IOException {
System.out.println("Reading extra forbidden structures from input file.");
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer token = new StringTokenizer(line);
String fgname = token.nextToken();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(reader);
}
catch (InvalidGraphFormatException e) {
System.out.println("Invalid functional group in "+fgname);
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname);
FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph);
ChemGraph.addForbiddenStructure(fg);
line = ChemParser.readMeaningfulLine(reader, true);
System.out.println(" Forbidden structure: "+fgname);
}
}
public void setSpectroscopicDataMode(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String sdeType = st.nextToken().toLowerCase();
if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
else if (sdeType.equals("off") || sdeType.equals("none")) {
SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
}
else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
/**
* Sets the pressure dependence options to on or off. If on, checks for
* more options and sets them as well.
* @param line The current line in the condition file; should start with "PressureDependence:"
* @param reader The reader currently being used to parse the condition file
*/
public String setPressureDependenceOptions(String line, BufferedReader reader) throws InvalidSymbolException {
// Determine pressure dependence mode
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken(); // Should be "PressureDependence:"
String pDepType = st.nextToken();
if (pDepType.toLowerCase().equals("off")) {
// No pressure dependence
reactionModelEnlarger = new RateBasedRME();
PDepNetwork.generateNetworks = false;
/*
* If the Spectroscopic Data Estimator field is set to "Frequency Groups,"
* terminate the RMG job and inform the user to either:
* a) Set the Spectroscopic Data Estimator field to "off," OR
* b) Select a pressure-dependent model
*
* Before, RMG would read in "Frequency Groups" with no pressure-dependence
* and carry on. However, the calculated frequencies would not be stored /
* reported (plus increase the runtime), so no point in calculating them.
*/
if (SpectroscopicData.mode != SpectroscopicData.mode.OFF) {
System.err.println("Terminating RMG simulation: User requested frequency estimation, " +
"yet no pressure-dependence.\nSUGGESTION: Set the " +
"SpectroscopicDataEstimator field in the input file to 'off'.");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
else if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
pDepType.toLowerCase().equals("reservoirstate") ||
pDepType.toLowerCase().equals("chemdis")) {
reactionModelEnlarger = new RateBasedPDepRME();
PDepNetwork.generateNetworks = true;
// Set pressure dependence method
if (pDepType.toLowerCase().equals("reservoirstate"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
else if (pDepType.toLowerCase().equals("modifiedstrongcollision"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
//else if (pDepType.toLowerCase().equals("chemdis"))
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
else
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence mode = " + pDepType);
RateBasedPDepRME pdepModelEnlarger = (RateBasedPDepRME) reactionModelEnlarger;
// Turn on spectroscopic data estimation if not already on
if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof FastMasterEqn && SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof Chemdis && SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
// Next line must be PDepKineticsModel
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
st = new StringTokenizer(line);
name = st.nextToken();
String pDepKinType = st.nextToken();
if (pDepKinType.toLowerCase().equals("chebyshev")) {
PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
// Default is to cubic order for basis functions
FastMasterEqn.setNumTBasisFuncs(4);
FastMasterEqn.setNumPBasisFuncs(4);
}
else if (pDepKinType.toLowerCase().equals("pdeparrhenius"))
PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
else if (pDepKinType.toLowerCase().equals("rate"))
PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
else
throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsModel = " + pDepKinType);
// For Chebyshev polynomials, optionally specify the number of
// temperature and pressure basis functions
// Such a line would read, e.g.: "PDepKineticsModel: Chebyshev 4 4"
if (st.hasMoreTokens() && PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
try {
int numTBasisFuncs = Integer.parseInt(st.nextToken());
int numPBasisFuncs = Integer.parseInt(st.nextToken());
FastMasterEqn.setNumTBasisFuncs(numTBasisFuncs);
FastMasterEqn.setNumPBasisFuncs(numPBasisFuncs);
}
catch (NoSuchElementException e) {
throw new InvalidSymbolException("condition.txt: Missing number of pressure basis functions for Chebyshev polynomials.");
}
}
}
else
throw new InvalidSymbolException("condition.txt: Missing PDepKineticsModel after PressureDependence line.");
// Determine temperatures and pressures to use
// These can be specified automatically using TRange and PRange or
// manually using Temperatures and Pressures
Temperature[] temperatures = null;
Pressure[] pressures = null;
String Tunits = "K";
Temperature Tmin = new Temperature(300.0, "K");
Temperature Tmax = new Temperature(2000.0, "K");
int Tnumber = 8;
String Punits = "bar";
Pressure Pmin = new Pressure(0.01, "bar");
Pressure Pmax = new Pressure(100.0, "bar");
int Pnumber = 5;
// Read next line of input
line = ChemParser.readMeaningfulLine(reader, true);
boolean done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
// Parse lines containing pressure dependence options
// Possible options are "TRange:", "PRange:", "Temperatures:", and "Pressures:"
// You must specify either TRange or Temperatures and either PRange or Pressures
// The order does not matter
while (!done) {
st = new StringTokenizer(line);
name = st.nextToken();
if (line.toLowerCase().startsWith("trange:")) {
Tunits = ChemParser.removeBrace(st.nextToken());
Tmin = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tmax = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("prange:")) {
Punits = ChemParser.removeBrace(st.nextToken());
Pmin = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pmax = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("temperatures:")) {
Tnumber = Integer.parseInt(st.nextToken());
Tunits = ChemParser.removeBrace(st.nextToken());
temperatures = new Temperature[Tnumber];
for (int i = 0; i < Tnumber; i++) {
temperatures[i] = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
}
Tmin = temperatures[0];
Tmax = temperatures[Tnumber-1];
}
else if (line.toLowerCase().startsWith("pressures:")) {
Pnumber = Integer.parseInt(st.nextToken());
Punits = ChemParser.removeBrace(st.nextToken());
pressures = new Pressure[Pnumber];
for (int i = 0; i < Pnumber; i++) {
pressures[i] = new Pressure(Double.parseDouble(st.nextToken()), Punits);
}
Pmin = pressures[0];
Pmax = pressures[Pnumber-1];
}
// Read next line of input
line = ChemParser.readMeaningfulLine(reader, true);
done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
}
// Set temperatures and pressures (if not already set manually)
if (temperatures == null) {
temperatures = new Temperature[Tnumber];
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Tnumber; i++) {
double T = -Math.cos((2 * i - 1) * Math.PI / (2 * Tnumber));
T = 2.0 / ((1.0/Tmax.getK() - 1.0/Tmin.getK()) * T + 1.0/Tmax.getK() + 1.0/Tmin.getK());
temperatures[i-1] = new Temperature(T, "K");
}
}
else {
// Distribute equally on a 1/T basis
double slope = (1.0/Tmax.getK() - 1.0/Tmin.getK()) / (Tnumber - 1);
for (int i = 0; i < Tnumber; i++) {
double T = 1.0/(slope * i + 1.0/Tmin.getK());
temperatures[i] = new Temperature(T, "K");
}
}
}
if (pressures == null) {
pressures = new Pressure[Pnumber];
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Pnumber; i++) {
double P = -Math.cos((2 * i - 1) * Math.PI / (2 * Pnumber));
P = Math.pow(10, 0.5 * ((Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) * P + Math.log10(Pmax.getBar()) + Math.log10(Pmin.getBar())));
pressures[i-1] = new Pressure(P, "bar");
}
}
else {
// Distribute equally on a log P basis
double slope = (Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) / (Pnumber - 1);
for (int i = 0; i < Pnumber; i++) {
double P = Math.pow(10, slope * i + Math.log10(Pmin.getBar()));
pressures[i] = new Pressure(P, "bar");
}
}
}
FastMasterEqn.setTemperatures(temperatures);
PDepRateConstant.setTemperatures(temperatures);
PDepRateConstant.setTMin(Tmin);
PDepRateConstant.setTMax(Tmax);
ChebyshevPolynomials.setTlow(Tmin);
ChebyshevPolynomials.setTup(Tmax);
FastMasterEqn.setPressures(pressures);
PDepRateConstant.setPressures(pressures);
PDepRateConstant.setPMin(Pmin);
PDepRateConstant.setPMax(Pmax);
ChebyshevPolynomials.setPlow(Pmin);
ChebyshevPolynomials.setPup(Pmax);
/*
* New option for input file: DecreaseGrainSize
* User now has the option to re-run fame with additional grains
* (smaller grain size) when the p-dep rate exceeds the
* high-P-limit rate.
* Default value: off
*/
if (line.toLowerCase().startsWith("decreasegrainsize")) {
st = new StringTokenizer(line);
String tempString = st.nextToken(); // "DecreaseGrainSize:"
tempString = st.nextToken().trim().toLowerCase();
if (tempString.equals("on") || tempString.equals("yes") ||
tempString.equals("true")) {
rerunFame = true;
} else rerunFame = false;
line = ChemParser.readMeaningfulLine(reader, true);
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
}
return line;
}
public void createTModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
public void createPModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
public LinkedHashMap populateInitialStatusListWithReactiveSpecies(BufferedReader reader) throws IOException {
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int numSpeciesStatus = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// The next token will be the concentration units
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
// Read in the graph (and make the species) before we parse all of the concentrations
// Will store each SpeciesStatus (NXM where N is the # of species and M is the # of
// concentrations) in a LinkedHashMap, with a (int) counter as the unique key
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
}
//System.out.println(name);
Species species = Species.make(name,cg);
int numConcentrations = 0; // The number of concentrations read-in for each species
// The remaining tokens are either:
// The desired concentrations
// The flag "unreactive"
// The flag "constantconcentration"
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
double concentration = 0.0;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
else if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
else {
concentration = Double.parseDouble(reactive);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
SpeciesStatus ss = new SpeciesStatus(species,1,concentration,0.0);
speciesStatus.put(numSpeciesStatus, ss);
++numSpeciesStatus;
++numConcentrations;
}
}
// Check if the number of concentrations read in is consistent with all previous
// concentration counts. The first time this function is called, the variable
// numberOfEquivalenceRatios will be initialized.
boolean goodToGo = areTheNumberOfConcentrationsConsistent(numConcentrations);
if (!goodToGo) {
System.out.println("\n\nThe number of concentrations (" + numConcentrations + ") supplied for species " + species.getName() +
"\nis not consistent with the number of concentrations (" + numberOfEquivalenceRatios + ") " +
"supplied for all previously read-in species \n\n" +
"Terminating RMG simulation.");
System.exit(0);
}
// Make a SpeciesStatus and store it in the LinkedHashMap
// double flux = 0;
// int species_type = 1; // reacted species
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
line = ChemParser.readMeaningfulLine(reader, true);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
int reactionSystemCounter = 0;
for (int totalConcs=0; totalConcs<numSpeciesStatus/speciesSet.size(); ++totalConcs) {
LinkedHashMap speStat = new LinkedHashMap();
for (int totalSpecs=0; totalSpecs<speciesSet.size(); ++totalSpecs) {
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(totalConcs+totalSpecs*numSpeciesStatus/speciesSet.size());
String blah = ssCopy.getSpecies().getName();
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
return speciesSet;
}
public void populateInitialStatusListWithInertSpecies(BufferedReader reader) {
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
// The next token is the units of concentration
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
// The remaining tokens are concentrations
double inertConc = 0.0;
int counter = 0;
int numberOfConcentrations = 0;
while (st.hasMoreTokens()) {
String conc = st.nextToken();
inertConc = Double.parseDouble(conc);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
int numberOfDiffTP = tempList.size() * presList.size();
for (int isIndex=counter; isIndex<initialStatusList.size(); isIndex+=initialStatusList.size()/numberOfDiffTP) {
InitialStatus is = ((InitialStatus)initialStatusList.get(isIndex));
((InitialStatus)initialStatusList.get(isIndex)).putInertGas(name,inertConc);
}
++counter;
++numberOfConcentrations;
}
// Check if the number of concentrations read in is consistent with all previous
// concentration counts. The first time this function is called, the variable
// numberOfEquivalenceRatios will be initialized.
boolean goodToGo = areTheNumberOfConcentrationsConsistent(numberOfConcentrations);
if (!goodToGo) {
System.out.println("\n\nThe number of concentrations (" + numberOfConcentrations + ") supplied for species " + name +
"\nis not consistent with the number of concentrations (" + numberOfEquivalenceRatios + ") " +
"supplied for all previously read-in species \n\n" +
"Terminating RMG simulation.");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
}
public String readMaxAtomTypes(String line, BufferedReader reader) {
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader, true);
}
return line;
}
public ReactionModelEnlarger getReactionModelEnlarger() {
return reactionModelEnlarger;
}
public LinkedList getTempList() {
return tempList;
}
public LinkedList getPressList() {
return presList;
}
public LinkedList getInitialStatusList() {
return initialStatusList;
}
public void writeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]);
if (temporaryRestartFile.exists()) temporaryRestartFile.renameTo(new File(listOfFiles[i]+"~"));
}
}
public void removeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]+"~");
temporaryRestartFile.delete();
}
}
public static boolean rerunFameWithAdditionalGrains() {
return rerunFame;
}
public void setLimitingReactantID(int id) {
limitingReactantID = id;
}
public int getLimitingReactantID() {
return limitingReactantID;
}
public void readAndMakePTransL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryTransportLibrary(new PrimaryTransportLibrary(name,path));
++numPTLs;
}
else {
getPrimaryTransportLibrary().appendPrimaryTransportLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (numPTLs == 0) setPrimaryTransportLibrary(null);
}
public PrimaryTransportLibrary getPrimaryTransportLibrary() {
return primaryTransportLibrary;
}
public void setPrimaryTransportLibrary(PrimaryTransportLibrary p_primaryTransportLibrary) {
primaryTransportLibrary = p_primaryTransportLibrary;
}
/**
* Print the current numbers of core and edge species and reactions to the
* console.
*/
public void printModelSize() {
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) getReactionModel();
int numberOfCoreSpecies = cerm.getReactedSpeciesSet().size();
int numberOfEdgeSpecies = cerm.getUnreactedSpeciesSet().size();
int numberOfCoreReactions = 0;
int numberOfEdgeReactions = 0;
double count = 0.0;
for (Iterator iter = cerm.getReactedReactionSet().iterator(); iter.hasNext(); ) {
Reaction rxn = (Reaction) iter.next();
if (rxn.hasReverseReaction()) count += 0.5;
else count += 1;
}
numberOfCoreReactions = (int) Math.round(count);
count = 0.0;
for (Iterator iter = cerm.getUnreactedReactionSet().iterator(); iter.hasNext(); ) {
Reaction rxn = (Reaction) iter.next();
if (rxn.hasReverseReaction()) count += 0.5;
else count += 1;
}
numberOfEdgeReactions = (int) Math.round(count);
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
numberOfCoreReactions += PDepNetwork.getNumCoreReactions(cerm);
numberOfEdgeReactions += PDepNetwork.getNumEdgeReactions(cerm);
}
System.out.println("The model core has " + Integer.toString(numberOfCoreReactions) + " reactions and "+ Integer.toString(numberOfCoreSpecies) + " species.");
System.out.println("The model edge has " + Integer.toString(numberOfEdgeReactions) + " reactions and "+ Integer.toString(numberOfEdgeSpecies) + " species.");
}
public boolean areTheNumberOfConcentrationsConsistent(int number) {
if (numberOfEquivalenceRatios == 0) numberOfEquivalenceRatios = number;
else {
if (number == numberOfEquivalenceRatios) return true;
else return false;
}
return true;
}
}
|
package com.indeed.proctor.store.cache;
import com.google.common.collect.Lists;
import com.indeed.proctor.common.model.TestDefinition;
import com.indeed.proctor.store.InMemoryProctorStore;
import com.indeed.proctor.store.ProctorStore;
import com.indeed.proctor.store.Revision;
import com.indeed.proctor.store.StoreException;
import com.indeed.proctor.store.StoreException.TestUpdateException;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static com.indeed.proctor.store.InMemoryProctorStoreTest.createDummyTestDefinition;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class CachingProctorStoreTest {
private static final List<Integer> DUMMY_HISTORY = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
private static final List<Revision> REVISION_HISTORY = Lists.newArrayList(
makeRevision("1"),
makeRevision("2"),
makeRevision("3"),
makeRevision("4"),
makeRevision("5")
);
private CachingProctorStore testee;
private ProctorStore delegate;
@Before
public void setUpTestee() throws TestUpdateException {
delegate = new InMemoryProctorStore();
delegate.addTestDefinition("Mike", "pwd", "tst1",
createDummyTestDefinition("1", "tst1"),
Collections.<String, String>emptyMap(), "commit tst1");
delegate.addTestDefinition("William", "pwd", "tst2",
createDummyTestDefinition("2", "tst2"),
Collections.<String, String>emptyMap(), "commit tst2");
testee = new CachingProctorStore(delegate);
/* we stop the background refresh task to perform in order to do better unit test */
testee.getRefreshTaskFuture().cancel(false);
}
@Test
public void testSelectHistorySet() {
final List<Integer> result = CachingProctorStore.selectHistorySet(DUMMY_HISTORY, 0, 1);
assertEquals(Lists.newArrayList(1), result);
}
@Test
public void testSelectHistorySetWithNegativeStart() {
final List<Integer> result = CachingProctorStore.selectHistorySet(DUMMY_HISTORY, -1, 1);
assertEquals(Lists.newArrayList(1), result);
}
@Test
public void testSelectHistorySetWithNonPositiveLimit() {
final List<Integer> result = CachingProctorStore.selectHistorySet(DUMMY_HISTORY, 2, -1);
assertEquals(Collections.<Integer>emptyList(), result);
}
@Test
public void testSelectHistorySetNotOverflow() {
List<Integer> result = CachingProctorStore.selectHistorySet(DUMMY_HISTORY, 0, Integer.MAX_VALUE);
assertEquals(DUMMY_HISTORY, result);
result = CachingProctorStore.selectHistorySet(DUMMY_HISTORY, 0, Integer.MIN_VALUE);
assertEquals(Collections.<Integer>emptyList(), result);
result = CachingProctorStore.selectHistorySet(DUMMY_HISTORY, Integer.MIN_VALUE, Integer.MAX_VALUE);
assertEquals(DUMMY_HISTORY, result);
}
@Test
public void testSelectRevisionHistorySetFrom() {
final List<Revision> result = CachingProctorStore.selectRevisionHistorySetFrom(REVISION_HISTORY, "2", 0, 3);
assertEquals(REVISION_HISTORY.subList(1, 4), result);
}
@Test
public void testSelectRevisionHistorySetFromReturnEmtpy() {
final List<Revision> result = CachingProctorStore.selectRevisionHistorySetFrom(REVISION_HISTORY, "5", 1, 3);
assertEquals(Collections.emptyList(), result);
}
@Test
public void testSelectRevisionHistorySetFromNonexistence() {
final List<Revision> result = CachingProctorStore.selectRevisionHistorySetFrom(REVISION_HISTORY, "hello", 0, 3);
assertEquals(Collections.emptyList(), result);
}
@Test
public void testAddTestDefinition() throws StoreException, InterruptedException {
final TestDefinition tst3 = createDummyTestDefinition("3", "tst3");
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.addTestDefinition("Mike", "pwd", "tst3", tst3, Collections.<String, String>emptyMap(), "Create tst2");
} catch (final TestUpdateException e) {
fail();
}
}
});
assertEquals("2", testee.getLatestVersion());
assertNull(testee.getCurrentTestDefinition("tst3"));
assertTrue(testee.getRefreshTaskFuture().isCancelled());
assertEquals(2, testee.getAllHistories().size());
startThreadsAndSleep(thread);
assertFalse(testee.getRefreshTaskFuture().isCancelled());
testee.getRefreshTaskFuture().cancel(false);
assertEquals(3, testee.getAllHistories().size());
assertEquals("3", testee.getLatestVersion());
assertEquals("description of tst3", testee.getCurrentTestDefinition("tst3").getDescription());
assertEquals("description of tst3", testee.getTestDefinition("tst3", "revision-3").getDescription());
}
@Test
public void testUpdateTestDefinition() throws StoreException, InterruptedException {
final TestDefinition newTst1 = createDummyTestDefinition("3", "tst1");
newTst1.setDescription("updated description tst1");
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.updateTestDefinition("Mike", "pwd", "2", "tst1", newTst1, Collections.<String, String>emptyMap(), "Update description of tst1");
} catch (final TestUpdateException e) {
fail();
}
}
});
assertEquals("description of tst1", testee.getCurrentTestDefinition("tst1").getDescription());
assertEquals(1, testee.getHistory("tst1", 0, 2).size());
startThreadsAndSleep(thread);
assertEquals("updated description tst1", testee.getCurrentTestDefinition("tst1").getDescription());
assertEquals(2, testee.getHistory("tst1", 0, 2).size());
assertEquals("updated description tst1", testee.getTestDefinition("tst1", "revision-3").getDescription());
assertEquals("description of tst1", testee.getTestDefinition("tst1", "revision-1").getDescription());
}
@Test
public void testUpdateTestDefinitionWithIncorrectPrevVersion() throws StoreException, InterruptedException {
final String incorrectPreviousVersion = "1";
final TestDefinition newTst1 = createDummyTestDefinition("3", "tst1");
newTst1.setDescription("updated description tst1");
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.updateTestDefinition("Mike", "pwd", incorrectPreviousVersion, "tst1", newTst1, Collections.<String, String>emptyMap(), "Update description of tst1");
fail();
} catch (final TestUpdateException e) {
/* expected */
}
}
});
thread.start();
assertEquals("description of tst1", testee.getCurrentTestDefinition("tst1").getDescription());
assertTrue(testee.getRefreshTaskFuture().isCancelled());
}
@Test
public void testTwoUpdates() throws StoreException, InterruptedException {
final TestDefinition newTst1 = createDummyTestDefinition("3", "tst1");
newTst1.setDescription("updated description tst1");
final TestDefinition newTst2 = createDummyTestDefinition("3", "tst1");
newTst2.setDescription("This test shouldn't be updated");
final Thread successThread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.updateTestDefinition("Mike", "pwd", "2", "tst1", newTst1, Collections.<String, String>emptyMap(), "Update description of tst1");
} catch (final TestUpdateException e) {
fail();
/* expected */
}
}
});
final Thread failureThread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.updateTestDefinition("Mike", "pwd", "2", "tst1", newTst2, Collections.<String, String>emptyMap(), "Update description of tst1");
fail();
} catch (final TestUpdateException e) {
/* expected */
}
}
});
startThreadsAndSleep(successThread, failureThread);
assertEquals("updated description tst1", testee.getCurrentTestDefinition("tst1").getDescription());
assertFalse(testee.getRefreshTaskFuture().isCancelled());
}
@Test
public void testOneUpdateAndOneAdd() throws StoreException, InterruptedException {
final TestDefinition newTst1 = createDummyTestDefinition("3", "tst1");
newTst1.setDescription("updated description tst1");
final TestDefinition tst4 = createDummyTestDefinition("4", "tst4");
final Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.updateTestDefinition("Mike", "pwd", "2", "tst1", newTst1, Collections.<String, String>emptyMap(), "Update description of tst1");
} catch (final TestUpdateException e) {
fail();
}
}
});
final Thread addThread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.addTestDefinition("Tom", "pwd", "tst4", tst4, Collections.<String, String>emptyMap(), "Create tst4");
} catch (final TestUpdateException e) {
fail();
}
}
});
assertEquals(1, testee.getHistory("tst1", 0, 4).size());
startThreadsAndSleep(updateThread, addThread);
assertEquals("updated description tst1", testee.getCurrentTestDefinition("tst1").getDescription());
assertEquals("description of tst4", testee.getCurrentTestDefinition("tst4").getDescription());
assertEquals(2, testee.getHistory("tst1", 0, 4).size());
assertEquals("Update description of tst1", testee.getHistory("tst1", 0, 4).get(0).getMessage());
}
@Test
public void testDelete() throws StoreException, InterruptedException {
final TestDefinition tst1 = createDummyTestDefinition("3", "tst1"); /* this would not be actually used */
final Thread deleteThread = new Thread(new Runnable() {
@Override
public void run() {
try {
testee.deleteTestDefinition("Mike", "pwd", "2", "tst1", tst1, "Delete tst1");
} catch (final TestUpdateException e) {
fail();
}
}
});
startThreadsAndSleep(deleteThread);
assertEquals("3", testee.getLatestVersion());
assertNull(testee.getCurrentTestDefinition("tst1"));
assertNotNull(testee.getTestDefinition("tst1", "revision-1"));
}
private static void startThreadsAndSleep(final Thread... threads) throws InterruptedException {
for (final Thread thread : threads) {
thread.start();
}
for (final Thread thread : threads) {
thread.join();
}
}
private static Revision makeRevision(final String revision) {
return new Revision(revision, "author", new Date(), "revision message");
}
}
|
package com.opengamma.transport.jms;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
/**
* A message sender that uses JMS. Messages are sent in the background, preserving their order.
*/
public class QueueingJmsByteArrayMessageSender extends JmsByteArrayMessageSender {
private static final Logger s_logger = LoggerFactory.getLogger(JmsByteArrayMessageSender.class);
private final BlockingQueue<byte[]> _messageQueue = new LinkedBlockingQueue<byte[]>();
private final Thread _senderThread;
/**
* Creates an instance associated with a destination and template.
*
* @param destinationName the destination name, not null
* @param jmsTemplate the template, not null
*/
public QueueingJmsByteArrayMessageSender(final String destinationName, final JmsTemplate jmsTemplate) {
super(destinationName, jmsTemplate);
_senderThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
byte[] nextMessage;
try {
nextMessage = _messageQueue.take();
sendSync(nextMessage);
} catch (InterruptedException e) {
s_logger.warn("Interrupted while waiting for next message to send", e);
return;
} catch (Exception e) {
s_logger.error("Failed to send message asynchronously", e);
}
}
}
}, String.format("QueueingJmsByteArrayMessageSender %s", destinationName));
_senderThread.setDaemon(true);
_senderThread.start();
}
@Override
public void send(byte[] message) {
_messageQueue.add(message);
}
public void shutdown() {
_senderThread.interrupt();
}
private void sendSync(byte[] message) {
super.send(message);
}
}
|
package org.idomac.training.sort.quicksort;
import org.idomac.training.sort.StdRandom;
import java.util.Scanner;
/**
* @author : lihaoquan
*
*
*/
public class QuickSort {
public static void sort(int[] a) {
StdRandom.shuffle(a);
sort(a,0,a.length-1);
}
/**
*
* @param a
* @param left
* @param right
*/
public static void sort(int[] a,int left,int right) {
if(right <= left) return;
int j = partition(a,left,right);
sort(a,left,j-1);
sort(a,j+1,right);
}
/**
*
* @param a
* @param left
* @param right
* @return
*/
public static int partition(int[] a,int left,int right) {
int i = left;
int j = right+1;
int v = a[i];
while(true) {
while(a[++i] < v) if(i == right) break;
while(v<a[--j]) if(j==left) break;
if(i>=j) break;
exchange(a,i,j);
}
exchange(a,left,j);
return j;
}
/**
*
* @param a
* @param i
* @param j
*/
public static void exchange(int[] a,int i,int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(",;");
String input = scanner.next();
String[] inputs = input.split(",");
int[] datas = new int[inputs.length];
for(int i = 0; i< inputs.length;i++) {
String data = inputs[i];
if("".equals(data) || null==data) {
data = "0";
}
datas[i] = Integer.parseInt(data);
}
sort(datas);
for(int i = 0; i<datas.length;i++) {
System.out.println("# "+datas[i]);
}
}
}
|
package org.batfish.datamodel.acl;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.ImmutableList;
import com.google.common.graph.Traverser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Stack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.batfish.datamodel.AclIpSpaceLine;
import org.batfish.datamodel.AclLine;
import org.batfish.datamodel.Flow;
import org.batfish.datamodel.HeaderSpace;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.IpAccessList;
import org.batfish.datamodel.IpSpace;
import org.batfish.datamodel.IpSpaceMetadata;
import org.batfish.datamodel.LineAction;
import org.batfish.datamodel.Protocol;
import org.batfish.datamodel.SubRange;
import org.batfish.datamodel.visitors.IpSpaceDescriber;
import org.batfish.datamodel.visitors.IpSpaceTracer;
/**
* Tracer for {@link IpAccessList}, {@link IpSpace}, {@link HeaderSpace}.<br>
* Acts like {@link Evaluator} on {@link IpAccessList}, except that it introduces tracing when
* encountering traceable classes.
*/
public final class AclTracer extends AclLineEvaluator {
public static AclTrace trace(
@Nonnull IpAccessList ipAccessList,
@Nonnull Flow flow,
@Nullable String srcInterface,
@Nonnull Map<String, IpAccessList> availableAcls,
@Nonnull Map<String, IpSpace> namedIpSpaces,
@Nonnull Map<String, IpSpaceMetadata> namedIpSpaceMetadata) {
AclTracer tracer =
new AclTracer(flow, srcInterface, availableAcls, namedIpSpaces, namedIpSpaceMetadata);
tracer.trace(ipAccessList);
return tracer.getTrace();
}
private final Map<IpSpace, IpSpaceMetadata> _ipSpaceMetadata;
private final Map<IpSpace, String> _ipSpaceNames;
private Stack<TraceNode> _nodeStack = new Stack<>();
public AclTracer(
@Nonnull Flow flow,
@Nullable String srcInterface,
@Nonnull Map<String, IpAccessList> availableAcls,
@Nonnull Map<String, IpSpace> namedIpSpaces,
@Nonnull Map<String, IpSpaceMetadata> namedIpSpaceMetadata) {
super(flow, srcInterface, availableAcls, namedIpSpaces);
_ipSpaceNames = new IdentityHashMap<>();
_ipSpaceMetadata = new IdentityHashMap<>();
_nodeStack.push(new TraceNode());
namedIpSpaces.forEach((name, ipSpace) -> _ipSpaceNames.put(ipSpace, name));
namedIpSpaceMetadata.forEach(
(name, ipSpaceMetadata) -> _ipSpaceMetadata.put(namedIpSpaces.get(name), ipSpaceMetadata));
}
private String computeLineDescription(AclIpSpaceLine line, IpSpaceDescriber describer) {
String srcText = line.getSrcText();
if (srcText != null) {
return srcText;
}
return line.getIpSpace().accept(describer);
}
public Flow getFlow() {
return _flow;
}
public Map<IpSpace, IpSpaceMetadata> getIpSpaceMetadata() {
return _ipSpaceMetadata;
}
public @Nonnull Map<IpSpace, String> getIpSpaceNames() {
return _ipSpaceNames;
}
public @Nonnull Map<String, IpSpace> getNamedIpSpaces() {
return _namedIpSpaces;
}
public @Nonnull AclTrace getTrace() {
checkState(!_nodeStack.isEmpty(), "Trace is missing");
TraceNode root = _nodeStack.get(0);
return new AclTrace(
ImmutableList.copyOf(Traverser.forTree(TraceNode::getChildren).depthFirstPreOrder(root))
.stream()
.map(TraceNode::getEvent)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList()));
}
public void recordAction(
@Nonnull IpAccessList ipAccessList, int index, @Nonnull AclLine line, LineAction action) {
String lineDescription = firstNonNull(line.getName(), line.toString());
String type = firstNonNull(ipAccessList.getSourceType(), "filter");
String name = firstNonNull(ipAccessList.getSourceName(), ipAccessList.getName());
String actionStr = action == LineAction.PERMIT ? "permitted" : "denied";
String description =
String.format(
"Flow %s by %s named %s, index %d: %s", actionStr, type, name, index, lineDescription);
if (action == LineAction.PERMIT) {
setEvent(new PermittedByAclLine(description, index, lineDescription, ipAccessList.getName()));
} else {
setEvent(new DeniedByAclLine(description, index, lineDescription, ipAccessList.getName()));
}
}
public void recordAction(
@Nonnull String aclIpSpaceName,
@Nullable IpSpaceMetadata ipSpaceMetadata,
int index,
@Nonnull AclIpSpaceLine line,
Ip ip,
String ipDescription,
IpSpaceDescriber describer) {
if (line.getAction() == LineAction.PERMIT) {
setEvent(
new PermittedByAclIpSpaceLine(
aclIpSpaceName,
ipSpaceMetadata,
index,
computeLineDescription(line, describer),
ip,
ipDescription));
} else {
setEvent(
new DeniedByAclIpSpaceLine(
aclIpSpaceName,
ipSpaceMetadata,
index,
computeLineDescription(line, describer),
ip,
ipDescription));
}
}
public void recordDefaultDeny(@Nonnull IpAccessList ipAccessList) {
setEvent(
new DefaultDeniedByIpAccessList(
ipAccessList.getName(), ipAccessList.getSourceName(), ipAccessList.getSourceType()));
}
public void recordDefaultDeny(
@Nonnull String aclIpSpaceName,
@Nullable IpSpaceMetadata ipSpaceMetadata,
Ip ip,
String ipDescription) {
setEvent(new DefaultDeniedByAclIpSpace(aclIpSpaceName, ip, ipDescription, ipSpaceMetadata));
}
private static boolean rangesContain(Collection<SubRange> ranges, @Nullable Integer num) {
return num != null && ranges.stream().anyMatch(sr -> sr.includes(num));
}
public void recordNamedIpSpaceAction(
@Nonnull String name,
@Nonnull String ipSpaceDescription,
IpSpaceMetadata ipSpaceMetadata,
boolean permit,
Ip ip,
String ipDescription) {
if (permit) {
setEvent(
new PermittedByNamedIpSpace(
ip, ipDescription, ipSpaceDescription, ipSpaceMetadata, name));
} else {
setEvent(
new DeniedByNamedIpSpace(ip, ipDescription, ipSpaceDescription, ipSpaceMetadata, name));
}
}
private boolean trace(@Nonnull HeaderSpace headerSpace) {
if (!headerSpace.getDscps().isEmpty() && !headerSpace.getDscps().contains(_flow.getDscp())) {
return false;
}
if (!headerSpace.getNotDscps().isEmpty()
&& headerSpace.getNotDscps().contains(_flow.getDscp())) {
return false;
}
if (headerSpace.getDstIps() != null && !traceDstIp(headerSpace.getDstIps(), _flow.getDstIp())) {
return false;
}
if (headerSpace.getNotDstIps() != null
&& traceDstIp(headerSpace.getNotDstIps(), _flow.getDstIp())) {
return false;
}
if (!headerSpace.getDstPorts().isEmpty()
&& !rangesContain(headerSpace.getDstPorts(), _flow.getDstPort())) {
return false;
}
if (!headerSpace.getNotDstPorts().isEmpty()
&& rangesContain(headerSpace.getNotDstPorts(), _flow.getDstPort())) {
return false;
}
if (!headerSpace.getDstProtocols().isEmpty()) {
boolean match = false;
for (Protocol dstProtocol : headerSpace.getDstProtocols()) {
if (dstProtocol.getIpProtocol().equals(_flow.getIpProtocol())) {
match = true;
Integer dstPort = dstProtocol.getPort();
if (!dstPort.equals(_flow.getDstPort())) {
match = false;
}
if (match) {
break;
}
}
}
if (!match) {
return false;
}
}
if (!headerSpace.getNotDstProtocols().isEmpty()) {
boolean match = false;
for (Protocol notDstProtocol : headerSpace.getNotDstProtocols()) {
if (notDstProtocol.getIpProtocol().equals(_flow.getIpProtocol())) {
match = true;
Integer dstPort = notDstProtocol.getPort();
if (!dstPort.equals(_flow.getDstPort())) {
match = false;
}
if (match) {
return false;
}
}
}
}
if (!headerSpace.getFragmentOffsets().isEmpty()
&& !rangesContain(headerSpace.getFragmentOffsets(), _flow.getFragmentOffset())) {
return false;
}
if (!headerSpace.getNotFragmentOffsets().isEmpty()
&& rangesContain(headerSpace.getNotFragmentOffsets(), _flow.getFragmentOffset())) {
return false;
}
if (!headerSpace.getIcmpCodes().isEmpty()
&& !rangesContain(headerSpace.getIcmpCodes(), _flow.getIcmpCode())) {
return false;
}
if (!headerSpace.getNotIcmpCodes().isEmpty()
&& rangesContain(headerSpace.getNotIcmpCodes(), _flow.getFragmentOffset())) {
return false;
}
if (!headerSpace.getIcmpTypes().isEmpty()
&& !rangesContain(headerSpace.getIcmpTypes(), _flow.getIcmpType())) {
return false;
}
if (!headerSpace.getNotIcmpTypes().isEmpty()
&& rangesContain(headerSpace.getNotIcmpTypes(), _flow.getFragmentOffset())) {
return false;
}
if (!headerSpace.getIpProtocols().isEmpty()
&& !headerSpace.getIpProtocols().contains(_flow.getIpProtocol())) {
return false;
}
if (!headerSpace.getNotIpProtocols().isEmpty()
&& headerSpace.getNotIpProtocols().contains(_flow.getIpProtocol())) {
return false;
}
if (!headerSpace.getPacketLengths().isEmpty()
&& !rangesContain(headerSpace.getPacketLengths(), _flow.getPacketLength())) {
return false;
}
if (!headerSpace.getNotPacketLengths().isEmpty()
&& rangesContain(headerSpace.getNotPacketLengths(), _flow.getPacketLength())) {
return false;
}
if (headerSpace.getSrcOrDstIps() != null
&& !(traceSrcIp(headerSpace.getSrcOrDstIps(), _flow.getSrcIp())
|| traceDstIp(headerSpace.getSrcOrDstIps(), _flow.getDstIp()))) {
return false;
}
if (!headerSpace.getSrcOrDstPorts().isEmpty()
&& !(rangesContain(headerSpace.getSrcOrDstPorts(), _flow.getSrcPort())
|| rangesContain(headerSpace.getSrcOrDstPorts(), _flow.getDstPort()))) {
return false;
}
if (!headerSpace.getSrcOrDstProtocols().isEmpty()) {
boolean match = false;
for (Protocol protocol : headerSpace.getSrcOrDstProtocols()) {
if (protocol.getIpProtocol().equals(_flow.getIpProtocol())) {
match = true;
Integer port = protocol.getPort();
if (!port.equals(_flow.getDstPort()) && !port.equals(_flow.getSrcPort())) {
match = false;
}
if (match) {
break;
}
}
}
if (!match) {
return false;
}
}
if (headerSpace.getSrcIps() != null && !traceSrcIp(headerSpace.getSrcIps(), _flow.getSrcIp())) {
return false;
}
if (headerSpace.getNotSrcIps() != null
&& traceSrcIp(headerSpace.getNotSrcIps(), _flow.getSrcIp())) {
return false;
}
if (!headerSpace.getSrcPorts().isEmpty()
&& !rangesContain(headerSpace.getSrcPorts(), _flow.getSrcPort())) {
return false;
}
if (!headerSpace.getNotSrcPorts().isEmpty()
&& rangesContain(headerSpace.getNotSrcPorts(), _flow.getSrcPort())) {
return false;
}
if (!headerSpace.getSrcProtocols().isEmpty()) {
boolean match = false;
for (Protocol srcProtocol : headerSpace.getSrcProtocols()) {
if (srcProtocol.getIpProtocol().equals(_flow.getIpProtocol())) {
match = true;
Integer srcPort = srcProtocol.getPort();
if (!srcPort.equals(_flow.getSrcPort())) {
match = false;
}
if (match) {
break;
}
}
}
if (!match) {
return false;
}
}
if (!headerSpace.getNotSrcProtocols().isEmpty()) {
boolean match = false;
for (Protocol notSrcProtocol : headerSpace.getNotSrcProtocols()) {
if (notSrcProtocol.getIpProtocol().equals(_flow.getIpProtocol())) {
match = true;
Integer srcPort = notSrcProtocol.getPort();
if (!srcPort.equals(_flow.getSrcPort())) {
match = false;
}
if (match) {
return false;
}
}
}
}
if (!headerSpace.getStates().isEmpty() && !headerSpace.getStates().contains(_flow.getState())) {
return false;
}
if (!headerSpace.getTcpFlags().isEmpty()
&& headerSpace.getTcpFlags().stream().noneMatch(tcpFlags -> tcpFlags.match(_flow))) {
return false;
}
return true;
}
private boolean trace(@Nonnull IpAccessList ipAccessList) {
List<AclLine> lines = ipAccessList.getLines();
newTrace();
for (int i = 0; i < lines.size(); i++) {
AclLine line = lines.get(i);
LineAction action = visit(line);
if (action != null) {
recordAction(ipAccessList, i, line, action);
endTrace();
return action == LineAction.PERMIT;
}
nextLine();
}
recordDefaultDeny(ipAccessList);
endTrace();
return false;
}
public boolean trace(@Nonnull IpSpace ipSpace, @Nonnull Ip ip, @Nonnull String ipDescription) {
return ipSpace.accept(new IpSpaceTracer(this, ip, ipDescription));
}
public boolean traceDstIp(@Nonnull IpSpace ipSpace, @Nonnull Ip ip) {
return ipSpace.accept(new IpSpaceTracer(this, ip, "destination IP"));
}
public boolean traceSrcIp(@Nonnull IpSpace ipSpace, @Nonnull Ip ip) {
return ipSpace.accept(new IpSpaceTracer(this, ip, "source IP"));
}
@Override
public Boolean visitMatchHeaderSpace(MatchHeaderSpace matchHeaderSpace) {
return trace(matchHeaderSpace.getHeaderspace());
}
@Override
public Boolean visitPermittedByAcl(PermittedByAcl permittedByAcl) {
return trace(_availableAcls.get(permittedByAcl.getAclName()));
}
@Override
public Boolean visitAndMatchExpr(AndMatchExpr andMatchExpr) {
return andMatchExpr.getConjuncts().stream()
.allMatch(
c -> {
newTrace();
Boolean result = c.accept(this);
endTrace();
return result;
});
}
@Override
public Boolean visitOrMatchExpr(OrMatchExpr orMatchExpr) {
return orMatchExpr.getDisjuncts().stream()
.anyMatch(
d -> {
newTrace();
Boolean result = d.accept(this);
endTrace();
return result;
});
}
/**
* Start a new trace at the current depth level. Indicates jump in a level of indirection to a new
* structure (even though said structure can still be part of a single ACL line.
*/
public void newTrace() {
// Add new child, set it as current node
_nodeStack.push(_nodeStack.peek().addChild());
}
/** End a trace: indicates that tracing of a structure is finished. */
public void endTrace() {
// Go up level of a tree, do not delete children
_nodeStack.pop();
}
/** Set the event of the current node. Precondition: current node's event is null. */
private void setEvent(TraceEvent event) {
TraceNode currentNode = _nodeStack.peek();
checkState(currentNode.getEvent() == null, "Clobbered current node's event");
currentNode.setEvent(event);
}
/**
* Indicate we are moving on to the next line in current data structure (i.e., did not match
* previous line)
*/
public void nextLine() {
// All previous children are of no interest since they resulted in a no-match on previous line
_nodeStack.peek().clearChildren();
}
/** For building trace event trees */
private static final class TraceNode {
private @Nullable TraceEvent _event;
private final @Nonnull List<TraceNode> _children;
private TraceNode() {
this(null, new ArrayList<>());
}
private TraceNode(@Nullable TraceEvent event, @Nonnull List<TraceNode> children) {
_event = event;
_children = children;
}
@Nonnull
private List<TraceNode> getChildren() {
return _children;
}
@Nullable
private TraceEvent getEvent() {
return _event;
}
private void setEvent(@Nonnull TraceEvent event) {
_event = event;
}
/** Adds a new child to this node trace node. Returns pointer to given node */
private TraceNode addChild() {
TraceNode child = new TraceNode();
_children.add(child);
return child;
}
/** Clears all children from this node */
private void clearChildren() {
_children.clear();
}
}
}
|
package org.bouncycastle.jcajce.provider.test;
import java.security.AlgorithmParameters;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import junit.framework.TestCase;
public class ECAlgorithmParametersTest
extends TestCase
{
public static String[] entries = {
"secp112r1",
"1.3.132.0.6",
"secp112r2",
"1.3.132.0.7",
"secp128r1",
"1.3.132.0.28",
"secp128r2",
"1.3.132.0.29",
"secp160k1",
"1.3.132.0.9",
"secp160r1",
"1.3.132.0.8",
"secp160r2",
"1.3.132.0.30",
"secp192k1",
"1.3.132.0.31",
"secp192r1",
"NIST P-192",
"X9.62 prime192v1",
"1.2.840.10045.3.1.1",
"secp224k1",
"1.3.132.0.32",
"secp224r1",
"NIST P-224",
"1.3.132.0.33",
"secp256k1",
"1.3.132.0.10",
"secp256r1",
"NIST P-256",
"X9.62 prime256v1",
"1.2.840.10045.3.1.7",
"secp384r1",
"NIST P-384",
"1.3.132.0.34",
"secp521r1",
"NIST P-521",
"1.3.132.0.35",
"X9.62 prime192v2",
"1.2.840.10045.3.1.2",
"X9.62 prime192v3",
"1.2.840.10045.3.1.3",
"X9.62 prime239v1",
"1.2.840.10045.3.1.4",
"X9.62 prime239v2",
"1.2.840.10045.3.1.5",
"X9.62 prime239v3",
"1.2.840.10045.3.1.6",
"sect113r1",
"1.3.132.0.4",
"sect113r2",
"1.3.132.0.5",
"sect131r1",
"1.3.132.0.22",
"sect131r2",
"1.3.132.0.23",
"sect163k1",
"NIST K-163",
"1.3.132.0.1",
"sect163r1",
"1.3.132.0.2",
"sect163r2",
"NIST B-163",
"1.3.132.0.15",
"sect193r1",
"1.3.132.0.24",
"sect193r2",
"1.3.132.0.25",
"sect233k1",
"NIST K-233",
"1.3.132.0.26",
"sect233r1",
"NIST B-233",
"1.3.132.0.27",
"sect239k1",
"1.3.132.0.3",
"sect283k1",
"NIST K-283",
"1.3.132.0.16",
"sect283r1",
"NIST B-283",
"1.3.132.0.17",
"sect409k1",
"NIST K-409",
"1.3.132.0.36",
"sect409r1",
"NIST B-409",
"1.3.132.0.37",
"sect571k1",
"NIST K-571",
"1.3.132.0.38",
"sect571r1",
"NIST B-571",
"1.3.132.0.39",
"X9.62 c2tnb191v1",
"1.2.840.10045.3.0.5",
"X9.62 c2tnb191v2",
"1.2.840.10045.3.0.6",
"X9.62 c2tnb191v3",
"1.2.840.10045.3.0.7",
"X9.62 c2tnb239v1",
"1.2.840.10045.3.0.11",
"X9.62 c2tnb239v2",
"1.2.840.10045.3.0.12",
"X9.62 c2tnb239v3",
"1.2.840.10045.3.0.13",
"X9.62 c2tnb359v1",
"1.2.840.10045.3.0.18",
"X9.62 c2tnb431r1",
"1.2.840.10045.3.0.20",
"X9.62 c2pnb163v1",
"1.2.840.10045.3.0.1",
"X9.62 c2pnb163v2",
"1.2.840.10045.3.0.2",
"X9.62 c2pnb163v3",
"1.2.840.10045.3.0.3",
"X9.62 c2pnb176w1",
"1.2.840.10045.3.0.4",
"X9.62 c2pnb208w1",
"1.2.840.10045.3.0.10",
"X9.62 c2pnb272w1",
"1.2.840.10045.3.0.16",
"X9.62 c2pnb304w1",
"1.2.840.10045.3.0.17",
"X9.62 c2pnb368w1",
"1.2.840.10045.3.0.19" };
public void testRecogniseStandardCurveNames()
throws Exception
{
for (int i = 0; i != entries.length; i++)
{
AlgorithmParameters algParams = AlgorithmParameters.getInstance("EC", "BC");
algParams.init(new ECGenParameterSpec(entries[i]));
algParams.getParameterSpec(ECParameterSpec.class);
ECGenParameterSpec spec = algParams.getParameterSpec(ECGenParameterSpec.class);
TestCase.assertEquals(nextOid(i), spec.getName());
}
}
private String nextOid(int index)
{
for (int i = index; i < entries.length; i++)
{
if (entries[i].charAt(0) >= '0' && entries[i].charAt(0) <= '2')
{
return entries[i];
}
}
return null;
}
}
|
package org.collectionspace.chain.csp.persistence.services.vocab;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.StringUtils;
import org.collectionspace.chain.csp.persistence.services.GenericStorage;
import org.collectionspace.chain.csp.persistence.services.XmlJsonConversion;
import org.collectionspace.chain.csp.persistence.services.connection.ConnectionException;
import org.collectionspace.chain.csp.persistence.services.connection.RequestMethod;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL;
import org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection;
import org.collectionspace.chain.csp.schema.Field;
import org.collectionspace.chain.csp.schema.FieldSet;
import org.collectionspace.chain.csp.schema.Group;
import org.collectionspace.chain.csp.schema.Instance;
import org.collectionspace.chain.csp.schema.Record;
import org.collectionspace.csp.api.core.CSPRequestCache;
import org.collectionspace.csp.api.core.CSPRequestCredentials;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.collectionspace.csp.helper.persistence.ContextualisedStorage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConfiguredVocabStorage extends GenericStorage {
private static final Logger log=LoggerFactory.getLogger(ConfiguredVocabStorage.class);
private ServicesConnection conn;
private VocabInstanceCache vocab_cache;
private URNProcessor urn_processor;
private Record r;
public ConfiguredVocabStorage(Record r,ServicesConnection conn) throws DocumentException, IOException {
super(r,conn);
this.conn=conn;
urn_processor=new URNProcessor(r.getURNSyntax());
Map<String,String> vocabs=new ConcurrentHashMap<String,String>();
for(Instance n : r.getAllInstances()) {
vocabs.put(n.getTitleRef(),n.getTitle());
}
vocab_cache=new VocabInstanceCache(r,conn,vocabs);
this.r=r;
}
private Document createEntry(String section,String namespace,String root_tag,JSONObject data,String vocab,String refname, Record r) throws UnderlyingStorageException, ConnectionException, ExistException, JSONException {
Document out=XmlJsonConversion.convertToXml(r,data,section);
Element root=out.getRootElement();
Element vocabtag=root.addElement(r.getInTag());
if(vocab!=null){
vocabtag.addText(vocab);
}
Element refnametag=root.addElement("refName");
if(refname!=null)
refnametag.addText(refname);
if(r.isType("compute-displayname")) {
Element dnc=root.addElement("displayNameComputed");
dnc.addText("false");
}
log.debug("create Configured Vocab Entry"+out.asXML());
return out;
}
private String getDisplayNameKey() throws UnderlyingStorageException {
Field dnf=(Field)r.getDisplayNameField();
if(dnf==null)
throw new UnderlyingStorageException("no display-name='yes' field");
return dnf.getID();
}
public String autocreateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath,JSONObject jsonObject)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
String name=jsonObject.getString(getDisplayNameKey());
String vocab=vocab_cache.getVocabularyId(creds,cache,filePath);
Map<String,Document> body=new HashMap<String,Document>();
for(String section : r.getServicesRecordPaths()) {
String path=r.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
String[] tag_path=record_path[1].split(",",2);
body.put(record_path[0],createEntry(section,tag_path[0],tag_path[1],jsonObject,vocab,null,r));
}
// First send without refid (don't know csid)
ReturnedURL out=conn.getMultipartURL(RequestMethod.POST,"/"+r.getServicesURL()+"/"+vocab+"/items",body,creds,cache);
if(out.getStatus()>299)
throw new UnderlyingStorageException("Could not create vocabulary",out.getStatus(),"/"+r.getServicesURL()+"/"+vocab+"/items");
// This time with refid
String csid=out.getURLTail();
String refname=urn_processor.constructURN("id",vocab,"id",out.getURLTail(),name);
body=new HashMap<String,Document>();
for(String section : r.getServicesRecordPaths()) {
String path=r.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
String[] tag_path=record_path[1].split(",",2);
body.put(record_path[0],createEntry(section,tag_path[0],tag_path[1],jsonObject,vocab,refname,r));
}
ReturnedMultipartDocument out2=conn.getMultipartXMLDocument(RequestMethod.PUT,"/"+r.getServicesURL()+"/"+vocab+"/items/"+csid,body,creds,cache);
if(out2.getStatus()>299)
throw new UnderlyingStorageException("Could not create vocabulary status="+out.getStatus());
cache.setCached(getClass(),new String[]{"namefor",vocab,out.getURLTail()},name);
cache.setCached(getClass(),new String[]{"reffor",vocab,out.getURLTail()},refname);
cache.setCached(getClass(),new String[]{"csidfor",vocab,out.getURLTail()},out.getURLTail());
// create related sub records?
for(FieldSet fs : r.getAllSubRecords()){
Record sr = fs.usesRecordId();
//sr.getID()
if(sr.isType("authority")){
String savePath = out.getURL() + "/" + sr.getServicesURL();
if(fs instanceof Field){//get the fields form inline XXX untested - might not work...
JSONObject subdata = new JSONObject();
//loop thr jsonObject and find the fields I need
for(FieldSet subfs: sr.getAllFields()){
String key = subfs.getID();
if(jsonObject.has(key)){
subdata.put(key, jsonObject.get(key));
}
}
subautocreateJSON(root,creds,cache,sr,subdata,savePath);
}
else if(fs instanceof Group){//JSONObject
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONObject){
JSONObject subrecord = (JSONObject)subdata;
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
}
else{//JSONArray
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
}
}
}
}
return out.getURLTail();
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Cannot parse surrounding JSON"+e.getLocalizedMessage(),e);
}
}
public String subautocreateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,Record myr,JSONObject jsonObject, String savePrefix)
throws ExistException, UnimplementedException, UnderlyingStorageException{
try {
Map<String,Document> body=new HashMap<String,Document>();
for(String section : myr.getServicesRecordPaths()) {
String path=myr.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
String[] tag_path=record_path[1].split(",",2);
body.put(record_path[0],createEntry(section,tag_path[0],tag_path[1],jsonObject,null,null,myr));
}
ReturnedURL out=conn.getMultipartURL(RequestMethod.POST,savePrefix,body,creds,cache);
if(out.getStatus()>299)
throw new UnderlyingStorageException("Could not create vocabulary",out.getStatus(),savePrefix);
// create related sub records?
for(FieldSet allfs : myr.getAllSubRecords()){
Record sr = allfs.usesRecordId();
//sr.getID()
if(sr.isType("authority")){
String savePath = out.getURL() + "/" + sr.getServicesURL();
if(jsonObject.has(sr.getID())){
Object subdata = jsonObject.get(sr.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
else if(subdata instanceof JSONObject){
JSONObject subrecord = (JSONObject)subdata;
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
}
}
return out.getURLTail();
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Cannot parse surrounding JSON"+e.getLocalizedMessage(),e);
}
}
public void deleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache, String filePath)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
String vocab=vocab_cache.getVocabularyId(creds,cache,filePath.split("/")[0]);
String url = generateURL(vocab,filePath.split("/")[1],"");
int status=conn.getNone(RequestMethod.DELETE,url,null,creds,cache);
if(status>299)
throw new UnderlyingStorageException("Could not retrieve vocabulary",status,url);
cache.removeCached(getClass(),new String[]{"namefor",vocab,filePath.split("/")[1]});
cache.removeCached(getClass(),new String[]{"reffor",vocab,filePath.split("/")[1]});
cache.removeCached(getClass(),new String[]{"shortId",vocab,filePath.split("/")[1]});
cache.removeCached(getClass(),new String[]{"csidfor",vocab,filePath.split("/")[1]});
//delete name and id versions from teh cache?
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
/**
* Returns JSON containing pagenumber, pagesize, itemsinpage, totalitems and the list of items itself
*/
@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String rootPath,JSONObject restrictions)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
JSONObject out = new JSONObject();
List<String> list=new ArrayList<String>();
String vocab=vocab_cache.getVocabularyId(creds,cache,rootPath);
String url="/"+r.getServicesURL()+"/"+vocab+"/items";
String postfix = "?";
String prefix=null;
Boolean queryadded = false;
if(restrictions!=null){
if(restrictions.has(getDisplayNameKey())){
prefix=restrictions.getString(getDisplayNameKey());
}
if(restrictions.has("pageSize")){
postfix += "pgSz="+restrictions.getString("pageSize")+"&";
}
if(restrictions.has("pageNum")){
postfix += "pgNum="+restrictions.getString("pageNum")+"&";
}
if(restrictions.has("queryTerm")){
String queryString = prefix;
if(restrictions.has("queryString")){
queryString=restrictions.getString("queryString");
}
postfix+=restrictions.getString("queryTerm")+"="+URLEncoder.encode(queryString,"UTF8")+"&";
queryadded = true;
}
}
if(prefix!=null && !queryadded){
postfix+="pt="+URLEncoder.encode(prefix,"UTF8")+"&";
}
postfix = postfix.substring(0, postfix.length()-1);
url+=postfix;
ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET,url,null,creds,cache);
Document doc=data.getDocument();
if(doc==null)
throw new UnderlyingStorageException("Could not retrieve vocabularies",500,url);
String[] tag_parts=r.getServicesListPath().split(",",2);
JSONObject pagination = new JSONObject();
/**
* Returns a list of items
*/
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String rootPath,JSONObject restrictions)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
List<String> out=new ArrayList<String>();
String vocab=vocab_cache.getVocabularyId(creds,cache,rootPath);
String url="/"+r.getServicesURL()+"/"+vocab+"/items";
String postfix = "?";
String prefix=null;
if(restrictions!=null){
if(restrictions.has(getDisplayNameKey())){
prefix=restrictions.getString(getDisplayNameKey());
}
if(restrictions.has("pageSize")){
postfix += "pgSz="+restrictions.getString("pageSize")+"&";
}
if(restrictions.has("pageNum")){
postfix += "pgNum="+restrictions.getString("pageNum")+"&";
}
}
if(prefix!=null){
postfix+="pt="+URLEncoder.encode(prefix,"UTF8")+"&";
}
postfix = postfix.substring(0, postfix.length()-1);
url+=postfix;
ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET,url,null,creds,cache);
Document doc=data.getDocument();
if(doc==null)
throw new UnderlyingStorageException("Could not retrieve vocabularies",500,url);
String[] tag_parts=r.getServicesListPath().split(",",2);
List<Node> objects=doc.getDocument().selectNodes(tag_parts[1]);
for(Node object : objects) {
String name=object.selectSingleNode("displayName").getText();
String csid=object.selectSingleNode("csid").getText();
if(prefix==null || name.toLowerCase().contains(prefix.toLowerCase()))
out.add(csid);
cache.setCached(getClass(),new String[]{"namefor",vocab,csid},name);
//why don't we just use refName that is sent in the payload?
String refname=urn_processor.constructURN("id",vocab,"id",csid,name);
cache.setCached(getClass(),new String[]{"reffor",vocab,csid},refname);
}
return out.toArray(new String[0]);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (UnsupportedEncodingException e) {
throw new UnderlyingStorageException("UTF-8 not supported!?"+e.getLocalizedMessage());
} catch (JSONException e) {
throw new UnderlyingStorageException("Error parsing JSON"+e.getLocalizedMessage());
}
}
private String generateURL(String vocab,String path,String extrapath,Record myr) throws ExistException, ConnectionException, UnderlyingStorageException {
String url = myr.getServicesURL()+"/"+vocab+"/items/"+path+extrapath;
return url;
}
private String generateURL(String vocab,String path,String extrapath) throws ExistException, ConnectionException, UnderlyingStorageException {
String url = r.getServicesURL()+"/"+vocab+"/items/"+path+extrapath;
return url;
}
private JSONObject urnGet(String vocab,String entry,String refname) throws JSONException, ExistException, UnderlyingStorageException {
JSONObject out=new JSONObject();
//use cache?
out.put("recordtype",r.getWebURL());
out.put("refid",refname);
out.put("csid",entry);
out.put("displayName",urn_processor.deconstructURN(refname,false)[5]);
return out;
}
public JSONObject retrieveJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache, String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Integer num = 0;
String[] parts=filePath.split("/");
//deal with different url structures
String vocab,csid;
if("_direct".equals(parts[0])) {
if("urn".equals(parts[1])) {
//this isn't simple pattern matching
return urnGet(parts[2],parts[3],parts[4]);
}
vocab=parts[2];
csid=parts[3];
num=4;
} else {
vocab=vocab_cache.getVocabularyId(creds,cache,parts[0]);
csid=parts[1];
num = 2;
}
if(parts.length>num) {
String extra = "";
Integer extradata = num + 1;
if(parts.length>extradata){
extra = parts[extradata];
}
return viewRetrieveJSON(root,creds,cache,vocab,csid,parts[num],extra);
} else
return simpleRetrieveJSON(root,creds,cache,vocab,csid);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch(JSONException x) {
throw new UnderlyingStorageException("Error building JSON"+x.getLocalizedMessage(),x);
}
}
public JSONObject viewRetrieveJSON(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String vocab, String csid,String view, String extra) throws ExistException,UnimplementedException, UnderlyingStorageException, JSONException {
try{
if(view.equals("view")){
return miniViewRetrieveJSON(storage, cache,creds,vocab, csid);
}
else if("authorityrefs".equals(view)){
String path = generateURL(vocab,csid,"/authorityrefs");
return refViewRetrieveJSON(storage,creds,cache,path);
}
else if("refObjs".equals(view)){
String path = generateURL(vocab,csid,"/refObjs");
return refObjViewRetrieveJSON(storage,creds,cache,path);
}
else
return new JSONObject();
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
public JSONObject miniViewRetrieveJSON(ContextualisedStorage storage,CSPRequestCache cache,CSPRequestCredentials creds,String vocab,String csid) throws ExistException,UnimplementedException, UnderlyingStorageException, JSONException {
try {
JSONObject out=new JSONObject();
//actually use cache
String name=(String)cache.getCached(getClass(),new String[]{"namefor",vocab,csid});
String refid=(String)cache.getCached(getClass(),new String[]{"reffor",vocab,csid});
String shortId=(String)cache.getCached(getClass(),new String[]{"shortId",vocab,csid});
String testcsid=(String)cache.getCached(getClass(),new String[]{"csidfor",vocab,csid});
//incase using nameurn
if(testcsid!=null && testcsid.equals("") && !testcsid.equals(csid))
{
csid = testcsid;
}
if(name != null && refid != null && name.length() >0 && refid.length()>0 && shortId !=null){
out.put(getDisplayNameKey(), name);
out.put("refid", refid);
out.put("csid",csid);
out.put("authorityid", vocab);
out.put("shortIdentifier", shortId);
out.put("recordtype",r.getWebURL());
}
else{
return simpleRetrieveJSON(storage, creds,cache,vocab,csid);
}
return out;
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
public JSONObject simpleRetrieveJSON(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String vocab, String csid) throws ConnectionException, ExistException, UnderlyingStorageException, JSONException{
JSONObject out=new JSONObject();
out=get(storage, creds,cache,vocab,csid);
cache.setCached(getClass(),new String[]{"csidfor",vocab,csid},out.get("csid"));//cos csid might be a refname at this point..
cache.setCached(getClass(),new String[]{"namefor",vocab,csid},out.get(getDisplayNameKey()));
cache.setCached(getClass(),new String[]{"reffor",vocab,csid},out.get("refid"));
cache.setCached(getClass(),new String[]{"shortId",vocab,csid},out.get("shortIdentifier"));
return out;
}
private JSONArray get(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String vocab,String csid,String filePath, Record thisr) throws ConnectionException, ExistException, UnderlyingStorageException, JSONException {
JSONArray itemarray = new JSONArray();
//get list view
|
package cucumber.eclipse.editor.markers;
import static cucumber.eclipse.editor.editors.DocumentUtil.read;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.IMarkerResolutionGenerator;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import cucumber.eclipse.editor.Activator;
import cucumber.eclipse.editor.editors.Editor;
import cucumber.eclipse.editor.editors.GherkinModel;
import cucumber.eclipse.editor.editors.PositionedElement;
import cucumber.eclipse.editor.snippet.ExtensionRegistryStepGeneratorProvider;
import cucumber.eclipse.editor.snippet.IStepGeneratorProvider;
import cucumber.eclipse.editor.snippet.SnippetApplicator;
import cucumber.eclipse.editor.steps.ExtensionRegistryStepProvider;
import cucumber.eclipse.steps.integration.Step;
public class StepCreationMarkerResolutionGenerator implements IMarkerResolutionGenerator {
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
Set<IFile> files = new HashSet<IFile>();
Set<Step> steps = new ExtensionRegistryStepProvider((IFile) marker.getResource())
.getStepsInEncompassingProject();
for (Step step : steps) {
files.add((IFile) step.getSource());
}
List<IFile> filesList = new ArrayList<IFile>(files);
Collections.sort(filesList, new Comparator<IFile>() {
@Override
public int compare(IFile o1, IFile o2) {
return o1.getName().compareTo(o2.getName());
}
});
IMarkerResolution[] resolutions = new IMarkerResolution[filesList.size()];
for (int i = 0; i < resolutions.length; i ++) {
resolutions[i] = new StepCreationMarkerResolution(filesList.get(i));
}
return resolutions;
}
private static class StepCreationMarkerResolution implements IMarkerResolution {
private final IFile stepFile;
public StepCreationMarkerResolution(IFile stepFile) {
this.stepFile = stepFile;
}
@Override
public void run(IMarker marker) {
IFile featureFile = ((IFile) marker.getResource());
IStepGeneratorProvider generatorProvider = new ExtensionRegistryStepGeneratorProvider();
try {
GherkinModel model = getCurrentModel(featureFile);
PositionedElement element = model.getStepElement(marker.getAttribute(IMarker.CHAR_START, 0));
gherkin.formatter.model.Step step = ((gherkin.formatter.model.Step) element.getStatement());
new SnippetApplicator(generatorProvider).generateSnippet(step, stepFile);
}
catch (IOException exception) {
logException(marker, exception);
}
catch (CoreException exception) {
logException(marker, exception);
}
catch (BadLocationException exception) {
logException(marker, exception);
}
}
@Override
public String getLabel() {
return String.format("Create step in %s", stepFile.getName());
}
private static GherkinModel getCurrentModel(IFile featureFile) throws IOException, CoreException {
GherkinModel model = getModelFromOpenEditor(featureFile);
if (model == null) {
model = getModelFromFile(featureFile);
}
return model;
}
private static GherkinModel getModelFromOpenEditor(IFile featureFile) throws PartInitException {
IEditorReference[] editorReferences = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getEditorReferences();
for (IEditorReference editorReference : editorReferences) {
if (editorReference.getEditorInput() instanceof FileEditorInput) {
FileEditorInput fileEditorInput = (FileEditorInput) editorReference.getEditorInput();
if (featureFile.equals(fileEditorInput.getFile())) {
IEditorPart editor = editorReference.getEditor(false);
if (editor instanceof Editor) {
return ((Editor) editor).getModel();
}
}
}
}
return null;
}
private static GherkinModel getModelFromFile(IFile featureFile) throws IOException, CoreException {
GherkinModel model = new GherkinModel();
model.updateFromDocument(read(featureFile.getContents(), featureFile.getCharset()));
return model;
}
private static void logException(IMarker marker, Exception exception) {
Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
String.format("Couldn't create step for %s", marker), exception));
}
}
}
|
package org.eclipse.birt.report.engine.layout.pdf.emitter;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.css.engine.StyleConstants;
import org.eclipse.birt.report.engine.layout.area.IArea;
import org.eclipse.birt.report.engine.layout.area.impl.AbstractArea;
import org.eclipse.birt.report.engine.layout.area.impl.AreaFactory;
import org.eclipse.birt.report.engine.layout.area.impl.CellArea;
import org.eclipse.birt.report.engine.layout.area.impl.ContainerArea;
import org.eclipse.birt.report.engine.layout.area.impl.RowArea;
import org.eclipse.birt.report.engine.layout.area.impl.TableArea;
import org.eclipse.birt.report.engine.layout.pdf.BorderConflictResolver;
import org.eclipse.birt.report.engine.layout.pdf.cache.CursorableList;
import org.eclipse.birt.report.engine.layout.pdf.cache.DummyCell;
import org.eclipse.birt.report.engine.layout.pdf.emitter.TableLayout.TableLayoutInfo;
import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil;
import org.eclipse.birt.report.engine.util.BidiAlignmentResolver;
import org.w3c.dom.css.CSSValue;
public class TableAreaLayout
{
protected CursorableList rows = new CursorableList( );
/**
* Border conflict resolver
*/
protected BorderConflictResolver bcr = new BorderConflictResolver( );
protected TableLayoutInfo layoutInfo = null;
protected ITableContent tableContent;
protected ICellContent[] cellCache = new ICellContent[2];
protected int startCol;
protected int endCol;
protected Row unresolvedRow;
public TableAreaLayout( ITableContent tableContent,
TableLayoutInfo layoutInfo, int startCol, int endCol )
{
this.tableContent = tableContent;
this.layoutInfo = layoutInfo;
this.startCol = startCol;
this.endCol = endCol;
if ( tableContent != null )
bcr.setRTL( tableContent.isRTL( ) );
}
public void setUnresolvedRow( Row row )
{
this.unresolvedRow = row;
}
public Row getUnresolvedRow( )
{
return (Row) rows.getCurrent( );
}
protected int resolveBottomBorder( CellArea cell )
{
IStyle tableStyle = tableContent.getComputedStyle( );
IContent cellContent = cell.getContent( );
IStyle columnStyle = getColumnStyle( cell.getColumnID( ) );
IStyle cellAreaStyle = cell.getStyle( );
IStyle cellContentStyle = cellContent.getComputedStyle( );
IStyle rowStyle = ( (IContent) cellContent.getParent( ) )
.getComputedStyle( );
bcr.resolveTableBottomBorder( tableStyle, rowStyle, columnStyle,
cellContentStyle, cellAreaStyle );
return PropertyUtil.getDimensionValue( cellAreaStyle
.getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) );
}
protected void add( ContainerArea area, ArrayList rows )
{
if ( area instanceof RowArea )
{
rows.add( area );
}
else
{
Iterator iter = area.getChildren( );
while ( iter.hasNext( ) )
{
ContainerArea container = (ContainerArea) iter.next( );
add( container, rows );
}
}
}
public void remove( TableArea table )
{
ArrayList rowColloection = new ArrayList( );
add( table, rowColloection );
Iterator iter = rows.iterator( );
while ( iter.hasNext( ) )
{
Row row = (Row) iter.next( );
if ( rowColloection.contains( row.getArea( ) ) )
{
iter.remove( );
}
}
rows.resetCursor( );
}
protected IStyle getLeftCellContentStyle( Row lastRow, int columnID )
{
if ( cellCache[1] != null
&& cellCache[1].getColumn( ) + cellCache[1].getColSpan( ) <= columnID )
{
if ( lastRow != null && columnID > 0 )
{
CellArea cell = lastRow.getCell( columnID - 1 );
if ( cell != null && cell.getRowSpan( ) < 0
&& cell.getContent( ) != null )
{
return cell.getContent( ).getComputedStyle( );
}
}
return cellCache[1].getComputedStyle( );
}
if ( lastRow != null && columnID > 0 )
{
CellArea cell = lastRow.getCell( columnID - 1 );
if ( cell != null && cell.getRowSpan( ) > 1
&& cell.getContent( ) != null )
{
return cell.getContent( ).getComputedStyle( );
}
}
return null;
}
/**
* resolve cell border conflict
*
* @param cellArea
*/
public void resolveBorderConflict( CellArea cellArea, boolean isFirst )
{
IContent cellContent = cellArea.getContent( );
int columnID = cellArea.getColumnID( );
int colSpan = cellArea.getColSpan( );
IRowContent row = (IRowContent) cellContent.getParent( );
IStyle cellContentStyle = cellContent.getComputedStyle( );
IStyle cellAreaStyle = cellArea.getStyle( );
IStyle tableStyle = tableContent.getComputedStyle( );
IStyle rowStyle = row.getComputedStyle( );
IStyle columnStyle = getColumnStyle( columnID );
IStyle preRowStyle = null;
IStyle preColumnStyle = getColumnStyle( columnID - 1 );
IStyle leftCellContentStyle = null;
IStyle topCellStyle = null;
Row lastRow = null;
if(cellCache[0]!=cellContent)
{
cellCache[1] = cellCache[0];
cellCache[0] = (ICellContent)cellContent;
}
if ( rows.size( ) > 0 )
{
lastRow = (Row) rows.getCurrent( );
}
leftCellContentStyle = getLeftCellContentStyle( lastRow, columnID );
if ( lastRow != null )
{
preRowStyle = lastRow.getContent( ).getComputedStyle( );
CellArea cell = lastRow.getCell( columnID );
if ( cell != null && cell.getContent( ) != null )
{
topCellStyle = cell.getContent( ).getComputedStyle( );
}
}
// FIXME
if ( rows.size( ) == 0 && lastRow == null )
{
// resolve top border
if ( isFirst )
{
bcr.resolveTableTopBorder( tableStyle, rowStyle, columnStyle,
cellContentStyle, cellAreaStyle );
}
else
{
bcr.resolveTableTopBorder( tableStyle, null, columnStyle, null,
cellAreaStyle );
}
// resolve left border
if ( columnID == startCol )
{
bcr.resolveTableLeftBorder( tableStyle, rowStyle, columnStyle,
cellContentStyle, cellAreaStyle );
}
else
{
bcr.resolveCellLeftBorder( preColumnStyle, columnStyle,
leftCellContentStyle, cellContentStyle, cellAreaStyle );
}
// resolve right border
if ( columnID + colSpan - 1 == endCol )
{
bcr.resolveTableRightBorder( tableStyle, rowStyle, columnStyle,
cellContentStyle, cellAreaStyle );
}
}
else
{
if ( isFirst )
{
bcr.resolveCellTopBorder( preRowStyle, rowStyle, topCellStyle,
cellContentStyle, cellAreaStyle );
}
else
{
bcr.resolveCellTopBorder( preRowStyle, null, topCellStyle,
null, cellAreaStyle );
}
// resolve left border
if ( columnID == startCol )
{
// first column
bcr.resolveTableLeftBorder( tableStyle, rowStyle, columnStyle,
cellContentStyle, cellAreaStyle );
}
else
{
// TODO fix row span conflict
bcr.resolveCellLeftBorder( preColumnStyle, columnStyle,
leftCellContentStyle, cellContentStyle, cellAreaStyle );
}
// resolve right border
if ( columnID + colSpan - 1 == endCol )
{
bcr.resolveTableRightBorder( tableStyle, rowStyle, columnStyle,
cellContentStyle, cellAreaStyle );
}
}
}
/**
* get column style
*
* @param columnID
* @return
*/
private IStyle getColumnStyle( int columnID )
{
// current not support column style
return null;
}
protected void verticalAlign( CellArea c )
{
CellArea cell;
if ( c instanceof DummyCell )
{
cell = ( (DummyCell) c ).getCell( );
}
else
{
cell = c;
}
IContent content = cell.getContent( );
if ( content == null )
{
return;
}
CSSValue verticalAlign = content.getComputedStyle( ).getProperty(
IStyle.STYLE_VERTICAL_ALIGN );
if ( IStyle.BOTTOM_VALUE.equals( verticalAlign )
|| IStyle.MIDDLE_VALUE.equals( verticalAlign ) )
{
int totalHeight = 0;
Iterator iter = cell.getChildren( );
while ( iter.hasNext( ) )
{
AbstractArea child = (AbstractArea) iter.next( );
totalHeight += child.getAllocatedHeight( );
}
int offset = cell.getContentHeight( ) - totalHeight;
if ( offset > 0 )
{
if ( IStyle.BOTTOM_VALUE.equals( verticalAlign ) )
{
iter = cell.getChildren( );
while ( iter.hasNext( ) )
{
AbstractArea child = (AbstractArea) iter.next( );
child.setAllocatedPosition( child.getAllocatedX( ),
child.getAllocatedY( ) + offset );
}
}
else if ( IStyle.MIDDLE_VALUE.equals( verticalAlign ) )
{
iter = cell.getChildren( );
while ( iter.hasNext( ) )
{
AbstractArea child = (AbstractArea) iter.next( );
child.setAllocatedPosition( child.getAllocatedX( ),
child.getAllocatedY( ) + offset / 2 );
}
}
}
}
CSSValue align = content.getComputedStyle( ).getProperty(
IStyle.STYLE_TEXT_ALIGN );
// bidi_hcg: handle empty or justify align in RTL direction as right
// alignment
boolean isRightAligned = BidiAlignmentResolver.isRightAligned( content,
align, false );
// single line
if ( isRightAligned || IStyle.CENTER_VALUE.equals( align ) )
{
Iterator iter = cell.getChildren( );
while ( iter.hasNext( ) )
{
AbstractArea area = (AbstractArea) iter.next( );
int spacing = cell.getContentWidth( )
- area.getAllocatedWidth( );
if ( spacing > 0 )
{
if ( isRightAligned )
{
area.setAllocatedPosition( spacing
+ area.getAllocatedX( ), area.getAllocatedY( ) );
}
else if ( IStyle.CENTER_VALUE.equals( align ) )
{
area.setAllocatedPosition( spacing / 2
+ area.getAllocatedX( ), area.getAllocatedY( ) );
}
}
}
}
}
public void reset( TableArea table )
{
Iterator iter = rows.iterator( );
while ( iter.hasNext( ) )
{
Row row = (Row) iter.next( );
if ( table.contains( row.getArea( ) ) )
{
iter.remove( );
}
}
rows.resetCursor( );
}
/**
* When pagination happens, if drop cells should be finished by force, we need to end these
* cells and vertical align for them.
*
*/
public int resolveAll( )
{
if ( rows.size( ) == 0 )
{
return 0;
}
Row row = (Row) rows.getCurrent( );
int originalRowHeight = row.getArea( ).getHeight( );
int height = originalRowHeight;
for ( int i = startCol; i <= endCol; i++ )
{
CellArea cell = row.getCell(i);
if ( null == cell )
{
// After padding empty cell and dummy cell, the cell should not be null.
continue;
}
if ( cell instanceof DummyCell )
{
DummyCell dummyCell = (DummyCell) cell;
int delta = dummyCell.getDelta( );
height = Math.max( height, delta );
}
else
{
height = Math.max( height, cell.getHeight( ) );
}
i = i + cell.getColSpan( ) - 1;
}
int dValue = height - originalRowHeight;
for ( int i = startCol; i <= endCol; i++ )
{
CellArea cell = row.getCell( i );
if ( cell == null )
{
// this should NOT happen.
continue;
}
if ( cell instanceof DummyCell )
{
if ( cell.getRowSpan( ) == 1 )
// this dummyCell and it reference cell height have already been
// updated.
{
if ( dValue != 0 )
{
CellArea refCell = ( (DummyCell) cell ).getCell( );
refCell.setHeight( refCell.getHeight( ) + height
- originalRowHeight );
verticalAlign( refCell );
}
}
else
{
CellArea refCell = ( (DummyCell) cell ).getCell( );
int delta = ( (DummyCell) cell ).getDelta( );
if ( delta < height )
{
refCell.setHeight( refCell.getHeight( ) - delta
+ height );
}
verticalAlign( refCell );
}
}
else
{
if ( dValue != 0 )
{
cell.setHeight( height );
verticalAlign( cell );
}
}
i = i + cell.getColSpan( ) - 1;
}
row.getArea( ).setHeight( height );
return dValue;
}
public int resolveBottomBorder( )
{
if ( rows.size( ) == 0 )
{
return 0;
}
Row row = (Row) rows.getCurrent( );
int result = 0;
int width = 0;
for ( int i = startCol; i <= endCol; i++ )
{
CellArea cell = row.getCell( i );
if ( cell == null )
{
// this should NOT happen.
continue;
}
if ( cell instanceof DummyCell )
{
width = resolveBottomBorder( ( (DummyCell) cell ).getCell( ) );
}
else
{
width = resolveBottomBorder( cell );
}
if ( width > result )
result = width;
i = i + cell.getColSpan( ) - 1;
}
// update cell height
if ( result > 0 )
{
row.getArea( ).setHeight( row.getArea( ).getHeight( ) + result );
for ( int i = startCol; i <= endCol; i++ )
{
CellArea cell = row.getCell( i );
if ( cell instanceof DummyCell )
{
CellArea refCell = ( (DummyCell) cell ).getCell( );
refCell.setHeight( refCell.getHeight( ) + result );
}
else
{
cell.setHeight( cell.getHeight( ) + result );
}
i = i + cell.getColSpan( ) - 1;
}
}
return result;
}
/**
* Adds the updated row wrapper to rows.
*/
public void addRow( RowArea rowArea )
{
addRow( rowArea, 0 );
}
/**
* Adds the updated row wrapper to rows.
*/
public void addRow( RowArea rowArea, int specifiedHeight )
{
Row row = updateRow( rowArea, specifiedHeight );
rows.add( row );
}
/**
* 1) Creates row wrapper. 2) For the null cell in the row wrapper, fills
* the responsible position with dummy cell or empty cell. 3) Updates the
* height of the row and the cells in the row.
*
* @param rowArea
* current rowArea.
*/
private Row updateRow( RowArea rowArea, int specifiedHeight )
{
int height = specifiedHeight;
Row lastRow = (Row) rows.getCurrent( );
Row row = new Row( rowArea, startCol, endCol );
for ( int i = startCol; i <= endCol; i++ )
{
CellArea upperCell = null;
if ( lastRow != null )
{
upperCell = lastRow.getCell( i );
}
// upperCell has row span, or is a drop cell.
if ( upperCell != null && ( upperCell.getRowSpan( ) > 1 ) )
{
DummyCell dummyCell = createDummyCell( upperCell );
row.addArea( dummyCell );
int delta = dummyCell.getDelta( );
if ( dummyCell.getRowSpan( ) == 1 )
{
height = Math.max( height, delta );
}
i = i + upperCell.getColSpan( ) - 1;
}
// upperCell has NO row span, and is NOT a drop cell.
// Or upperCell is null.
else
{
CellArea cell = row.getCell( i );
if ( cell == null )
{
if ( unresolvedRow != null )
{
upperCell = unresolvedRow.getCell( i );
}
cell = createEmptyCell( upperCell, i, row, lastRow );
}
if( cell.getRowSpan( ) == 1 )
{
height = Math.max( height, cell.getHeight( ) );
}
i = i + cell.getColSpan( ) - 1;
}
}
updateRowHeight( row, height );
return row;
}
/**
* Creates dummy cell and updates its delta value.
* @param upperCell the upper cell.
* @return the created dummy cell.
*/
private DummyCell createDummyCell( CellArea upperCell )
{
DummyCell dummyCell = null;
CellArea refCell = null;
Row lastRow = (Row) rows.getCurrent( );
int lastRowHeight = lastRow.getArea( ).getHeight( );
int delta = 0;
if ( upperCell instanceof DummyCell )
{
refCell = ( (DummyCell) upperCell ).getCell( );
dummyCell = new DummyCell( refCell );
delta = ( (DummyCell) upperCell ).getDelta( ) - lastRowHeight;
dummyCell.setDelta( delta );
}
else
{
refCell = upperCell;
dummyCell = new DummyCell( upperCell );
delta = refCell.getHeight( ) - lastRowHeight;
dummyCell.setDelta( delta );
}
dummyCell.setRowSpan( upperCell.getRowSpan( ) - 1 );
dummyCell.setColSpan( upperCell.getColSpan( ) );
return dummyCell;
}
private CellArea createEmptyCell( CellArea upperCell,
int columnId, Row row, Row lastRow )
{
ICellContent cellContent = null;
int rowSpan = 1;
if ( upperCell != null )
{
cellContent = (ICellContent) upperCell.getContent( );
rowSpan = upperCell.getRowSpan( );
}
if ( cellContent == null )
{
cellContent = tableContent.getReportContent( )
.createCellContent( );
cellContent.setColumn( columnId );
cellContent.setColSpan( 1 );
cellContent.setRowSpan( 1 );
cellContent.setParent( row.getArea( ).getContent( ) );
}
int emptyCellColID = cellContent.getColumn( );
int emptyCellColSpan = cellContent.getColSpan( );
CellArea emptyCell = AreaFactory
.createCellArea( cellContent );
emptyCell.setRowSpan( rowSpan );
row.addArea( emptyCell );
CellArea leftSideCellArea = null;
if ( emptyCellColID > startCol )
{
leftSideCellArea = row.getCell( emptyCellColID - 1 );
if ( leftSideCellArea == null )
{
// the left-side cell is a dummy cell which will be
// created in addRow()
cellCache[1] = (ICellContent) lastRow.getCell(
emptyCellColID - 1 ).getContent( );
int k = emptyCellColID - 1;
while ( leftSideCellArea == null && k > startCol )
{
k
leftSideCellArea = row.getCell( k );
}
}
else
{
cellCache[1] = (ICellContent) leftSideCellArea.getContent( );
}
}
else
{
leftSideCellArea = null;
}
resolveBorderConflict( emptyCell, true );
IStyle areaStyle = emptyCell.getStyle( );
areaStyle.setProperty( IStyle.STYLE_PADDING_TOP, IStyle.NUMBER_0 );
areaStyle.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0 );
emptyCell.setWidth( getCellWidth( emptyCellColID, emptyCellColID
+ emptyCellColSpan ) );
emptyCell.setPosition( layoutInfo.getXPosition( columnId ), 0 );
if ( leftSideCellArea != null )
{
int index = row.getArea( ).indexOf( leftSideCellArea );
row.getArea( ).addChild( index + 1, emptyCell );
}
else
{
row.getArea( ).addChild( 0, emptyCell );
}
return emptyCell;
}
/**
* Updates the row height and the height of the cells in the row.
* @param rowArea
* @param height
*/
private void updateRowHeight( Row row, int height )
{
if ( height < 0 )
return;
row.getArea( ).setHeight( height );
for ( int i = startCol; i <= endCol; i++ )
{
CellArea cell = row.getCell( i );
if ( cell.getRowSpan( ) == 1 )
{
if ( cell instanceof DummyCell )
{
CellArea refCell = ( (DummyCell) cell ).getCell( );
int delta = ( (DummyCell) cell ).getDelta( );
if ( delta < height )
{
refCell.setHeight( refCell.getHeight( ) - delta + height );
}
( (DummyCell) cell ).setDelta( 0 );
verticalAlign( refCell );
}
else
{
cell.setHeight( height );
verticalAlign( cell );
}
}
i = i + cell.getColSpan( ) - 1;
}
}
private int getCellWidth( int startColumn, int endColumn )
{
if ( layoutInfo != null )
{
return layoutInfo.getCellWidth( startColumn, endColumn );
}
return 0;
}
public static class Row
{
protected int start;
protected int length;
protected int end;
protected RowArea row;
protected CellArea[] cells;
Row( RowArea row, int start, int end )
{
this.row = row;
this.start = start;
this.end = end;
this.length = end - start + 1;
cells = new CellArea[length];
Iterator iter = row.getChildren( );
while ( iter.hasNext( ) )
{
CellArea cell = (CellArea) iter.next( );
int colId = cell.getColumnID( );
int colSpan = cell.getColSpan( );
if ( ( colId >= start ) && ( colId + colSpan - 1 <= end ) )
{
int loopEnd = Math.min( colSpan, end - colId + 1 );
for ( int j = 0; j < loopEnd; j++ )
{
cells[colId - start + j] = cell;
}
}
}
}
public IContent getContent( )
{
return row.getContent( );
}
public void remove( int colId )
{
// FIXME
row.removeChild( getCell( colId ) );
}
public void remove( IArea area )
{
if ( area != null )
{
if ( !( area instanceof DummyCell ) )
{
row.removeChild( area );
}
CellArea cell = (CellArea) area;
int colId = cell.getColumnID( );
int colSpan = cell.getColSpan( );
if ( ( colId >= start ) && ( colId + colSpan - 1 <= end ) )
{
int loopEnd = Math.min( colSpan, end - colId + 1 );
for ( int j = 0; j < loopEnd; j++ )
{
cells[colId - start + j] = null;
}
}
}
}
public CellArea getCell( int colId )
{
if ( colId < start || colId > end )
{
assert ( false );
return null;
}
return cells[colId - start];
}
public void addArea( IArea area )
{
CellArea cell = (CellArea) area;
int colId = cell.getColumnID( );
int colSpan = cell.getColSpan( );
if ( ( colId >= start ) && ( colId + colSpan - 1 <= end ) )
{
int loopEnd = Math.min( colSpan, end - colId + 1 );
for ( int j = 0; j < loopEnd; j++ )
{
cells[colId - start + j] = cell;
}
}
}
/**
* row content
*/
public RowArea getArea( )
{
return row;
}
}
}
|
package it.unibz.inf.ontop.answering.reformulation.impl;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.answering.reformulation.QueryCache;
import it.unibz.inf.ontop.answering.reformulation.QueryReformulator;
import it.unibz.inf.ontop.answering.reformulation.generation.NativeQueryGenerator;
import it.unibz.inf.ontop.answering.reformulation.input.InputQuery;
import it.unibz.inf.ontop.answering.reformulation.input.InputQueryFactory;
import it.unibz.inf.ontop.answering.reformulation.input.translation.InputQueryTranslator;
import it.unibz.inf.ontop.answering.reformulation.rewriting.QueryRewriter;
import it.unibz.inf.ontop.answering.reformulation.unfolding.QueryUnfolder;
import it.unibz.inf.ontop.dbschema.DBMetadata;
import it.unibz.inf.ontop.exception.OntopReformulationException;
import it.unibz.inf.ontop.injection.IntermediateQueryFactory;
import it.unibz.inf.ontop.injection.TranslationFactory;
import it.unibz.inf.ontop.iq.IQ;
import it.unibz.inf.ontop.iq.IntermediateQuery;
import it.unibz.inf.ontop.iq.exception.EmptyQueryException;
import it.unibz.inf.ontop.iq.optimizer.*;
import it.unibz.inf.ontop.iq.tools.ExecutorRegistry;
import it.unibz.inf.ontop.iq.tools.IQConverter;
import it.unibz.inf.ontop.model.atom.AtomFactory;
import it.unibz.inf.ontop.model.atom.DistinctVariableOnlyDataAtom;
import it.unibz.inf.ontop.model.term.Variable;
import it.unibz.inf.ontop.spec.OBDASpecification;
import it.unibz.inf.ontop.spec.mapping.Mapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO: rename it QueryTranslatorImpl ?
*
* See ReformulationFactory for creating a new instance.
*
*/
public class QuestQueryProcessor implements QueryReformulator {
private final QueryRewriter rewriter;
private final NativeQueryGenerator datasourceQueryGenerator;
private final QueryCache queryCache;
private final QueryUnfolder queryUnfolder;
private final BindingLiftOptimizer bindingLiftOptimizer;
private static final Logger log = LoggerFactory.getLogger(QuestQueryProcessor.class);
private final ExecutorRegistry executorRegistry;
private final DBMetadata dbMetadata;
private final JoinLikeOptimizer joinLikeOptimizer;
private final InputQueryTranslator inputQueryTranslator;
private final InputQueryFactory inputQueryFactory;
private final FlattenUnionOptimizer flattenUnionOptimizer;
private final PushUpBooleanExpressionOptimizer pullUpExpressionOptimizer;
private final IQConverter iqConverter;
private final AtomFactory atomFactory;
private final IntermediateQueryFactory iqFactory;
private final OrderBySimplifier orderBySimplifier;
private final AggregationSimplifier aggregationSimplifier;
@AssistedInject
private QuestQueryProcessor(@Assisted OBDASpecification obdaSpecification,
@Assisted ExecutorRegistry executorRegistry,
QueryCache queryCache,
BindingLiftOptimizer bindingLiftOptimizer,
TranslationFactory translationFactory,
QueryRewriter queryRewriter,
JoinLikeOptimizer joinLikeOptimizer,
InputQueryFactory inputQueryFactory,
FlattenUnionOptimizer flattenUnionOptimizer,
PushUpBooleanExpressionOptimizer pullUpExpressionOptimizer,
InputQueryTranslator inputQueryTranslator,
IQConverter iqConverter,
AtomFactory atomFactory, IntermediateQueryFactory iqFactory,
OrderBySimplifier orderBySimplifier, AggregationSimplifier aggregationSimplifier) {
this.bindingLiftOptimizer = bindingLiftOptimizer;
this.joinLikeOptimizer = joinLikeOptimizer;
this.inputQueryFactory = inputQueryFactory;
this.flattenUnionOptimizer = flattenUnionOptimizer;
this.pullUpExpressionOptimizer = pullUpExpressionOptimizer;
this.iqConverter = iqConverter;
this.rewriter = queryRewriter;
this.atomFactory = atomFactory;
this.iqFactory = iqFactory;
this.orderBySimplifier = orderBySimplifier;
this.aggregationSimplifier = aggregationSimplifier;
this.rewriter.setTBox(obdaSpecification.getSaturatedTBox());
Mapping saturatedMapping = obdaSpecification.getSaturatedMapping();
if(log.isDebugEnabled()){
log.debug("Mapping: \n{}", Joiner.on("\n").join(
saturatedMapping.getRDFAtomPredicates().stream()
.flatMap(p -> saturatedMapping.getQueries(p).stream())
.iterator()));
}
this.queryUnfolder = translationFactory.create(saturatedMapping);
this.dbMetadata = obdaSpecification.getDBMetadata();
this.datasourceQueryGenerator = translationFactory.create(dbMetadata);
this.inputQueryTranslator = inputQueryTranslator;
this.queryCache = queryCache;
this.executorRegistry = executorRegistry;
log.info("Ontop has completed the setup and it is ready for query answering!");
}
@Override
public IQ reformulateIntoNativeQuery(InputQuery inputQuery)
throws OntopReformulationException {
IQ cachedQuery = queryCache.get(inputQuery);
if (cachedQuery != null)
return cachedQuery;
try {
log.debug("SPARQL query:\n{}", inputQuery.getInputString());
IQ convertedIQ = inputQuery.translate(inputQueryTranslator);
log.debug("Parsed query converted into IQ (after normalization):\n{}", convertedIQ);
//InternalSparqlQuery translation = inputQuery.translate(inputQueryTranslator);
try {
// IQ convertedIQ = preProcess(translation);
log.debug("Start the rewriting process...");
IQ rewrittenIQ = rewriter.rewrite(convertedIQ);
log.debug("Rewritten IQ:\n{}",rewrittenIQ);
log.debug("Start the unfolding...");
IQ unfoldedIQ = queryUnfolder.optimize(rewrittenIQ);
if (unfoldedIQ.getTree().isDeclaredAsEmpty())
throw new EmptyQueryException();
log.debug("Unfolded query: \n" + unfoldedIQ.toString());
// Non-final
IntermediateQuery intermediateQuery = iqConverter.convert(unfoldedIQ, executorRegistry);
//lift bindings and union when it is possible
intermediateQuery = bindingLiftOptimizer.optimize(intermediateQuery);
log.debug("New query after substitution lift optimization: \n" + intermediateQuery.toString());
log.debug("New lifted query: \n" + intermediateQuery.toString());
intermediateQuery = pullUpExpressionOptimizer.optimize(intermediateQuery);
log.debug("After pushing up boolean expressions: \n" + intermediateQuery.toString());
intermediateQuery = new ProjectionShrinkingOptimizer().optimize(intermediateQuery);
log.debug("After projection shrinking: \n" + intermediateQuery.toString());
intermediateQuery = joinLikeOptimizer.optimize(intermediateQuery);
log.debug("New query after fixed point join optimization: \n" + intermediateQuery.toString());
intermediateQuery = flattenUnionOptimizer.optimize(intermediateQuery);
log.debug("New query after flattening Unions: \n" + intermediateQuery.toString());
IQ queryAfterAggregationSimplification = aggregationSimplifier.optimize(iqConverter.convert(intermediateQuery));
IQ optimizedQuery = orderBySimplifier.optimize(queryAfterAggregationSimplification);
IQ executableQuery = generateExecutableQuery(optimizedQuery);
queryCache.put(inputQuery, executableQuery);
return executableQuery;
}
catch (EmptyQueryException e) {
ImmutableList<Variable> signature = convertedIQ.getProjectionAtom().getArguments();
DistinctVariableOnlyDataAtom projectionAtom = atomFactory.getDistinctVariableOnlyDataAtom(
atomFactory.getRDFAnswerPredicate(signature.size()),
signature);
return iqFactory.createIQ(projectionAtom,
iqFactory.createEmptyNode(projectionAtom.getVariables()));
}
catch (OntopReformulationException e) {
throw e;
}
}
/*
* Bug: should normally not be reached
* TODO: remove it
*/
catch (Exception e) {
log.warn("Unexpected exception: " + e.getMessage(), e);
throw new OntopReformulationException(e);
//throw new OntopReformulationException("Error rewriting and unfolding into SQL\n" + e.getMessage());
}
}
private IQ generateExecutableQuery(IQ iq)
throws OntopReformulationException {
log.debug("Producing the native query string...");
IQ executableQuery = datasourceQueryGenerator.generateSourceQuery(iq, executorRegistry);
log.debug("Resulting native query: \n{}", executableQuery);
return executableQuery;
}
/**
* Returns the final rewriting of the given query
*/
@Override
public String getRewritingRendering(InputQuery query) throws OntopReformulationException {
log.debug("SPARQL query:\n{}", query.getInputString());
IQ convertedIQ = query.translate(inputQueryTranslator);
log.debug("Parsed query converted into IQ:\n{}", convertedIQ);
try {
// IQ convertedIQ = preProcess(translation);
IQ rewrittenIQ = rewriter.rewrite(convertedIQ);
return rewrittenIQ.toString();
}
catch (EmptyQueryException e) {
e.printStackTrace();
}
return "EMPTY REWRITING";
}
@Override
public InputQueryFactory getInputQueryFactory() {
return inputQueryFactory;
}
}
|
package org.trianacode.pegasus.dax;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class DaxJobChunk implements Serializable {
private String jobName = "";
private String jobArgs = "";
private String outputFilename = "";
private List<String> inFiles = new ArrayList();
private List<String> outFiles = new ArrayList();
private boolean isStub = false;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobArgs() {
return jobArgs;
}
public void setJobArgs(String jobArgs) {
this.jobArgs = jobArgs;
}
public void addJobArg(String jobArg){
jobArgs += jobArg;
}
public String getOutputFilename() {
return outputFilename;
}
public void setOutputFilename(String outputFilename) {
this.outputFilename = outputFilename;
}
public List getInFiles() {
return inFiles;
}
public void addInFile(String file) {
inFiles.add(file);
}
public List getOutFiles() {
return outFiles;
}
public void addOutFile(String file) {
outFiles.add(file);
}
public boolean isStub() {
return isStub;
}
public void setStub(boolean stub) {
isStub = stub;
}
}
|
package de.danielnaber.languagetool.rules;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.Language;
/**
* Abstract rule class. A Rule drescribes a language error and can
* test whether a given pre-analyzed text contains that error using the
* {@link Rule#match} method.
*
* @author Daniel Naber
*/
public abstract class Rule {
private List<String> correctExamples;
private List<IncorrectExample> incorrectExamples;
private Category category = null;
/**
* If true, then the rule is turned off
* by default.
*/
private boolean defaultOff = false;
protected ResourceBundle messages;
/**
* Called by language-dependant rules.
*/
public Rule() {
}
/**
* Called by language-independant rules.
*/
public Rule(final ResourceBundle messages) {
this.messages = messages;
}
public abstract String getId();
public abstract String getDescription();
/**
* Used by paragraph rules to signal that they can
* remove previous rule matches.
*/
private boolean paragraphBackTrack = false;
/**
* The final list of RuleMatches, without removed
* matches.
*/
private List <RuleMatch> previousMatches = null;
private List <RuleMatch> removedMatches = null;
/**
* Check whether the given text matche this error rule, i.e. whether the
* text contains this error.
*
* @param text a pre-analyzed sentence
* @return an array of RuleMatch object for each match.
*/
//public abstract RuleMatch[] match(AnalyzedSentence text);
/**
* Check whether the given text matche this error rule, i.e. whether the
* text contains this error.
*
* @param text a pre-analyzed sentence
* @return an array of RuleMatch object for each match.
*/
public abstract RuleMatch[] match(AnalyzedSentence text) throws IOException ;
/**
* If a rule keeps it state over more than the check of one
* sentence, this must be implemented so the internal state
* it reset. It will be called before a new text is going
* to be checked.
*/
public abstract void reset();
/**
* Whether this rule can be used for text in the given language.
*/
public boolean supportsLanguage(final Language language) {
Set<String> relevantIDs = language.getRelevantRuleIDs();
if (relevantIDs != null && relevantIDs.contains(getId())) {
return true;
} else {
return false;
}
}
/**
* TODO: Return the number of false positives to be expected.
*
public int getFalsePositives() {
return -1;
}*/
public void setCorrectExamples(final List<String> correctExamples) {
this.correctExamples = correctExamples;
}
/**
* Get example sentences that are correct and thus will not
* match this rule.
*/
public List<String> getCorrectExamples() {
return correctExamples;
}
public void setIncorrectExamples(final List<IncorrectExample> incorrectExamples) {
this.incorrectExamples = incorrectExamples;
}
/**
* Get example sentences that are incorrect and thus will
* match this rule.
*/
public List<IncorrectExample> getIncorrectExamples() {
return incorrectExamples;
}
public Category getCategory() {
return category;
}
public void setCategory(final Category category) {
this.category = category;
}
protected RuleMatch[] toRuleMatchArray(final List<RuleMatch> ruleMatches) {
return (RuleMatch[])ruleMatches.toArray(new RuleMatch[0]);
}
public boolean isParagraphBackTrack() {
return paragraphBackTrack;
}
public void setParagraphBackTrack(boolean backTrack) {
paragraphBackTrack = backTrack;
}
/**
* Method to add matches.
* @param r RuleMatch - matched rule added by check()
*/
public final void addRuleMatch(RuleMatch r) {
if (previousMatches == null) {
previousMatches = new ArrayList <RuleMatch>();
}
previousMatches.add(r);
}
/**
* Deletes (or disables) previously matched rule.
* @param i Index of the rule that should be deleted.
*/
public final void setAsDeleted(int i) {
if (removedMatches == null) {
removedMatches = new ArrayList <RuleMatch>();
}
removedMatches.add(previousMatches.get(i));
}
public final boolean isInRemoved(RuleMatch r) {
if (removedMatches == null) {
return false;
} else {
return removedMatches.contains(r);
}
}
public final boolean isInMatches(int i) {
if (previousMatches == null) {
return false;
} else {
if (previousMatches.size() >= i) {
return (previousMatches.get(i) != null);
} else {
return false;
}
}
}
public final void clearMatches() {
if (previousMatches != null) {
previousMatches.clear();
}
}
public final int getMatchesIndex() {
if (previousMatches == null) {
return 0;
} else {
return previousMatches.size();
}
}
public final List <RuleMatch> getMatches() {
return previousMatches;
}
/**
* Checks whether the rule has been turned off
* by default by the rule author.
* @return True if the rule is turned off by
* default.
*/
public final boolean isDefaultOff() {
return defaultOff;
}
/**
* Turns the rule by default off.
**/
public final void setDefaultOff() {
defaultOff = true;
}
}
|
package twitter4j.examples;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Timer;
import twitter4j.*;
import twitter4j.conf.Configuration;
import twitter4j.conf.PropertyConfiguration;
import twitter4j.http.AccessToken;
/**
* <p>
* This is a code example of Twitter4J Streaming API - user stream.<br>
* Usage: java twitter4j.examples.PrintUserStream. Needs a valid twitter4j.properties file with Basic Auth _and_ OAuth properties set<br>
* </p>
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @author Remy Rakic - remy dot rakic at gmail.com
*/
public final class PrintUserStream implements StatusListener
{
public static void main (String [] args) throws TwitterException
{
PrintUserStream printSampleStream = new PrintUserStream (args);
printSampleStream.startConsuming ();
}
private TwitterStream twitterStream;
// used for getting status and user info, for favoriting, following and unfollowing events
private Twitter twitter;
private User currentUser;
private int currentUserId;
public PrintUserStream (String [] args)
{
Configuration conf = new PropertyConfiguration (getClass ().getResourceAsStream ("twitter4j.properties"));
twitterStream = new TwitterStreamFactory ().getInstance (conf.getUser (), conf.getPassword ());
twitter = new TwitterFactory().getOAuthAuthorizedInstance (conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));
try
{
currentUser = twitter.verifyCredentials ();
currentUserId = currentUser.getId ();
}
catch (TwitterException e)
{
System.out.println ("Unexpected exception caught while trying to retrieve the current user: " + e);
e.printStackTrace();
System.exit (-1);
}
Timer t = new Timer (5 * 60 * 1000, new ActionListener ()
{
@Override
public void actionPerformed (ActionEvent e)
{
System.out.println ("");
}
});
t.start ();
}
private void startConsuming () throws TwitterException
{
// the user() method internally creates a thread which manipulates
// TwitterStream and calls these adequate listener methods continuously.
twitterStream.setStatusListener (this);
twitterStream.user ();
}
private Map<Integer, SoftReference<User>> friends;
@Override
public void onFriendList (int [] friendIds)
{
System.out.println ("Received friends list - Following " + friendIds.length + " people");
friends = new HashMap<Integer, SoftReference<User>> ();
for (int id : friendIds)
friends.put (id, null);
friends.put (currentUser.getId (), new SoftReference<User> (currentUser));
}
private User friend (int id)
{
User friend = null;
SoftReference<User> ref = friends.get (id);
if (ref != null)
friend = ref.get ();
if (friend == null)
{
try
{
friend = twitter.showUser (id);
friends.put (id, new SoftReference<User> (friend));
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
if (friend == null)
{
System.out.println ("User id " + id + " lookup failed");
return new NullUser();
}
return friend;
}
public void onStatus (Status status)
{
int replyTo = status.getInReplyToUserId ();
if (replyTo > 0 && !friends.containsKey (replyTo))
System.out.print ("[Out of band] "); // I've temporarily labeled "out of bands" messages that are sent to people you don't follow
User user = status.getUser ();
System.out.println (user.getName () + " [" + user.getScreenName () + "] : " + status.getText ());
}
@Override
public void onDirectMessage (DirectMessage dm)
{
System.out.println ("DM from " + dm.getSenderScreenName () + " to " + dm.getRecipientScreenName () + ": " + dm.getText ());
}
public void onDeletionNotice (StatusDeletionNotice notice)
{
if (notice == null)
{
System.out.println ("Deletion notice is null!"); // there's a problem in the stream, should be done before notification
return;
}
User user = friend (notice.getUserId ());
System.out.println (user.getName () + " [" + user.getScreenName () + "] deleted the tweet "
+ notice.getStatusId ());
}
public void onTrackLimitationNotice (int numberOfLimitedStatuses)
{
System.out.println ("track limitation: " + numberOfLimitedStatuses);
}
public void onException (Exception ex)
{
ex.printStackTrace ();
}
@Override
public void onFavorite (int source, int target, long targetObject)
{
User user = friend (source);
Status rt = status (targetObject);
System.out.print (user.getName () + " [" + user.getScreenName () + "] favorited ");
if (rt == null)
System.out.println ("a protected tweet");
else
System.out.println (rt.getUser ().getName () + "'s [" + rt.getUser ().getScreenName () + "] tweet: " + rt.getText ());
}
@Override
public void onUnfavorite (int source, int target, long targetObject)
{
User user = friend (source);
Status rt = status (targetObject);
System.out.print (user.getName () + " [" + user.getScreenName () + "] unfavorited ");
if (rt == null)
System.out.println ("a protected tweet");
else
System.out.println (rt.getUser ().getName () + "'s [" + rt.getUser ().getScreenName () + "] tweet: " + rt.getText ());
}
@Override
public void onFollow (int source, int target)
{
User user = friend (source);
User friend = friend (target);
System.out.println (user.getName () + " [" + user.getScreenName () + "] started following "
+ friend.getName () + " [" + friend.getScreenName () +"]");
if (source == currentUserId && friend != null)
friends.put (target, new SoftReference<User> (friend));
}
@Override
public void onUnfollow (int source, int target)
{
User user = friend (source);
User friend = friend (target);
System.out.println (user.getName () + " [" + user.getScreenName () + "] unfollowed "
+ friend.getName () + " [" + friend.getScreenName () +"]");
if (source == currentUserId)
friends.remove (target);
}
@Override
public void onRetweet (int source, int target, long targetObject)
{
}
private Status status (long id)
{
try
{
return twitter.showStatus (id);
}
catch (TwitterException e)
{
if (e.getStatusCode () != 403) // forbidden
e.printStackTrace();
}
return null;
}
// Preventing the null users in most situations, only used in when there's problems in the stream
private static class NullUser implements User
{
@Override
public Date getCreatedAt ()
{
return null;
}
@Override
public String getDescription ()
{
return null;
}
@Override
public int getFavouritesCount ()
{
return 0;
}
@Override
public int getFollowersCount ()
{
return 0;
}
@Override
public int getFriendsCount ()
{
return 0;
}
@Override
public int getId ()
{
return 0;
}
@Override
public String getLang ()
{
return null;
}
@Override
public String getLocation ()
{
return null;
}
@Override
public String getName ()
{
return null;
}
@Override
public String getProfileBackgroundColor ()
{
return null;
}
@Override
public String getProfileBackgroundImageUrl ()
{
return null;
}
@Override
public URL getProfileImageURL ()
{
return null;
}
@Override
public String getProfileLinkColor ()
{
return null;
}
@Override
public String getProfileSidebarBorderColor ()
{
return null;
}
@Override
public String getProfileSidebarFillColor ()
{
return null;
}
@Override
public String getProfileTextColor ()
{
return null;
}
@Override
public String getScreenName ()
{
return null;
}
@Override
public Status getStatus ()
{
return null;
}
@Override
public Date getStatusCreatedAt ()
{
return null;
}
@Override
public long getStatusId ()
{
return 0;
}
@Override
public String getStatusInReplyToScreenName ()
{
return null;
}
@Override
public long getStatusInReplyToStatusId ()
{
return 0;
}
@Override
public int getStatusInReplyToUserId ()
{
return 0;
}
@Override
public String getStatusSource ()
{
return null;
}
@Override
public String getStatusText ()
{
return null;
}
@Override
public int getStatusesCount ()
{
return 0;
}
@Override
public String getTimeZone ()
{
return null;
}
@Override
public URL getURL ()
{
return null;
}
@Override
public int getUtcOffset ()
{
return 0;
}
@Override
public boolean isContributorsEnabled ()
{
return false;
}
@Override
public boolean isGeoEnabled ()
{
return false;
}
@Override
public boolean isProfileBackgroundTiled ()
{
return false;
}
@Override
public boolean isProtected ()
{
return false;
}
@Override
public boolean isStatusFavorited ()
{
return false;
}
@Override
public boolean isStatusTruncated ()
{
return false;
}
@Override
public boolean isVerified ()
{
return false;
}
@Override
public int compareTo (User o)
{
return 0;
}
@Override
public RateLimitStatus getRateLimitStatus ()
{
return null;
}
}
}
|
package com.yubico.client.v2;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.yubico.client.v2.exceptions.YubicoReplayedRequestException;
import com.yubico.client.v2.exceptions.YubicoValidationException;
import com.yubico.client.v2.impl.YubicoResponseImpl;
/**
* Fires off a number of validation requests to each specified URL
* in parallel.
*
* @author Simon Buckle <[email protected]>
*/
public class YubicoValidationService {
/**
* Fires off a validation request to each url in the list, returning the first one
* that is not {@link YubicoResponseStatus#REPLAYED_REQUEST}
*
* @param urls a list of validation urls to be contacted
* @param userAgent userAgent to send in request, if null one will be generated
* @return {@link YubicoResponse} object from the first server response that's not
* {@link YubicoResponseStatus#REPLAYED_REQUEST}
* @throws YubicoValidationException if validation fails on all urls
*/
public YubicoResponse fetch(List<String> urls, String userAgent) throws YubicoValidationException {
ExecutorService pool = Executors.newFixedThreadPool(urls.size());
List<Callable<YubicoResponse>> tasks = new ArrayList<Callable<YubicoResponse>>();
for(String url : urls) {
tasks.add(new VerifyTask(url, userAgent));
}
YubicoResponse response = null;
try {
response = pool.invokeAny(tasks, 1L, TimeUnit.MINUTES);
} catch (ExecutionException e) {
throw new YubicoValidationException("Exception while executing validation.", e.getCause());
} catch (TimeoutException e) {
throw new YubicoValidationException("Timeout waiting for validation server response.", e);
} catch (InterruptedException e) {
throw new YubicoValidationException("Validation interrupted.", e);
}
return response;
}
/**
* Inner class for doing requests to validation server.
*/
class VerifyTask implements Callable<YubicoResponse> {
private final String url;
private final String userAgent;
/**
* Set up a VerifyTask for the Yubico Validation protocol v2
* @param url the url to be used
* @param userAgent the userAgent to be sent to the server, or NULL and one is calculated
*/
public VerifyTask(String url, String userAgent) {
this.url = url;
this.userAgent = userAgent;
}
/**
* Do the validation query for previous URL.
* @throws Exception {@link IOException} or {@link YubicoReplayedRequestException}
*/
public YubicoResponse call() throws Exception {
URL url = new URL(this.url);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if(userAgent == null) {
conn.setRequestProperty("User-Agent", "yubico-java-client version:" + Version.version());
} else {
conn.setRequestProperty("User-Agent", userAgent);
}
conn.setConnectTimeout(15000); // 15 second timeout
conn.setReadTimeout(15000); // for both read and connect
YubicoResponse resp = new YubicoResponseImpl(conn.getInputStream());
if (YubicoResponseStatus.REPLAYED_REQUEST.equals(resp.getStatus())) {
throw new YubicoReplayedRequestException("Replayed request.");
}
return resp;
}
}
}
|
package so.blacklight.vault.store;
import fj.F;
import fj.Unit;
import fj.data.Either;
import fj.data.List;
import fj.data.Option;
import so.blacklight.vault.*;
import so.blacklight.vault.collection.Tuple2;
import so.blacklight.vault.io.VaultInputStream;
import so.blacklight.vault.io.VaultOutputStream;
import so.blacklight.vault.io.VaultRecord;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Optional;
import static fj.data.List.list;
public class StreamVaultStore implements VaultStore {
@Override
public void save(Vault vault, Credentials credentials, File vaultFile) {
if (!vaultFile.exists() || vaultFile.canWrite()) {
try {
final FileOutputStream fos = new FileOutputStream(vaultFile);
save(vault, credentials, fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private List<Either<String, List<VaultRecord>>> saveInternal(final Vault vault, final Credentials credentials) {
final List<Credential> creds = list(credentials.getCredentials());
final List<F<List<Credential>, List<List<Credential>>>> fs = list(
l -> list(new List[] { l }),
l -> l.map(c -> l.filter(cf -> !cf.equals(c))),
l -> l.map(c1 -> l.map(c2 -> l.filter(cf -> !cf.equals(c1) && !cf.equals(c2) && !c1.equals(c2))))
.foldRight((currentItem, foldList) -> foldList.append(currentItem), List.<List<Credential>>list())
.filter(fl -> fl.length() > 0).nub()
);
final List<F<Vault, Optional<Vault>>> fv = list(
v -> Optional.of(v),
v -> v.getRecoverySegment(),
v -> v.getDegradedSegment()
);
List<Either<String, List<VaultRecord>>> map = fs.map(f ->
f.f(creds).map(list ->
list.map(EncryptionParameters::new)))
.zipWith(fv.map(f ->
f.f(vault)), (l, v) -> new Tuple2(v, l)).map(tuple -> generateRecords(tuple));
return map;
}
@Override
public void save(Vault vault, Credentials credentials, OutputStream outputStream) {
try {
final ByteArrayOutputStream safetyBuffer = new ByteArrayOutputStream();
final VaultOutputStream vos = new VaultOutputStream(safetyBuffer);
final Layout layout = new Layout(vault, credentials);
vos.writeMagicBytes();
vos.writeLayout(layout);
final List<Either<String, List<VaultRecord>>> result = saveInternal(vault, credentials);
if (result.find(Either::isLeft).length() > 0) {
// TODO better error handling
} else {
result.map(r -> r.right().value()).map(l -> l.foreach(r -> writeBlock(vos, r)));
}
vos.close();
// All's fine if the end's fine
outputStream.write(safetyBuffer.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
private Either<String, List<VaultRecord>> generateRecords(final Tuple2<Optional<Vault>, List<List<EncryptionParameters>>> tuple) {
final Optional<Vault> maybeVault = tuple.first();
final List<List<EncryptionParameters>> params = tuple.second();
if (maybeVault.isPresent()) {
final Vault currentVault = maybeVault.get();
List<Either<String, VaultRecord>> result = params.map(param -> generateRecord(currentVault, param));
Option<String> firstError = result.filter(Either::isLeft).map(e -> e.left().value()).find(i -> true);
if (firstError.isNone()) {
return Either.right(result.map(r -> r.right().value()));
} else {
return Either.left(firstError.some());
}
}
return Either.left("ERROR: No vault present");
}
private Either<String, VaultRecord> generateRecord(final Vault vault, List<EncryptionParameters> params) {
final Crypto<Vault> crypto = new CryptoImpl<>();
Either<String, byte[]> encrypt = crypto.encrypt(vault, params.toJavaList());
if (encrypt.isRight()) {
final VaultRecord record = new VaultRecord(encrypt.right().value());
record.addIvs(params.map(p -> p.getIv()).toJavaList());
record.addSalts(params.map(p -> p.getSalt()).toJavaList());
return Either.right(record);
} else {
return Either.left(encrypt.left().value());
}
}
private Unit writeBlock(final VaultOutputStream out, VaultRecord record) {
try {
out.writeBlock(record);
} catch (IOException e) {
e.printStackTrace();
}
return Unit.unit();
}
@Override
public Either<String, Vault> load(Credentials credentials, File vaultFile) {
if (vaultFile.exists() && vaultFile.canRead()) {
try {
final FileInputStream fis = new FileInputStream(vaultFile);
final Either<String, Vault> maybeVault = load(credentials, fis);
fis.close();
return maybeVault;
} catch (FileNotFoundException e) {
return Either.left(e.getMessage());
} catch (IOException e) {
return Either.left(e.getMessage());
}
}
return Either.left("ERROR: File not found or not readable: " + vaultFile.getAbsolutePath());
}
@Override
public Either<String, Vault> load(Credentials credentials, InputStream inputStream) {
try {
final List<Credential> cl = list(credentials.getCredentials());
final List<VaultRecord> records = readAllRecords(inputStream, (r -> r.count() == cl.length()));
final List<Either<String, Vault>> unlocked = decryptRecords(cl, records).filter(e -> e.isRight());
if (unlocked.length() > 0) {
return unlocked.index(0);
} else {
return Either.left("Sorry :(");
}
} catch (IOException e) {
return Either.left("Error during loading: " + e.getMessage());
}
}
private List<VaultRecord> readAllRecords(final InputStream in, final F<VaultRecord, Boolean> f) throws IOException {
return readAllRecords(in).filter(f);
}
private List<VaultRecord> readAllRecords(final InputStream in) throws IOException {
final VaultInputStream vis = new VaultInputStream(in);
final List<VaultRecord> allRecords = vis.readAll();
vis.close();
return allRecords;
}
private List<Either<String, Vault>> decryptRecords(final List<Credential> credentials, final List<VaultRecord> records) {
final Crypto<Vault> crypto = new CryptoImpl<>();
final List<Either<String, Vault>> result = records.map(r -> {
final byte[][] ivs = r.getIvs();
final byte[][] salts = r.getSalts();
// we're leveraging a mutable collection here
final java.util.List<EncryptionParameters> params = new ArrayList<>();
for (int i = 0; i < r.count(); i++) {
params.add(new EncryptionParameters(credentials.index(i), ivs[i], salts[i]));
}
Collections.reverse(params);
return crypto.decrypt(r.getBlock(), params);
});
return result;
}
}
|
package hudson.plugins.warnings;
import hudson.model.AbstractBuild;
import hudson.plugins.analysis.core.AbstractResultAction;
import hudson.plugins.analysis.core.HealthDescriptor;
import hudson.plugins.analysis.core.PluginDescriptor;
import hudson.plugins.warnings.parser.ParserRegistry;
import org.jvnet.localizer.Localizable;
/**
* Controls the live cycle of the warnings results. This action persists the
* results of the warnings analysis of a build and displays the results on the
* build page. The actual visualization of the results is defined in the
* matching <code>summary.jelly</code> file.
* <p>
* Moreover, this class renders the warnings result trend.
* </p>
*
* @author Ulli Hafner
*/
public class WarningsResultAction extends AbstractResultAction<WarningsResult> {
private Localizable actionName;
private final String parserName;
/**
* Creates a new instance of <code>WarningsResultAction</code>.
*
* @param owner
* the associated build of this action
* @param healthDescriptor
* health descriptor to use
* @param result
* the result in this build
* @param parserName the name of the parser
*/
public WarningsResultAction(final AbstractBuild<?, ?> owner, final HealthDescriptor healthDescriptor, final WarningsResult result, final String parserName) {
super(owner, new WarningsHealthDescriptor(healthDescriptor), result);
this.parserName = parserName;
actionName = ParserRegistry.getParser(parserName).getLinkName();
}
/**
* Adds old name for 3.x serializations.
*
* @return the created object
*/
private Object readResolve() {
if (actionName == null) {
actionName = Messages._Warnings_ProjectAction_Name();
}
return this;
}
@Override
public String getUrlName() {
return WarningsDescriptor.getResultUrl(parserName);
}
/**
* Returns the parser group this result belongs to.
*
* @return the parser group
*/
public String getParser() {
return parserName;
}
/** {@inheritDoc} */
public String getDisplayName() {
return actionName.toString();
}
@Override
protected String getSmallImage() {
return ParserRegistry.getParser(parserName).getSmallImage();
}
/**
* Returns the URL of the 48x48 image used in the build summary.
*
* @return the URL of the image
*/
public String getLargeImage() {
return ParserRegistry.getParser(parserName).getLargeImage();
}
@Override
protected PluginDescriptor getDescriptor() {
return new WarningsDescriptor();
}
}
|
package edu.cornell.mannlib.vitro.webapp.reasoner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.AnnotationProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.rdf.listeners.StatementListener;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
/**
* Allows for real-time incremental materialization or retraction of RDFS-
* style class and property subsumption based ABox inferences as statements
* are added to or removed from the (ABox or TBox) knowledge base.
*/
public class SimpleReasoner extends StatementListener {
private static final Log log = LogFactory.getLog(SimpleReasoner.class);
//private static final MyTempLogger log = new MyTempLogger();
private OntModel tboxModel; // asserted and inferred TBox axioms
private OntModel aboxModel; // ABox assertions
private Model inferenceModel; // ABox inferences
private Model inferenceRebuildModel; // work area for re-computing all ABox inferences
private Model scratchpadModel; // work area for re-computing all ABox inferences
private static final String topObjectPropertyURI = "http://www.w3.org/2002/07/owl#topObjectProperty";
private static final String bottomObjectPropertyURI = "http://www.w3.org/2002/07/owl#bottomObjectProperty";
private static final String topDataPropertyURI = "http://www.w3.org/2002/07/owl#topDataProperty";
private static final String bottomDataPropertyURI = "http://www.w3.org/2002/07/owl#bottomDataProperty";
private static final String mostSpecificTypePropertyURI = "http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType";
private AnnotationProperty mostSpecificType = (ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM)).createAnnotationProperty(mostSpecificTypePropertyURI);
/**
* @param tboxModel - input. This model contains both asserted and inferred TBox axioms
* @param aboxModel - input. This model contains asserted ABox statements
* @param inferenceModel - output. This is the model in which inferred (materialized) ABox statements are maintained (added or retracted).
* @param inferenceRebuildModel - output. This the model temporarily used when the whole ABox inference model is rebuilt
* @param inferenceScratchpadModel - output. This the model temporarily used when the whole ABox inference model is rebuilt
*/
public SimpleReasoner(OntModel tboxModel, OntModel aboxModel, Model inferenceModel,
Model inferenceRebuildModel, Model scratchpadModel) {
this.tboxModel = tboxModel;
this.aboxModel = aboxModel;
this.inferenceModel = inferenceModel;
this.inferenceRebuildModel = inferenceRebuildModel;
this.scratchpadModel = scratchpadModel;
aboxModel.register(this);
}
/**
* This constructor is used for the unit tests only
*
* @param tboxModel - input. This model contains both asserted and inferred TBox axioms
* @param aboxModel - input. This model contains asserted ABox statements
* @param inferenceModel - output. This is the model in which inferred (materialized) ABox statements are maintained (added or retracted).
*/
public SimpleReasoner(OntModel tboxModel, OntModel aboxModel, Model inferenceModel) {
this.tboxModel = tboxModel;
this.aboxModel = aboxModel;
this.inferenceModel = inferenceModel;
this.inferenceRebuildModel = ModelFactory.createDefaultModel();
this.scratchpadModel = ModelFactory.createDefaultModel();
}
/*
* Performs selected incremental ABox reasoning based
* on the addition of a new statement (aka assertion)
* to the ABox.
*/
@Override
public void addedStatement(Statement stmt) {
try {
if (stmt.getPredicate().equals(RDF.type)) {
addedABoxTypeAssertion(stmt, inferenceModel);
setMostSpecificTypes(stmt.getSubject(), inferenceModel);
}
/* uncomment this to enable subproperty/equivalent property inferencing. sjm222 5/13/2011
else {
addedABoxAssertion(stmt,inferenceModel);
}
*/
} catch (Exception e) {
// don't stop the edit if there's an exception
log.error("Exception while adding inferences: ", e);
}
}
/*
* Performs selected incremental ABox reasoning based
* on the retraction of a statement (aka assertion)
* from the ABox.
*/
@Override
public void removedStatement(Statement stmt) {
try {
if (stmt.getPredicate().equals(RDF.type)) {
removedABoxTypeAssertion(stmt, inferenceModel);
setMostSpecificTypes(stmt.getSubject(), inferenceModel);
}
/* uncomment this to enable subproperty/equivalent property inferencing. sjm222 5/13/2011
else {
removedABoxAssertion(stmt, inferenceModel);
}
*/
} catch (Exception e) {
// don't stop the edit if there's an exception
log.error("Exception while retracting inferences: ", e);
}
}
/*
* Performs incremental selected ABox reasoning based
* on changes to the class or property hierarchy.
*
* Handles rdfs:subclassOf, owl:equivalentClass,
* rdfs:subPropertyOf and owl:equivalentProperty assertions
*/
public void addedTBoxStatement(Statement stmt) {
addedTBoxStatement(stmt, inferenceModel);
}
public void addedTBoxStatement(Statement stmt, Model inferenceModel) {
try {
log.debug("added TBox assertion = " + stmt.toString());
if ( stmt.getPredicate().equals(RDFS.subClassOf) || stmt.getPredicate().equals(OWL.equivalentClass) ) {
// ignore anonymous classes
if (stmt.getSubject().isAnon() || stmt.getObject().isAnon()) {
return;
}
if ( stmt.getObject().isResource() && (stmt.getObject().asResource()).getURI() == null ) {
log.warn("The object of this assertion has a null URI: " + stmtString(stmt));
return;
}
if ( stmt.getSubject().getURI() == null ) {
log.warn("The subject of this assertion has a null URI: " + stmtString(stmt));
return;
}
OntClass subject = tboxModel.getOntClass((stmt.getSubject()).getURI());
if (subject == null) {
log.debug("didn't find subject class in the tbox: " + (stmt.getSubject()).getURI());
return;
}
OntClass object = tboxModel.getOntClass(((Resource)stmt.getObject()).getURI());
if (object == null) {
log.debug("didn't find object class in the tbox: " + ((Resource)stmt.getObject()).getURI());
return;
}
if (stmt.getPredicate().equals(RDFS.subClassOf)) {
addedSubClass(subject,object,inferenceModel);
} else {
// equivalent class is the same as subclass in both directions
addedSubClass(subject,object,inferenceModel);
addedSubClass(object,subject,inferenceModel);
}
}
/* uncomment this to enable sub property/equivalent property inferencing. sjm222 5/13/2011
else if (stmt.getPredicate().equals(RDFS.subPropertyOf) || stmt.getPredicate().equals(OWL.equivalentProperty)) {
OntProperty subject = tboxModel.getOntProperty((stmt.getSubject()).getURI());
OntProperty object = tboxModel.getOntProperty(((Resource)stmt.getObject()).getURI());
if (stmt.getPredicate().equals(RDFS.subPropertyOf)) {
addedSubProperty(subject,object,inferenceModel);
} else {
// equivalent property is the same as subProperty in both directions
addedSubProperty(subject,object,inferenceModel);
addedSubProperty(object,subject,inferenceModel);
}
}
*/
} catch (Exception e) {
// don't stop the edit if there's an exception
log.error("Exception while adding inference(s): ", e);
}
}
/*
* Performs incremental selected ABox reasoning based
* on changes to the class or property hierarchy.
*
* Handles rdfs:subclassOf, owl:equivalentClass,
* rdfs:subPropertyOf and owl:equivalentProperty assertions
*/
public void removedTBoxStatement(Statement stmt) {
try {
log.debug("removed TBox assertion = " + stmt.toString());
if ( stmt.getPredicate().equals(RDFS.subClassOf) || stmt.getPredicate().equals(OWL.equivalentClass) ) {
// ignore anonymous classes
if (stmt.getSubject().isAnon() || stmt.getObject().isAnon()) {
return;
}
if ( stmt.getObject().isResource() && (stmt.getObject().asResource()).getURI() == null ) {
log.warn("The object of this assertion has a null URI: " + stmtString(stmt));
return;
}
if ( stmt.getSubject().getURI() == null ) {
log.warn("The subject of this assertion has a null URI: " + stmtString(stmt));
return;
}
OntClass subject = tboxModel.getOntClass((stmt.getSubject()).getURI());
if (subject == null) {
log.debug("didn't find subject class in the tbox: " + (stmt.getSubject()).getURI());
return;
}
OntClass object = tboxModel.getOntClass(((Resource)stmt.getObject()).getURI());
if (object == null) {
log.debug("didn't find object class in the tbox: " + ((Resource)stmt.getObject()).getURI());
return;
}
if (stmt.getPredicate().equals(RDFS.subClassOf)) {
removedSubClass(subject,object,inferenceModel);
} else {
// equivalent class is the same as subclass in both directions
removedSubClass(subject,object,inferenceModel);
removedSubClass(object,subject,inferenceModel);
}
}
/* uncomment this to enable sub property / equivalent property inferencing. sjm222 5/13/2011.
else if (stmt.getPredicate().equals(RDFS.subPropertyOf) || stmt.getPredicate().equals(OWL.equivalentProperty)) {
OntProperty subject = tboxModel.getOntProperty((stmt.getSubject()).getURI());
OntProperty object = tboxModel.getOntProperty(((Resource)stmt.getObject()).getURI());
if (stmt.getPredicate().equals(RDFS.subPropertyOf)) {
removedSubProperty(subject,object);
} else {
// equivalent property is the same as subProperty in both directions
removedSubProperty(subject,object);
removedSubProperty(object,subject);
}
}
*/
} catch (Exception e) {
// don't stop the edit if there's an exception
log.error("Exception while removing inference(s): ", e);
}
}
/*
* Performs incremental reasoning based on a new type assertion
* added to the ABox (assertion that an individual is of a certain
* type).
*
* If it is added that B is of type A, then for each superclass of
* A assert that B is of that type.
*
*/
public void addedABoxTypeAssertion(Statement stmt, Model inferenceModel) {
//System.out.println("sjm: addedABoxTypeAssertion: " + stmtString(stmt));
tboxModel.enterCriticalSection(Lock.READ);
try {
OntClass cls = null;
if ( (stmt.getObject().asResource()).getURI() != null ) {
cls = tboxModel.getOntClass(stmt.getObject().asResource().getURI());
if (cls != null) {
List<OntClass> parents = (cls.listSuperClasses(false)).toList();
parents.addAll((cls.listEquivalentClasses()).toList());
Iterator<OntClass> parentIt = parents.iterator();
while (parentIt.hasNext()) {
OntClass parentClass = parentIt.next();
// VIVO doesn't materialize statements that assert anonymous types
// for individuals. Also, sharing an identical anonymous node is
// not allowed in owl-dl. picklist population code looks at qualities
// of classes not individuals.
if (parentClass.isAnon()) continue;
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), RDF.type, parentClass);
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
if (!inferenceModel.contains(infStmt) && !infStmt.equals(stmt) ) {
//log.debug("Adding this inferred statement: " + infStmt.toString() );
inferenceModel.add(infStmt);
}
} finally {
inferenceModel.leaveCriticalSection();
}
}
} else {
log.warn("Didn't find target class (the object of the added rdf:type statement) in the TBox: " + ((Resource)stmt.getObject()).getURI());
}
} else {
log.warn("The object of this rdf:type assertion has a null URI: " + stmtString(stmt));
return;
}
} finally {
tboxModel.leaveCriticalSection();
}
}
/*
* Performs incremental property-based reasoning.
*
* Materializes inferences based on the rdfs:subPropertyOf relationship.
* If it is added that x propB y and propB is a sub-property of propA
* then add x propA y to the inference graph.
*/
public void addedABoxAssertion(Statement stmt, Model inferenceModel) {
tboxModel.enterCriticalSection(Lock.READ);
try {
OntProperty prop = tboxModel.getOntProperty(stmt.getPredicate().getURI());
if (prop != null) {
// not reasoning on properties in the OWL, RDF or RDFS namespace
if ((prop.getNameSpace()).equals(OWL.NS) ||
(prop.getNameSpace()).equals("http://www.w3.org/2000/01/rdf-schema
(prop.getNameSpace()).equals("http://www.w3.org/1999/02/22-rdf-syntax-ns
return;
}
//TODO: have trouble paramterizing the template with ? extends OntProperty
List superProperties = prop.listSuperProperties(false).toList();
superProperties.addAll(prop.listEquivalentProperties().toList());
Iterator<OntProperty> superIt = superProperties.iterator();
while (superIt.hasNext()) {
OntProperty superProp = superIt.next();
if ( !((prop.isObjectProperty() && superProp.isObjectProperty()) || (prop.isDatatypeProperty() && superProp.isDatatypeProperty())) ) {
log.warn("sub-property and super-property do not have the same type. No inferencing will be performed. sub-property: " + prop.getURI() + " super-property:" + superProp.getURI());
continue;
}
if (superProp.getURI().equals(topObjectPropertyURI) || superProp.getURI().equals(topDataPropertyURI)) {
continue;
}
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), superProp, stmt.getObject());
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
if (!inferenceModel.contains(infStmt) && !infStmt.equals(stmt) ) {
inferenceModel.add(infStmt);
}
} finally {
inferenceModel.leaveCriticalSection();
}
}
} else {
log.debug("Didn't find target property (the predicate of the added statement) in the TBox: " + stmt.getPredicate().getURI());
}
} finally {
tboxModel.leaveCriticalSection();
}
}
/*
* If it is removed that B is of type A, then for each superclass of A remove
* the inferred statement that B is of that type UNLESS it is otherwise entailed
* that B is of that type.
*
*/
public void removedABoxTypeAssertion(Statement stmt, Model inferenceModel) {
//System.out.println("sjm: removedABoxTypeAssertion: " + stmtString(stmt));
tboxModel.enterCriticalSection(Lock.READ);
// convert this method to use generic resources - not get ontclass, not cls.listSuperClasses...
// use model contains if want to log warning about type owl class
try {
OntClass cls = null;
if ( (stmt.getObject().asResource()).getURI() != null ) {
cls = tboxModel.getOntClass(stmt.getObject().asResource().getURI());
if (cls != null) {
List<OntClass> parents = null;
parents = (cls.listSuperClasses(false)).toList();
parents.addAll((cls.listEquivalentClasses()).toList());
Iterator<OntClass> parentIt = parents.iterator();
while (parentIt.hasNext()) {
OntClass parentClass = parentIt.next();
// VIVO doesn't materialize statements that assert anonymous types
// for individuals. Also, sharing an identical anonymous node is
// not allowed in owl-dl. picklist population code looks at qualities
// of classes not individuals.
if (parentClass.isAnon()) continue;
if (entailedType(stmt.getSubject(),parentClass)) continue; // if a type is still entailed without the
// removed statement, then don't remove it
// from the inferences
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), RDF.type, parentClass);
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
if (inferenceModel.contains(infStmt)) {
//log.debug("Removing this inferred statement: " + infStmt.toString() + " - " + infStmt.getSubject().toString() + " - " + infStmt.getPredicate().toString() + " - " + infStmt.getObject().toString());
inferenceModel.remove(infStmt);
}
} finally {
inferenceModel.leaveCriticalSection();
}
}
} else {
log.warn("Didn't find target class (the object of the removed rdf:type statement) in the TBox: " + ((Resource)stmt.getObject()).getURI());
}
} else {
log.warn("The object of this rdf:type assertion has a null URI: " + stmtString(stmt));
}
} catch (Exception e) {
log.warn("exception while removing abox type assertions: " + e.getMessage());
} finally {
tboxModel.leaveCriticalSection();
}
}
/*
* Performs incremental property-based reasoning.
*
* Retracts inferences based on the rdfs:subPropertyOf relationship.
* If it is removed that x propB y and propB is a sub-property of propA
* then remove x propA y from the inference graph UNLESS it that
* statement is otherwise entailed.
*/
public void removedABoxAssertion(Statement stmt, Model inferenceModel) {
tboxModel.enterCriticalSection(Lock.READ);
try {
OntProperty prop = tboxModel.getOntProperty(stmt.getPredicate().getURI());
if (prop != null) {
//TODO: trouble parameterizing these templates with "? extends OntProperty"
List superProperties = prop.listSuperProperties(false).toList();
superProperties.addAll(prop.listEquivalentProperties().toList());
Iterator<OntProperty> superIt = superProperties.iterator();
while (superIt.hasNext()) {
OntProperty superProp = superIt.next();
if ( !((prop.isObjectProperty() && superProp.isObjectProperty()) || (prop.isDatatypeProperty() && superProp.isDatatypeProperty())) ) {
log.warn("sub-property and super-property do not have the same type. No inferencing will be performed. sub-property: " + prop.getURI() + " super-property:" + superProp.getURI());
return;
}
// if the statement is still entailed without the removed
// statement then don't remove it from the inferences
if (entailedByPropertySubsumption(stmt.getSubject(), superProp, stmt.getObject())) continue;
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), superProp, stmt.getObject());
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
if (inferenceModel.contains(infStmt)) {
inferenceModel.remove(infStmt);
}
} finally {
inferenceModel.leaveCriticalSection();
}
}
} else {
log.debug("Didn't find target predicate (the predicate of the removed statement) in the TBox: " + stmt.getPredicate().getURI());
}
} finally {
tboxModel.leaveCriticalSection();
}
}
// Returns true if it is entailed by class subsumption that
// subject is of type cls; otherwise returns false.
public boolean entailedType(Resource subject, OntClass cls) {
//log.debug("subject = " + subject.getURI() + " class = " + cls.getURI());
aboxModel.enterCriticalSection(Lock.READ);
tboxModel.enterCriticalSection(Lock.READ);
try {
ExtendedIterator<OntClass> iter = cls.listSubClasses(false);
while (iter.hasNext()) {
OntClass childClass = iter.next();
Statement stmt = ResourceFactory.createStatement(subject, RDF.type, childClass);
if (aboxModel.contains(stmt)) return true;
}
return false;
} catch (Exception e) {
log.debug("exception in method entailedType: " + e.getMessage());
return false;
} finally {
aboxModel.leaveCriticalSection();
tboxModel.leaveCriticalSection();
}
}
// Returns true if the statement is entailed by property subsumption
public boolean entailedByPropertySubsumption(Resource subject, OntProperty prop, RDFNode object) {
aboxModel.enterCriticalSection(Lock.READ);
tboxModel.enterCriticalSection(Lock.READ);
try {
ExtendedIterator<? extends OntProperty> iter = prop.listSubProperties(false);
while (iter.hasNext()) {
OntProperty subProp = iter.next();
Statement stmt = ResourceFactory.createStatement(subject, subProp, object);
if (aboxModel.contains(stmt)) return true;
}
return false;
} finally {
aboxModel.leaveCriticalSection();
tboxModel.leaveCriticalSection();
}
}
/*
* If it is added that B is a subClass of A, then for each
* individual that is typed as B, either in the ABox or in the
* inferred model, assert that it is of type A.
*/
public void addedSubClass(OntClass subClass, OntClass superClass, Model inferenceModel) {
log.debug("subClass = " + subClass.getURI() + " superClass = " + superClass.getURI());
aboxModel.enterCriticalSection(Lock.WRITE);
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
OntModel unionModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
unionModel.addSubModel(aboxModel);
unionModel.addSubModel(inferenceModel);
StmtIterator iter = unionModel.listStatements((Resource) null, RDF.type, subClass);
while (iter.hasNext()) {
Statement stmt = iter.next();
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), RDF.type, superClass);
inferenceModel.enterCriticalSection(Lock.WRITE);
if (!inferenceModel.contains(infStmt)) {
inferenceModel.add(infStmt);
setMostSpecificTypes(infStmt.getSubject(), inferenceModel);
}
}
} finally {
aboxModel.leaveCriticalSection();
inferenceModel.leaveCriticalSection();
}
}
/*
* If removed that B is a subclass of A, then for each individual
* that is of type B, either inferred or in the ABox, remove the
* assertion that it is of type A from the inferred model,
* UNLESS the individual is of some type C that is a subClass
* of A (including A itself)
*/
public void removedSubClass(OntClass subClass, OntClass superClass, Model inferenceModel) {
log.debug("subClass = " + subClass.getURI() + ". superClass = " + superClass.getURI());
aboxModel.enterCriticalSection(Lock.WRITE);
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
OntModel unionModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
unionModel.addSubModel(aboxModel);
unionModel.addSubModel(inferenceModel);
StmtIterator iter = unionModel.listStatements((Resource) null, RDF.type, subClass);
while (iter.hasNext()) {
Statement stmt = iter.next();
Resource ind = stmt.getSubject();
if (entailedType(ind,superClass)) continue;
Statement infStmt = ResourceFactory.createStatement(ind, RDF.type, superClass);
inferenceModel.enterCriticalSection(Lock.WRITE);
if (inferenceModel.contains(infStmt)) {
inferenceModel.remove(infStmt);
setMostSpecificTypes(infStmt.getSubject(), inferenceModel);
}
}
} finally {
aboxModel.leaveCriticalSection();
inferenceModel.leaveCriticalSection();
}
}
/*
* If it is added that B is a subProperty of A, then for each assertion
* involving predicate B, either in the ABox or in the inferred model
* assert the same relationship for predicate A
*/
public void addedSubProperty(OntProperty subProp, OntProperty superProp, Model inferenceModel) {
log.debug("subProperty = " + subProp.getURI() + " superProperty = " + subProp.getURI());
if ( !((subProp.isObjectProperty() && superProp.isObjectProperty()) || (subProp.isDatatypeProperty() && superProp.isDatatypeProperty())) ) {
log.warn("sub-property and super-property do not have the same type. No inferencing will be performed. sub-property: " + subProp.getURI() + " super-property:" + superProp.getURI());
return;
}
aboxModel.enterCriticalSection(Lock.READ);
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
OntModel unionModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
unionModel.addSubModel(aboxModel);
unionModel.addSubModel(inferenceModel);
StmtIterator iter = unionModel.listStatements((Resource) null, subProp, (RDFNode) null);
while (iter.hasNext()) {
Statement stmt = iter.next();
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), superProp, stmt.getObject());
inferenceModel.enterCriticalSection(Lock.WRITE);
if (!inferenceModel.contains(infStmt)) {
inferenceModel.add(infStmt);
}
}
} finally {
aboxModel.leaveCriticalSection();
inferenceModel.leaveCriticalSection();
}
}
/*
* If it is removed that B is a subProperty of A, then for each
* assertion involving predicate B, either in the ABox or in the
* inferred model, remove the same assertion involving predicate
* A from the inferred model, UNLESS the assertion is otherwise
* entailed by property subsumption.
*/
public void removedSubProperty(OntProperty subProp, OntProperty superProp) {
log.debug("subProperty = " + subProp.getURI() + " superProperty = " + subProp.getURI());
if ( !((subProp.isObjectProperty() && superProp.isObjectProperty()) || (subProp.isDatatypeProperty() && superProp.isDatatypeProperty())) ) {
log.warn("sub-property and super-property do not have the same type. No inferencing will be performed. sub-property: " + subProp.getURI() + " super-property:" + superProp.getURI());
return;
}
aboxModel.enterCriticalSection(Lock.READ);
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
OntModel unionModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
unionModel.addSubModel(aboxModel);
unionModel.addSubModel(inferenceModel);
StmtIterator iter = unionModel.listStatements((Resource) null, subProp, (RDFNode) null);
while (iter.hasNext()) {
Statement stmt = iter.next();
// if the statement is entailed without the removed subPropertyOf
// relationship then don't remove it from the inferences
if (entailedByPropertySubsumption(stmt.getSubject(), superProp, stmt.getObject())) continue;
Statement infStmt = ResourceFactory.createStatement(stmt.getSubject(), superProp, stmt.getObject());
inferenceModel.enterCriticalSection(Lock.WRITE);
if (inferenceModel.contains(infStmt)) {
inferenceModel.remove(infStmt);
}
}
} finally {
aboxModel.leaveCriticalSection();
inferenceModel.leaveCriticalSection();
}
}
/*
* Find the most specific types (classes) of an individual and
* indicate them for the individual with the core:mostSpecificType
* annotation.
*/
public void setMostSpecificTypes(Resource individual, Model inferenceModel) {
//System.out.println("sjm: setMostSpecificTypes called for individual " + individual.getURI());
inferenceModel.enterCriticalSection(Lock.WRITE);
aboxModel.enterCriticalSection(Lock.READ);
tboxModel.enterCriticalSection(Lock.READ);
try {
OntModel unionModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
unionModel.addSubModel(aboxModel);
unionModel.addSubModel(inferenceModel);
List<OntClass> types = new ArrayList<OntClass>();
StmtIterator stmtIter = unionModel.listStatements(individual, RDF.type, (RDFNode) null);
while (stmtIter.hasNext()) {
Statement stmt = stmtIter.next();
if ( !stmt.getObject().isResource() ) {
log.warn("The object of this rdf:type assertion is expected to be a resource: " + stmtString(stmt));
continue;
}
OntClass ontClass = null;
if ( (stmt.getObject().asResource()).getURI() != null ) {
ontClass = tboxModel.getOntClass(stmt.getObject().asResource().getURI());
} else {
log.warn("The object of this rdf:type assertion has a null URI: " + stmtString(stmt));
continue;
}
if (ontClass == null) {
log.warn("(setMostSpecificType) Didn't find target class (the object of the added rdf:type statement) in the TBox: " + (stmt.getObject().asResource()).getURI());
continue;
}
if (ontClass.isAnon()) continue;
types.add(ontClass);
}
HashSet<String> typeURIs = new HashSet<String>();
List<OntClass> types2 = new ArrayList<OntClass>();
types2.addAll(types);
Iterator<OntClass> typeIter = types.iterator();
while (typeIter.hasNext()) {
OntClass type = typeIter.next();
boolean add = true;
Iterator<OntClass> typeIter2 = types2.iterator();
while (typeIter2.hasNext()) {
OntClass type2 = typeIter2.next();
if (type.equals(type2)) {
continue;
}
if (type.hasSubClass(type2, false) && !type2.hasSubClass(type, false)) {
add = false;
break;
}
}
if (add) {
typeURIs.add(type.getURI());
Iterator<OntClass> eIter = type.listEquivalentClasses();
while (eIter.hasNext()) {
OntClass equivClass = eIter.next();
if (equivClass.isAnon()) continue;
typeURIs.add(equivClass.getURI());
}
}
}
setMostSpecificTypes(individual, typeURIs, inferenceModel);
} finally {
aboxModel.leaveCriticalSection();
tboxModel.leaveCriticalSection();
inferenceModel.leaveCriticalSection();
}
return;
}
public void setMostSpecificTypes(Resource individual, HashSet<String> typeURIs, Model inferenceModel) {
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
Model retractions = ModelFactory.createDefaultModel();
// remove obsolete most-specific-type assertions
StmtIterator iter = inferenceModel.listStatements(individual, mostSpecificType, (RDFNode) null);
while (iter.hasNext()) {
Statement stmt = iter.next();
if ( !stmt.getObject().isResource() ) {
log.warn("The object of this assertion is expected to be a resource: " + stmtString(stmt));
continue;
}
if (!typeURIs.contains(stmt.getObject().asResource().getURI())) {
retractions.add(stmt);
}
}
inferenceModel.remove(retractions);
// add new most-specific-type assertions
Iterator<String> typeIter = typeURIs.iterator();
while (typeIter.hasNext()) {
String typeURI = typeIter.next();
Resource mstResource = ResourceFactory.createResource(typeURI);
if (!inferenceModel.contains(individual, mostSpecificType, mstResource)) {
inferenceModel.add(individual, mostSpecificType, mstResource);
}
}
} finally {
inferenceModel.leaveCriticalSection();
}
return;
}
private boolean recomputing = false;
/**
* Returns true if the reasoner is in the process of recomputing all
* inferences.
*/
public boolean isRecomputing() {
return recomputing;
}
/**
* Recompute all inferences.
*/
public synchronized void recompute() {
recomputing = true;
try {
recomputeABox();
} finally {
recomputing = false;
}
}
/*
* Recompute the entire ABox inference graph. The new
* inference graph is built up in a separate model and
* then reconciled with the inference graph used by the
* application. The model reconciliation must be done
* without reading the whole inference models into
* memory since we are supporting very large ABox
* inference models.
*/
public synchronized void recomputeABox() {
// recompute the inferences
inferenceRebuildModel.enterCriticalSection(Lock.WRITE);
aboxModel.enterCriticalSection(Lock.WRITE);
tboxModel.enterCriticalSection(Lock.READ);
try {
inferenceRebuildModel.removeAll();
StmtIterator iter = aboxModel.listStatements((Resource) null, RDF.type, (RDFNode) null);
log.info("Computing class-based ABox inferences");
while (iter.hasNext()) {
Statement stmt = iter.next();
addedABoxTypeAssertion(stmt, inferenceRebuildModel);
setMostSpecificTypes(stmt.getSubject(), inferenceRebuildModel);
}
log.info("Computing property-based ABox inferences");
iter = tboxModel.listStatements((Resource) null, RDFS.subPropertyOf, (RDFNode) null);
int numStmts = 0;
while (iter.hasNext()) {
Statement stmt = iter.next();
if (stmt.getSubject().getURI().equals(bottomObjectPropertyURI) || stmt.getSubject().getURI().equals(bottomDataPropertyURI) ||
(stmt.getObject().isResource() && (stmt.getObject().asResource().getURI().equals(topObjectPropertyURI) ||
stmt.getObject().asResource().getURI().equals(topDataPropertyURI))) ) {
continue;
}
if ( stmt.getSubject().equals(stmt.getObject()) ) {
continue;
}
addedTBoxStatement(stmt, inferenceRebuildModel);
numStmts++;
if ((numStmts % 500) == 0) {
log.info("Still computing property-based ABox inferences...");
}
}
iter = tboxModel.listStatements((Resource) null, OWL.equivalentProperty, (RDFNode) null);
while (iter.hasNext()) {
Statement stmt = iter.next();
if ( stmt.getSubject().equals(stmt.getObject()) ) {
continue;
}
addedTBoxStatement(stmt, inferenceRebuildModel);
numStmts++;
if ((numStmts % 500) == 0) {
log.info("Still computing property-based ABox inferences...");
}
}
} catch (Exception e) {
log.error("Exception while recomputing ABox inference model", e);
inferenceRebuildModel.removeAll(); // don't do this in the finally, it's needed in the case
// where there isn't an exception
return;
} finally {
aboxModel.leaveCriticalSection();
tboxModel.leaveCriticalSection();
inferenceRebuildModel.leaveCriticalSection();
}
// reflect the recomputed inferences into the application inference
// model.
inferenceRebuildModel.enterCriticalSection(Lock.WRITE);
scratchpadModel.enterCriticalSection(Lock.WRITE);
log.info("Updating ABox inference model");
// Remove everything from the current inference model that is not
// in the recomputed inference model
try {
inferenceModel.enterCriticalSection(Lock.READ);
try {
scratchpadModel.removeAll();
StmtIterator iter = inferenceModel.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.next();
if (!inferenceRebuildModel.contains(stmt)) {
scratchpadModel.add(stmt);
}
}
} catch (Exception e) {
log.error("Exception while reconciling the current and recomputed ABox inference models", e);
} finally {
inferenceModel.leaveCriticalSection();
}
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
inferenceModel.remove(scratchpadModel);
} catch (Exception e){
log.error("Exception while reconciling the current and recomputed ABox inference models", e);
} finally {
inferenceModel.leaveCriticalSection();
}
// Add everything from the recomputed inference model that is not already
// in the current inference model to the current inference model.
inferenceModel.enterCriticalSection(Lock.READ);
try {
scratchpadModel.removeAll();
StmtIterator iter = inferenceRebuildModel.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.next();
if (!inferenceModel.contains(stmt)) {
scratchpadModel.add(stmt);
}
}
} catch (Exception e) {
log.error("Exception while reconciling the current and recomputed ABox inference models", e);
} finally {
inferenceModel.leaveCriticalSection();
}
inferenceModel.enterCriticalSection(Lock.WRITE);
try {
inferenceModel.add(scratchpadModel);
} catch (Exception e){
log.error("Exception while reconciling the current and recomputed ABox inference models", e);
} finally {
inferenceModel.leaveCriticalSection();
}
} finally {
inferenceRebuildModel.removeAll();
scratchpadModel.removeAll();
inferenceRebuildModel.leaveCriticalSection();
scratchpadModel.leaveCriticalSection();
}
log.info("ABox inference model updated");
}
public static SimpleReasoner getSimpleReasonerFromServletContext(ServletContext ctx) {
Object simpleReasoner = ctx.getAttribute("simpleReasoner");
if (simpleReasoner instanceof SimpleReasoner) {
return (SimpleReasoner) simpleReasoner;
} else {
return null;
}
}
public static boolean isABoxReasoningAsynchronous(ServletContext ctx) {
return (getSimpleReasonerFromServletContext(ctx) == null);
}
public static String stmtString(Statement statement) {
return " [subject = " + statement.getSubject().getURI() +
"] [property = " + statement.getPredicate().getURI() +
"] [object = " + (statement.getObject().isLiteral() ? ((Literal)statement.getObject()).getLexicalForm() + " (Literal)"
: ((Resource)statement.getObject()).getURI() + " (Resource)") + "]";
}
}
|
import java.util.*;
public class Hall
{
private String hallID;
private ArrayList<Room>rooms=new ArrayList<>();
public ArrayList<Room>getRoom()
{
return rooms;
}
public Hall(String hallID)
{
this.hallID=hallID;
}
public void addRoom(Room r)
{
rooms.add(r);
}
}
|
import javax.swing.*;
public class OptionM extends MenuVue {
public JComboBox<String> listeTaille;
public JButton up;
public JButton down;
public JButton left;
public JButton right;
public JButton retour;
}
}
|
package rlpark.plugin.rltoys.algorithms.predictions.td;
import rlpark.plugin.rltoys.algorithms.traces.ATraces;
import rlpark.plugin.rltoys.algorithms.traces.EligibilityTraceAlgorithm;
import rlpark.plugin.rltoys.algorithms.traces.Traces;
import rlpark.plugin.rltoys.math.vector.RealVector;
import zephyr.plugin.core.api.monitoring.annotations.Monitor;
public class TDLambda extends TD implements EligibilityTraceAlgorithm {
private static final long serialVersionUID = 8613865620293286722L;
private final double lambda;
@Monitor
public final Traces e;
double gamma_t;
public TDLambda(double lambda, double gamma, double alpha, int nbFeatures) {
this(lambda, gamma, alpha, nbFeatures, new ATraces());
}
public TDLambda(double lambda, double gamma, double alpha, int nbFeatures, Traces prototype) {
super(gamma, alpha, nbFeatures);
this.lambda = lambda;
e = prototype.newTraces(nbFeatures);
}
@Override
protected double initEpisode() {
e.clear();
gamma_t = gamma;
return super.initEpisode();
}
@Override
public double update(RealVector x_t, RealVector x_tp1, double r_tp1, double gamma_tp1) {
if (x_t == null)
return initEpisode();
v_t = v.dotProduct(x_t);
delta_t = r_tp1 + gamma_tp1 * v.dotProduct(x_tp1) - v_t;
e.update(lambda * gamma_t, x_t);
v.addToSelf(alpha_v * delta_t, e.vect());
gamma_t = gamma_tp1;
return delta_t;
}
@Override
public void resetWeight(int index) {
super.resetWeight(index);
e.vect().setEntry(index, 0);
}
@Override
public Traces traces() {
return e;
}
}
|
package org.innovateuk.ifs.docusign.transactional;
import com.docusign.esign.api.EnvelopesApi;
import com.docusign.esign.api.EnvelopesApi.ListStatusChangesOptions;
import com.docusign.esign.client.ApiException;
import com.docusign.esign.model.*;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import com.sun.jersey.core.util.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.innovateuk.ifs.commons.exception.IFSRuntimeException;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.docusign.api.DocusignApi;
import org.innovateuk.ifs.docusign.domain.DocusignDocument;
import org.innovateuk.ifs.docusign.repository.DocusignDocumentRepository;
import org.innovateuk.ifs.docusign.resource.DocusignRequest;
import org.innovateuk.ifs.docusign.resource.DocusignType;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.innovateuk.ifs.file.transactional.FileService;
import org.innovateuk.ifs.project.core.domain.Project;
import org.innovateuk.ifs.project.grantofferletter.configuration.workflow.GrantOfferLetterWorkflowHandler;
import org.innovateuk.ifs.transactional.RootTransactionalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COULD_NOT_SEND_FILE_TO_DOCUSIGN;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
@Service
public class DocusignServiceImpl extends RootTransactionalService implements DocusignService {
private static final Log LOG = LogFactory.getLog(DocusignServiceImpl.class);
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
@Value("${ifs.docusign.api.account}")
private String accountId;
@Value("${ifs.web.baseURL}")
private String webBaseUrl;
@Autowired
private DocusignDocumentRepository docusignDocumentRepository;
@Autowired
private FileService fileService;
@Autowired
private GrantOfferLetterWorkflowHandler grantOfferLetterWorkflowHandler;
@Autowired
private DocusignApi docusignApi;
@Override
@Transactional
public ServiceResult<DocusignDocument> send(DocusignRequest request) {
try {
return serviceSuccess(doSend(request));
} catch (ApiException | IOException e) {
LOG.error(e);
return serviceFailure(COULD_NOT_SEND_FILE_TO_DOCUSIGN);
}
}
@Override
@Transactional
public ServiceResult<DocusignDocument> resend(long docusignDocumentId, DocusignRequest request) {
try {
docusignDocumentRepository.deleteById(docusignDocumentId);
return serviceSuccess(doSend(request));
} catch (ApiException | IOException e) {
throw new IFSRuntimeException("Unable to send docusign doc", e);
}
}
private DocusignDocument doSend(DocusignRequest request) throws ApiException, IOException {
DocusignDocument docusignDocument = docusignDocumentRepository.save(new DocusignDocument(request.getRecipientUserId(), request.getDocusignType()));
byte[] data = ByteStreams.toByteArray(request.getFileAndContents().getContentsSupplier().get());
Document document = createDocusignDocument(data,
request.getFileAndContents().getFileEntry().getName(),
docusignDocument.getId());
Signer signer = createDocusignSigner(request.getEmail(),
request.getName(),
request.getRecipientUserId(),
webBaseUrl + request.getRedirectUrl());
Tabs tabs = createDefaultTabs(data, document, signer);
signer.setTabs(tabs);
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
envelopeDefinition.setEmailSubject(request.getSubject());
envelopeDefinition.setDocuments(asList(document));
Recipients recipients = new Recipients();
recipients.setSigners(asList(signer));
envelopeDefinition.setRecipients(recipients);
envelopeDefinition.setStatus("sent");
envelopeDefinition.setEmailBlurb(request.getEmailBody());
EnvelopesApi envelopesApi = new EnvelopesApi(docusignApi.getApiClient());
EnvelopeSummary results = envelopesApi.createEnvelope(accountId, envelopeDefinition);
docusignDocument.setEnvelopeId(results.getEnvelopeId());
return docusignDocument;
}
private Signer createDocusignSigner(String email, String name, long recipientUserId, String redirectUrl) {
return new Signer()
.email(email)
.name(name)
.recipientId(String.valueOf(recipientUserId))
.clientUserId(String.valueOf(recipientUserId))
.embeddedRecipientStartURL(redirectUrl);
}
private Document createDocusignDocument(byte[] data, String documentName, Long documentId) {
String docBase64 = new String(Base64.encode(data));
return new Document().documentBase64(docBase64)
.name(documentName)
.fileExtension("pdf")
.documentId(String.valueOf(documentId));
}
private Tabs createDefaultTabs(byte[] data, Document document, Signer signer) throws IOException {
PDDocument doc = PDDocument.load(data);
List<InitialHere> initialHereList = new ArrayList<>();
int i = 0;
for (PDPage page : doc.getPages()) {
i++;
InitialHere initialHere = new InitialHere();
initialHere.setDocumentId(document.getDocumentId());
initialHere.setPageNumber(String.valueOf(i));
initialHere.setRecipientId(signer.getRecipientId());
initialHere.setTabLabel("Initial here");
initialHere.setXPosition(String.valueOf((int) page.getMediaBox().getWidth() - 50));
initialHere.setYPosition("20");
initialHereList.add(initialHere);
}
doc.close();
SignHere anchor = new SignHere();
anchor.setAnchorString("Signed: _");
anchor.setAnchorHorizontalAlignment("right");
anchor.setAnchorYOffset("-8");
anchor.setAnchorIgnoreIfNotPresent("false");
FullName print = new FullName();
print.anchorString("Print name: _");
print.setAnchorHorizontalAlignment("right");
print.setAnchorYOffset("-8");
DateSigned date = new DateSigned();
date.anchorString("Date: _");
date.setAnchorHorizontalAlignment("right");
date.setAnchorYOffset("-8");
Text projectStartDate = new Text();
projectStartDate.anchorString("Project start date _");
projectStartDate.setAnchorHorizontalAlignment("right");
projectStartDate.setWidth("200");
projectStartDate.setAnchorYOffset("-8");
projectStartDate.setTabLabel("start date");
Text projectEndDate = new Text();
projectEndDate.anchorString("Project end date _");
projectEndDate.setAnchorHorizontalAlignment("right");
projectEndDate.setWidth("200");
projectEndDate.setAnchorYOffset("-8");
projectEndDate.setTabLabel("end date");
// Add the tabs to the signer object
// The Tabs object wants arrays of the different field/tab types
Tabs tabs = new Tabs();
tabs.setSignHereTabs(singletonList(anchor));
tabs.setFullNameTabs(singletonList(print));
tabs.setDateSignedTabs(singletonList(date));
tabs.setInitialHereTabs(initialHereList);
tabs.setTextTabs(asList(projectStartDate, projectEndDate));
return tabs;
}
@Override
@Transactional
public void downloadFileIfSigned() throws ApiException, IOException {
LOG.info("Starting import of docusign documents.");
EnvelopesApi envelopesApi = new EnvelopesApi(docusignApi.getApiClient());
ListStatusChangesOptions options = envelopesApi.new ListStatusChangesOptions();
LocalDate date = LocalDate.now().minusDays(1);
options.setFromDate(DATE_FORMATTER.format(date));
options.setFromToStatus("completed");
EnvelopesInformation envelopesInformation = envelopesApi.listStatusChanges(accountId, options);
for (Envelope envelope : envelopesInformation.getEnvelopes()) {
Optional<DocusignDocument> document = docusignDocumentRepository.findByEnvelopeId(envelope.getEnvelopeId());
document = document.filter(d -> d.getSignedDocumentImported() == null);
if (document.isPresent()) {
importDocument(document.get());
}
}
}
@Override
public String getDocusignUrl(String envelopeId, long userId, String name, String email, String redirect) {
try {
Optional<DocusignDocument> document = docusignDocumentRepository.findByEnvelopeId(envelopeId);
if (document.isPresent()) {
RecipientViewRequest viewRequest = new RecipientViewRequest();
viewRequest.setReturnUrl(webBaseUrl + redirect);
viewRequest.setAuthenticationMethod("none");
viewRequest.setEmail(email);
viewRequest.setUserName(name);
viewRequest.recipientId(String.valueOf(userId));
viewRequest.setPingUrl(webBaseUrl);
viewRequest.setPingFrequency("600");
viewRequest.clientUserId(String.valueOf(userId));
EnvelopesApi envelopesApi = new EnvelopesApi(docusignApi.getApiClient());
ViewUrl viewUrl = envelopesApi.createRecipientView(accountId, envelopeId, viewRequest);
return viewUrl.getUrl();
}
return null;
} catch (ApiException e) {
LOG.error(e);
return null;
}
}
@Override
public ServiceResult<Void> importDocument(String envelopeId) {
try {
EnvelopesApi envelopesApi = new EnvelopesApi(docusignApi.getApiClient());
Envelope envelope = envelopesApi.getEnvelope(accountId, envelopeId);
if (envelope.getStatus().equals("completed")) {
Optional<DocusignDocument> document = docusignDocumentRepository.findByEnvelopeId(envelopeId);
document = document.filter(d -> d.getSignedDocumentImported() == null);
if (document.isPresent()) {
importDocument(document.get());
}
}
return serviceSuccess();
} catch (ApiException| IOException e) {
throw new IFSRuntimeException(e);
}
}
private void importDocument(DocusignDocument docusignDocument) throws ApiException, IOException {
LOG.info("importing docusign document " + docusignDocument.getEnvelopeId());
EnvelopesApi envelopesApi = new EnvelopesApi(docusignApi.getApiClient());
byte[] results = envelopesApi.getDocument(accountId, docusignDocument.getEnvelopeId(), String.valueOf(docusignDocument.getId()));
if (docusignDocument.getType().equals(DocusignType.SIGNED_GRANT_OFFER_LETTER)) {
linkGrantOfferLetterFileToProject(results, docusignDocument.getProject());
}
//Add other document types here.
docusignDocument.setSignedDocumentImported(ZonedDateTime.now());
}
private void linkGrantOfferLetterFileToProject(byte[] results, Project project) throws IOException {
try (InputStream stream = ByteSource.wrap(results).openStream()) {
FileEntryResource fileEntryResource = new FileEntryResource("SignedGrantOfferLetter.pdf", MediaType.APPLICATION_PDF.toString(), results.length);
fileService.createFile(fileEntryResource, () -> stream)
.andOnSuccessReturnVoid(fileDetails -> {
FileEntry fileEntry = fileDetails.getValue();
project.setSignedGrantOfferLetter(fileEntry);
project.setOfferSubmittedDate(ZonedDateTime.now());
grantOfferLetterWorkflowHandler.sign(project);
});
}
}
}
|
package com.atlassian.jira.plugins.dvcs.activeobjects.v3;
import java.util.Date;
import net.java.ao.Entity;
import net.java.ao.Preload;
import net.java.ao.schema.Table;
@Preload
@Table("RepositoryMapping")
public interface RepositoryMapping extends Entity
{
public static final String ORGANIZATION_ID = "ORGANIZATION_ID";
public static final String SLUG = "SLUG";
public static final String NAME = "NAME";
public static final String LAST_COMMIT_DATE = "LAST_COMMIT_DATE";
public static final String LINKED = "LINKED";
public static final String DELETED = "DELETED";
public static final String SMARTCOMMITS_ENABLED = "SMARTCOMMITS_ENABLED";
int getOrganizationId();
String getSlug();
String getName();
Date getLastCommitDate();
@Deprecated
String getLastChangesetNode();
boolean isLinked();
boolean isDeleted();
boolean isSmartcommitsEnabled();
void setOrganizationId(int organizationId);
void setSlug(String slug);
void setName(String name);
void setLastCommitDate(Date lastCommitDate);
@Deprecated
void setLastChangesetNode(String lastChangesetNode);
void setLinked(boolean linked);
void setDeleted(boolean deleted);
void setSmartcommitsEnabled(boolean enabled);
}
|
package org.jfree.chart.axis;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
public class SegmentedTimeline implements Timeline, Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 1093779862539903110L;
// predetermined segments sizes
/** Defines a day segment size in ms. */
public static final long DAY_SEGMENT_SIZE = 24 * 60 * 60 * 1000;
/** Defines a one hour segment size in ms. */
public static final long HOUR_SEGMENT_SIZE = 60 * 60 * 1000;
/** Defines a 15-minute segment size in ms. */
public static final long FIFTEEN_MINUTE_SEGMENT_SIZE = 15 * 60 * 1000;
/** Defines a one-minute segment size in ms. */
public static final long MINUTE_SEGMENT_SIZE = 60 * 1000;
// other constants
/**
* Utility constant that defines the startTime as the first monday after
* 1/1/1970. This should be used when creating a SegmentedTimeline for
* Monday through Friday. See static block below for calculation of this
* constant.
*
* @deprecated As of 1.0.7. This field doesn't take into account changes
* to the default time zone.
*/
public static long FIRST_MONDAY_AFTER_1900;
/**
* Utility TimeZone object that has no DST and an offset equal to the
* default TimeZone. This allows easy arithmetic between days as each one
* will have equal size.
*
* @deprecated As of 1.0.7. This field is initialised based on the
* default time zone, and doesn't take into account subsequent
* changes to the default.
*/
public static TimeZone NO_DST_TIME_ZONE;
/**
* This is the default time zone where the application is running. See
* getTime() below where we make use of certain transformations between
* times in the default time zone and the no-dst time zone used for our
* calculations.
*
* @deprecated As of 1.0.7. When the default time zone is required,
* just call <code>TimeZone.getDefault()</code>.
*/
public static TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault();
/**
* This will be a utility calendar that has no DST but is shifted relative
* to the default time zone's offset.
*/
private Calendar workingCalendarNoDST;
/**
* This will be a utility calendar that used the default time zone.
*/
private Calendar workingCalendar = Calendar.getInstance();
// private attributes
/** Segment size in ms. */
private long segmentSize;
/** Number of consecutive segments to include in a segment group. */
private int segmentsIncluded;
/** Number of consecutive segments to exclude in a segment group. */
private int segmentsExcluded;
/** Number of segments in a group (segmentsIncluded + segmentsExcluded). */
private int groupSegmentCount;
/**
* Start of time reference from time zero (1/1/1970).
* This is the start of segment #0.
*/
private long startTime;
/** Consecutive ms in segmentsIncluded (segmentsIncluded * segmentSize). */
private long segmentsIncludedSize;
/** Consecutive ms in segmentsExcluded (segmentsExcluded * segmentSize). */
private long segmentsExcludedSize;
/** ms in a segment group (segmentsIncludedSize + segmentsExcludedSize). */
private long segmentsGroupSize;
/**
* List of exception segments (exceptions segments that would otherwise be
* included based on the periodic (included, excluded) grouping).
*/
private List exceptionSegments = new ArrayList();
/**
* This base timeline is used to specify exceptions at a higher level. For
* example, if we are a intraday timeline and want to exclude holidays,
* instead of having to exclude all intraday segments for the holiday,
* segments from this base timeline can be excluded. This baseTimeline is
* always optional and is only a convenience method.
* <p>
* Additionally, all excluded segments from this baseTimeline will be
* considered exceptions at this level.
*/
private SegmentedTimeline baseTimeline;
/** A flag that controls whether or not to adjust for daylight saving. */
private boolean adjustForDaylightSaving = false;
// static block
static {
// make a time zone with no DST for our Calendar calculations
int offset = TimeZone.getDefault().getRawOffset();
NO_DST_TIME_ZONE = new SimpleTimeZone(offset, "UTC-" + offset);
// calculate midnight of first monday after 1/1/1900 relative to
// current locale
Calendar cal = new GregorianCalendar(NO_DST_TIME_ZONE);
cal.set(1900, 0, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DATE, 1);
}
// FIRST_MONDAY_AFTER_1900 = cal.getTime().getTime();
// preceding code won't work with JDK 1.3
FIRST_MONDAY_AFTER_1900 = cal.getTime().getTime();
}
// constructors and factory methods
/**
* Constructs a new segmented timeline, optionaly using another segmented
* timeline as its base. This chaining of SegmentedTimelines allows further
* segmentation into smaller timelines.
*
* If a base
*
* @param segmentSize the size of a segment in ms. This time unit will be
* used to compute the included and excluded segments of the
* timeline.
* @param segmentsIncluded Number of consecutive segments to include.
* @param segmentsExcluded Number of consecutive segments to exclude.
*/
public SegmentedTimeline(long segmentSize,
int segmentsIncluded,
int segmentsExcluded) {
this.segmentSize = segmentSize;
this.segmentsIncluded = segmentsIncluded;
this.segmentsExcluded = segmentsExcluded;
this.groupSegmentCount = this.segmentsIncluded + this.segmentsExcluded;
this.segmentsIncludedSize = this.segmentsIncluded * this.segmentSize;
this.segmentsExcludedSize = this.segmentsExcluded * this.segmentSize;
this.segmentsGroupSize = this.segmentsIncludedSize
+ this.segmentsExcludedSize;
int offset = TimeZone.getDefault().getRawOffset();
TimeZone z = new SimpleTimeZone(offset, "UTC-" + offset);
this.workingCalendarNoDST = new GregorianCalendar(z,
Locale.getDefault());
}
/**
* Returns the milliseconds for midnight of the first Monday after
* 1-Jan-1900, ignoring daylight savings.
*
* @return The milliseconds.
*
* @since 1.0.7
*/
public static long firstMondayAfter1900() {
int offset = TimeZone.getDefault().getRawOffset();
TimeZone z = new SimpleTimeZone(offset, "UTC-" + offset);
// calculate midnight of first monday after 1/1/1900 relative to
// current locale
Calendar cal = new GregorianCalendar(z);
cal.set(1900, 0, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DATE, 1);
}
//return cal.getTimeInMillis();
// preceding code won't work with JDK 1.3
return cal.getTime().getTime();
}
/**
* Factory method to create a Monday through Friday SegmentedTimeline.
* <P>
* The <code>startTime</code> of the resulting timeline will be midnight
* of the first Monday after 1/1/1900.
*
* @return A fully initialized SegmentedTimeline.
*/
public static SegmentedTimeline newMondayThroughFridayTimeline() {
SegmentedTimeline timeline
= new SegmentedTimeline(DAY_SEGMENT_SIZE, 5, 2);
timeline.setStartTime(firstMondayAfter1900());
return timeline;
}
/**
* Factory method to create a 15-min, 9:00 AM thought 4:00 PM, Monday
* through Friday SegmentedTimeline.
* <P>
* This timeline uses a segmentSize of FIFTEEN_MIN_SEGMENT_SIZE. The
* segment group is defined as 28 included segments (9:00 AM through
* 4:00 PM) and 68 excluded segments (4:00 PM through 9:00 AM the next day).
* <P>
* In order to exclude Saturdays and Sundays it uses a baseTimeline that
* only includes Monday through Friday days.
* <P>
* The <code>startTime</code> of the resulting timeline will be 9:00 AM
* after the startTime of the baseTimeline. This will correspond to 9:00 AM
* of the first Monday after 1/1/1900.
*
* @return A fully initialized SegmentedTimeline.
*/
public static SegmentedTimeline newFifteenMinuteTimeline() {
SegmentedTimeline timeline = new SegmentedTimeline(
FIFTEEN_MINUTE_SEGMENT_SIZE, 28, 68);
timeline.setStartTime(firstMondayAfter1900() + 36
* timeline.getSegmentSize());
timeline.setBaseTimeline(newMondayThroughFridayTimeline());
return timeline;
}
/**
* Returns the flag that controls whether or not the daylight saving
* adjustment is applied.
*
* @return A boolean.
*/
public boolean getAdjustForDaylightSaving() {
return this.adjustForDaylightSaving;
}
/**
* Sets the flag that controls whether or not the daylight saving adjustment
* is applied.
*
* @param adjust the flag.
*/
public void setAdjustForDaylightSaving(boolean adjust) {
this.adjustForDaylightSaving = adjust;
}
// operations
/**
* Sets the start time for the timeline. This is the beginning of segment
* zero.
*
* @param millisecond the start time (encoded as in java.util.Date).
*/
public void setStartTime(long millisecond) {
this.startTime = millisecond;
}
/**
* Returns the start time for the timeline. This is the beginning of
* segment zero.
*
* @return The start time.
*/
public long getStartTime() {
return this.startTime;
}
/**
* Returns the number of segments excluded per segment group.
*
* @return The number of segments excluded.
*/
public int getSegmentsExcluded() {
return this.segmentsExcluded;
}
/**
* Returns the size in milliseconds of the segments excluded per segment
* group.
*
* @return The size in milliseconds.
*/
public long getSegmentsExcludedSize() {
return this.segmentsExcludedSize;
}
/**
* Returns the number of segments in a segment group. This will be equal to
* segments included plus segments excluded.
*
* @return The number of segments.
*/
public int getGroupSegmentCount() {
return this.groupSegmentCount;
}
/**
* Returns the size in milliseconds of a segment group. This will be equal
* to size of the segments included plus the size of the segments excluded.
*
* @return The segment group size in milliseconds.
*/
public long getSegmentsGroupSize() {
return this.segmentsGroupSize;
}
/**
* Returns the number of segments included per segment group.
*
* @return The number of segments.
*/
public int getSegmentsIncluded() {
return this.segmentsIncluded;
}
/**
* Returns the size in ms of the segments included per segment group.
*
* @return The segment size in milliseconds.
*/
public long getSegmentsIncludedSize() {
return this.segmentsIncludedSize;
}
/**
* Returns the size of one segment in ms.
*
* @return The segment size in milliseconds.
*/
public long getSegmentSize() {
return this.segmentSize;
}
/**
* Returns a list of all the exception segments. This list is not
* modifiable.
*
* @return The exception segments.
*/
public List getExceptionSegments() {
return Collections.unmodifiableList(this.exceptionSegments);
}
/**
* Sets the exception segments list.
*
* @param exceptionSegments the exception segments.
*/
public void setExceptionSegments(List exceptionSegments) {
this.exceptionSegments = exceptionSegments;
}
/**
* Returns our baseTimeline, or <code>null</code> if none.
*
* @return The base timeline.
*/
public SegmentedTimeline getBaseTimeline() {
return this.baseTimeline;
}
/**
* Sets the base timeline.
*
* @param baseTimeline the timeline.
*/
public void setBaseTimeline(SegmentedTimeline baseTimeline) {
// verify that baseTimeline is compatible with us
if (baseTimeline != null) {
if (baseTimeline.getSegmentSize() < this.segmentSize) {
throw new IllegalArgumentException(
"baseTimeline.getSegmentSize() "
+ "is smaller than segmentSize");
}
else if (baseTimeline.getStartTime() > this.startTime) {
throw new IllegalArgumentException(
"baseTimeline.getStartTime() is after startTime");
}
else if ((baseTimeline.getSegmentSize() % this.segmentSize) != 0) {
throw new IllegalArgumentException(
"baseTimeline.getSegmentSize() is not multiple of "
+ "segmentSize");
}
else if (((this.startTime
- baseTimeline.getStartTime()) % this.segmentSize) != 0) {
throw new IllegalArgumentException(
"baseTimeline is not aligned");
}
}
this.baseTimeline = baseTimeline;
}
/**
* Translates a value relative to the domain value (all Dates) into a value
* relative to the segmented timeline. The values relative to the segmented
* timeline are all consecutives starting at zero at the startTime.
*
* @param millisecond the millisecond (as encoded by java.util.Date).
*
* @return The timeline value.
*/
public long toTimelineValue(long millisecond) {
long result;
long rawMilliseconds = millisecond - this.startTime;
long groupMilliseconds = rawMilliseconds % this.segmentsGroupSize;
long groupIndex = rawMilliseconds / this.segmentsGroupSize;
if (groupMilliseconds >= this.segmentsIncludedSize) {
result = toTimelineValue(this.startTime + this.segmentsGroupSize
* (groupIndex + 1));
}
else {
Segment segment = getSegment(millisecond);
if (segment.inExceptionSegments()) {
int p;
while ((p = binarySearchExceptionSegments(segment)) >= 0) {
segment = getSegment(millisecond = ((Segment)
this.exceptionSegments.get(p)).getSegmentEnd() + 1);
}
result = toTimelineValue(millisecond);
}
else {
long shiftedSegmentedValue = millisecond - this.startTime;
long x = shiftedSegmentedValue % this.segmentsGroupSize;
long y = shiftedSegmentedValue / this.segmentsGroupSize;
long wholeExceptionsBeforeDomainValue =
getExceptionSegmentCount(this.startTime, millisecond - 1);
// long partialTimeInException = 0;
// Segment ss = getSegment(millisecond);
// if (ss.inExceptionSegments()) {
// partialTimeInException = millisecond
// - ss.getSegmentStart();
if (x < this.segmentsIncludedSize) {
result = this.segmentsIncludedSize * y
+ x - wholeExceptionsBeforeDomainValue
* this.segmentSize;
// - partialTimeInException;
}
else {
result = this.segmentsIncludedSize * (y + 1)
- wholeExceptionsBeforeDomainValue
* this.segmentSize;
// - partialTimeInException;
}
}
}
return result;
}
/**
* Translates a date into a value relative to the segmented timeline. The
* values relative to the segmented timeline are all consecutives starting
* at zero at the startTime.
*
* @param date date relative to the domain.
*
* @return The timeline value (in milliseconds).
*/
public long toTimelineValue(Date date) {
return toTimelineValue(getTime(date));
//return toTimelineValue(dateDomainValue.getTime());
}
/**
* Translates a value relative to the timeline into a millisecond.
*
* @param timelineValue the timeline value (in milliseconds).
*
* @return The domain value (in milliseconds).
*/
public long toMillisecond(long timelineValue) {
// calculate the result as if no exceptions
Segment result = new Segment(this.startTime + timelineValue
+ (timelineValue / this.segmentsIncludedSize)
* this.segmentsExcludedSize);
long lastIndex = this.startTime;
// adjust result for any exceptions in the result calculated
while (lastIndex <= result.segmentStart) {
// skip all whole exception segments in the range
long exceptionSegmentCount;
while ((exceptionSegmentCount = getExceptionSegmentCount(
lastIndex, (result.millisecond / this.segmentSize)
* this.segmentSize - 1)) > 0
) {
lastIndex = result.segmentStart;
// move forward exceptionSegmentCount segments skipping
// excluded segments
for (int i = 0; i < exceptionSegmentCount; i++) {
do {
result.inc();
}
while (result.inExcludeSegments());
}
}
lastIndex = result.segmentStart;
// skip exception or excluded segments we may fall on
while (result.inExceptionSegments() || result.inExcludeSegments()) {
result.inc();
lastIndex += this.segmentSize;
}
lastIndex++;
}
return getTimeFromLong(result.millisecond);
}
/**
* Converts a date/time value to take account of daylight savings time.
*
* @param date the milliseconds.
*
* @return The milliseconds.
*/
public long getTimeFromLong(long date) {
long result = date;
if (this.adjustForDaylightSaving) {
this.workingCalendarNoDST.setTime(new Date(date));
this.workingCalendar.set(
this.workingCalendarNoDST.get(Calendar.YEAR),
this.workingCalendarNoDST.get(Calendar.MONTH),
this.workingCalendarNoDST.get(Calendar.DATE),
this.workingCalendarNoDST.get(Calendar.HOUR_OF_DAY),
this.workingCalendarNoDST.get(Calendar.MINUTE),
this.workingCalendarNoDST.get(Calendar.SECOND)
);
this.workingCalendar.set(Calendar.MILLISECOND,
this.workingCalendarNoDST.get(Calendar.MILLISECOND));
// result = this.workingCalendar.getTimeInMillis();
// preceding code won't work with JDK 1.3
result = this.workingCalendar.getTime().getTime();
}
return result;
}
/**
* Returns <code>true</code> if a value is contained in the timeline.
*
* @param millisecond the value to verify.
*
* @return <code>true</code> if value is contained in the timeline.
*/
public boolean containsDomainValue(long millisecond) {
Segment segment = getSegment(millisecond);
return segment.inIncludeSegments();
}
/**
* Returns <code>true</code> if a value is contained in the timeline.
*
* @param date date to verify
*
* @return <code>true</code> if value is contained in the timeline
*/
public boolean containsDomainValue(Date date) {
return containsDomainValue(getTime(date));
}
/**
* Returns <code>true</code> if a range of values are contained in the
* timeline. This is implemented verifying that all segments are in the
* range.
*
* @param domainValueStart start of the range to verify
* @param domainValueEnd end of the range to verify
*
* @return <code>true</code> if the range is contained in the timeline
*/
public boolean containsDomainRange(long domainValueStart,
long domainValueEnd) {
if (domainValueEnd < domainValueStart) {
throw new IllegalArgumentException(
"domainValueEnd (" + domainValueEnd
+ ") < domainValueStart (" + domainValueStart + ")");
}
Segment segment = getSegment(domainValueStart);
boolean contains = true;
do {
contains = (segment.inIncludeSegments());
if (segment.contains(domainValueEnd)) {
break;
}
else {
segment.inc();
}
}
while (contains);
return (contains);
}
/**
* Returns <code>true</code> if a range of values are contained in the
* timeline. This is implemented verifying that all segments are in the
* range.
*
* @param dateDomainValueStart start of the range to verify
* @param dateDomainValueEnd end of the range to verify
*
* @return <code>true</code> if the range is contained in the timeline
*/
public boolean containsDomainRange(Date dateDomainValueStart,
Date dateDomainValueEnd) {
return containsDomainRange(getTime(dateDomainValueStart),
getTime(dateDomainValueEnd));
}
/**
* Adds a segment as an exception. An exception segment is defined as a
* segment to exclude from what would otherwise be considered a valid
* segment of the timeline. An exception segment can not be contained
* inside an already excluded segment. If so, no action will occur (the
* proposed exception segment will be discarded).
* <p>
* The segment is identified by a domainValue into any part of the segment.
* Therefore the segmentStart <= domainValue <= segmentEnd.
*
* @param millisecond domain value to treat as an exception
*/
public void addException(long millisecond) {
addException(new Segment(millisecond));
}
/**
* Adds a segment range as an exception. An exception segment is defined as
* a segment to exclude from what would otherwise be considered a valid
* segment of the timeline. An exception segment can not be contained
* inside an already excluded segment. If so, no action will occur (the
* proposed exception segment will be discarded).
* <p>
* The segment range is identified by a domainValue that begins a valid
* segment and ends with a domainValue that ends a valid segment.
* Therefore the range will contain all segments whose segmentStart
* <= domainValue and segmentEnd <= toDomainValue.
*
* @param fromDomainValue start of domain range to treat as an exception
* @param toDomainValue end of domain range to treat as an exception
*/
public void addException(long fromDomainValue, long toDomainValue) {
addException(new SegmentRange(fromDomainValue, toDomainValue));
}
/**
* Adds a segment as an exception. An exception segment is defined as a
* segment to exclude from what would otherwise be considered a valid
* segment of the timeline. An exception segment can not be contained
* inside an already excluded segment. If so, no action will occur (the
* proposed exception segment will be discarded).
* <p>
* The segment is identified by a Date into any part of the segment.
*
* @param exceptionDate Date into the segment to exclude.
*/
public void addException(Date exceptionDate) {
addException(getTime(exceptionDate));
//addException(exceptionDate.getTime());
}
/**
* Adds a list of dates as segment exceptions. Each exception segment is
* defined as a segment to exclude from what would otherwise be considered
* a valid segment of the timeline. An exception segment can not be
* contained inside an already excluded segment. If so, no action will
* occur (the proposed exception segment will be discarded).
* <p>
* The segment is identified by a Date into any part of the segment.
*
* @param exceptionList List of Date objects that identify the segments to
* exclude.
*/
public void addExceptions(List exceptionList) {
for (Iterator iter = exceptionList.iterator(); iter.hasNext();) {
addException((Date) iter.next());
}
}
/**
* Adds a segment as an exception. An exception segment is defined as a
* segment to exclude from what would otherwise be considered a valid
* segment of the timeline. An exception segment can not be contained
* inside an already excluded segment. This is verified inside this
* method, and if so, no action will occur (the proposed exception segment
* will be discarded).
*
* @param segment the segment to exclude.
*/
private void addException(Segment segment) {
if (segment.inIncludeSegments()) {
int p = binarySearchExceptionSegments(segment);
this.exceptionSegments.add(-(p + 1), segment);
}
}
/**
* Adds a segment relative to the baseTimeline as an exception. Because a
* base segment is normally larger than our segments, this may add one or
* more segment ranges to the exception list.
* <p>
* An exception segment is defined as a segment
* to exclude from what would otherwise be considered a valid segment of
* the timeline. An exception segment can not be contained inside an
* already excluded segment. If so, no action will occur (the proposed
* exception segment will be discarded).
* <p>
* The segment is identified by a domainValue into any part of the
* baseTimeline segment.
*
* @param domainValue domain value to teat as a baseTimeline exception.
*/
public void addBaseTimelineException(long domainValue) {
Segment baseSegment = this.baseTimeline.getSegment(domainValue);
if (baseSegment.inIncludeSegments()) {
// cycle through all the segments contained in the BaseTimeline
// exception segment
Segment segment = getSegment(baseSegment.getSegmentStart());
while (segment.getSegmentStart() <= baseSegment.getSegmentEnd()) {
if (segment.inIncludeSegments()) {
// find all consecutive included segments
long fromDomainValue = segment.getSegmentStart();
long toDomainValue;
do {
toDomainValue = segment.getSegmentEnd();
segment.inc();
}
while (segment.inIncludeSegments());
// add the interval as an exception
addException(fromDomainValue, toDomainValue);
}
else {
// this is not one of our included segment, skip it
segment.inc();
}
}
}
}
/**
* Adds a segment relative to the baseTimeline as an exception. An
* exception segment is defined as a segment to exclude from what would
* otherwise be considered a valid segment of the timeline. An exception
* segment can not be contained inside an already excluded segment. If so,
* no action will occure (the proposed exception segment will be discarded).
* <p>
* The segment is identified by a domainValue into any part of the segment.
* Therefore the segmentStart <= domainValue <= segmentEnd.
*
* @param date date domain value to treat as a baseTimeline exception
*/
public void addBaseTimelineException(Date date) {
addBaseTimelineException(getTime(date));
}
/**
* Adds all excluded segments from the BaseTimeline as exceptions to our
* timeline. This allows us to combine two timelines for more complex
* calculations.
*
* @param fromBaseDomainValue Start of the range where exclusions will be
* extracted.
* @param toBaseDomainValue End of the range to process.
*/
public void addBaseTimelineExclusions(long fromBaseDomainValue,
long toBaseDomainValue) {
// find first excluded base segment starting fromDomainValue
Segment baseSegment = this.baseTimeline.getSegment(fromBaseDomainValue);
while (baseSegment.getSegmentStart() <= toBaseDomainValue
&& !baseSegment.inExcludeSegments()) {
baseSegment.inc();
}
// cycle over all the base segments groups in the range
while (baseSegment.getSegmentStart() <= toBaseDomainValue) {
long baseExclusionRangeEnd = baseSegment.getSegmentStart()
+ this.baseTimeline.getSegmentsExcluded()
* this.baseTimeline.getSegmentSize() - 1;
// cycle through all the segments contained in the base exclusion
// area
Segment segment = getSegment(baseSegment.getSegmentStart());
while (segment.getSegmentStart() <= baseExclusionRangeEnd) {
if (segment.inIncludeSegments()) {
// find all consecutive included segments
long fromDomainValue = segment.getSegmentStart();
long toDomainValue;
do {
toDomainValue = segment.getSegmentEnd();
segment.inc();
}
while (segment.inIncludeSegments());
// add the interval as an exception
addException(new BaseTimelineSegmentRange(
fromDomainValue, toDomainValue));
}
else {
// this is not one of our included segment, skip it
segment.inc();
}
}
// go to next base segment group
baseSegment.inc(this.baseTimeline.getGroupSegmentCount());
}
}
/**
* Returns the number of exception segments wholly contained in the
* (fromDomainValue, toDomainValue) interval.
*
* @param fromMillisecond the beginning of the interval.
* @param toMillisecond the end of the interval.
*
* @return Number of exception segments contained in the interval.
*/
public long getExceptionSegmentCount(long fromMillisecond,
long toMillisecond) {
if (toMillisecond < fromMillisecond) {
return (0);
}
int n = 0;
for (Iterator iter = this.exceptionSegments.iterator();
iter.hasNext();) {
Segment segment = (Segment) iter.next();
Segment intersection = segment.intersect(fromMillisecond,
toMillisecond);
if (intersection != null) {
n += intersection.getSegmentCount();
}
}
return (n);
}
/**
* Returns a segment that contains a domainValue. If the domainValue is
* not contained in the timeline (because it is not contained in the
* baseTimeline), a Segment that contains
* <code>index + segmentSize*m</code> will be returned for the smallest
* <code>m</code> possible.
*
* @param millisecond index into the segment
*
* @return A Segment that contains index, or the next possible Segment.
*/
public Segment getSegment(long millisecond) {
return new Segment(millisecond);
}
/**
* Returns a segment that contains a date. For accurate calculations,
* the calendar should use TIME_ZONE for its calculation (or any other
* similar time zone).
*
* If the date is not contained in the timeline (because it is not
* contained in the baseTimeline), a Segment that contains
* <code>date + segmentSize*m</code> will be returned for the smallest
* <code>m</code> possible.
*
* @param date date into the segment
*
* @return A Segment that contains date, or the next possible Segment.
*/
public Segment getSegment(Date date) {
return (getSegment(getTime(date)));
}
/**
* Convenient method to test equality in two objects, taking into account
* nulls.
*
* @param o first object to compare
* @param p second object to compare
*
* @return <code>true</code> if both objects are equal or both
* <code>null</code>, <code>false</code> otherwise.
*/
private boolean equals(Object o, Object p) {
return (o == p || ((o != null) && o.equals(p)));
}
/**
* Returns true if we are equal to the parameter
*
* @param o Object to verify with us
*
* @return <code>true</code> or <code>false</code>
*/
public boolean equals(Object o) {
if (o instanceof SegmentedTimeline) {
SegmentedTimeline other = (SegmentedTimeline) o;
boolean b0 = (this.segmentSize == other.getSegmentSize());
boolean b1 = (this.segmentsIncluded == other.getSegmentsIncluded());
boolean b2 = (this.segmentsExcluded == other.getSegmentsExcluded());
boolean b3 = (this.startTime == other.getStartTime());
boolean b4 = equals(this.exceptionSegments,
other.getExceptionSegments());
return b0 && b1 && b2 && b3 && b4;
}
else {
return (false);
}
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
public int hashCode() {
int result = 19;
result = 37 * result
+ (int) (this.segmentSize ^ (this.segmentSize >>> 32));
result = 37 * result + (int) (this.startTime ^ (this.startTime >>> 32));
return result;
}
/**
* Preforms a binary serach in the exceptionSegments sorted array. This
* array can contain Segments or SegmentRange objects.
*
* @param segment the key to be searched for.
*
* @return index of the search segment, if it is contained in the list;
* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
* <i>insertion point</i> is defined as the point at which the
* segment would be inserted into the list: the index of the first
* element greater than the key, or <tt>list.size()</tt>, if all
* elements in the list are less than the specified segment. Note
* that this guarantees that the return value will be >= 0 if
* and only if the key is found.
*/
private int binarySearchExceptionSegments(Segment segment) {
int low = 0;
int high = this.exceptionSegments.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
Segment midSegment = (Segment) this.exceptionSegments.get(mid);
// first test for equality (contains or contained)
if (segment.contains(midSegment) || midSegment.contains(segment)) {
return mid;
}
if (midSegment.before(segment)) {
low = mid + 1;
}
else if (midSegment.after(segment)) {
high = mid - 1;
}
else {
throw new IllegalStateException("Invalid condition.");
}
}
return -(low + 1); // key not found
}
/**
* Special method that handles conversion between the Default Time Zone and
* a UTC time zone with no DST. This is needed so all days have the same
* size. This method is the prefered way of converting a Data into
* milliseconds for usage in this class.
*
* @param date Date to convert to long.
*
* @return The milliseconds.
*/
public long getTime(Date date) {
long result = date.getTime();
if (this.adjustForDaylightSaving) {
this.workingCalendar.setTime(date);
this.workingCalendarNoDST.set(
this.workingCalendar.get(Calendar.YEAR),
this.workingCalendar.get(Calendar.MONTH),
this.workingCalendar.get(Calendar.DATE),
this.workingCalendar.get(Calendar.HOUR_OF_DAY),
this.workingCalendar.get(Calendar.MINUTE),
this.workingCalendar.get(Calendar.SECOND));
this.workingCalendarNoDST.set(Calendar.MILLISECOND,
this.workingCalendar.get(Calendar.MILLISECOND));
Date revisedDate = this.workingCalendarNoDST.getTime();
result = revisedDate.getTime();
}
return result;
}
/**
* Converts a millisecond value into a {@link Date} object.
*
* @param value the millisecond value.
*
* @return The date.
*/
public Date getDate(long value) {
this.workingCalendarNoDST.setTime(new Date(value));
return (this.workingCalendarNoDST.getTime());
}
/**
* Returns a clone of the timeline.
*
* @return A clone.
*
* @throws CloneNotSupportedException ??.
*/
public Object clone() throws CloneNotSupportedException {
SegmentedTimeline clone = (SegmentedTimeline) super.clone();
return clone;
}
/**
* Internal class to represent a valid segment for this timeline. A segment
* is valid on a timeline if it is part of its included, excluded or
* exception segments.
* <p>
* Each segment will know its segment number, segmentStart, segmentEnd and
* index inside the segment.
*/
public class Segment implements Comparable, Cloneable, Serializable {
/** The segment number. */
protected long segmentNumber;
/** The segment start. */
protected long segmentStart;
/** The segment end. */
protected long segmentEnd;
/** A reference point within the segment. */
protected long millisecond;
/**
* Protected constructor only used by sub-classes.
*/
protected Segment() {
// empty
}
/**
* Creates a segment for a given point in time.
*
* @param millisecond the millisecond (as encoded by java.util.Date).
*/
protected Segment(long millisecond) {
this.segmentNumber = calculateSegmentNumber(millisecond);
this.segmentStart = SegmentedTimeline.this.startTime
+ this.segmentNumber * SegmentedTimeline.this.segmentSize;
this.segmentEnd
= this.segmentStart + SegmentedTimeline.this.segmentSize - 1;
this.millisecond = millisecond;
}
/**
* Calculates the segment number for a given millisecond.
*
* @param millis the millisecond (as encoded by java.util.Date).
*
* @return The segment number.
*/
public long calculateSegmentNumber(long millis) {
if (millis >= SegmentedTimeline.this.startTime) {
return (millis - SegmentedTimeline.this.startTime)
/ SegmentedTimeline.this.segmentSize;
}
else {
return ((millis - SegmentedTimeline.this.startTime)
/ SegmentedTimeline.this.segmentSize) - 1;
}
}
/**
* Returns the segment number of this segment. Segments start at 0.
*
* @return The segment number.
*/
public long getSegmentNumber() {
return this.segmentNumber;
}
/**
* Returns always one (the number of segments contained in this
* segment).
*
* @return The segment count (always 1 for this class).
*/
public long getSegmentCount() {
return 1;
}
/**
* Gets the start of this segment in ms.
*
* @return The segment start.
*/
public long getSegmentStart() {
return this.segmentStart;
}
/**
* Gets the end of this segment in ms.
*
* @return The segment end.
*/
public long getSegmentEnd() {
return this.segmentEnd;
}
/**
* Returns the millisecond used to reference this segment (always
* between the segmentStart and segmentEnd).
*
* @return The millisecond.
*/
public long getMillisecond() {
return this.millisecond;
}
/**
* Returns a {@link java.util.Date} that represents the reference point
* for this segment.
*
* @return The date.
*/
public Date getDate() {
return SegmentedTimeline.this.getDate(this.millisecond);
}
/**
* Returns true if a particular millisecond is contained in this
* segment.
*
* @param millis the millisecond to verify.
*
* @return <code>true</code> if the millisecond is contained in the
* segment.
*/
public boolean contains(long millis) {
return (this.segmentStart <= millis && millis <= this.segmentEnd);
}
/**
* Returns <code>true</code> if an interval is contained in this
* segment.
*
* @param from the start of the interval.
* @param to the end of the interval.
*
* @return <code>true</code> if the interval is contained in the
* segment.
*/
public boolean contains(long from, long to) {
return (this.segmentStart <= from && to <= this.segmentEnd);
}
/**
* Returns <code>true</code> if a segment is contained in this segment.
*
* @param segment the segment to test for inclusion
*
* @return <code>true</code> if the segment is contained in this
* segment.
*/
public boolean contains(Segment segment) {
return contains(segment.getSegmentStart(), segment.getSegmentEnd());
}
/**
* Returns <code>true</code> if this segment is contained in an
* interval.
*
* @param from the start of the interval.
* @param to the end of the interval.
*
* @return <code>true</code> if this segment is contained in the
* interval.
*/
public boolean contained(long from, long to) {
return (from <= this.segmentStart && this.segmentEnd <= to);
}
/**
* Returns a segment that is the intersection of this segment and the
* interval.
*
* @param from the start of the interval.
* @param to the end of the interval.
*
* @return A segment.
*/
public Segment intersect(long from, long to) {
if (from <= this.segmentStart && this.segmentEnd <= to) {
return this;
}
else {
return null;
}
}
/**
* Returns <code>true</code> if this segment is wholly before another
* segment.
*
* @param other the other segment.
*
* @return A boolean.
*/
public boolean before(Segment other) {
return (this.segmentEnd < other.getSegmentStart());
}
/**
* Returns <code>true</code> if this segment is wholly after another
* segment.
*
* @param other the other segment.
*
* @return A boolean.
*/
public boolean after(Segment other) {
return (this.segmentStart > other.getSegmentEnd());
}
/**
* Tests an object (usually another <code>Segment</code>) for equality
* with this segment.
*
* @param object The other segment to compare with us
*
* @return <code>true</code> if we are the same segment
*/
public boolean equals(Object object) {
if (object instanceof Segment) {
Segment other = (Segment) object;
return (this.segmentNumber == other.getSegmentNumber()
&& this.segmentStart == other.getSegmentStart()
&& this.segmentEnd == other.getSegmentEnd()
&& this.millisecond == other.getMillisecond());
}
else {
return false;
}
}
/**
* Returns a copy of ourselves or <code>null</code> if there was an
* exception during cloning.
*
* @return A copy of this segment.
*/
public Segment copy() {
try {
return (Segment) this.clone();
}
catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Will compare this Segment with another Segment (from Comparable
* interface).
*
* @param object The other Segment to compare with
*
* @return -1: this < object, 0: this.equal(object) and
* +1: this > object
*/
public int compareTo(Object object) {
Segment other = (Segment) object;
if (this.before(other)) {
return -1;
}
else if (this.after(other)) {
return +1;
}
else {
return 0;
}
}
/**
* Returns true if we are an included segment and we are not an
* exception.
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean inIncludeSegments() {
if (getSegmentNumberRelativeToGroup()
< SegmentedTimeline.this.segmentsIncluded) {
return !inExceptionSegments();
}
else {
return false;
}
}
/**
* Returns true if we are an excluded segment.
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean inExcludeSegments() {
return getSegmentNumberRelativeToGroup()
>= SegmentedTimeline.this.segmentsIncluded;
}
/**
* Calculate the segment number relative to the segment group. This
* will be a number between 0 and segmentsGroup-1. This value is
* calculated from the segmentNumber. Special care is taken for
* negative segmentNumbers.
*
* @return The segment number.
*/
private long getSegmentNumberRelativeToGroup() {
long p = (this.segmentNumber
% SegmentedTimeline.this.groupSegmentCount);
if (p < 0) {
p += SegmentedTimeline.this.groupSegmentCount;
}
return p;
}
/**
* Returns true if we are an exception segment. This is implemented via
* a binary search on the exceptionSegments sorted list.
*
* If the segment is not listed as an exception in our list and we have
* a baseTimeline, a check is performed to see if the segment is inside
* an excluded segment from our base. If so, it is also considered an
* exception.
*
* @return <code>true</code> if we are an exception segment.
*/
public boolean inExceptionSegments() {
return binarySearchExceptionSegments(this) >= 0;
}
/**
* Increments the internal attributes of this segment by a number of
* segments.
*
* @param n Number of segments to increment.
*/
public void inc(long n) {
this.segmentNumber += n;
long m = n * SegmentedTimeline.this.segmentSize;
this.segmentStart += m;
this.segmentEnd += m;
this.millisecond += m;
}
/**
* Increments the internal attributes of this segment by one segment.
* The exact time incremented is segmentSize.
*/
public void inc() {
inc(1);
}
/**
* Decrements the internal attributes of this segment by a number of
* segments.
*
* @param n Number of segments to decrement.
*/
public void dec(long n) {
this.segmentNumber -= n;
long m = n * SegmentedTimeline.this.segmentSize;
this.segmentStart -= m;
this.segmentEnd -= m;
this.millisecond -= m;
}
/**
* Decrements the internal attributes of this segment by one segment.
* The exact time decremented is segmentSize.
*/
public void dec() {
dec(1);
}
/**
* Moves the index of this segment to the beginning if the segment.
*/
public void moveIndexToStart() {
this.millisecond = this.segmentStart;
}
/**
* Moves the index of this segment to the end of the segment.
*/
public void moveIndexToEnd() {
this.millisecond = this.segmentEnd;
}
}
/**
* Private internal class to represent a range of segments. This class is
* mainly used to store in one object a range of exception segments. This
* optimizes certain timelines that use a small segment size (like an
* intraday timeline) allowing them to express a day exception as one
* SegmentRange instead of multi Segments.
*/
protected class SegmentRange extends Segment {
/** The number of segments in the range. */
private long segmentCount;
/**
* Creates a SegmentRange between a start and end domain values.
*
* @param fromMillisecond start of the range
* @param toMillisecond end of the range
*/
public SegmentRange(long fromMillisecond, long toMillisecond) {
Segment start = getSegment(fromMillisecond);
Segment end = getSegment(toMillisecond);
// if (start.getSegmentStart() != fromMillisecond
// || end.getSegmentEnd() != toMillisecond) {
// + fromMillisecond + "," + toMillisecond + "]");
this.millisecond = fromMillisecond;
this.segmentNumber = calculateSegmentNumber(fromMillisecond);
this.segmentStart = start.segmentStart;
this.segmentEnd = end.segmentEnd;
this.segmentCount
= (end.getSegmentNumber() - start.getSegmentNumber() + 1);
}
/**
* Returns the number of segments contained in this range.
*
* @return The segment count.
*/
public long getSegmentCount() {
return this.segmentCount;
}
/**
* Returns a segment that is the intersection of this segment and the
* interval.
*
* @param from the start of the interval.
* @param to the end of the interval.
*
* @return The intersection.
*/
public Segment intersect(long from, long to) {
// Segment fromSegment = getSegment(from);
// fromSegment.inc();
// Segment toSegment = getSegment(to);
// toSegment.dec();
long start = Math.max(from, this.segmentStart);
long end = Math.min(to, this.segmentEnd);
// long start = Math.max(
// fromSegment.getSegmentStart(), this.segmentStart
// long end = Math.min(toSegment.getSegmentEnd(), this.segmentEnd);
if (start <= end) {
return new SegmentRange(start, end);
}
else {
return null;
}
}
/**
* Returns true if all Segments of this SegmentRenge are an included
* segment and are not an exception.
*
* @return <code>true</code> or </code>false</code>.
*/
public boolean inIncludeSegments() {
for (Segment segment = getSegment(this.segmentStart);
segment.getSegmentStart() < this.segmentEnd;
segment.inc()) {
if (!segment.inIncludeSegments()) {
return (false);
}
}
return true;
}
/**
* Returns true if we are an excluded segment.
*
* @return <code>true</code> or </code>false</code>.
*/
public boolean inExcludeSegments() {
for (Segment segment = getSegment(this.segmentStart);
segment.getSegmentStart() < this.segmentEnd;
segment.inc()) {
if (!segment.inExceptionSegments()) {
return (false);
}
}
return true;
}
public void inc(long n) {
throw new IllegalArgumentException(
"Not implemented in SegmentRange");
}
}
/**
* Special <code>SegmentRange</code> that came from the BaseTimeline.
*/
protected class BaseTimelineSegmentRange extends SegmentRange {
/**
* Constructor.
*
* @param fromDomainValue the start value.
* @param toDomainValue the end value.
*/
public BaseTimelineSegmentRange(long fromDomainValue,
long toDomainValue) {
super(fromDomainValue, toDomainValue);
}
}
}
|
package com.opengamma.strata.pricer.impl.rate;
import java.time.LocalDate;
import com.opengamma.strata.basics.index.PriceIndex;
import com.opengamma.strata.finance.rate.InflationMonthlyRateObservation;
import com.opengamma.strata.pricer.rate.RateObservationFn;
import com.opengamma.strata.pricer.rate.RatesProvider;
import com.opengamma.strata.pricer.sensitivity.PointSensitivityBuilder;
/**
* Rate observation implementation for a price index.
* <p>
* The pay-off for a unit notional is {@code (Index_End / Index_Start - 1)}, where
* start index value and end index value are simply returned by {@code RatesProvider}.
*/
public class ForwardInflationMonthlyRateObservationFn
implements RateObservationFn<InflationMonthlyRateObservation> {
/**
* Default instance.
*/
public static final ForwardInflationMonthlyRateObservationFn DEFAULT =
new ForwardInflationMonthlyRateObservationFn();
/**
* Creates an instance.
*/
public ForwardInflationMonthlyRateObservationFn() {
}
@Override
public double rate(InflationMonthlyRateObservation observation, LocalDate startDate, LocalDate endDate,
RatesProvider provider) {
PriceIndex index = observation.getIndex();
double indexStart = provider.inflationIndexRate(index, observation.getReferenceStartMonth());
double indexEnd = provider.inflationIndexRate(index, observation.getReferenceEndMonth());
return indexEnd / indexStart - 1.0d;
}
@Override
public PointSensitivityBuilder rateSensitivity(InflationMonthlyRateObservation observation, LocalDate startDate,
LocalDate endDate, RatesProvider provider) {
PriceIndex index = observation.getIndex();
double indexStartInv = 1.0 / provider.inflationIndexRate(index, observation.getReferenceStartMonth());
double indexEnd = provider.inflationIndexRate(index, observation.getReferenceEndMonth());
PointSensitivityBuilder indexStartSensitivity =
provider.inflationIndexRateSensitivity(index, observation.getReferenceStartMonth());
PointSensitivityBuilder indexEndSensitivity =
provider.inflationIndexRateSensitivity(index, observation.getReferenceEndMonth());
indexEndSensitivity = indexEndSensitivity.multipliedBy(indexStartInv);
indexStartSensitivity = indexStartSensitivity.multipliedBy(-indexEnd * indexStartInv * indexStartInv);
return indexStartSensitivity.combinedWith(indexEndSensitivity);
}
}
|
package org.jfree.chart.panel;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.event.OverlayChangeEvent;
import org.jfree.chart.plot.Crosshair;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.util.ParamChecks;
import org.jfree.text.TextUtilities;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.TextAnchor;
import org.jfree.util.ObjectUtilities;
import org.jfree.util.PublicCloneable;
/**
* An overlay for a {@link ChartPanel} that draws crosshairs on a plot.
*
* @since 1.0.13
*/
public class CrosshairOverlay extends AbstractOverlay implements Overlay,
PropertyChangeListener, PublicCloneable, Cloneable, Serializable {
/** Storage for the crosshairs along the x-axis. */
private List xCrosshairs;
/** Storage for the crosshairs along the y-axis. */
private List yCrosshairs;
/**
* Default constructor.
*/
public CrosshairOverlay() {
super();
this.xCrosshairs = new java.util.ArrayList();
this.yCrosshairs = new java.util.ArrayList();
}
/**
* Adds a crosshair against the domain axis and sends an
* {@link OverlayChangeEvent} to all registered listeners.
*
* @param crosshair the crosshair (<code>null</code> not permitted).
*
* @see #removeDomainCrosshair(org.jfree.chart.plot.Crosshair)
* @see #addRangeCrosshair(org.jfree.chart.plot.Crosshair)
*/
public void addDomainCrosshair(Crosshair crosshair) {
ParamChecks.nullNotPermitted(crosshair, "crosshair");
this.xCrosshairs.add(crosshair);
crosshair.addPropertyChangeListener(this);
fireOverlayChanged();
}
/**
* Removes a domain axis crosshair and sends an {@link OverlayChangeEvent}
* to all registered listeners.
*
* @param crosshair the crosshair (<code>null</code> not permitted).
*
* @see #addDomainCrosshair(org.jfree.chart.plot.Crosshair)
*/
public void removeDomainCrosshair(Crosshair crosshair) {
ParamChecks.nullNotPermitted(crosshair, "crosshair");
if (this.xCrosshairs.remove(crosshair)) {
crosshair.removePropertyChangeListener(this);
fireOverlayChanged();
}
}
/**
* Clears all the domain crosshairs from the overlay and sends an
* {@link OverlayChangeEvent} to all registered listeners.
*/
public void clearDomainCrosshairs() {
if (this.xCrosshairs.isEmpty()) {
return; // nothing to do
}
List crosshairs = getDomainCrosshairs();
for (int i = 0; i < crosshairs.size(); i++) {
Crosshair c = (Crosshair) crosshairs.get(i);
this.xCrosshairs.remove(c);
c.removePropertyChangeListener(this);
}
fireOverlayChanged();
}
/**
* Returns a new list containing the domain crosshairs for this overlay.
*
* @return A list of crosshairs.
*/
public List getDomainCrosshairs() {
return new ArrayList(this.xCrosshairs);
}
/**
* Adds a crosshair against the range axis and sends an
* {@link OverlayChangeEvent} to all registered listeners.
*
* @param crosshair the crosshair (<code>null</code> not permitted).
*/
public void addRangeCrosshair(Crosshair crosshair) {
ParamChecks.nullNotPermitted(crosshair, "crosshair");
this.yCrosshairs.add(crosshair);
crosshair.addPropertyChangeListener(this);
fireOverlayChanged();
}
/**
* Removes a range axis crosshair and sends an {@link OverlayChangeEvent}
* to all registered listeners.
*
* @param crosshair the crosshair (<code>null</code> not permitted).
*
* @see #addRangeCrosshair(org.jfree.chart.plot.Crosshair)
*/
public void removeRangeCrosshair(Crosshair crosshair) {
ParamChecks.nullNotPermitted(crosshair, "crosshair");
if (this.yCrosshairs.remove(crosshair)) {
crosshair.removePropertyChangeListener(this);
fireOverlayChanged();
}
}
/**
* Clears all the range crosshairs from the overlay and sends an
* {@link OverlayChangeEvent} to all registered listeners.
*/
public void clearRangeCrosshairs() {
if (this.yCrosshairs.isEmpty()) {
return; // nothing to do
}
List crosshairs = getRangeCrosshairs();
for (int i = 0; i < crosshairs.size(); i++) {
Crosshair c = (Crosshair) crosshairs.get(i);
this.yCrosshairs.remove(c);
c.removePropertyChangeListener(this);
}
fireOverlayChanged();
}
/**
* Returns a new list containing the range crosshairs for this overlay.
*
* @return A list of crosshairs.
*/
public List getRangeCrosshairs() {
return new ArrayList(this.yCrosshairs);
}
/**
* Receives a property change event (typically a change in one of the
* crosshairs).
*
* @param e the event.
*/
@Override
public void propertyChange(PropertyChangeEvent e) {
fireOverlayChanged();
}
/**
* Paints the crosshairs in the layer.
*
* @param g2 the graphics target.
* @param chartPanel the chart panel.
*/
@Override
public void paintOverlay(Graphics2D g2, ChartPanel chartPanel) {
Shape savedClip = g2.getClip();
Rectangle2D dataArea = chartPanel.getScreenDataArea();
g2.clip(dataArea);
JFreeChart chart = chartPanel.getChart();
XYPlot plot = (XYPlot) chart.getPlot();
ValueAxis xAxis = plot.getDomainAxis();
RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
Iterator iterator = this.xCrosshairs.iterator();
while (iterator.hasNext()) {
Crosshair ch = (Crosshair) iterator.next();
if (ch.isVisible()) {
double x = ch.getValue();
double xx = xAxis.valueToJava2D(x, dataArea, xAxisEdge);
if (plot.getOrientation() == PlotOrientation.VERTICAL) {
drawVerticalCrosshair(g2, dataArea, xx, ch);
}
else {
drawHorizontalCrosshair(g2, dataArea, xx, ch);
}
}
}
ValueAxis yAxis = plot.getRangeAxis();
RectangleEdge yAxisEdge = plot.getRangeAxisEdge();
iterator = this.yCrosshairs.iterator();
while (iterator.hasNext()) {
Crosshair ch = (Crosshair) iterator.next();
if (ch.isVisible()) {
double y = ch.getValue();
double yy = yAxis.valueToJava2D(y, dataArea, yAxisEdge);
if (plot.getOrientation() == PlotOrientation.VERTICAL) {
drawHorizontalCrosshair(g2, dataArea, yy, ch);
}
else {
drawVerticalCrosshair(g2, dataArea, yy, ch);
}
}
}
g2.setClip(savedClip);
}
/**
* Draws a crosshair horizontally across the plot.
*
* @param g2 the graphics target.
* @param dataArea the data area.
* @param y the y-value in Java2D space.
* @param crosshair the crosshair.
*/
protected void drawHorizontalCrosshair(Graphics2D g2, Rectangle2D dataArea,
double y, Crosshair crosshair) {
if (y >= dataArea.getMinY() && y <= dataArea.getMaxY()) {
Line2D line = new Line2D.Double(dataArea.getMinX(), y,
dataArea.getMaxX(), y);
Paint savedPaint = g2.getPaint();
Stroke savedStroke = g2.getStroke();
g2.setPaint(crosshair.getPaint());
g2.setStroke(crosshair.getStroke());
g2.draw(line);
if (crosshair.isLabelVisible()) {
String label = crosshair.getLabelGenerator().generateLabel(
crosshair);
RectangleAnchor anchor = crosshair.getLabelAnchor();
Point2D pt = calculateLabelPoint(line, anchor, 5, 5);
float xx = (float) pt.getX();
float yy = (float) pt.getY();
TextAnchor alignPt = textAlignPtForLabelAnchorH(anchor);
Shape hotspot = TextUtilities.calculateRotatedStringBounds(
label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
if (!dataArea.contains(hotspot.getBounds2D())) {
anchor = flipAnchorV(anchor);
pt = calculateLabelPoint(line, anchor, 5, 5);
xx = (float) pt.getX();
yy = (float) pt.getY();
alignPt = textAlignPtForLabelAnchorH(anchor);
hotspot = TextUtilities.calculateRotatedStringBounds(
label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
}
g2.setPaint(crosshair.getLabelBackgroundPaint());
g2.fill(hotspot);
g2.setPaint(crosshair.getLabelOutlinePaint());
g2.draw(hotspot);
TextUtilities.drawAlignedString(label, g2, xx, yy, alignPt);
}
g2.setPaint(savedPaint);
g2.setStroke(savedStroke);
}
}
/**
* Draws a crosshair vertically on the plot.
*
* @param g2 the graphics target.
* @param dataArea the data area.
* @param x the x-value in Java2D space.
* @param crosshair the crosshair.
*/
protected void drawVerticalCrosshair(Graphics2D g2, Rectangle2D dataArea,
double x, Crosshair crosshair) {
if (x >= dataArea.getMinX() && x <= dataArea.getMaxX()) {
Line2D line = new Line2D.Double(x, dataArea.getMinY(), x,
dataArea.getMaxY());
Paint savedPaint = g2.getPaint();
Stroke savedStroke = g2.getStroke();
g2.setPaint(crosshair.getPaint());
g2.setStroke(crosshair.getStroke());
g2.draw(line);
if (crosshair.isLabelVisible()) {
String label = crosshair.getLabelGenerator().generateLabel(
crosshair);
RectangleAnchor anchor = crosshair.getLabelAnchor();
Point2D pt = calculateLabelPoint(line, anchor, 5, 5);
float xx = (float) pt.getX();
float yy = (float) pt.getY();
TextAnchor alignPt = textAlignPtForLabelAnchorV(anchor);
Shape hotspot = TextUtilities.calculateRotatedStringBounds(
label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
if (!dataArea.contains(hotspot.getBounds2D())) {
anchor = flipAnchorH(anchor);
pt = calculateLabelPoint(line, anchor, 5, 5);
xx = (float) pt.getX();
yy = (float) pt.getY();
alignPt = textAlignPtForLabelAnchorV(anchor);
hotspot = TextUtilities.calculateRotatedStringBounds(
label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
}
g2.setPaint(crosshair.getLabelBackgroundPaint());
g2.fill(hotspot);
g2.setPaint(crosshair.getLabelOutlinePaint());
g2.draw(hotspot);
TextUtilities.drawAlignedString(label, g2, xx, yy, alignPt);
}
g2.setPaint(savedPaint);
g2.setStroke(savedStroke);
}
}
/**
* Calculates the anchor point for a label.
*
* @param line the line for the crosshair.
* @param anchor the anchor point.
* @param deltaX the x-offset.
* @param deltaY the y-offset.
*
* @return The anchor point.
*/
private Point2D calculateLabelPoint(Line2D line, RectangleAnchor anchor,
double deltaX, double deltaY) {
double x, y;
boolean left = (anchor == RectangleAnchor.BOTTOM_LEFT
|| anchor == RectangleAnchor.LEFT
|| anchor == RectangleAnchor.TOP_LEFT);
boolean right = (anchor == RectangleAnchor.BOTTOM_RIGHT
|| anchor == RectangleAnchor.RIGHT
|| anchor == RectangleAnchor.TOP_RIGHT);
boolean top = (anchor == RectangleAnchor.TOP_LEFT
|| anchor == RectangleAnchor.TOP
|| anchor == RectangleAnchor.TOP_RIGHT);
boolean bottom = (anchor == RectangleAnchor.BOTTOM_LEFT
|| anchor == RectangleAnchor.BOTTOM
|| anchor == RectangleAnchor.BOTTOM_RIGHT);
Rectangle rect = line.getBounds();
// we expect the line to be vertical or horizontal
if (line.getX1() == line.getX2()) { // vertical
x = line.getX1();
y = (line.getY1() + line.getY2()) / 2.0;
if (left) {
x = x - deltaX;
}
if (right) {
x = x + deltaX;
}
if (top) {
y = Math.min(line.getY1(), line.getY2()) + deltaY;
}
if (bottom) {
y = Math.max(line.getY1(), line.getY2()) - deltaY;
}
}
else { // horizontal
x = (line.getX1() + line.getX2()) / 2.0;
y = line.getY1();
if (left) {
x = Math.min(line.getX1(), line.getX2()) + deltaX;
}
if (right) {
x = Math.max(line.getX1(), line.getX2()) - deltaX;
}
if (top) {
y = y - deltaY;
}
if (bottom) {
y = y + deltaY;
}
}
return new Point2D.Double(x, y);
}
/**
* Returns the text anchor that is used to align a label to its anchor
* point.
*
* @param anchor the anchor.
*
* @return The text alignment point.
*/
private TextAnchor textAlignPtForLabelAnchorV(RectangleAnchor anchor) {
TextAnchor result = TextAnchor.CENTER;
if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
result = TextAnchor.TOP_RIGHT;
}
else if (anchor.equals(RectangleAnchor.TOP)) {
result = TextAnchor.TOP_CENTER;
}
else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
result = TextAnchor.TOP_LEFT;
}
else if (anchor.equals(RectangleAnchor.LEFT)) {
result = TextAnchor.HALF_ASCENT_RIGHT;
}
else if (anchor.equals(RectangleAnchor.RIGHT)) {
result = TextAnchor.HALF_ASCENT_LEFT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
result = TextAnchor.BOTTOM_RIGHT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM)) {
result = TextAnchor.BOTTOM_CENTER;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
result = TextAnchor.BOTTOM_LEFT;
}
return result;
}
/**
* Returns the text anchor that is used to align a label to its anchor
* point.
*
* @param anchor the anchor.
*
* @return The text alignment point.
*/
private TextAnchor textAlignPtForLabelAnchorH(RectangleAnchor anchor) {
TextAnchor result = TextAnchor.CENTER;
if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
result = TextAnchor.BOTTOM_LEFT;
}
else if (anchor.equals(RectangleAnchor.TOP)) {
result = TextAnchor.BOTTOM_CENTER;
}
else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
result = TextAnchor.BOTTOM_RIGHT;
}
else if (anchor.equals(RectangleAnchor.LEFT)) {
result = TextAnchor.HALF_ASCENT_LEFT;
}
else if (anchor.equals(RectangleAnchor.RIGHT)) {
result = TextAnchor.HALF_ASCENT_RIGHT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
result = TextAnchor.TOP_LEFT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM)) {
result = TextAnchor.TOP_CENTER;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
result = TextAnchor.TOP_RIGHT;
}
return result;
}
private RectangleAnchor flipAnchorH(RectangleAnchor anchor) {
RectangleAnchor result = anchor;
if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
result = RectangleAnchor.TOP_RIGHT;
}
else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
result = RectangleAnchor.TOP_LEFT;
}
else if (anchor.equals(RectangleAnchor.LEFT)) {
result = RectangleAnchor.RIGHT;
}
else if (anchor.equals(RectangleAnchor.RIGHT)) {
result = RectangleAnchor.LEFT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
result = RectangleAnchor.BOTTOM_RIGHT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
result = RectangleAnchor.BOTTOM_LEFT;
}
return result;
}
private RectangleAnchor flipAnchorV(RectangleAnchor anchor) {
RectangleAnchor result = anchor;
if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
result = RectangleAnchor.BOTTOM_LEFT;
}
else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
result = RectangleAnchor.BOTTOM_RIGHT;
}
else if (anchor.equals(RectangleAnchor.TOP)) {
result = RectangleAnchor.BOTTOM;
}
else if (anchor.equals(RectangleAnchor.BOTTOM)) {
result = RectangleAnchor.TOP;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
result = RectangleAnchor.TOP_LEFT;
}
else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
result = RectangleAnchor.TOP_RIGHT;
}
return result;
}
/**
* Tests this overlay for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CrosshairOverlay)) {
return false;
}
CrosshairOverlay that = (CrosshairOverlay) obj;
if (!this.xCrosshairs.equals(that.xCrosshairs)) {
return false;
}
if (!this.yCrosshairs.equals(that.yCrosshairs)) {
return false;
}
return true;
}
/**
* Returns a clone of this instance.
*
* @return A clone of this instance.
*
* @throws java.lang.CloneNotSupportedException if there is some problem
* with the cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
CrosshairOverlay clone = (CrosshairOverlay) super.clone();
clone.xCrosshairs = (List) ObjectUtilities.deepClone(this.xCrosshairs);
clone.yCrosshairs = (List) ObjectUtilities.deepClone(this.yCrosshairs);
return clone;
}
}
|
package com.baomidou.mybatisplus.extension.plugins;
import com.baomidou.mybatisplus.annotation.Version;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.*;
import lombok.Data;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* <p>
* Optimistic Lock Light version<BR>
* Intercept on {@link Executor}.update;<BR>
* Support version types: int/Integer, long/Long, java.util.Date, java.sql.Timestamp<BR>
* For extra types, please define a subclass and override {@code getUpdatedVersionVal}() method.<BR>
* <BR>
* How to use?<BR>
* (1) Define an Entity and add {@link Version} annotation on one entity field.<BR>
* (2) Add {@link OptimisticLockerInterceptor} into mybatis plugin.
* <p>
* How to work?<BR>
* if update entity with version column=1:<BR>
* (1) no {@link OptimisticLockerInterceptor}:<BR>
* SQL: update tbl_test set name='abc' where id=100001;<BR>
* (2) add {@link OptimisticLockerInterceptor}:<BR>
* SQL: update tbl_test set name='abc',version=2 where id=100001 and version=1;
* </p>
*
* @author yuxiaobin
* @since 2017/5/24
*/
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class OptimisticLockerInterceptor implements Interceptor {
public static final String MP_OPTLOCK_VERSION_ORIGINAL = "MP_OPTLOCK_VERSION_ORIGINAL";
public static final String MP_OPTLOCK_VERSION_COLUMN = "MP_OPTLOCK_VERSION_COLUMN";
public static final String MP_OPTLOCK_ET_ORIGINAL = "MP_OPTLOCK_ET_ORIGINAL";
private static final String NAME_ENTITY = Constants.ENTITY;
private static final String NAME_ENTITY_WRAPPER = Constants.WRAPPER;
private static final String PARAM_UPDATE_METHOD_NAME = "update";
private final Map<Class<?>, EntityField> versionFieldCache = new ConcurrentHashMap<>();
private final Map<Class<?>, List<EntityField>> entityFieldsCache = new ConcurrentHashMap<>();
@Override
@SuppressWarnings("unchecked")
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
if (SqlCommandType.UPDATE != ms.getSqlCommandType()) {
return invocation.proceed();
}
Object param = args[1];
// JavaBean class
Class<?> entityClass = null;
// optimistic, Version Field
Field versionField = null;
// optimistic field annotated by Version
String versionColumnName = null;
// new version value, Long, Integer ...
Object updatedVersionVal = null;
// wrapper = ew
Wrapper ew = null;
// entity = et
Object et = null;
if (param instanceof Map) {
Map map = (Map) param;
if (map.containsKey(NAME_ENTITY_WRAPPER)) {
// mapper.update(updEntity, QueryWrapper<>(whereEntity);
ew = (Wrapper) map.get(NAME_ENTITY_WRAPPER);
}
//else updateById(entity) -->> change updateById(entity) to updateById(@Param("et") entity)
// TODO
// if mannual sql or updagteById(entity),unsupport OCC,proceed as usual unless use updateById(@Param("et") entity)
//if(!map.containsKey(NAME_ENTITY)) {
// return invocation.proceed();
if (map.containsKey(NAME_ENTITY)) {
et = map.get(NAME_ENTITY);
}
if (ew != null) { // entityWrapper. baseMapper.update(et,ew);
Object entity = ew.getEntity();
if (entity != null) {
entityClass = ClassUtils.getUserClass(entity.getClass());
EntityField ef = getVersionField(entityClass);
versionField = ef == null ? null : ef.getField();
if (versionField != null) {
Object originalVersionVal = versionField.get(entity);
if (originalVersionVal != null) {
updatedVersionVal = getUpdatedVersionVal(originalVersionVal);
versionField.set(et, updatedVersionVal);
}
}
}
} else if (et != null) { // entity
String methodId = ms.getId();
String updateMethodName = methodId.substring(ms.getId().lastIndexOf(StringPool.DOT) + 1);
if (PARAM_UPDATE_METHOD_NAME.equals(updateMethodName)) {
// update(entityClass, null) -->> update all. ignore version
return invocation.proceed();
}
//invoke: baseMapper.updateById()
entityClass = ClassUtils.getUserClass(et.getClass());
EntityField entityField = this.getVersionField(entityClass);
versionField = entityField == null ? null : entityField.getField();
Object originalVersionVal;
if (versionField != null && (originalVersionVal = versionField.get(et)) != null) {
TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
// fixed github 299
while (null == tableInfo && null != entityClass) {
entityClass = ClassUtils.getUserClass(entityClass.getSuperclass());
tableInfo = TableInfoHelper.getTableInfo(entityClass);
}
Map<String, Object> entityMap = new HashMap<>();
List<EntityField> fields = getEntityFields(entityClass);
for (EntityField ef : fields) {
Field fd = ef.getField();
if (fd.isAccessible()) {
entityMap.put(fd.getName(), fd.get(et));
if (ef.isVersion()) {
versionField = fd;
}
}
}
String versionPropertyName = versionField.getName();
List<TableFieldInfo> fieldList = tableInfo.getFieldList();
versionColumnName = entityField.getColumnName();
if (versionColumnName == null) {
for (TableFieldInfo tf : fieldList) {
if (versionPropertyName.equals(tf.getProperty())) {
versionColumnName = tf.getColumn();
}
}
}
if (versionColumnName != null) {
entityField.setColumnName(versionColumnName);
updatedVersionVal = getUpdatedVersionVal(originalVersionVal);
entityMap.put(versionField.getName(), updatedVersionVal);
entityMap.put(MP_OPTLOCK_VERSION_ORIGINAL, originalVersionVal);
entityMap.put(MP_OPTLOCK_VERSION_COLUMN, versionColumnName);
entityMap.put(MP_OPTLOCK_ET_ORIGINAL, et);
map.put(NAME_ENTITY, entityMap);
}
}
}
}
Object resultObj = invocation.proceed();
if (resultObj instanceof Integer) {
Integer effRow = (Integer) resultObj;
if (effRow != 0 && et != null && versionField != null && updatedVersionVal != null) {
//updated version value set to entity.
versionField.set(et, updatedVersionVal);
}
}
return resultObj;
}
/**
* This method provides the control for version value.<BR>
* Returned value type must be the same as original one.
*
* @param originalVersionVal
* @return updated version val
*/
protected Object getUpdatedVersionVal(Object originalVersionVal) {
Class<?> versionValClass = originalVersionVal.getClass();
if (long.class.equals(versionValClass)) {
return ((long) originalVersionVal) + 1;
} else if (Long.class.equals(versionValClass)) {
return ((Long) originalVersionVal) + 1;
} else if (int.class.equals(versionValClass)) {
return ((int) originalVersionVal) + 1;
} else if (Integer.class.equals(versionValClass)) {
return ((Integer) originalVersionVal) + 1;
} else if (Date.class.equals(versionValClass)) {
return new Date();
} else if (Timestamp.class.equals(versionValClass)) {
return new Timestamp(System.currentTimeMillis());
} else if (LocalDateTime.class.equals(versionValClass)) {
return LocalDateTime.now();
}
return originalVersionVal;//not supported type, return original val.
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties properties) {
// to do nothing
}
private EntityField getVersionField(Class<?> parameterClass) {
synchronized (parameterClass.getName()) {
if (versionFieldCache.containsKey(parameterClass)) {
return versionFieldCache.get(parameterClass);
}
EntityField field = this.getVersionFieldRegular(parameterClass);
if (field != null) {
versionFieldCache.put(parameterClass, field);
return field;
}
return null;
}
}
/**
* <p>
*
* </p>
*
* @param parameterClass
* @return
*/
private EntityField getVersionFieldRegular(Class<?> parameterClass) {
if (parameterClass != Object.class) {
for (Field field : parameterClass.getDeclaredFields()) {
if (field.isAnnotationPresent(Version.class)) {
field.setAccessible(true);
return new EntityField(field, true);
}
}
return this.getVersionFieldRegular(parameterClass.getSuperclass());
}
return null;
}
private List<EntityField> getEntityFields(Class<?> parameterClass) {
if (entityFieldsCache.containsKey(parameterClass)) {
return entityFieldsCache.get(parameterClass);
}
List<EntityField> fields = this.getFieldsFromClazz(parameterClass, null);
entityFieldsCache.put(parameterClass, fields);
return fields;
}
private List<EntityField> getFieldsFromClazz(Class<?> parameterClass, List<EntityField> fieldList) {
if (fieldList == null) {
fieldList = new ArrayList<>();
}
List<Field> fields = ReflectionKit.getFieldList(parameterClass);
for (Field field : fields) {
field.setAccessible(true);
if (field.isAnnotationPresent(Version.class)) {
fieldList.add(new EntityField(field, true));
} else {
fieldList.add(new EntityField(field, false));
}
}
return fieldList;
}
@Data
private class EntityField {
private Field field;
private boolean version;
private String columnName;
EntityField(Field field, boolean version) {
this.field = field;
this.version = version;
}
}
}
|
package org.nuxeo.ecm.platform.mail.utils;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.CORE_SESSION_ID_KEY;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.EMAILS_LIMIT_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.EMAIL_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.HOST_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.IMAP;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.MIMETYPE_SERVICE_KEY;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PARENT_PATH_KEY;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PASSWORD_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PORT_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PROTOCOL_TYPE_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.SOCKET_FACTORY_FALLBACK_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.SOCKET_FACTORY_PORT_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.SSL_PROTOCOLS_PROPERTY_NAME;
import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.STARTTLS_ENABLE_PROPERTY_NAME;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.platform.mail.action.ExecutionContext;
import org.nuxeo.ecm.platform.mail.action.MessageActionPipe;
import org.nuxeo.ecm.platform.mail.action.Visitor;
import org.nuxeo.ecm.platform.mail.service.MailService;
import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry;
import org.nuxeo.runtime.api.Framework;
/**
* Helper of Mail Core
*
* @author <a href="mailto:[email protected]">Catalin Baican</a>
*
*/
public final class MailCoreHelper {
private static final Log log = LogFactory.getLog(MailCoreHelper.class);
public static final String PIPE_NAME = "nxmail";
public static final String INBOX = "INBOX";
public static final String DELETED_LIFECYCLE_STATE = "deleted";
public static final long EMAILS_LIMIT_DEFAULT = 100;
private static MailService mailService;
private static MimetypeRegistry mimeService;
private MailCoreHelper() {
}
private static MailService getMailService() {
if (mailService == null) {
try {
mailService = Framework.getService(MailService.class);
} catch (Exception e) {
log.error("Exception in get mail service");
}
}
return mailService;
}
private static MimetypeRegistry getMimeService() {
if (mimeService == null) {
try {
mimeService = Framework.getService(MimetypeRegistry.class);
} catch (Exception e) {
log.error("Exception in get mime service");
}
}
return mimeService;
}
/**
* Creates MailMessage documents for every unread mail found in the INBOX.
* The parameters needed to connect to the email INBOX are retrieved from
* the MailFolder document passed as a parameter.
*
* @param currentMailFolder
* @param coreSession
* @throws Exception
*/
public static void checkMail(DocumentModel currentMailFolder,
CoreSession coreSession) throws Exception {
String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
mailService = getMailService();
MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);
Visitor visitor = new Visitor(pipe);
Thread.currentThread().setContextClassLoader(
Framework.class.getClassLoader());
// initialize context
ExecutionContext initialExecutionContext = new ExecutionContext();
initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());
initialExecutionContext.put(PARENT_PATH_KEY,
currentMailFolder.getPathAsString());
initialExecutionContext.put(CORE_SESSION_ID_KEY,
coreSession.getSessionId());
Folder rootFolder = null;
try {
String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
Boolean socketFactoryFallback = (Boolean) currentMailFolder.getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
String socketFactoryPort = (String) currentMailFolder.getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
Boolean starttlsEnable = (Boolean) currentMailFolder.getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT
: emailsLimit.longValue();
Properties properties = new Properties();
properties.put("mail.store.protocol", protocolType);
// Is IMAP connection
if (IMAP.equals(protocolType)) {
properties.put("mail.imap.host", host);
properties.put("mail.imap.port", port);
properties.put("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.imap.socketFactory.fallback",
socketFactoryFallback.toString());
properties.put("mail.imap.socketFactory.port",
socketFactoryPort);
properties.put("mail.imap.starttls.enable",
starttlsEnable.toString());
properties.put("mail.imap.ssl.protocols", sslProtocols);
} else {
// Is POP3 connection
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", port);
properties.put("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.pop3.socketFactory.fallback",
socketFactoryFallback.toString());
properties.put("mail.pop3.socketFactory.port",
socketFactoryPort);
}
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore();
store.connect(email, password);
rootFolder = store.getFolder(INBOX);
rootFolder.open(Folder.READ_WRITE);
Message[] allMessages = rootFolder.getMessages();
FetchProfile fetchProfile = new FetchProfile();
fetchProfile.add(FetchProfile.Item.FLAGS);
rootFolder.fetch(allMessages, fetchProfile);
List<Message> unreadMessagesList = new ArrayList<Message>();
for (int i = 0; i < allMessages.length; i++) {
Flags flags = allMessages[i].getFlags();
int unreadMessagesListSize = unreadMessagesList.size();
if (flags != null && !flags.contains(Flag.SEEN)
&& unreadMessagesListSize < emailsLimitLongValue) {
unreadMessagesList.add(allMessages[i]);
if (unreadMessagesListSize == emailsLimitLongValue - 1) {
break;
}
}
}
// perform email import
visitor.visit(
unreadMessagesList.toArray(new Message[unreadMessagesList.size()]),
initialExecutionContext);
} finally {
if (rootFolder != null && rootFolder.isOpen()) {
rootFolder.close(true);
}
}
}
}
}
|
package org.opendaylight.controller.test.sal.binding.it;
import static org.ops4j.pax.exam.CoreOptions.frameworkProperty;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemPackages;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.DefaultCompositeOption;
import org.ops4j.pax.exam.util.PathUtils;
/**
* @deprecated Use config-it and/or mdsal-it instead.
*/
@Deprecated
public class TestHelper {
public static final String CONTROLLER = "org.opendaylight.controller";
public static final String MDSAL = "org.opendaylight.mdsal";
public static final String YANGTOOLS = "org.opendaylight.yangtools";
public static final String CONTROLLER_MODELS = "org.opendaylight.controller.model";
public static final String MDSAL_MODELS = "org.opendaylight.mdsal.model";
public static Option mdSalCoreBundles() {
return new DefaultCompositeOption(
mavenBundle(YANGTOOLS, "concepts").versionAsInProject(),
mavenBundle(YANGTOOLS, "util").versionAsInProject(),
mavenBundle(MDSAL, "yang-binding").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-common").versionAsInProject(),
mavenBundle(YANGTOOLS, "object-cache-api").versionAsInProject(),
mavenBundle(YANGTOOLS, "object-cache-guava").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-common-api").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-common-impl").versionAsInProject(),
mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),
mavenBundle("com.google.guava", "guava").versionAsInProject(),
mavenBundle("com.github.romix", "java-concurrent-hash-trie-map").versionAsInProject()
);
}
public static Option configMinumumBundles() {
return new DefaultCompositeOption(
mavenBundle(CONTROLLER, "config-api").versionAsInProject(),
bindingAwareSalBundles(),
mavenBundle("commons-codec", "commons-codec").versionAsInProject(),
systemPackages("sun.nio.ch", "sun.misc"),
mavenBundle(CONTROLLER, "config-manager").versionAsInProject(),
mavenBundle(CONTROLLER, "config-util").versionAsInProject(),
mavenBundle("commons-io", "commons-io").versionAsInProject(),
mavenBundle(CONTROLLER, "config-manager-facade-xml").versionAsInProject(),
mavenBundle(CONTROLLER, "yang-jmx-generator").versionAsInProject(),
mavenBundle(CONTROLLER, "logback-config").versionAsInProject(),
mavenBundle(CONTROLLER, "config-persister-api").versionAsInProject(),
mavenBundle(CONTROLLER, "config-persister-impl").versionAsInProject(),
mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xerces", "2.11.0_1"),
mavenBundle("org.eclipse.birt.runtime.3_7_1", "org.apache.xml.resolver", "1.2.0"),
mavenBundle(CONTROLLER, "config-persister-file-xml-adapter").versionAsInProject().noStart(),
mavenBundle("org.eclipse.persistence", "org.eclipse.persistence.moxy").versionAsInProject(),
mavenBundle("org.eclipse.persistence", "org.eclipse.persistence.core").versionAsInProject());
}
public static Option bindingAwareSalBundles() {
return new DefaultCompositeOption(
mdSalCoreBundles(),
mavenBundle("org.javassist", "javassist").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-data-api").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-data-util").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-data-impl").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-model-api").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-model-util").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-parser-api").versionAsInProject(),
mavenBundle(YANGTOOLS, "yang-parser-impl").versionAsInProject(),
mavenBundle(MDSAL, "mdsal-binding-generator-api").versionAsInProject(),
mavenBundle(MDSAL, "mdsal-binding-generator-util").versionAsInProject(),
mavenBundle(MDSAL, "mdsal-binding-generator-impl").versionAsInProject(),
mavenBundle(MDSAL, "mdsal-binding-dom-codec").versionAsInProject(),
mavenBundle("org.antlr", "antlr4-runtime").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-binding-util").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-common-util").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-core-api").versionAsInProject().update(),
mavenBundle(CONTROLLER, "sal-binding-api").versionAsInProject(),
mavenBundle("com.lmax", "disruptor").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-broker-impl").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-dom-config").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-inmemory-datastore").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-dom-broker-config").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-core-spi").versionAsInProject().update(),
mavenBundle(CONTROLLER, "sal-binding-broker-impl").versionAsInProject(),
mavenBundle(CONTROLLER, "sal-binding-config").versionAsInProject(),
systemProperty("netconf.config.persister.active").value("1"),
systemProperty("netconf.config.persister.1.storageAdapterClass").value(
"org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter"),
systemProperty("netconf.config.persister.1.properties.fileStorage")
.value(PathUtils.getBaseDir() + "/src/test/resources/controller.xml"),
systemProperty("netconf.config.persister.1.properties.numberOfBackups").value("1")
);
}
public static Option bindingIndependentSalBundles() {
return new DefaultCompositeOption(
);
}
public static Option protocolFrameworkBundles() {
return new DefaultCompositeOption(
mavenBundle("io.netty", "netty-common").versionAsInProject(),
mavenBundle("io.netty", "netty-buffer").versionAsInProject(),
mavenBundle("io.netty", "netty-handler").versionAsInProject(),
mavenBundle("io.netty", "netty-codec").versionAsInProject(),
mavenBundle("io.netty", "netty-transport").versionAsInProject(),
mavenBundle(CONTROLLER, "netty-config-api").versionAsInProject(),
mavenBundle(CONTROLLER, "protocol-framework").versionAsInProject()
);
}
public static Option flowCapableModelBundles() {
return new DefaultCompositeOption(
mavenBundle(CONTROLLER_MODELS, "model-inventory").versionAsInProject()
);
}
/**
* @return option containing models for testing purposes
*/
public static Option salTestModelBundles() {
return new DefaultCompositeOption(
mavenBundle(CONTROLLER, "sal-test-model").versionAsInProject()
);
}
public static Option baseModelBundles() {
return new DefaultCompositeOption(
mavenBundle(MDSAL+".model", "yang-ext").versionAsInProject(),
mavenBundle(MDSAL_MODELS, "ietf-type-util").versionAsInProject(),
mavenBundle(MDSAL_MODELS, "ietf-inet-types").versionAsInProject(),
mavenBundle(MDSAL_MODELS, "ietf-yang-types").versionAsInProject(),
mavenBundle(MDSAL_MODELS, "opendaylight-l2-types").versionAsInProject()
);
}
public static Option junitAndMockitoBundles() {
return new DefaultCompositeOption(
// Repository required to load harmcrest (OSGi-fied version).
// Mockito
mavenBundle("org.mockito", "mockito-core", "1.10.19"),
mavenBundle("org.objenesis", "objenesis", "2.2"),
junitBundles(),
/*
* Felix has implicit boot delegation enabled by default. It
* conflicts with Mockito: java.lang.LinkageError: loader
* constraint violation in interface itable initialization: when
* resolving method
* "org.osgi.service.useradmin.User$$EnhancerByMockitoWithCGLIB$$dd2f81dc
* .
* newInstance(Lorg/mockito/cglib/proxy/Callback;)Ljava/lang/Object
* ;" the class loader (instance of
* org/mockito/internal/creation/jmock/SearchingClassLoader) of
* the current class, org/osgi/service/useradmin/
* User$$EnhancerByMockitoWithCGLIB$$dd2f81dc, and the class
* loader (instance of org/apache/felix/framework/
* BundleWiringImpl$BundleClassLoaderJava5) for interface
* org/mockito/cglib/proxy/Factory have different Class objects
* for the type org/mockito/cglib/ proxy/Callback used in the
* signature
*
* So we disable the bootdelegation. this property has no effect
* on the other OSGi implementation.
*/
frameworkProperty("felix.bootdelegation.implicit").value("false"));
}
}
|
package com.intellij.internal.statistic.collectors.fus.fileTypes;
import com.intellij.internal.statistic.beans.UsageDescriptor;
import com.intellij.internal.statistic.eventLog.FeatureUsageData;
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector;
import com.intellij.internal.statistic.utils.PluginInfo;
import com.intellij.internal.statistic.utils.PluginInfoDetectorKt;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.project.ProjectKt;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class FileTypeUsagesCollector extends ProjectUsagesCollector {
private static final String DEFAULT_ID = "third.party";
@NotNull
@Override
public String getGroupId() {
return "file.types";
}
@NotNull
@Override
public Set<UsageDescriptor> getUsages(@NotNull final Project project) {
return getDescriptors(project);
}
@NotNull
public static Set<UsageDescriptor> getDescriptors(@NotNull Project project) {
final Set<UsageDescriptor> descriptors = new HashSet<>();
final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
if (fileTypeManager == null) {
return Collections.emptySet();
}
final FileType[] registeredFileTypes = fileTypeManager.getRegisteredFileTypes();
for (final FileType fileType : registeredFileTypes) {
if (project.isDisposed()) {
return Collections.emptySet();
}
final FeatureUsageData data = new FeatureUsageData();
final String id = toReportedId(fileType, data);
ApplicationManager.getApplication().runReadAction(() -> {
FileTypeIndex.processFiles(fileType, file -> {
//skip files from .idea directory otherwise 99% of projects would have XML and PLAIN_TEXT file types
if (!ProjectKt.getStateStore(project).isProjectFile(file)) {
descriptors.add(new UsageDescriptor(id, 1, data));
return false;
}
return true;
}, GlobalSearchScope.projectScope(project));
});
}
return descriptors;
}
@NotNull
public static String toReportedId(@NotNull FileType type, @NotNull FeatureUsageData data) {
final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(type.getClass());
data.addPluginInfo(info);
return info.isDevelopedByJetBrains() ? type.getName() : DEFAULT_ID;
}
}
|
package org.pocketcampus.plugin.freeroom.android.views;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.tracker.Tracker;
import org.pocketcampus.android.platform.sdk.ui.element.InputBarElement;
import org.pocketcampus.android.platform.sdk.ui.element.OnKeyPressedListener;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout;
import org.pocketcampus.android.platform.sdk.ui.list.LabeledListViewElement;
import org.pocketcampus.plugin.freeroom.R;
import org.pocketcampus.plugin.freeroom.android.FreeRoomAbstractView;
import org.pocketcampus.plugin.freeroom.android.FreeRoomController;
import org.pocketcampus.plugin.freeroom.android.FreeRoomModel;
import org.pocketcampus.plugin.freeroom.android.adapter.ActualOccupationArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewFavoriteAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.FRRoomSuggestionArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.iface.IFreeRoomView;
import org.pocketcampus.plugin.freeroom.android.utils.FRRequestDetails;
import org.pocketcampus.plugin.freeroom.android.utils.FRTimesClient;
import org.pocketcampus.plugin.freeroom.android.utils.FRUtilsClient;
import org.pocketcampus.plugin.freeroom.android.utils.OrderMapListFew;
import org.pocketcampus.plugin.freeroom.android.utils.SetArrayList;
import org.pocketcampus.plugin.freeroom.shared.ActualOccupation;
import org.pocketcampus.plugin.freeroom.shared.AutoCompleteRequest;
import org.pocketcampus.plugin.freeroom.shared.FRPeriod;
import org.pocketcampus.plugin.freeroom.shared.FRRequest;
import org.pocketcampus.plugin.freeroom.shared.FRRoom;
import org.pocketcampus.plugin.freeroom.shared.ImWorkingRequest;
import org.pocketcampus.plugin.freeroom.shared.Occupancy;
import org.pocketcampus.plugin.freeroom.shared.WorkingOccupancy;
import org.pocketcampus.plugin.freeroom.shared.utils.FRStruct;
import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.Toast;
import com.markupartist.android.widget.ActionBar.Action;
/**
* <code>FreeRoomHomeView</code> is the main <code>View</code>, it's the entry
* of the plugin. It displays the availabilities for the search given, and for
* your favorites NOW at the start.
* <p>
* All others views are supposed to be dialog windows, therefore it's always
* visible.
* <p>
* <code>AlertDialog</code> that exists are the following:
* <p>
* INFO ROOM display detailed information and occupancy about a room, and give
* the ability to share the location.
* <p>
* SEARCH enables the user to enter a customized search, and retrieves
* previously entered searches.
* <p>
* FAVORITES show the current favorites, with the possibility to remove them one
* by one. Adding is done by the ADD ROOM dialog.
* <p>
* ADD ROOM gives the possibility to construct an user-defined list of selected
* rooms, with auto-complete capabilities. It can be user to add favorites or a
* custom search.
* <p>
* SHARE give the possibility to share the location with friends through a share
* Intent. The server will also be notified, such that approximately occupancies
* continues to be as accurate as possible.
* <p>
*
* @author FreeRoom Project Team (2014/05)
* @author Julien WEBER <[email protected]>
* @author Valentin MINDER <[email protected]>
*/
public class FreeRoomHomeView extends FreeRoomAbstractView implements
IFreeRoomView {
/* MVC STRUCTURE */
/**
* FreeRoom controller in MVC scheme.
*/
private FreeRoomController mController;
/**
* FreeRoom model in MVC scheme.
*/
private FreeRoomModel mModel;
/**
* Reference to times utility method for client-side.
*/
private FRTimesClient times;
/**
* Reference to other utility method for client-side.
*/
private FRUtilsClient u;
/* COMMON SHARED VALUES */
/**
* Width of the main Activity.
*/
private int activityWidth;
/**
* Height of the main Activity.
*/
private int activityHeight;
/**
* Common LayoutInflater for all Layout inflated from xml.
*/
private LayoutInflater mLayoutInflater;
/* UI OF MAIN ACTIVITY */
/**
* Titled layout that holds the title and the main layout.
*/
private StandardTitledLayout titleLayout;
/**
* Main layout that hold all UI components.
*/
private LinearLayout mainLayout;
/**
* TextView to display a short message about what is currently displayed.
*/
private TextView mTextView;
/**
* ExpandableListView to display the results of occupancies building by
* building.
*/
private ExpandableListView mExpListView;
/**
* Adapter for the results (to display the occupancies).
*/
private ExpandableListViewAdapter<Occupancy> mExpListAdapter;
/* VIEW/DIALOGS FOR ALL ALERTDIALOG */
/**
* View that holds the INFO dialog content, defined in xml in layout folder.
*/
private View mInfoRoomView;
/**
* AlertDialog that holds the INFO dialog.
*/
private AlertDialog mInfoRoomDialog;
/**
* View that holds the SEARCH dialog content, defined in xml in layout
* folder.
*/
private View mSearchView;
/**
* Dialog that holds the SEARCH Dialog.
*/
private AlertDialog mSearchDialog;
/**
* View that holds the FAVORITES dialog content, defined in xml in layout
* folder.
*/
private View mFavoritesView;
/**
* AlertDialog that holds the FAVORITES dialog.
*/
private AlertDialog mFavoritesDialog;
/**
* View that holds the ADDROOM dialog content, defined in xml in layout
* folder.
*/
private View mAddRoomView;
/**
* AlertDialog that holds the ADDROOM dialog.
*/
private AlertDialog mAddRoomDialog;
/**
* View that holds the SHARE dialog content, defined in xml in layout
* folder.
*/
private View mShareView;
/**
* Dialog that holds the SHARE Dialog.
*/
private AlertDialog mShareDialog;
/**
* Dialog that holds the WARNING Dialog.
*/
private AlertDialog mWarningDialog;
/* UI ELEMENTS FOR ALL DIALOGS */
/* UI ELEMENTS FOR DIALOGS - INFO ROOM */
/* UI ELEMENTS FOR DIALOGS - SEARCH */
/**
* ListView that holds previous searches.
*/
private ListView mSearchPreviousListView;
/**
* TextView to write "previous searches" +show/hide
*/
private TextView prevSearchTitle;
/**
* Layout of the first part, the search input (without the second part,
* previous searches).
*/
private LinearLayout searchDialogUpperLinearLayout;
/**
* Main layout of the search dialog.
*/
private LinearLayout searchDialogMainLinearLayout;
/**
* Stores the height available
*/
private int searchDialogMainLayoutHeightAvailable = 0;
/**
* Stores if the screen is too small
*/
private boolean searchDialogHasHeightExtenstionProblem = false;
/**
* Ratio of dialog that should be occupied with searches input when NOT
* displaying previous request.
*/
private double searchDialogNonExtended = 0.90;
/**
* Ratio of dialog that should be occupied with searches input when
* displaying previous request.
*/
private double searchDialogExtended = 0.70;
/**
* Stores if the previous search has been hidden (the rest is more
* extended).
*/
private boolean searchDialogExtendMoreTriggered = false;
/* UI ELEMENTS FOR DIALOGS - FAVORITES */
/* UI ELEMENTS FOR DIALOGS - ADDROOM */
/* UI ELEMENTS FOR DIALOGS - SHARE */
/* OTHER UTILS */
/**
* Enum to have types and store the last caller of the "Add" dialog.
*
*/
private enum AddRoomCaller {
FAVORITES, SEARCH;
}
/**
* Stores the last caller of the ADDROOM dialog.
*/
private AddRoomCaller lastCaller = null;
/* ACTIONS FOR THE ACTION BAR */
/**
* Action to perform a customized search, by showing the search dialog.
*/
private Action search = new Action() {
public void performAction(View view) {
displaySearchDialog();
}
public int getDrawable() {
return R.drawable.magnify2x06;
}
};
/**
* Action to edit the user's favorites, by showing the favorites dialog.
*/
private Action editFavorites = new Action() {
public void performAction(View view) {
mFavoritesAdapter.notifyDataSetChanged();
mFavoritesDialog.show();
}
public int getDrawable() {
return R.drawable.star2x28;
}
};
/**
* Action to refresh the view (it sends the same stored request again).
* <p>
* TODO: useful? useless ? delete !
*/
private Action refresh = new Action() {
public void performAction(View view) {
refresh();
}
public int getDrawable() {
return R.drawable.refresh2x01;
}
};
/* MAIN ACTIVITY - OVERRIDEN METHODS */
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return FreeRoomController.class;
}
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
// Tracker
Tracker.getInstance().trackPageView("freeroom");
// Get and cast the controller and model
mController = (FreeRoomController) controller;
mModel = (FreeRoomModel) controller.getModel();
times = new FRTimesClient(this);
u = new FRUtilsClient(this);
// Setup the layout
mLayoutInflater = this.getLayoutInflater();
titleLayout = new StandardTitledLayout(this);
mainLayout = (LinearLayout) mLayoutInflater.inflate(
R.layout.freeroom_layout_home, null);
// The ActionBar is added automatically when you call setContentView
setContentView(titleLayout);
setTitle();
mExpListView = (ExpandableListView) mainLayout
.findViewById(R.id.freeroom_layout_home_list);
mTextView = (TextView) mainLayout
.findViewById(R.id.freeroom_layout_home_text_summary);
setTextSummary(getString(R.string.freeroom_home_init_please_wait));
initializeView();
// add the main layout to the pocketcampus titled layout.
titleLayout.addFillerView(mainLayout);
}
/**
* This is called when the Activity is resumed.
*
* If the user presses back on the Authentication window, This Activity is
* resumed but we do not have the freeroomCookie. In this case we close the
* Activity.
*/
@Override
protected void onResume() {
super.onResume();
/*
* if(mModel != null && mModel.getFreeRoomCookie() == null) { // Resumed
* and lot logged in? go back finish(); }
*/
}
@Override
protected void handleIntent(Intent intent) {
u.logV("Starting the app: handling an Intent");
// Intent and/or action seems to be null in some cases... so we just
// skip these cases and launch the default settings.
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equalsIgnoreCase(
"android.intent.action.MAIN")) {
u.logV("starting MAIN and default mode");
defaultMainStart();
} else if (intent.getAction().equalsIgnoreCase(
"android.intent.action.VIEW")) {
u.logV("starting the app and handling simple VIEW intent");
String errorIntentHandled = ""
+ getString(R.string.freeroom_urisearch_error_URINotUnderstood)
+ " "
+ getString(R.string.freeroom_urisearch_error_URINotSupported);
String intentScheme = intent.getScheme();
Uri intentUri = intent.getData();
if (intentScheme != null && intentUri != null) {
String intentUriHost = intentUri.getHost();
String intentUriPath = intentUri.getPath();
if (intentUriHost != null && intentUriPath != null) {
String intentUriPathQuery = FRStruct
.removeFirstCharSafely(intentUriPath);
// using standard epfl http page
if (intentScheme.equalsIgnoreCase("http")
&& intentUriHost
.equalsIgnoreCase("occupancy.epfl.ch")) {
u.logV("Found an EPFL http://occupancy.epfl.ch/room URI");
u.logV("With room query: \"" + intentUriPathQuery
+ "\"");
errorIntentHandled = searchByUriPrepareArguments(intentUriPathQuery);
}
// using freeroom links.
else if (intentScheme.equalsIgnoreCase("pocketcampus")
&& intentUriHost
.equalsIgnoreCase("freeroom.plugin.pocketcampus.org")) {
u.logV("Found a pocketcampus://freeroom.plugin.pocketcampus.org/data URI");
u.logV("With room query: \"" + intentUriPathQuery
+ "\"");
// TODO: do something.
errorIntentHandled = "URI NOR supported right now!";
} else {
u.logE("Unknow URI: \"" + intentUri + "\"");
}
}
}
if (errorIntentHandled.length() != 0) {
onErrorHandleIntent(errorIntentHandled);
}
} else {
u.logE("ERROR: Found an unhandled action: \""
+ intent.getAction() + "\"");
u.logE("Starting the app in default mode anyway");
defaultMainStart();
}
} else {
if (intent == null) {
u.logE("ERROR: Found a null Intent !!!");
} else if (intent.getAction() == null) {
u.logE("ERROR: Found a null Action !!!");
u.logE("This issue may appear by launching the app from the pocketcampus dashboard");
}
u.logE("Starting the app in default mode anyway");
defaultMainStart();
}
}
/**
* In case of error while handling an Intent, display a message to the user,
* and then launch a default request (without taking the favorites into
* account).
*
* @param errorMessage
* the error message to display.
*/
private void onErrorHandleIntent(String errorMessage) {
// TODO: display a popup
u.logE(getString(R.string.freeroom_urisearch_error_basis));
u.logE(errorMessage);
u.logE(getString(R.string.freeroom_urisearch_error_end));
if (mController != null && mModel != null) {
initDefaultRequest(false);
refresh();
}
}
/**
* Constructs the default request and refreshes it.
*/
private void defaultMainStart() {
u.logV("Starting in default mode.");
if (mController != null && mModel != null) {
initDefaultRequest(true);
refresh();
u.logV("Successful start in default mode: wait for server response.");
} else {
u.logE("Controller or Model not defined: cannot start default mode.");
}
}
/**
* Stores if a search by URI has been initiated recently, in order for
* auto-complete to automatically launch a new search if triggered, using
* <code>searchByUriMakeRequest</code>
*/
private boolean mSearchByUriTriggered = false;
/**
* Initiates a search by URI with the given constraint as the argument for
* the auto-complete.
*
* <p>
* If the requirement for autocomplete are not met, it will simply start a
* standard request (any free room now). If the autocomplete gave relevant
* results, it will search the availabilities of these rooms now. If
* autocomplete gave no results, it will also search for any free room now.
*
* @param constraint
* argument for the auto-complete to search for rooms.
* @return an empty String if successful, an error message if
*/
private String searchByUriPrepareArguments(String constraint) {
// TODO: constraint in common!!
if (constraint.length() < 2) {
return getString(R.string.freeroom_urisearch_error_AutoComplete_error)
+ " "
+ getString(R.string.freeroom_urisearch_error_AutoComplete_precond);
} else {
mSearchByUriTriggered = true;
// TODO: group
AutoCompleteRequest req = new AutoCompleteRequest(constraint, 1);
mController.autoCompleteBuilding(this, req);
return "";
}
}
/**
* Make a FRRequest with the FRRoom given in argument, for the rest of the
* day. If the argument is empty, it will display free room now.
*
* @param collection
* collection of FRRoom to make a new search on.
*/
private void searchByUriMakeRequest(Collection<FRRoom> collection) {
mSearchByUriTriggered = false;
boolean empty = collection.isEmpty();
if (empty) {
// if nothing matched the search, we notify the user.
onErrorHandleIntent(getString(R.string.freeroom_urisearch_error_AutoComplete_error)
+ " "
+ getString(R.string.freeroom_urisearch_error_AutoComplete_noMatch));
} else {
// TODO: warn if there is more than 1 result ? Val. think no.
// search for the rest of the day.
FRPeriod period = FRTimes.getNextValidPeriodTillEndOfDay();
FRRequestDetails request = null;
List<String> uidList = new ArrayList<String>();
SetArrayList<FRRoom> uidNonFav = new SetArrayList<FRRoom>();
// TODO: find a simpler and more efficient way ?
Iterator<FRRoom> iter = collection.iterator();
while (iter.hasNext()) {
FRRoom room = iter.next();
uidList.add(room.getUid());
uidNonFav.add(room);
}
// TODO: usergroup
request = new FRRequestDetails(period, false, uidList, false,
false, true, uidNonFav, 1);
mModel.setFRRequestDetails(request, !empty);
refresh();
}
}
/* MAIN ACTIVITY - INITIALIZATION */
@Override
public void initializeView() {
// retrieve display dimensions
Rect displayRectangle = new Rect();
Window window = this.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
activityWidth = displayRectangle.width();
activityHeight = displayRectangle.height();
mExpListAdapter = new ExpandableListViewAdapter<Occupancy>(
getApplicationContext(), mModel.getOccupancyResults(),
mController, this);
mExpListView.setAdapter(mExpListAdapter);
addActionToActionBar(refresh);
addActionToActionBar(editFavorites);
addActionToActionBar(search);
initInfoDialog();
initSearchDialog();
initFavoritesDialog();
initAddRoomDialog();
initShareDialog();
initWarningDialog();
}
/**
* Inits the dialog to diplay the information about a room.
*/
private void initInfoDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("room name");
builder.setIcon(R.drawable.details_white_50);
builder.setPositiveButton(
getString(R.string.freeroom_dialog_info_share), null);
builder.setNegativeButton(
getString(R.string.freeroom_dialog_fav_close), null);
// Get the AlertDialog from create()
mInfoRoomDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mInfoRoomDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mInfoRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mInfoRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mInfoRoomDialog.getWindow().setAttributes(lp);
mInfoRoomView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_info, null);
// these work perfectly
mInfoRoomView.setMinimumWidth((int) (activityWidth * 0.9f));
mInfoRoomView.setMinimumHeight((int) (activityHeight * 0.8f));
mInfoRoomDialog.setView(mInfoRoomView);
mInfoRoomDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
}
});
}
/**
* Inits the dialog to diplay the favorites.
*/
private ExpandableListViewFavoriteAdapter mFavoritesAdapter;
private void initFavoritesDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_fav_title));
builder.setIcon(R.drawable.star2x28);
builder.setPositiveButton(getString(R.string.freeroom_dialog_fav_add),
null);
builder.setNegativeButton(
getString(R.string.freeroom_dialog_fav_close), null);
builder.setNeutralButton(getString(R.string.freeroom_dialog_fav_reset),
null);
// Get the AlertDialog from create()
mFavoritesDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mFavoritesDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mFavoritesDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mFavoritesDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mFavoritesDialog.getWindow().setAttributes(lp);
mFavoritesView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_fav, null);
// these work perfectly
mFavoritesView.setMinimumWidth((int) (activityWidth * 0.9f));
mFavoritesView.setMinimumHeight((int) (activityHeight * 0.8f));
mFavoritesDialog.setView(mFavoritesView);
mFavoritesDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
mFavoritesAdapter.notifyDataSetChanged();
}
});
mFavoritesDialog.hide();
mFavoritesDialog.show();
mFavoritesDialog.dismiss();
mFavoritesDialog
.setOnDismissListener(new AlertDialog.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// sends a new request with the new favorites
initDefaultRequest(true);
refresh();
}
});
Button tv = mFavoritesDialog.getButton(DialogInterface.BUTTON_POSITIVE);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mAddRoomDialog.isShowing()) {
displayAddRoomDialog(AddRoomCaller.FAVORITES);
}
}
});
Button bt = mFavoritesDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mWarningDialog.show();
}
});
ExpandableListView lv = (ExpandableListView) mFavoritesView
.findViewById(R.id.freeroom_layout_dialog_fav_list);
mFavoritesAdapter = new ExpandableListViewFavoriteAdapter(this, mModel
.getFavorites().keySetOrdered(), mModel.getFavorites(), mModel);
lv.setAdapter(mFavoritesAdapter);
mFavoritesAdapter.notifyDataSetChanged();
}
private void displayAddRoomDialog(AddRoomCaller calling) {
mAddRoomDialog.show();
// TODO: reset the data ? the text input, the selected room ?
lastCaller = calling;
}
private void dimissAddRoomDialog() {
if (lastCaller.equals(AddRoomCaller.FAVORITES)) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom mRoom = iter.next();
// TODO: add all in batch!
mModel.addFavorite(mRoom);
}
mFavoritesAdapter.notifyDataSetChanged();
resetUserDefined();
} else if (lastCaller.equals(AddRoomCaller.SEARCH)) {
// we do nothing: reset will be done at search time
mSummarySelectedRoomsTextViewSearchMenu.setText(u
.getSummaryTextFromCollection(selectedRooms));
}
}
private void initAddRoomDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_add_room_title));
builder.setIcon(R.drawable.ic_dialog_adding);
// Get the AlertDialog from create()
mAddRoomDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mAddRoomDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mAddRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mAddRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mAddRoomDialog.getWindow().setAttributes(lp);
mAddRoomView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_add_room, null);
// these work perfectly
mAddRoomView.setMinimumWidth((int) (activityWidth * 0.9f));
// mAddRoomView.setMinimumHeight((int) (activityHeight * 0.8f));
mAddRoomDialog.setView(mAddRoomView);
mAddRoomDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
// searchButton.setEnabled(auditSubmit() == 0);
}
});
Button bt_done = (Button) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_room_done);
bt_done.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismissSoftKeyBoard(v);
mAddRoomDialog.dismiss();
dimissAddRoomDialog();
}
});
mSummarySelectedRoomsTextView = (TextView) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_room_summary);
UIConstructInputBar();
LinearLayout ll = (LinearLayout) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_layout_main);
ll.addView(mAutoCompleteSuggestionInputBarElement);
createSuggestionsList();
}
private void initShareDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_share_title));
builder.setPositiveButton(
getString(R.string.freeroom_dialog_share_button_friends), null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(
getString(R.string.freeroom_dialog_share_button_server), null);
builder.setIcon(R.drawable.share_white_50);
// Get the AlertDialog from create()
mShareDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mShareDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
mShareDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mShareDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mShareDialog.getWindow().setAttributes(lp);
mShareView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_share, null);
// these work perfectly
mShareView.setMinimumWidth((int) (activityWidth * 0.95f));
// mShareView.setMinimumHeight((int) (activityHeight * 0.8f));
mShareDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
dismissSoftKeyBoard(mShareView);
}
});
mShareDialog.setView(mShareView);
}
public void displayShareDialog(final FRPeriod mPeriod, final FRRoom mRoom) {
mShareDialog.hide();
mShareDialog.show();
final TextView tv = (TextView) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_textBasic);
tv.setText(u.wantToShare(mPeriod, mRoom, ""));
final EditText ed = (EditText) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_text_edit);
ed.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
tv.setText(u.wantToShare(mPeriod, mRoom, ed.getText()
.toString()));
dismissSoftKeyBoard(arg0);
return true;
}
});
Button shareWithServer = mShareDialog
.getButton(DialogInterface.BUTTON_NEUTRAL);
shareWithServer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, false, ed.getText().toString());
mShareDialog.dismiss();
}
});
Button shareWithFriends = mShareDialog
.getButton(DialogInterface.BUTTON_POSITIVE);
shareWithFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, true, ed.getText().toString());
mShareDialog.dismiss();
}
});
Spinner spinner = (Spinner) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_spinner_course);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the mFavoritesAdapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO do something with that
System.out.println("selected" + arg0.getItemAtPosition(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO find out how is this relevant
System.out.println("nothing selected!");
}
});
// it's automatically in center of screen!
mShareDialog.show();
}
/**
* Dismiss the keyboard associated with the view.
*
* @param v
*/
private void dismissSoftKeyBoard(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
/**
* Inits the dialog to diplay the information about a room.
*/
private void initSearchDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Various setter methods to set the searchDialog characteristics
builder.setTitle(getString(R.string.freeroom_search_title));
builder.setPositiveButton(getString(R.string.freeroom_search_search),
null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(getString(R.string.freeroom_search_reset),
null);
builder.setIcon(R.drawable.magnify2x06);
// Get the AlertDialog from create()
mSearchDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mSearchDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
mSearchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mSearchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mSearchDialog.getWindow().setAttributes(lp);
mSearchView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_search, null);
// these work perfectly
mSearchView.setMinimumWidth((int) (activityWidth * 0.9f));
mSearchView.setMinimumHeight((int) (activityHeight * 0.8f));
mSearchDialog.setView(mSearchView);
final String textTitlePrevious = getString(R.string.freeroom_search_previous_search);
prevSearchTitle = (TextView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_prev_search_title);
prevSearchTitle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
searchDialogMissSpaceExtendChangeState(searchDialogExtendMoreTriggered);
if (searchDialogHasHeightExtenstionProblem) {
if (searchDialogExtendMoreTriggered) {
prevSearchTitle
.setText(textTitlePrevious
+ ": "
+ getString(R.string.freeroom_search_previous_hide));
} else {
prevSearchTitle
.setText(textTitlePrevious
+ ": "
+ getString(R.string.freeroom_search_previous_show));
}
}
searchDialogExtendMoreTriggered = !searchDialogExtendMoreTriggered;
}
});
mSearchDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
searchButton.setEnabled(auditSubmit() == 0);
if (mModel.getPreviousRequest().isEmpty()) {
prevSearchTitle.setText("");
} else if (searchDialogHasHeightExtenstionProblem) {
prevSearchTitle
.setText(textTitlePrevious
+ ": "
+ getString(R.string.freeroom_search_previous_show));
} else {
prevSearchTitle.setText(textTitlePrevious);
}
}
});
// this is necessary o/w buttons don't exists!
mSearchDialog.hide();
mSearchDialog.show();
mSearchDialog.dismiss();
resetButton = mSearchDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
searchButton = mSearchDialog.getButton(DialogInterface.BUTTON_POSITIVE);
mSummarySelectedRoomsTextViewSearchMenu = (TextView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_text_summary);
// the view will be removed or the text changed, no worry
mSummarySelectedRoomsTextViewSearchMenu.setText("empty");
// display the previous searches
mSearchPreviousListView = (ListView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_prev_search_list);
ArrayAdapter<FRRequestDetails> adapter = new ArrayAdapter<FRRequestDetails>(
this, R.layout.sdk_list_entry, R.id.sdk_list_entry_text,
mModel.getPreviousRequest());
mSearchPreviousListView.setAdapter(adapter);
mSearchPreviousListView
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
FRRequestDetails req = mModel.getPreviousRequest().get(
arg2);
if (req != null) {
fillSearchDialog(req);
}
searchDialogExtendMoreTriggered = true;
if (searchDialogHasHeightExtenstionProblem) {
prevSearchTitle
.setText(textTitlePrevious
+ ": "
+ getString(R.string.freeroom_search_previous_show));
}
searchDialogMissSpaceExtendChangeState(false);
}
});
searchDialogUpperLinearLayout = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_scroll_main);
searchDialogMainLinearLayout = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_main);
initSearch();
}
/**
* Finds if the available height in the search popup is not enough to store
* the layout, in order the minimize it's size.
* <p>
* TODO: this method has an issue and never work on 1st time! The mock
* filling seems not to be working regarding to the mesurements.
*
* @return true if no problem
*/
private boolean findIfHeightProblem() {
// TODO: seems useless regarding the issue
searchDialogUpperLinearLayout
.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, 1700));
searchDialogUpperLinearLayout
.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
FRRequestDetails request = validRequest(true);
request.setAny(false);
request.setFav(true);
request.setUser(true);
SetArrayList<FRRoom> set = new SetArrayList<FRRoom>(100);
List<String> uidList = new ArrayList<String>(100);
for (int i = 0; i < 100; i++) {
set.add(new FRRoom("BC898989", i + "123"));
uidList.add(i + "123");
}
request.setUidNonFav(set);
request.setUidList(uidList);
fillSearchDialog(request);
mSearchDialog.show();
// TODO: seems useless regarding the issue
searchDialogUpperLinearLayout.refreshDrawableState();
searchDialogUpperLinearLayout.getDrawableState();
searchDialogMainLayoutHeightAvailable = searchDialogMainLinearLayout
.getMeasuredHeight();
boolean toreturn = (searchDialogUpperLinearLayout.getMeasuredHeight() > (searchDialogExtended * searchDialogMainLayoutHeightAvailable));
fillSearchDialog();
return toreturn;
}
/**
* Display the search dialog and checks the compatibility of the UI and make
* some change if necessary.
*/
private void displaySearchDialog() {
if (findIfHeightProblem()) {
searchDialogHasHeightExtenstionProblem = true;
}
fillSearchDialog();
if (!mModel.getPreviousRequest().isEmpty()) {
searchDialogMissSpaceExtendChangeState(false);
} else {
searchDialogUpperLinearLayout
.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
mSearchDialog.show();
}
/**
* Modify the height of the upper layout of the search dialog in order to
* show/hide the previous requests.
*
* @param lessExtend
*/
private void searchDialogMissSpaceExtendChangeState(boolean lessExtend) {
if (searchDialogHasHeightExtenstionProblem) {
int height = (int) (searchDialogNonExtended * searchDialogMainLayoutHeightAvailable);
if (lessExtend) {
height = (int) (searchDialogExtended * searchDialogMainLayoutHeightAvailable);
}
searchDialogUpperLinearLayout
.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, height));
searchDialogUpperLinearLayout.refreshDrawableState();
}
}
private void initWarningDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_warn_title));
builder.setMessage(getString(R.string.freeroom_dialog_warn_delete_fav_text));
builder.setIcon(R.drawable.warning_white_50);
builder.setPositiveButton(
getString(R.string.freeroom_dialog_warn_confirm),
new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mModel.resetFavorites();
mFavoritesAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton(
getString(R.string.freeroom_dialog_warn_cancel), null);
// Get the AlertDialog from create()
mWarningDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mWarningDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.WRAP_CONTENT;
lp.height = LayoutParams.WRAP_CONTENT;
mWarningDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mWarningDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mWarningDialog.getWindow().setAttributes(lp);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
System.out
.println("TOuch outside the dialog ******************** ");
mSearchDialog.dismiss();
}
return false;
}
/**
* Overrides the legacy <code>onKeyDown</code> method in order to close the
* dialog if one was opened. TODO: test if really needed.
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Override back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
boolean flag = false;
if (mInfoRoomDialog.isShowing()) {
mInfoRoomDialog.dismiss();
flag = true;
}
if (mSearchDialog.isShowing()) {
mSearchDialog.dismiss();
flag = true;
}
if (mFavoritesDialog.isShowing()) {
mFavoritesDialog.dismiss();
flag = true;
}
selectedRooms.clear();
if (flag) {
resetUserDefined();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void anyError() {
setTitle();
setTextSummary(getString(R.string.freeroom_home_error_sorry));
}
/**
* Sets the summary text box to the specified text.
* <p>
* It doesn't need to start by a space, the text view already contains an
* appropriate padding.
*
* @param text
* the new summary to be displayed.
*/
private void setTextSummary(String text) {
mTextView.setText(text);
}
/**
* Sets the title to the default value.
* <p>
* same effect as <br>
* <code>String default = getString(R.string.freeroom_title_main_title)</code>
* <br>
* <code>titleLayout.setTitle(defaultTitle);</code>
*
*/
private void setTitle() {
setTitle(getString(R.string.freeroom_title_main_title));
}
/**
* Sets the title to the given value.
* <p>
* same effect as <br>
* <code>titleLayout.setTitle(titleValue);</code>
*
* @param titleValue
* the new title
*
*/
private void setTitle(String titleValue) {
titleLayout.setTitle(titleValue);
}
/**
* Constructs the default request and sets it in the model for future use.
* You may call <code>refresh</code> in order to actually send it to the
* server.
*
* @param useFavorites
* if the constructor of the request should consider the
* favorites or not
*/
private void initDefaultRequest(boolean useFavorites) {
mModel.setFRRequestDetails(validRequest(useFavorites), false);
}
/**
* Construct a valid and default request. If useFavorites is true, it will
* check all the favorites for the next valid period, otherwise or if there
* are not.
*
* @param useFavorites
* if it should consider the favorites or not
* @return a valid and default request, based or nor on the favorites.
*/
private FRRequestDetails validRequest(boolean useFavorites) {
OrderMapListFew<String, List<FRRoom>, FRRoom> set = mModel
.getFavorites();
FRRequestDetails details = null;
// if there are no favorites or we dont want to use them.
if (set.isEmpty() || !useFavorites) {
// NO FAV = check all free rooms
// TODO change group accordingly, set to 1 by default and for
// testing purpose
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), true,
new ArrayList<String>(1), true, false, false,
new SetArrayList<FRRoom>(), 1);
} else {
// FAV: check occupancy of ALL favs
ArrayList<String> array = new ArrayList<String>(set.size());
addAllFavoriteToCollection(array, AddCollectionCaller.SEARCH, true);
// TODO change group accordingly, set to 1 by default and for
// testing purpose
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), false,
array, false, true, false, new SetArrayList<FRRoom>(), 1);
}
return details;
}
/**
* Asks the controller to send again the request which was already set in
* the model.
*/
private void refresh() {
setTextSummary(getString(R.string.freeroom_home_please_wait));
setTitle();
// cleans the previous results
mModel.getOccupancyResults().clear();
mExpListAdapter.notifyDataSetChanged();
mController.sendFRRequest(this);
}
@Override
public void occupancyResultsUpdated() {
setTitle();
String subtitle = "";
if (mModel.getOccupancyResults().isEmpty()) {
// TODO: popup with no results message ?
subtitle = getString(R.string.freeroom_home_error_no_results);
} else {
FRRequest request = mModel.getFRRequestDetails();
String title = "";
if (request.isOnlyFreeRooms()) {
title = getString(R.string.freeroom_home_info_free_rooms);
} else {
title = getString(R.string.freeroom_home_info_rooms);
}
FRPeriod period = mModel.getOverAllTreatedPeriod();
setTitle(title + times.generateShortTimeSummary(period));
subtitle = times.generateFullTimeSummary(period);
// if the info dialog is opened, we update the CORRECT occupancy
// with the new data.
if (mInfoRoomDialog.isShowing()) {
FRRoom room = mModel.getDisplayedOccupancy().getRoom();
List<?> list = mModel.getOccupancyResults().get(
mModel.getKey(room));
Iterator<?> iter = list.iterator();
label: while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof Occupancy) {
if (((Occupancy) o).getRoom().getUid()
.equals(room.getUid())) {
mModel.setDisplayedOccupancy((Occupancy) o);
// doesn't work
mInfoActualOccupationAdapter.notifyDataSetChanged();
// works!
displayInfoDialog();
break label;
}
}
}
}
// if there's only one result, we display immediately the info
// dialog, to get the detailed information (very useful in context
// of QR codes)
if (mModel.getOccupancyResults().size() == 1) {
List<?> list = mModel.getOccupancyResults().get(0);
if (list != null && list.size() == 1) {
Object elem = list.get(0);
if (elem != null && elem instanceof Occupancy) {
mModel.setDisplayedOccupancy((Occupancy) elem);
displayInfoDialog();
}
}
}
}
setTextSummary(subtitle);
mExpListAdapter.notifyDataSetChanged();
updateCollapse(mExpListView, mExpListAdapter);
}
/**
* Expands all the groups if there are no more than 4 groups or not more
* than 10 results.
* <p>
* TODO defines these consts somewhere else
*
* @param ev
*/
public void updateCollapse(ExpandableListView ev,
ExpandableListViewAdapter<Occupancy> ad) {
System.out.println("check: " + ad.getGroupCount() + "/"
+ ad.getChildrenTotalCount()); // TODO delete
if (ad.getGroupCount() <= 4 || ad.getChildrenTotalCount() <= 10) {
System.out.println("i wanted to expand");
// TODO: this cause troubles in performance when first launch
for (int i = 0; i < ad.getGroupCount(); i++) {
ev.expandGroup(i);
}
}
}
/**
* Put a onClickListener on an imageView in order to share the location and
* time when clicking share, if available.
*
* @param shareImageView
* the view on which to put the listener
* @param homeView
* reference to the home view
* @param mOccupancy
* the holder of data for location and time
*/
public void setShareClickListener(View shareImageView,
final FreeRoomHomeView homeView, final Occupancy mOccupancy) {
if (!mOccupancy.isIsAtLeastOccupiedOnce()
&& mOccupancy.isIsAtLeastFreeOnce()) {
shareImageView.setClickable(true);
shareImageView.setEnabled(true);
if (shareImageView instanceof ImageView) {
((ImageView) shareImageView).setImageResource(R.drawable.share);
}
shareImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
homeView.displayShareDialog(mOccupancy.getTreatedPeriod(),
mOccupancy.getRoom());
}
});
} else {
shareImageView.setClickable(false);
shareImageView.setEnabled(false);
if (shareImageView instanceof ImageView) {
((ImageView) shareImageView)
.setImageResource(R.drawable.share_disabled);
}
}
}
private ActualOccupationArrayAdapter<ActualOccupation> mInfoActualOccupationAdapter;
/**
* Display the dialog that provides more info about the occupation of the
* selected room.
*/
public void displayInfoDialog() {
final Occupancy mOccupancy = mModel.getDisplayedOccupancy();
if (mOccupancy != null) {
mInfoRoomDialog.hide();
mInfoRoomDialog.show();
final FRRoom mRoom = mOccupancy.getRoom();
String text = mRoom.getDoorCode();
if (mRoom.isSetDoorCodeAlias()) {
// alias is displayed IN PLACE of the official name
// the official name can be found in bottom of dialog
text = mRoom.getDoorCodeAlias();
}
mInfoRoomDialog.setTitle(text);
TextView periodTextView = (TextView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_period);
if (mOccupancy.isSetTreatedPeriod()
&& mOccupancy.getTreatedPeriod() != null) {
periodTextView.setText(times.generateFullTimeSummary(mOccupancy
.getTreatedPeriod()));
} else {
// TODO: error coming from server ??
periodTextView.setText("Error: cannot display period");
}
ImageView iv = (ImageView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_share);
setShareClickListener(iv, this, mOccupancy);
Button share = mInfoRoomDialog
.getButton(AlertDialog.BUTTON_POSITIVE);
share.setEnabled(mOccupancy.isIsAtLeastFreeOnce()
&& !mOccupancy.isIsAtLeastOccupiedOnce());
setShareClickListener(share, this, mOccupancy);
ListView roomOccupancyListView = (ListView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_roomOccupancy);
mInfoActualOccupationAdapter = new ActualOccupationArrayAdapter<ActualOccupation>(
getApplicationContext(), mOccupancy.getOccupancy(),
mController, this);
roomOccupancyListView.setAdapter(mInfoActualOccupationAdapter);
TextView detailsTextView = (TextView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_details);
detailsTextView.setText(u.getInfoFRRoom(mOccupancy.getRoom()));
mInfoRoomDialog.show();
}
}
private void fillSearchDialog() {
final FRRequestDetails request = mModel.getFRRequestDetails();
if (request != null) {
fillSearchDialog(request);
}
}
private void fillSearchDialog(final FRRequestDetails request) {
reset();
resetTimes(request.getPeriod());
anyButton.setChecked(request.isAny());
specButton.setChecked(!request.isAny());
favButton.setChecked(request.isFav());
userDefButton.setChecked(request.isUser());
freeButton.setChecked(request.isOnlyFreeRooms());
boolean enabled = !request.isAny();
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
if (enabled) {
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
if (request.isUser()) {
mOptionalLineLinearLayoutWrapper
.addView(mOptionalLineLinearLayoutWrapperIn);
selectedRooms.addAll(request.getUidNonFav());
mSummarySelectedRoomsTextViewSearchMenu.setText(u
.getSummaryTextFromCollection(selectedRooms));
}
updateDateTimePickersAndButtons();
// MUST be the last action: after all field are set, check if the
// request is valid
searchButton.setEnabled(auditSubmit() == 0);
}
private void share(FRPeriod mPeriod, FRRoom mRoom, boolean withFriends,
String toShare) {
WorkingOccupancy work = new WorkingOccupancy(mPeriod, mRoom);
ImWorkingRequest request = new ImWorkingRequest(work,
mModel.getAnonymID());
mController.prepareImWorking(request);
mModel.setOnlyServer(!withFriends);
mController.ImWorking(this);
if (withFriends) {
shareWithFriends(mPeriod, mRoom, toShare);
}
}
/**
* Construct the Intent to share the location and time with friends. The
* same information is shared with the server at the same time
*
* @param mPeriod
* time period
* @param mRoom
* location
*/
private void shareWithFriends(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
String sharing = u.wantToShare(mPeriod, mRoom, toShare);
sharing += " \n" + getString(R.string.freeroom_share_ref_pocket);
Log.v(this.getClass().getName() + "-share", "sharing:" + sharing);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sharing);
// this ensure that our handler, that is handling home-made text types,
// will also work. But our won't work outside the app, which is needed,
// because it waits for this special type.
/** The input bar to make the search */
/** Adapter for the <code>mListView</code> */
/**
* TRUE: "only free rooms" FALSE: "allow non-free rooms"
*/
private CheckBox freeButton;
private Button searchButton;
private Button resetButton;
private Button userDefEditButton;
private Button userDefAddButton;
private Button userDefResetButton;
private ImageButton addHourButton;
private ImageButton upToEndHourButton;
/**
* Stores if the "up to end" button has been trigged.
* <p>
* If yes, the endHour don't follow anymore the startHour when you change
* it. It will be disabled when you change manually the endHour to a value
* under the maximal hour.
*/
private boolean upToEndSelected = false;
private TextView mSummarySelectedRoomsTextView;
private TextView mSummarySelectedRoomsTextViewSearchMenu;
private int yearSelected = -1;
private int monthSelected = -1;
private int dayOfMonthSelected = -1;
private int startHourSelected = -1;
private int startMinSelected = -1;
private int endHourSelected = -1;
private int endMinSelected = -1;
private SimpleDateFormat dateFormat;
private SimpleDateFormat timeFormat;
private LinearLayout mOptionalLineLinearLayoutWrapper;
private LinearLayout mOptionalLineLinearLayoutWrapperIn;
private LinearLayout mOptionalLineLinearLayoutContainer;
private void initSearch() {
mOptionalLineLinearLayoutWrapper = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper);
mOptionalLineLinearLayoutContainer = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_container);
mOptionalLineLinearLayoutWrapperIn = (LinearLayout) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper_in);
selectedRooms = new SetArrayList<FRRoom>();
formatters();
// createSuggestionsList();
// addAllFavsToAutoComplete();
mAutoCompleteSuggestionArrayListFRRoom = new ArrayList<FRRoom>(10);
resetTimes();
UIConstructPickers();
UIConstructButton();
// UIConstructInputBar();
reset();
}
private void formatters() {
dateFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format_default));
timeFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format_default));
}
private void UIConstructPickers() {
// First allow the user to select a date
showDatePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_date);
mDatePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int nYear,
int nMonthOfYear, int nDayOfMonth) {
yearSelected = nYear;
monthSelected = nMonthOfYear;
dayOfMonthSelected = nDayOfMonth;
updateDatePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, yearSelected, monthSelected, dayOfMonthSelected);
showDatePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDatePickerDialog.show();
}
});
// Then the starting time of the period
showStartTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_start);
mTimePickerStartDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
int previous = startHourSelected;
startHourSelected = nHourOfDay;
startMinSelected = nMinute;
if (startHourSelected < FRTimes.FIRST_HOUR_CHECK) {
startHourSelected = FRTimes.FIRST_HOUR_CHECK;
startMinSelected = 0;
}
if (startHourSelected >= FRTimes.LAST_HOUR_CHECK) {
startHourSelected = FRTimes.LAST_HOUR_CHECK - 1;
startMinSelected = 0;
}
if (startHourSelected != -1 && !upToEndSelected) {
int shift = startHourSelected - previous;
int newEndHour = endHourSelected + shift;
if (newEndHour > FRTimes.LAST_HOUR_CHECK) {
newEndHour = FRTimes.LAST_HOUR_CHECK;
}
if (newEndHour < FRTimes.FIRST_HOUR_CHECK) {
newEndHour = FRTimes.FIRST_HOUR_CHECK + 1;
}
endHourSelected = newEndHour;
if (endHourSelected == FRTimes.LAST_HOUR_CHECK) {
endMinSelected = 0;
}
updateEndTimePickerAndButton();
}
updateStartTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, startHourSelected, startMinSelected, true);
showStartTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerStartDialog.show();
}
});
// Then the ending time of the period
showEndTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end);
mTimePickerEndDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
endHourSelected = nHourOfDay;
endMinSelected = nMinute;
if (endHourSelected < startHourSelected) {
endHourSelected = startHourSelected + 1;
}
if (endHourSelected < FRTimes.FIRST_HOUR_CHECK) {
endHourSelected = FRTimes.FIRST_HOUR_CHECK + 1;
endMinSelected = 0;
}
if (endHourSelected == FRTimes.FIRST_HOUR_CHECK
&& endMinSelected <= FRTimes.MIN_MINUTE_INTERVAL) {
endMinSelected = FRTimes.MIN_MINUTE_INTERVAL;
// TODO: if start is not 8h00 (eg 8h10 dont work)
}
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
}
if (endHourSelected != FRTimes.LAST_HOUR_CHECK) {
upToEndSelected = false;
upToEndHourButton.setEnabled(!upToEndSelected);
}
updateEndTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, endHourSelected, endMinSelected, true);
showEndTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerEndDialog.show();
}
});
}
private void resetUserDefined() {
// TODO: add/remove
// mGlobalSubLayout.removeView(mAutoCompleteSuggestionInputBarElement);
// mGlobalSubLayout.removeView(mSummarySelectedRoomsTextView);
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
selectedRooms.clear();
userDefButton.setChecked(false);
mSummarySelectedRoomsTextView.setText(u
.getSummaryTextFromCollection(selectedRooms));
mSummarySelectedRoomsTextViewSearchMenu.setText(u
.getSummaryTextFromCollection(selectedRooms));
mAutoCompleteSuggestionInputBarElement.setInputText("");
}
private void UIConstructButton() {
specButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_spec);
specButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (specButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(true);
anyButton.setChecked(false);
anyButton.setEnabled(true);
specButton.setChecked(true);
freeButton.setChecked(false);
boolean enabled = true;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// TODO: is this great ? this guarantees that search is always
// available, but requires two steps to remove the fav (ass
// user-def, remove fav)
favButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
anyButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_any);
anyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (anyButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(false);
resetUserDefined();
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
favButton.setChecked(false);
userDefButton.setChecked(false);
freeButton.setChecked(true);
anyButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
favButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_fav);
favButton.setEnabled(true);
favButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!userDefButton.isChecked()) {
favButton.setChecked(true);
}
anyButton.setChecked(false);
specButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
userDefButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user);
userDefButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (userDefButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
// TODO: init and use the data.
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
mOptionalLineLinearLayoutWrapper
.addView(mOptionalLineLinearLayoutWrapperIn);
mSummarySelectedRoomsTextViewSearchMenu.setText(u
.getSummaryTextFromCollection(selectedRooms));
displayAddRoomDialog(AddRoomCaller.SEARCH);
} else if (!favButton.isChecked()) {
userDefButton.setChecked(true);
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
} else {
resetUserDefined();
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
freeButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_non_free);
freeButton.setEnabled(true);
freeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!freeButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
searchButton.setEnabled(auditSubmit() == 0);
searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
prepareSearchQuery();
}
});
resetButton.setEnabled(true);
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
reset();
// addAllFavsToAutoComplete();
// we reset the input bar...
// TODO
// mAutoCompleteSuggestionInputBarElement.setInputText("");
}
});
addHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_plus);
addHourButton.setEnabled(true);
addHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (endHourSelected <= 18) {
endHourSelected += 1;
updateEndTimePickerAndButton();
mTimePickerEndDialog.updateTime(endHourSelected,
endMinSelected);
}
if (endHourSelected >= 19) {
addHourButton.setEnabled(false);
}
}
});
upToEndHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_toend);
upToEndHourButton.setEnabled(true);
upToEndHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
updateEndTimePickerAndButton();
mTimePickerEndDialog
.updateTime(endHourSelected, endMinSelected);
upToEndSelected = true;
upToEndHourButton.setEnabled(!upToEndSelected);
searchButton.setEnabled(auditSubmit() == 0);
}
});
userDefAddButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_add);
userDefAddButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
displayAddRoomDialog(AddRoomCaller.SEARCH);
}
});
userDefEditButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_edit);
userDefEditButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO: display something else! Edit, not adding!!!
displayAddRoomDialog(AddRoomCaller.SEARCH);
}
});
userDefResetButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_reset);
userDefResetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
resetUserDefined();
}
});
// on vertical screens, choose fav and choose user-def are vertically
// aligned
// on horizontal screens, there are horizontally aligned.
if (activityHeight > activityWidth) {
LinearLayout mLinearLayout = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_semi);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
if (activityWidth <= 480) {
LinearLayout header_main = (LinearLayout) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_upper_main);
header_main.setOrientation(LinearLayout.VERTICAL);
LinearLayout header_1st = (LinearLayout) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_upper_first);
LinearLayout header_2nd = (LinearLayout) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_upper_second);
header_1st.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
header_1st.getLayoutParams().width = LayoutParams.FILL_PARENT;
header_2nd.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
header_2nd.getLayoutParams().width = LayoutParams.FILL_PARENT;
}
}
}
// TODO: the InputBar is not used so far
private void UIConstructInputBar() {
final IFreeRoomView view = this;
mAutoCompleteSuggestionInputBarElement = new InputBarElement(
this,
null,
getString(R.string.freeroom_check_occupancy_search_inputbarhint));
mAutoCompleteSuggestionInputBarElement
.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
// click on magnify glass on the keyboard
mAutoCompleteSuggestionInputBarElement
.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
dismissSoftKeyBoard(v);
AutoCompleteRequest request = new AutoCompleteRequest(
query, 1);
mController.autoCompleteBuilding(view, request);
}
return true;
}
});
// click on BUTTON magnify glass on the inputbar
mAutoCompleteSuggestionInputBarElement
.setOnButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
if (query.length() >= 2) {
dismissSoftKeyBoard(v);
// TODO change group accordingly, set to 1 by
// default and for testing purpose
AutoCompleteRequest request = new AutoCompleteRequest(
query, 1);
mController.autoCompleteBuilding(view, request);
}
}
});
mAdapter = new FRRoomSuggestionArrayAdapter<FRRoom>(
getApplicationContext(),
mAutoCompleteSuggestionArrayListFRRoom, mModel);
mAutoCompleteSuggestionInputBarElement
.setOnKeyPressedListener(new OnKeyPressedListener() {
@Override
public void onKeyPressed(String text) {
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
mAutoCompleteSuggestionInputBarElement
.setButtonText(null);
mAutoCompleteSuggestionListView.invalidate();
addAllFavsToAutoComplete();
} else {
mAutoCompleteSuggestionInputBarElement
.setButtonText("");
if (text.length() >= 2) {
// TODO change group accordingly, set to 1 by
// default and for testing purpose
// remove this if you don't want auto-complete
// without pressing the button
AutoCompleteRequest request = new AutoCompleteRequest(
text, 1);
mController.autoCompleteBuilding(view, request);
}
}
}
});
}
private void addAllFavsToAutoComplete() {
mAutoCompleteSuggestionArrayListFRRoom.clear();
addAllFavoriteToCollection(mAutoCompleteSuggestionArrayListFRRoom,
AddCollectionCaller.ADDALLFAV, false);
mAdapter.notifyDataSetChanged();
}
private enum AddCollectionCaller {
ADDALLFAV, SEARCH;
}
/**
* Add all the favorites FRRoom to the collection. Caller is needed in order
* to have special condition depending on the caller. The collection will be
* cleared prior to any adding.
*
* @param collection
* collection in which you want the favorites to be added.
* @param caller
* identification of the caller, to provide conditions.
* @param addOnlyUID
* true to add UID, false to add fully FRRoom object.
*/
private void addAllFavoriteToCollection(Collection collection,
AddCollectionCaller caller, boolean addOnlyUID) {
collection.clear();
OrderMapListFew<String, List<FRRoom>, FRRoom> set = mModel
.getFavorites();
Iterator<String> iter = set.keySetOrdered().iterator();
while (iter.hasNext()) {
String key = iter.next();
Iterator<FRRoom> iter2 = set.get(key).iterator();
label: while (iter2.hasNext()) {
FRRoom mRoom = iter2.next();
// condition of adding depending on the caller
if (caller.equals(AddCollectionCaller.ADDALLFAV)) {
if (selectedRooms.contains(mRoom)) {
break label;
}
}
if (addOnlyUID) {
collection.add(mRoom.getUid());
} else {
collection.add(mRoom);
}
}
}
}
/**
* Initialize the autocomplete suggestion list
*/
private void createSuggestionsList() {
mAutoCompleteSuggestionListView = new LabeledListViewElement(this);
mAutoCompleteSuggestionInputBarElement
.addView(mAutoCompleteSuggestionListView);
mAutoCompleteSuggestionListView
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int pos, long id) {
FRRoom room = mAutoCompleteSuggestionArrayListFRRoom
.get(pos);
addRoomToCheck(room);
searchButton.setEnabled(auditSubmit() == 0);
// refresh the autocomplete, such that selected rooms
// are not displayed
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
addAllFavsToAutoComplete();
} else {
autoCompletedUpdated();
}
// WE DONT REMOVE the text in the input bar
// INTENTIONNALLY: user may want to select multiple
// rooms in the same building
}
});
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
}
private void addRoomToCheck(FRRoom room) {
// we only add if it already contains the room
if (!selectedRooms.contains(room)) {
selectedRooms.add(room);
mSummarySelectedRoomsTextView.setText(u
.getSummaryTextFromCollection(selectedRooms));
} else {
Log.e(this.getClass().toString(),
"room cannot be added: already added");
}
}
/**
* Reset the year, month, day, hour_start, minute_start, hour_end,
* minute_end to their initial values. DONT forget to update the date/time
* pickers afterwards.
*/
private void resetTimes() {
FRPeriod mFrPeriod = FRTimes.getNextValidPeriod();
resetTimes(mFrPeriod);
}
private void resetTimes(FRPeriod mFrPeriod) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampStart());
yearSelected = mCalendar.get(Calendar.YEAR);
monthSelected = mCalendar.get(Calendar.MONTH);
dayOfMonthSelected = mCalendar.get(Calendar.DAY_OF_MONTH);
startHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
startMinSelected = mCalendar.get(Calendar.MINUTE);
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampEnd());
endHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
endMinSelected = mCalendar.get(Calendar.MINUTE);
}
private void reset() {
searchButton.setEnabled(false);
// // reset the list of selected rooms
selectedRooms.clear();
// mSummarySelectedRoomsTextView
// .setText(getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms));
mAutoCompleteSuggestionArrayListFRRoom.clear();
resetTimes();
anyButton.setChecked(true);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
specButton.setChecked(false);
favButton.setChecked(false);
userDefButton.setChecked(false);
// resetUserDefined(); TODO
freeButton.setChecked(true);
// verify the submit
searchButton.setEnabled(auditSubmit() == 0);
upToEndHourButton.setEnabled(true);
upToEndSelected = false;
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// show the buttons
updateDateTimePickersAndButtons();
}
/**
* Updates ALL the date and time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date/time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date/time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateDateTimePickersAndButtons() {
updateDatePickerAndButton();
updateStartTimePickerAndButton();
updateEndTimePickerAndButton();
}
/**
* Updates the date <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date has changed from somewhere else,
* the <code>PickerDialog</code> will reopen with the new value.
*
*/
private void updateDatePickerAndButton() {
// creating selected time
Calendar selected = Calendar.getInstance();
selected.setTimeInMillis(prepareFRFrPeriod().getTimeStampStart());
showDatePicker.setText(times.getDateText(selected, dateFormat));
mDatePickerDialog.updateDate(yearSelected, monthSelected,
dayOfMonthSelected);
}
/**
* Updates the START time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the START time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the START time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateStartTimePickerAndButton() {
showStartTimePicker.setText(generateTime(
getString(R.string.freeroom_selectstartHour),
prepareFRFrPeriod().getTimeStampStart()));
mTimePickerStartDialog.updateTime(startHourSelected, startMinSelected);
}
/**
* Updates the END time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the END time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the END time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateEndTimePickerAndButton() {
showEndTimePicker.setText(generateTime(
getString(R.string.freeroom_selectendHour), prepareFRFrPeriod()
.getTimeStampEnd()));
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK
|| (endHourSelected == FRTimes.LAST_HOUR_CHECK - 1 && endMinSelected != 0)) {
addHourButton.setEnabled(false);
} else {
addHourButton.setEnabled(true);
}
mTimePickerEndDialog.updateTime(endHourSelected, endMinSelected);
}
/**
* Generates the start and end time summary. On small screens, specific
* start and end are not written.
*
* @param prefix
* eg. "start"
* @param time
* in milliseconds, time to display
* @return a formatted time with an optional prefix.
*/
private String generateTime(String prefix, long time) {
String returned = "";
if (activityWidth < 480) {
returned = timeFormat.format(new Date(time));
} else {
returned = prefix + " " + timeFormat.format(new Date(time));
}
return returned;
}
/**
* Construct the <code>FRPeriod</code> object asscociated with the current
* selected times.
*
* @return
*/
private FRPeriod prepareFRFrPeriod() {
Calendar start = Calendar.getInstance();
start.set(yearSelected, monthSelected, dayOfMonthSelected,
startHourSelected, startMinSelected, 0);
start.set(Calendar.MILLISECOND, 0);
Calendar end = Calendar.getInstance();
end.set(yearSelected, monthSelected, dayOfMonthSelected,
endHourSelected, endMinSelected, 0);
end.set(Calendar.MILLISECOND, 0);
// constructs the request
return new FRPeriod(start.getTimeInMillis(), end.getTimeInMillis(),
false);
}
/**
* Prepare the actual query to send and set it in the controller
*/
private void prepareSearchQuery() {
FRPeriod period = prepareFRFrPeriod();
List<String> mUIDList = new ArrayList<String>(selectedRooms.size());
if (favButton.isChecked()) {
addAllFavoriteToCollection(mUIDList, AddCollectionCaller.SEARCH,
true);
}
SetArrayList<FRRoom> userDef = new SetArrayList<FRRoom>(
selectedRooms.size());
if (userDefButton.isChecked()) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom room = iter.next();
userDef.add(room);
mUIDList.add(room.getUid());
}
}
boolean any = anyButton.isChecked();
boolean fav = favButton.isChecked();
boolean user = userDefButton.isChecked();
// TODO change group accordingly, set to 1 by default and for testing
// purpose
FRRequestDetails details = new FRRequestDetails(period,
freeButton.isChecked(), mUIDList, any, fav, user, userDef, 1);
mModel.setFRRequestDetails(details, true);
refresh();
mSearchDialog.dismiss();
resetUserDefined(); // cleans the selectedRooms of userDefined
}
/**
* Check that the times set are valid, according to the shared definition.
*
* @return 0 if times are valids, positive integer otherwise
*/
private int auditTimes() {
// NOT EVEN SET, we don't bother checking
if (yearSelected == -1 || monthSelected == -1
|| dayOfMonthSelected == -1) {
return 1;
}
if (startHourSelected == -1 || endHourSelected == -1
|| startMinSelected == -1 || endMinSelected == -1) {
return 1;
}
// IF SET, we use the shared method checking the prepared period
String errors = FRTimes.validCalendarsString(prepareFRFrPeriod());
if (errors.equals("")) {
return 0;
}
Toast.makeText(
getApplicationContext(),
"Please review the time, should be between Mo-Fr 8am-7pm.\n"
+ "The end should also be after the start, and at least 5 minutes.",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Errors remaining: \n" + errors, Toast.LENGTH_LONG).show();
return 1;
}
/**
* This method check if the client is allowed to submit a request to the
* server.
*
* @return 0 if there is no error and the client can send the request,
* something else otherwise.
*/
private int auditSubmit() {
if (selectedRooms == null
|| (!anyButton.isChecked() && !favButton.isChecked()
&& userDefButton.isChecked() && selectedRooms.isEmpty())) {
return 1;
}
if (anyButton.isChecked()
&& (favButton.isChecked() || userDefButton.isChecked())) {
return 1;
}
if (!anyButton.isChecked() && !favButton.isChecked()
&& !userDefButton.isChecked()) {
return 1;
}
boolean isFavEmpty = mModel.getFavorites().isEmpty();
if (favButton.isChecked()
&& isFavEmpty
&& (!userDefButton.isChecked() || (userDefButton.isChecked() && selectedRooms
.isEmpty()))) {
return 1;
}
// we dont allow query all the room, including non-free
if (anyButton.isChecked() && !freeButton.isChecked()) {
return 1;
}
return auditTimes();
}
@Override
public void autoCompletedUpdated() {
mAdapter.notifyDataSetInvalidated();
mAutoCompleteSuggestionArrayListFRRoom.clear();
// TODO: adapt to use the new version of autocomplete mapped by building
Iterator<List<FRRoom>> iter = mModel.getAutoComplete().values()
.iterator();
// TODO: syso
System.out.println(mModel.getAutoComplete().values().size());
while (iter.hasNext()) {
List<FRRoom> list = iter.next();
// TODO: syso
System.out.println(list.size());
Iterator<FRRoom> iterroom = list.iterator();
while (iterroom.hasNext()) {
FRRoom room = iterroom.next();
// rooms that are already selected are not displayed...
if (!selectedRooms.contains(room)) {
mAutoCompleteSuggestionArrayListFRRoom.add(room);
}
}
}
if (mSearchByUriTriggered) {
searchByUriMakeRequest(mAutoCompleteSuggestionArrayListFRRoom);
}
mAdapter.notifyDataSetChanged();
}
@Override
public void refreshOccupancies() {
refresh();
}
}
|
package org.pocketcampus.plugin.freeroom.android.views;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.tracker.Tracker;
import org.pocketcampus.android.platform.sdk.ui.element.InputBarElement;
import org.pocketcampus.android.platform.sdk.ui.element.OnKeyPressedListener;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout;
import org.pocketcampus.android.platform.sdk.ui.list.LabeledListViewElement;
import org.pocketcampus.plugin.freeroom.R;
import org.pocketcampus.plugin.freeroom.android.FreeRoomAbstractView;
import org.pocketcampus.plugin.freeroom.android.FreeRoomController;
import org.pocketcampus.plugin.freeroom.android.FreeRoomModel;
import org.pocketcampus.plugin.freeroom.android.adapter.ActualOccupationArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewFavoriteAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.FRRoomSuggestionArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.iface.IFreeRoomView;
import org.pocketcampus.plugin.freeroom.android.utils.FRRequestDetails;
import org.pocketcampus.plugin.freeroom.android.utils.SetArrayList;
import org.pocketcampus.plugin.freeroom.shared.ActualOccupation;
import org.pocketcampus.plugin.freeroom.shared.AutoCompleteRequest;
import org.pocketcampus.plugin.freeroom.shared.FRPeriod;
import org.pocketcampus.plugin.freeroom.shared.FRRequest;
import org.pocketcampus.plugin.freeroom.shared.FRRoom;
import org.pocketcampus.plugin.freeroom.shared.ImWorkingRequest;
import org.pocketcampus.plugin.freeroom.shared.Occupancy;
import org.pocketcampus.plugin.freeroom.shared.WorkingOccupancy;
import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.Toast;
import com.markupartist.android.widget.ActionBar.Action;
/**
* <code>FreeRoomHomeView</code> is the main <code>View</code>, it's the entry
* of the plugin. It displays the availabilities for the search given, and for
* your favorites NOW at the start.
* <p>
* All others views are supposed to be popup windows, therefore it's always
* visible.
*
* @author FreeRoom Project Team (2014/05)
* @author Julien WEBER <[email protected]>
* @author Valentin MINDER <[email protected]>
*/
public class FreeRoomHomeView extends FreeRoomAbstractView implements
IFreeRoomView {
/**
* FreeRoom controller in MVC scheme.
*/
private FreeRoomController mController;
/**
* FreeRoom model in MVC scheme.
*/
private FreeRoomModel mModel;
/**
* Titled layout that holds the title and the main layout.
*/
private StandardTitledLayout titleLayout;
/**
* Main layout that hold all UI components.
*/
private LinearLayout mainLayout;
/**
* TextView to display a short message about what is currently displayed.
* It's also the anchor to all the popup windows.
*/
private TextView mTextView;
/**
* ExpandableListView to display the results of occupancies building by
* building.
*/
private ExpandableListView mExpListView;
/**
* Adapter for the results (to display the occupancies).
*/
private ExpandableListViewAdapter<Occupancy> mExpListAdapter;
/**
* View that holds the INFO popup content, defined in xml in layout folder.
*/
private View popupInfoView;
/**
* Window that holds the INFO popup. Note: popup window can be closed by:
* the closing button (red cross), back button, or clicking outside the
* popup.
*/
private PopupWindow popupInfoWindow;
/**
* View that holds the SEARCH dialog content, defined in xml in layout
* folder.
*/
private View mSearchView;
/**
* ListView that holds previous searches.
*/
private ListView searchPreviousListView;
private AlertDialog searchDialog;
/**
* View that holds the FAVORITES popup content, defined in xml in layout
* folder.
*/
private View popupFavoritesView;
/**
* Window that holds the FAVORITES popup. Note: popup window can be closed
* by: the closing button (red cross), back button, or clicking outside the
* popup.
*/
private PopupWindow popupFavoritesWindow;
/**
* View that holds the ADDROOM popup content, defined in xml in layout
* folder.
*/
private View popupAddRoomView;
/**
* Window that holds the ADDROOM popup. Note: popup window can be closed by:
* the closing button (red cross), back button, or clicking outside the
* popup.
*/
private PopupWindow popupAddRoomWindow;
/**
* View that holds the SHARE popup content, defined in xml in layout folder.
*/
private View popupShareView;
/**
* Window that holds the SHARE popup. Note: popup window can be closed by:
* the closing button (red cross), back button, or clicking outside the
* popup.
*/
private PopupWindow popupShareWindow;
private int activityWidth;
private int activityHeight;
private LayoutInflater mLayoutInflater;
/**
* Action to perform a customized search.
*/
private Action search = new Action() {
public void performAction(View view) {
refreshPopupSearch();
searchDialog.show();
}
public int getDrawable() {
return R.drawable.magnify2x06;
}
};
/**
* Action to edit the user's favorites.
*/
private Action editFavorites = new Action() {
public void performAction(View view) {
mAdapterFav.notifyDataSetChanged();
popupFavoritesWindow.showAsDropDown(mTextView, 0, 0);
}
public int getDrawable() {
return R.drawable.star2x28;
}
};
/**
* Action to refresh the view (it sends the same stored request again).
* <p>
* TODO: useful? useless ? delete !
*/
private Action refresh = new Action() {
public void performAction(View view) {
refresh();
}
public int getDrawable() {
return R.drawable.refresh2x01;
}
};
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return FreeRoomController.class;
}
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
// Tracker
Tracker.getInstance().trackPageView("freeroom");
// Get and cast the controller and model
mController = (FreeRoomController) controller;
mModel = (FreeRoomModel) controller.getModel();
// Setup the layout
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
titleLayout = (StandardTitledLayout) layoutInflater.inflate(
R.layout.freeroom_layout_home, null);
mainLayout = (LinearLayout) titleLayout
.findViewById(R.id.freeroom_layout_home_main_layout);
// The ActionBar is added automatically when you call setContentView
setContentView(titleLayout);
titleLayout.setTitle(getString(R.string.freeroom_title_main_title));
mExpListView = (ExpandableListView) titleLayout
.findViewById(R.id.freeroom_layout_home_list);
mTextView = (TextView) titleLayout
.findViewById(R.id.freeroom_layout_home_text_summary);
setTextSummary(getString(R.string.freeroom_home_init_please_wait));
initializeView();
titleLayout.removeView(mainLayout);
titleLayout.addFillerView(mainLayout);
initDefaultRequest();
refresh();
// TODO: NOT the right call to handle the intent
handleIntent(getIntent());
}
/**
* This is called when the Activity is resumed.
*
* If the user presses back on the Authentication window, This Activity is
* resumed but we do not have the freeroomCookie. In this case we close the
* Activity.
*/
@Override
protected void onResume() {
super.onResume();
/*
* if(mModel != null && mModel.getFreeRoomCookie() == null) { // Resumed
* and lot logged in? go back finish(); }
*/
if (mController != null) {
mController.sendFRRequest(this);
}
}
/**
* Handles an intent for a search coming from outside.
* <p>
* // TODO: handles occupancy.epfl.ch + pockecampus://
*
* @param intent
* the intent to handle
*/
private void handleSearchIntent(Intent intent) {
// TODO: if search launched by other plugin.
}
@Override
public void initializeView() {
mLayoutInflater = this.getLayoutInflater();
// retrieve display dimensions
Rect displayRectangle = new Rect();
Window window = this.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
activityWidth = displayRectangle.width();
activityHeight = displayRectangle.height();
mExpListAdapter = new ExpandableListViewAdapter<Occupancy>(
getApplicationContext(), mModel.getOccupancyResults(),
mController, this);
mExpListView.setAdapter(mExpListAdapter);
addActionToActionBar(refresh);
addActionToActionBar(editFavorites);
addActionToActionBar(search);
initPopupInfoRoom();
initPopupSearch();
initPopupFavorites();
initPopupAddRoom();
initPopupShare();
}
/**
* Inits the popup to diplay the information about a room.
*/
private void initPopupInfoRoom() {
// construct the popup
// it MUST fill the parent in height, such that weight works in xml for
// heights. Otherwise, some elements may not be displayed anymore
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
popupInfoView = layoutInflater.inflate(
R.layout.freeroom_layout_popup_info, null);
popupInfoWindow = new PopupWindow(popupInfoView,
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
// allows outside clicks to close the popup
popupInfoWindow.setOutsideTouchable(true);
popupInfoWindow.setBackgroundDrawable(new BitmapDrawable());
TextView tv = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_name);
tv.setText("room"); // TODO
}
/**
* Inits the popup to diplay the favorites.
*/
private ArrayList<String> buildings;
private Map<String, List<FRRoom>> rooms;
private ExpandableListViewFavoriteAdapter mAdapterFav;
private void initPopupFavorites() {
// construct the popup
// it MUST fill the parent in height, such that weight works in xml for
// heights. Otherwise, some elements may not be displayed anymore
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
popupFavoritesView = layoutInflater.inflate(
R.layout.freeroom_layout_popup_fav, null);
popupFavoritesWindow = new PopupWindow(popupFavoritesView,
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
// allows outside clicks to close the popup
popupFavoritesWindow.setOutsideTouchable(true);
popupFavoritesWindow.setBackgroundDrawable(new BitmapDrawable());
Button tv = (Button) popupFavoritesView
.findViewById(R.id.freeroom_layout_popup_fav_add);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!popupAddRoomWindow.isShowing()) {
showPopupAddRoom(true);
}
}
});
ExpandableListView lv = (ExpandableListView) popupFavoritesView
.findViewById(R.id.freeroom_layout_popup_fav_list);
// TODO: THIS IS AWWWWWWWFUUUUULLL
// PLEASE STORE FRROOM OBJECTS, NOT THESE UIDS
Map<String, String> allFavorites = mModel.getAllRoomMapFavorites();
HashSet<FRRoom> favoritesAsFRRoom = new HashSet<FRRoom>();
for (Entry<String, String> e : allFavorites.entrySet()) {
// Favorites beeing stored as uid -> doorCode
favoritesAsFRRoom.add(new FRRoom(e.getValue(), e.getKey()));
}
rooms = mModel.sortFRRoomsByBuildingsAndFavorites(favoritesAsFRRoom,
false);
buildings = new ArrayList<String>(rooms.keySet());
mAdapterFav = new ExpandableListViewFavoriteAdapter(this, buildings,
rooms, mModel);
lv.setAdapter(mAdapterFav);
mAdapterFav.notifyDataSetChanged();
}
// true: fav // false: user-def search
private boolean calling = true;
private void showPopupAddRoom(boolean calling) {
popupAddRoomWindow.showAsDropDown(mTextView, 0, 55);
// TODO: reset the data ? the text input, the selected room ?
this.calling = calling;
}
private void treatEndAddPopup() {
if (calling) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom mRoom = iter.next();
mModel.addRoomFavorites(mRoom.getUid(), mRoom.getDoorCode());
}
resetUserDefined();
} else {
// we do nothing: reset will be done at search time
}
}
private void initPopupAddRoom() {
// construct the popup
// it MUST fill the parent in height, such that weight works in xml for
// heights. Otherwise, some elements may not be displayed anymore
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
popupAddRoomView = layoutInflater.inflate(
R.layout.freeroom_layout_popup_add_room, null);
popupAddRoomWindow = new PopupWindow(popupAddRoomView,
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
// allows outside clicks to close the popup
popupAddRoomWindow.setOutsideTouchable(true);
popupAddRoomWindow.setBackgroundDrawable(new BitmapDrawable());
Button bt_done = (Button) popupAddRoomView
.findViewById(R.id.freeroom_layout_popup_add_room_done);
bt_done.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popupAddRoomWindow.dismiss();
treatEndAddPopup();
}
});
mSummarySelectedRoomsTextView = (TextView) popupAddRoomView
.findViewById(R.id.freeroom_layout_popup_add_room_summary);
UIConstructInputBar();
LinearLayout ll = (LinearLayout) popupAddRoomView
.findViewById(R.id.freeroom_layout_popup_add_layout_main);
ll.addView(mAutoCompleteSuggestionInputBarElement);
createSuggestionsList();
}
private void initPopupShare() {
// construct the popup
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
popupShareView = layoutInflater.inflate(
R.layout.freeroom_layout_popup_share, null);
popupShareWindow = new PopupWindow(popupShareView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
// allows outside clicks to close the popup
popupShareWindow.setOutsideTouchable(true);
popupShareWindow.setBackgroundDrawable(new BitmapDrawable());
}
public void showPopupShare(final FRPeriod mPeriod, final FRRoom mRoom) {
final TextView tv = (TextView) popupShareView
.findViewById(R.id.freeroom_layout_popup_share_textBasic);
tv.setText(wantToShare(mPeriod, mRoom, ""));
final EditText ed = (EditText) popupShareView
.findViewById(R.id.freeroom_layout_popup_share_text_edit);
ed.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
tv.setText(wantToShare(mPeriod, mRoom, ed.getText().toString()));
return true;
}
});
Button shareWithServer = (Button) popupShareView
.findViewById(R.id.freeroom_layout_popup_share_server);
shareWithServer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, false, ed.getText().toString());
popupShareWindow.dismiss();
}
});
Button shareWithFriends = (Button) popupShareView
.findViewById(R.id.freeroom_layout_popup_share_friends);
shareWithFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, true, ed.getText().toString());
popupShareWindow.dismiss();
}
});
Spinner spinner = (Spinner) popupShareView
.findViewById(R.id.freeroom_layout_popup_share_spinner_course);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO do something with that
System.out.println("selected" + arg0.getItemAtPosition(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO find out how is this relevant
System.out.println("nothing selected!");
}
});
// TODO: make it in center of screen!
popupShareWindow.showAsDropDown(mTextView, 0, 0);
}
/**
* Inits the popup to diplay the information about a room.
*/
private void initPopupSearch() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Various setter methods to set the searchDialog characteristics
builder.setTitle(getString(R.string.freeroom_search_title));
builder.setPositiveButton(getString(R.string.freeroom_search_search),
null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(getString(R.string.freeroom_search_reset),
null);
builder.setIcon(R.drawable.magnify2x06);
// Get the AlertDialog from create()
searchDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = searchDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
searchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
searchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
searchDialog.getWindow().setAttributes(lp);
mSearchView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_search, null);
// these work perfectly
mSearchView.setMinimumWidth((int) (activityWidth * 0.9f));
mSearchView.setMinimumHeight((int) (activityHeight * 0.8f));
searchDialog.setView(mSearchView);
searchDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
searchButton.setEnabled(auditSubmit() == 0);
}
});
// this is necessary o/w buttons don't exists!
searchDialog.hide();
searchDialog.show();
searchDialog.dismiss();
resetButton = searchDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
searchButton = searchDialog.getButton(DialogInterface.BUTTON_POSITIVE);
searchPreviousListView = (ListView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_prev_search);
// TODO: previous search
// searchPreviousListView.setAdapter();
initSearch();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
System.out
.println("TOuch outside the dialog ******************** ");
searchDialog.dismiss();
}
return false;
}
/**
* Overrides the legacy <code>onKeyDown</code> method in order to close the
* popupWindow if one was opened.
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Override back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
boolean flag = false;
if (popupInfoWindow.isShowing()) {
popupInfoWindow.dismiss();
flag = true;
}
if (searchDialog.isShowing()) {
searchDialog.dismiss();
flag = true;
}
if (popupFavoritesWindow.isShowing()) {
popupFavoritesWindow.dismiss();
flag = true;
}
selectedRooms.clear();
if (flag) {
resetUserDefined();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void anyError() {
setTextSummary(getString(R.string.freeroom_home_error_sorry));
}
/**
* Sets the summary text box to the specified text.
*
* @param text
* the new summary to be displayed.
*/
private void setTextSummary(String text) {
mTextView.setText(text);
}
/**
* Constructs the default request (check all the favorites for the next
* valid period) and sets it in the model for future use. You may call
* <code>refresh</code> in order to send it to the server.
*/
private void initDefaultRequest() {
mModel.setFRRequestDetails(validRequest());
}
private FRRequestDetails validRequest() {
Set<String> set = mModel.getAllRoomMapFavorites().keySet();
FRRequestDetails details = null;
if (set.isEmpty()) {
// NO FAV = check all free rooms
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), true,
new ArrayList<String>(1), true, false, false,
new SetArrayList<FRRoom>());
} else {
// FAV: check occupancy of ALL favs
ArrayList<String> array = new ArrayList<String>(set.size());
array.addAll(set);
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), false,
array, false, true, false, new SetArrayList<FRRoom>());
}
return details;
}
/**
* Asks the controller to send again the request which was already set in
* the model.
*/
private void refresh() {
setTextSummary(getString(R.string.freeroom_home_please_wait));
mController.sendFRRequest(this);
}
@Override
public void freeRoomResultsUpdated() {
// we do nothing here
}
@Override
public void occupancyResultUpdated() {
// we do nothing here
}
@Override
public void occupancyResultsUpdated() {
StringBuilder build = new StringBuilder(50);
if (mModel.getOccupancyResults().isEmpty()) {
build.append(getString(R.string.freeroom_home_error_no_results));
} else {
FRRequest request = mModel.getFRRequestDetails();
if (request.isOnlyFreeRooms()) {
build.append(getString(R.string.freeroom_home_info_free_rooms));
} else {
build.append(getString(R.string.freeroom_home_info_rooms));
}
FRPeriod period = request.getPeriod();
build.append(generateFullTimeSummary(period));
}
setTextSummary(build.toString());
mExpListAdapter.notifyDataSetChanged();
updateCollapse(mExpListView, mExpListAdapter);
}
/**
* Expands all the groups if there are no more than 4 groups or not more
* than 10 results.
* <p>
* TODO defines these consts somewhere else
*
* @param ev
*/
public void updateCollapse(ExpandableListView ev,
ExpandableListViewAdapter<Occupancy> ad) {
System.out.println("check: " + ad.getGroupCount() + "/"
+ ad.getChildrenTotalCount()); // TODO delete
if (ad.getGroupCount() <= 4 || ad.getChildrenTotalCount() <= 10) {
System.out.println("i wanted to expand");
// TODO: this cause troubles in performance when first launch
for (int i = 0; i < ad.getGroupCount(); i++) {
ev.expandGroup(i);
}
}
}
/**
* Generates a string summary of a given period of time.
* <p>
* eg: "Wednesday Apr 24 from 9am to 12pm"
*
* @param period
* the period of time
* @return a string summary of a given period of time.
*/
private String generateFullTimeSummary(FRPeriod period) {
StringBuilder build = new StringBuilder(100);
Date endDate = new Date(period.getTimeStampEnd());
Date startDate = new Date(period.getTimeStampStart());
SimpleDateFormat day_month = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format));
SimpleDateFormat hour_min = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
build.append(" ");
// TODO: if date is today, use "today" instead of specifying date
build.append(getString(R.string.freeroom_check_occupancy_result_onthe));
build.append(" ");
build.append(day_month.format(startDate));
build.append(" ");
build.append(getString(R.string.freeroom_check_occupancy_result_from));
build.append(" ");
build.append(hour_min.format(startDate));
build.append(" ");
build.append(getString(R.string.freeroom_check_occupancy_result_to));
build.append(" ");
build.append(hour_min.format(endDate));
return build.toString();
}
/**
* Generates a short string summary of a given period of time.
* <p>
* eg: "9:00\n12:00pm"
*
* @param period
* the period of time
* @return a string summary of a given period of time.
*/
private String generateShortTimeSummary(FRPeriod period) {
StringBuilder build = new StringBuilder(100);
Date endDate = new Date(period.getTimeStampEnd());
Date startDate = new Date(period.getTimeStampStart());
SimpleDateFormat hour_min = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
build.append(hour_min.format(startDate));
build.append("\n");
build.append(hour_min.format(endDate));
return build.toString();
}
/**
* Put a onClickListener on an imageView in order to share the location and
* time when clicking share, if available.
*
* @param shareImageView
* the view on which to put the listener
* @param homeView
* reference to the home view
* @param mOccupancy
* the holder of data for location and time
*/
public void setShareClickListener(ImageView shareImageView,
final FreeRoomHomeView homeView, final Occupancy mOccupancy) {
if (!mOccupancy.isIsAtLeastOccupiedOnce()
&& mOccupancy.isIsAtLeastFreeOnce()) {
shareImageView.setClickable(true);
shareImageView.setImageResource(R.drawable.share);
shareImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
homeView.showPopupShare(
getMaxPeriodFromList(mOccupancy.getOccupancy()),
mOccupancy.getRoom());
}
});
} else {
shareImageView.setClickable(false);
shareImageView.setImageResource(R.drawable.share_disabled);
}
}
/**
* Finds the whole period covered by a list of contiguous and ordered of
* occupancies.
*
* @param listOccupations
* the list of occupancies.
* @return the period covered by the list
*/
private FRPeriod getMaxPeriodFromList(List<ActualOccupation> listOccupations) {
long tss = listOccupations.get(0).getPeriod().getTimeStampStart();
long tse = listOccupations.get(listOccupations.size() - 1).getPeriod()
.getTimeStampEnd();
return new FRPeriod(tss, tse, false);
}
/**
* Display the popup that provides more info about the occupation of the
* selected room.
*/
public void displayPopupInfo() {
final Occupancy mOccupancy = mModel.getDisplayedOccupancy();
if (mOccupancy != null) {
TextView tv = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_name);
final FRRoom mRoom = mOccupancy.getRoom();
String text = mRoom.getDoorCode();
if (mRoom.isSetDoorCodeAlias()) {
// alias is displayed IN PLACE of the official name
// the official name can be found in bottom of popup
text = mRoom.getDoorCodeAlias();
}
tv.setText(text);
TextView periodTextView = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_period);
periodTextView
.setText(generateShortTimeSummary(getMaxPeriodFromList(mOccupancy
.getOccupancy())));
ImageView iv = (ImageView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_share);
setShareClickListener(iv, this, mOccupancy);
ListView roomOccupancyListView = (ListView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_roomOccupancy);
roomOccupancyListView
.setAdapter(new ActualOccupationArrayAdapter<ActualOccupation>(
getApplicationContext(), mOccupancy.getOccupancy(),
mController, this));
TextView detailsTextView = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_details);
detailsTextView.setText(getInfoFRRoom(mOccupancy.getRoom()));
popupInfoWindow.showAsDropDown(mTextView, 0, 0);
}
}
private void refreshPopupSearch() {
final FRRequestDetails request = mModel.getFRRequestDetails();
if (request != null) {
refreshPopupSearch(request);
}
}
private void refreshPopupSearch(final FRRequestDetails request) {
resetTimes(request.getPeriod());
anyButton.setChecked(request.isAny());
specButton.setChecked(!request.isAny());
favButton.setChecked(request.isFav());
userDefButton.setChecked(request.isUser());
freeButton.setChecked(request.isOnlyFreeRooms());
searchButton.setEnabled(auditSubmit() == 0);
boolean enabled = !request.isAny();
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
if (enabled) {
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
}
public String wantToShare(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
// TODO: in case of "now" request (nextPeriodValid is now), just put
// "i am, now, " instead of
// time
StringBuilder textBuilder = new StringBuilder(100);
textBuilder.append(getString(R.string.freeroom_share_iwillbe) + " ");
textBuilder.append(getString(R.string.freeroom_share_in_room) + " ");
if (mRoom.isSetDoorCodeAlias()) {
textBuilder.append(mRoom.getDoorCodeAlias() + " ("
+ mRoom.getDoorCode() + ") ");
} else {
textBuilder.append(mRoom.getDoorCode() + " ");
}
// TODO: which period to use ?
// in case of specified in request, we should use the personalized
// period
textBuilder.append(generateFullTimeSummary(mPeriod) + ". ");
if (toShare.length() == 0) {
textBuilder.append(getString(R.string.freeroom_share_please_come));
} else {
textBuilder.append(toShare);
}
return textBuilder.toString();
}
private void share(FRPeriod mPeriod, FRRoom mRoom, boolean withFriends,
String toShare) {
WorkingOccupancy work = new WorkingOccupancy(mPeriod, mRoom);
ImWorkingRequest request = new ImWorkingRequest(work,
mModel.getAnonymID());
mController.prepareImWorking(request);
mController.ImWorking(this);
if (withFriends) {
shareWithFriends(mPeriod, mRoom, toShare);
}
}
/**
* Construct the Intent to share the location and time with friends. The
* same information is shared with the server at the same time
*
* @param mPeriod
* time period
* @param mRoom
* location
*/
private void shareWithFriends(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
String sharing = wantToShare(mPeriod, mRoom, toShare);
sharing += " \n" + getString(R.string.freeroom_share_ref_pocket);
Log.v(this.getClass().getName() + "-share", "sharing:" + sharing);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sharing);
// this ensure that our handler, that is handling home-made text types,
// will also work. But our won't work outside the app, which is needed,
// because it waits for this special type.
/**
* Converts a FRRoom to a String of only major properties, in order to
* display them. It includes name (with alias), type, capacity, surface and
* UID.
* <p>
* TODO: this method may be changed
*
* @param mFrRoom
* @return
*/
private String getInfoFRRoom(FRRoom mFrRoom) {
StringBuilder builder = new StringBuilder(50);
if (mFrRoom.isSetDoorCode()) {
if (mFrRoom.isSetDoorCodeAlias()) {
builder.append(mFrRoom.getDoorCode() + " (alias: "
+ mFrRoom.getDoorCodeAlias() + ")");
} else {
builder.append(mFrRoom.getDoorCode());
}
}
if (mFrRoom.isSetTypeFR() || mFrRoom.isSetTypeEN()) {
builder.append(" / " + getString(R.string.freeroom_popup_info_type)
+ ": ");
if (mFrRoom.isSetTypeFR()) {
builder.append(mFrRoom.getTypeFR());
}
if (mFrRoom.isSetTypeFR() && mFrRoom.isSetTypeEN()) {
builder.append(" / ");
}
if (mFrRoom.isSetTypeFR()) {
builder.append(mFrRoom.getTypeEN());
}
}
if (mFrRoom.isSetCapacity()) {
builder.append(" / "
+ getString(R.string.freeroom_popup_info_capacity) + ": "
+ mFrRoom.getCapacity() + " "
+ getString(R.string.freeroom_popup_info_places));
}
if (mFrRoom.isSetSurface()) {
builder.append(" / "
+ getString(R.string.freeroom_popup_info_surface) + ": "
+ mFrRoom.getSurface() + " "
+ getString(R.string.freeroom_popup_info_sqm));
}
// TODO: for production, remove UID (it's useful for debugging for the
// moment)
if (mFrRoom.isSetUid()) {
// uniq UID must be 1201XXUID, with XX filled with 0 such that
// it has 10 digit
// the prefix "1201" indiquates that it's a EPFL room (not a phone,
// a computer)
String communUID = "1201";
String roomUID = mFrRoom.getUid();
for (int i = roomUID.length() + 1; i <= 6; i++) {
communUID += "0";
}
communUID += roomUID;
builder.append(" / "
+ getString(R.string.freeroom_popup_info_uniqID) + ": "
+ communUID);
}
return builder.toString();
}
// ** REUSED FROM SCRATCH FROM FreeRoomSearchView ** //
private SetArrayList<FRRoom> selectedRooms;
private ListView mAutoCompleteSuggestionListView;
private List<FRRoom> mAutoCompleteSuggestionArrayListFRRoom;
/** The input bar to make the search */
private InputBarElement mAutoCompleteSuggestionInputBarElement;
/** Adapter for the <code>mListView</code> */
private FRRoomSuggestionArrayAdapter<FRRoom> mAdapter;
private DatePickerDialog mDatePickerDialog;
private TimePickerDialog mTimePickerStartDialog;
private TimePickerDialog mTimePickerEndDialog;
private Button showDatePicker;
private Button showStartTimePicker;
private Button showEndTimePicker;
private RadioButton specButton;
private RadioButton anyButton;
private CheckBox favButton;
private CheckBox userDefButton;
/**
* TRUE: "only free rooms" FALSE: "allow non-free rooms"
*/
private CheckBox freeButton;
private Button searchButton;
private Button resetButton;
private ImageButton addHourButton;
private ImageButton upToEndHourButton;
private TextView mSummarySelectedRoomsTextView;
private int yearSelected = -1;
private int monthSelected = -1;
private int dayOfMonthSelected = -1;
private int startHourSelected = -1;
private int startMinSelected = -1;
private int endHourSelected = -1;
private int endMinSelected = -1;
private SimpleDateFormat dateFormat;
private SimpleDateFormat timeFormat;
private LinearLayout mOptionalLineLinearLayoutWrapper;
private LinearLayout mOptionalLineLinearLayoutContainer;
private void initSearch() {
mOptionalLineLinearLayoutWrapper = (LinearLayout) searchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper);
mOptionalLineLinearLayoutContainer = (LinearLayout) searchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_container);
selectedRooms = new SetArrayList<FRRoom>();
formatters();
// createSuggestionsList();
// addAllFavsToAutoComplete();
mAutoCompleteSuggestionArrayListFRRoom = new ArrayList<FRRoom>(10);
resetTimes();
UIConstructPickers();
UIConstructButton();
// UIConstructInputBar();
reset();
}
private void formatters() {
dateFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format));
timeFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
}
private void UIConstructPickers() {
// First allow the user to select a date
showDatePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_date);
mDatePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int nYear,
int nMonthOfYear, int nDayOfMonth) {
yearSelected = nYear;
monthSelected = nMonthOfYear;
dayOfMonthSelected = nDayOfMonth;
updateDatePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, yearSelected, monthSelected, dayOfMonthSelected);
showDatePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDatePickerDialog.show();
}
});
// Then the starting time of the period
showStartTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_start);
mTimePickerStartDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
int previous = startHourSelected;
startHourSelected = nHourOfDay;
startMinSelected = nMinute;
if (startHourSelected < FRTimes.FIRST_HOUR_CHECK) {
startHourSelected = FRTimes.FIRST_HOUR_CHECK;
startMinSelected = 0;
}
if (startHourSelected >= FRTimes.LAST_HOUR_CHECK) {
startHourSelected = FRTimes.LAST_HOUR_CHECK - 1;
startMinSelected = 0;
}
if (startHourSelected != -1) {
int shift = startHourSelected - previous;
int newEndHour = endHourSelected + shift;
if (newEndHour > FRTimes.LAST_HOUR_CHECK) {
newEndHour = FRTimes.LAST_HOUR_CHECK;
}
if (newEndHour < FRTimes.FIRST_HOUR_CHECK) {
newEndHour = FRTimes.FIRST_HOUR_CHECK + 1;
}
endHourSelected = newEndHour;
if (endHourSelected == FRTimes.LAST_HOUR_CHECK) {
endMinSelected = 0;
}
updateEndTimePickerAndButton();
}
updateStartTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, startHourSelected, startMinSelected, true);
showStartTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerStartDialog.show();
}
});
// Then the ending time of the period
showEndTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end);
mTimePickerEndDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
endHourSelected = nHourOfDay;
endMinSelected = nMinute;
if (endHourSelected < startHourSelected) {
endHourSelected = startHourSelected + 1;
}
if (endHourSelected < FRTimes.FIRST_HOUR_CHECK) {
endHourSelected = FRTimes.FIRST_HOUR_CHECK + 1;
endMinSelected = 0;
}
if (endHourSelected == FRTimes.FIRST_HOUR_CHECK
&& endMinSelected <= FRTimes.MIN_MINUTE_INTERVAL) {
endMinSelected = FRTimes.MIN_MINUTE_INTERVAL;
// TODO: if start is not 8h00 (eg 8h10 dont work)
}
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
}
updateEndTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, endHourSelected, endMinSelected, true);
showEndTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerEndDialog.show();
}
});
}
private void resetUserDefined() {
// TODO: add/remove
// mGlobalSubLayout.removeView(mAutoCompleteSuggestionInputBarElement);
// mGlobalSubLayout.removeView(mSummarySelectedRoomsTextView);
selectedRooms.clear();
userDefButton.setChecked(false);
mSummarySelectedRoomsTextView
.setText(getSummaryTextFromCollection(selectedRooms));
mAutoCompleteSuggestionInputBarElement.setInputText("");
}
private void UIConstructButton() {
specButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_spec);
specButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (specButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(true);
anyButton.setChecked(false);
anyButton.setEnabled(true);
specButton.setChecked(true);
freeButton.setChecked(false);
boolean enabled = true;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// TODO: is this great ? this guarantees that search is always
// available, but requires two steps to remove the fav (ass
// user-def, remove fav)
favButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
anyButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_any);
anyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (anyButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(false);
// TODO
// resetUserDefined();
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
favButton.setChecked(false);
userDefButton.setChecked(false);
freeButton.setChecked(true);
anyButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
favButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_fav);
favButton.setEnabled(true);
favButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!userDefButton.isChecked()) {
favButton.setChecked(true);
}
anyButton.setChecked(false);
specButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
userDefButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user);
userDefButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (userDefButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
// TODO: init and use the data.
showPopupAddRoom(false);
} else if (!favButton.isChecked()) {
userDefButton.setChecked(true);
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
showPopupAddRoom(false);
} else {
resetUserDefined();
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
freeButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_non_free);
freeButton.setEnabled(true);
freeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!freeButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
searchButton.setEnabled(auditSubmit() == 0);
searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
prepareSearchQuery();
}
});
resetButton.setEnabled(true);
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
reset();
// addAllFavsToAutoComplete();
// we reset the input bar...
// TODO
// mAutoCompleteSuggestionInputBarElement.setInputText("");
}
});
addHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_plus);
addHourButton.setEnabled(true);
addHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (endHourSelected <= 18) {
endHourSelected += 1;
updateEndTimePickerAndButton();
mTimePickerEndDialog.updateTime(endHourSelected,
endMinSelected);
}
if (endHourSelected >= 19) {
addHourButton.setEnabled(false);
}
}
});
upToEndHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_toend);
upToEndHourButton.setEnabled(true);
upToEndHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
updateEndTimePickerAndButton();
mTimePickerEndDialog
.updateTime(endHourSelected, endMinSelected);
searchButton.setEnabled(auditSubmit() == 0);
}
});
// on vertical screens, choose fav and choose user-def are vertically
// aligned
// on horizontal screens, there are horizontally aligned.
if (activityHeight > activityWidth) {
LinearLayout mLinearLayout = (LinearLayout) searchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_semi);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
}
}
// TODO: the InputBar is not used so far
private void UIConstructInputBar() {
final IFreeRoomView view = this;
mAutoCompleteSuggestionInputBarElement = new InputBarElement(
this,
null,
getString(R.string.freeroom_check_occupancy_search_inputbarhint));
mAutoCompleteSuggestionInputBarElement
.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
mAutoCompleteSuggestionInputBarElement
.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
Log.v(this.getClass().toString(),
"we do nothing here... with query: "
+ query);
}
return true;
}
});
mAutoCompleteSuggestionInputBarElement
.setOnButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
if (query.length() >= 2) {
AutoCompleteRequest request = new AutoCompleteRequest(
query);
mController.autoCompleteBuilding(view, request);
}
}
});
mAdapter = new FRRoomSuggestionArrayAdapter<FRRoom>(
getApplicationContext(),
mAutoCompleteSuggestionArrayListFRRoom, mModel);
mAutoCompleteSuggestionInputBarElement
.setOnKeyPressedListener(new OnKeyPressedListener() {
@Override
public void onKeyPressed(String text) {
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
mAutoCompleteSuggestionInputBarElement
.setButtonText(null);
mAutoCompleteSuggestionListView.invalidate();
addAllFavsToAutoComplete();
} else {
mAutoCompleteSuggestionInputBarElement
.setButtonText("");
if (text.length() >= 2) {
AutoCompleteRequest request = new AutoCompleteRequest(
text);
mController.autoCompleteBuilding(view, request);
}
}
}
});
}
private void addAllFavsToAutoComplete() {
Map<String, String> map = mModel.getAllRoomMapFavorites();
mAutoCompleteSuggestionArrayListFRRoom.clear();
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String uid = iter.next();
String doorCode = map.get(uid);
FRRoom room = new FRRoom(doorCode, uid);
if (!selectedRooms.contains(room)) {
mAutoCompleteSuggestionArrayListFRRoom.add(room);
}
}
mAdapter.notifyDataSetChanged();
}
/**
* Initialize the autocomplete suggestion list
*/
private void createSuggestionsList() {
mAutoCompleteSuggestionListView = new LabeledListViewElement(this);
mAutoCompleteSuggestionInputBarElement
.addView(mAutoCompleteSuggestionListView);
mAutoCompleteSuggestionListView
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int pos, long id) {
FRRoom room = mAutoCompleteSuggestionArrayListFRRoom
.get(pos);
addRoomToCheck(room);
searchButton.setEnabled(auditSubmit() == 0);
// refresh the autocomplete, such that selected rooms
// are not displayed
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
addAllFavsToAutoComplete();
} else {
autoCompletedUpdated();
}
// WE DONT REMOVE the text in the input bar
// INTENTIONNALLY: user may want to select multiple
// rooms in the same building
}
});
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
}
private void addRoomToCheck(FRRoom room) {
// we only add if it already contains the room
if (!selectedRooms.contains(room)) {
selectedRooms.add(room);
mSummarySelectedRoomsTextView
.setText(getSummaryTextFromCollection(selectedRooms));
} else {
Log.e(this.getClass().toString(),
"room cannot be added: already added");
}
}
private String getSummaryTextFromCollection(Collection<FRRoom> collec) {
Iterator<FRRoom> iter = collec.iterator();
StringBuffer buffer = new StringBuffer(collec.size() * 5);
FRRoom room = null;
buffer.append(getString(R.string.freeroom_check_occupancy_search_text_selected_rooms)
+ " ");
boolean empty = true;
while (iter.hasNext()) {
empty = false;
room = iter.next();
buffer.append(room.getDoorCode() + ", ");
}
buffer.setLength(buffer.length() - 2);
int MAX = 1000;
if (buffer.length() > MAX) {
buffer.setLength(MAX);
buffer.append("...");
}
String result = "";
if (empty) {
result = getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms);
} else {
result = buffer.toString();
}
return result;
}
/**
* Reset the year, month, day, hour_start, minute_start, hour_end,
* minute_end to their initial values. DONT forget to update the date/time
* pickers afterwards.
*/
private void resetTimes() {
FRPeriod mFrPeriod = FRTimes.getNextValidPeriod();
resetTimes(mFrPeriod);
}
private void resetTimes(FRPeriod mFrPeriod) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampStart());
yearSelected = mCalendar.get(Calendar.YEAR);
monthSelected = mCalendar.get(Calendar.MONTH);
dayOfMonthSelected = mCalendar.get(Calendar.DAY_OF_MONTH);
startHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
startMinSelected = mCalendar.get(Calendar.MINUTE);
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampEnd());
endHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
endMinSelected = mCalendar.get(Calendar.MINUTE);
}
private void reset() {
searchButton.setEnabled(false);
// // reset the list of selected rooms
selectedRooms.clear();
// mSummarySelectedRoomsTextView
// .setText(getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms));
mAutoCompleteSuggestionArrayListFRRoom.clear();
resetTimes();
anyButton.setChecked(true);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
specButton.setChecked(false);
favButton.setChecked(false);
userDefButton.setChecked(false);
// resetUserDefined(); TODO
freeButton.setChecked(true);
// verify the submit
searchButton.setEnabled(auditSubmit() == 0);
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// show the buttons
updateDateTimePickersAndButtons();
}
/**
* Updates ALL the date and time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date/time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date/time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateDateTimePickersAndButtons() {
updateDatePickerAndButton();
updateStartTimePickerAndButton();
updateEndTimePickerAndButton();
}
/**
* Updates the date <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date has changed from somewhere else,
* the <code>PickerDialog</code> will reopen with the new value.
*
* <p>
* Instead of the usual format "Wed 24 May", the date is summarize to
* "today", "yesterday", "tomorrow" when relevant.
*/
private void updateDatePickerAndButton() {
// creating selected time
Calendar selected = Calendar.getInstance();
selected.setTimeInMillis(prepareFRFrPeriod().getTimeStampStart());
// creating now time reference
Calendar now = Calendar.getInstance();
// creating tomorrow time reference
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DAY_OF_MONTH, true);
// creating yesterday time reference
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DAY_OF_MONTH, false);
if (FRTimes.compareCalendars(now, selected)) {
showDatePicker.setText(getString(R.string.freeroom_search_today));
} else if (FRTimes.compareCalendars(tomorrow, selected)) {
showDatePicker
.setText(getString(R.string.freeroom_search_tomorrow));
} else if (FRTimes.compareCalendars(yesterday, selected)) {
showDatePicker
.setText(getString(R.string.freeroom_search_yesterday));
} else {
showDatePicker.setText(dateFormat.format(selected.getTime()));
}
mDatePickerDialog.updateDate(yearSelected, monthSelected,
dayOfMonthSelected);
}
/**
* Updates the START time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the START time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the START time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateStartTimePickerAndButton() {
showStartTimePicker
.setText(getString(R.string.freeroom_check_occupancy_search_start)
+ " "
+ timeFormat.format(new Date(prepareFRFrPeriod()
.getTimeStampStart())));
mTimePickerStartDialog.updateTime(startHourSelected, startMinSelected);
}
/**
* Updates the END time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the END time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the END time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateEndTimePickerAndButton() {
showEndTimePicker
.setText(getString(R.string.freeroom_check_occupancy_search_end)
+ " "
+ timeFormat.format(new Date(prepareFRFrPeriod()
.getTimeStampEnd())));
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK
|| (endHourSelected == FRTimes.LAST_HOUR_CHECK - 1 && endMinSelected != 0)) {
addHourButton.setEnabled(false);
} else {
addHourButton.setEnabled(true);
}
mTimePickerEndDialog.updateTime(endHourSelected, endMinSelected);
}
/**
* Construct the <code>FRPeriod</code> object asscociated with the current
* selected times.
*
* @return
*/
private FRPeriod prepareFRFrPeriod() {
Calendar start = Calendar.getInstance();
start.set(yearSelected, monthSelected, dayOfMonthSelected,
startHourSelected, startMinSelected, 0);
start.set(Calendar.MILLISECOND, 0);
Calendar end = Calendar.getInstance();
end.set(yearSelected, monthSelected, dayOfMonthSelected,
endHourSelected, endMinSelected, 0);
end.set(Calendar.MILLISECOND, 0);
// constructs the request
return new FRPeriod(start.getTimeInMillis(), end.getTimeInMillis(),
false);
}
/**
* Prepare the actual query to send and set it in the controller
*/
private void prepareSearchQuery() {
FRPeriod period = prepareFRFrPeriod();
List<String> mUIDList = new ArrayList<String>(selectedRooms.size());
if (favButton.isChecked()) {
mUIDList.addAll(mModel.getAllRoomMapFavorites().keySet());
}
if (userDefButton.isChecked()) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom room = iter.next();
mUIDList.add(room.getUid());
}
}
boolean any = anyButton.isChecked();
boolean fav = favButton.isChecked();
boolean user = userDefButton.isChecked();
FRRequestDetails details = new FRRequestDetails(period,
freeButton.isChecked(), mUIDList, any, fav, user, selectedRooms);
mModel.setFRRequestDetails(details);
mController.sendFRRequest(this);
searchDialog.dismiss();
resetUserDefined(); // cleans the selectedRooms of userDefined
}
/**
* Check that the times set are valid, according to the shared definition.
*
* @return 0 if times are valids, positive integer otherwise
*/
private int auditTimes() {
// NOT EVEN SET, we don't bother checking
if (yearSelected == -1 || monthSelected == -1
|| dayOfMonthSelected == -1) {
return 1;
}
if (startHourSelected == -1 || endHourSelected == -1
|| startMinSelected == -1 || endMinSelected == -1) {
return 1;
}
// IF SET, we use the shared method checking the prepared period
String errors = FRTimes.validCalendarsString(prepareFRFrPeriod());
if (errors.equals("")) {
return 0;
}
Toast.makeText(
getApplicationContext(),
"Please review the time, should be between Mo-Fr 8am-7pm.\n"
+ "The end should also be after the start, and at least 5 minutes.",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Errors remaining: \n" + errors, Toast.LENGTH_LONG).show();
return 1;
}
/**
* This method check if the client is allowed to submit a request to the
* server.
*
* @return 0 if there is no error and the client can send the request,
* something else otherwise.
*/
private int auditSubmit() {
if (selectedRooms == null
|| (!anyButton.isChecked() && !favButton.isChecked()
&& userDefButton.isChecked() && selectedRooms.isEmpty())) {
return 1;
}
if (anyButton.isChecked()
&& (favButton.isChecked() || userDefButton.isChecked())) {
return 1;
}
if (!anyButton.isChecked() && !favButton.isChecked()
&& !userDefButton.isChecked()) {
return 1;
}
Set<String> set = mModel.getAllRoomMapFavorites().keySet();
if (favButton.isChecked()
&& set.isEmpty()
&& (!userDefButton.isChecked() || (userDefButton.isChecked() && selectedRooms
.isEmpty()))) {
return 1;
}
// we dont allow query all the room, including non-free
if (anyButton.isChecked() && !freeButton.isChecked()) {
return 1;
}
return auditTimes();
}
@Override
public void autoCompletedUpdated() {
mAdapter.notifyDataSetInvalidated();
mAutoCompleteSuggestionArrayListFRRoom.clear();
// TODO: adapt to use the new version of autocomplete mapped by building
Iterator<List<FRRoom>> iter = mModel.getAutoComplete().values()
.iterator();
System.out.println(mModel.getAutoComplete().values().size());
while (iter.hasNext()) {
List<FRRoom> list = iter.next();
System.out.println(list.size());
Iterator<FRRoom> iterroom = list.iterator();
while (iterroom.hasNext()) {
FRRoom room = iterroom.next();
// rooms that are already selected are not displayed...
if (!selectedRooms.contains(room)) {
mAutoCompleteSuggestionArrayListFRRoom.add(room);
}
}
}
mAdapter.notifyDataSetChanged();
}
}
|
package org.pocketcampus.plugin.freeroom.android.views;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.tracker.Tracker;
import org.pocketcampus.android.platform.sdk.ui.element.InputBarElement;
import org.pocketcampus.android.platform.sdk.ui.element.OnKeyPressedListener;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout;
import org.pocketcampus.android.platform.sdk.ui.list.LabeledListViewElement;
import org.pocketcampus.plugin.freeroom.R;
import org.pocketcampus.plugin.freeroom.android.FreeRoomAbstractView;
import org.pocketcampus.plugin.freeroom.android.FreeRoomController;
import org.pocketcampus.plugin.freeroom.android.FreeRoomModel;
import org.pocketcampus.plugin.freeroom.android.adapter.ActualOccupationArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewFavoriteAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.FRRoomSuggestionArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.iface.IFreeRoomView;
import org.pocketcampus.plugin.freeroom.android.utils.FRRequestDetails;
import org.pocketcampus.plugin.freeroom.android.utils.OrderMapListFew;
import org.pocketcampus.plugin.freeroom.android.utils.SetArrayList;
import org.pocketcampus.plugin.freeroom.shared.ActualOccupation;
import org.pocketcampus.plugin.freeroom.shared.AutoCompleteRequest;
import org.pocketcampus.plugin.freeroom.shared.FRPeriod;
import org.pocketcampus.plugin.freeroom.shared.FRRequest;
import org.pocketcampus.plugin.freeroom.shared.FRRoom;
import org.pocketcampus.plugin.freeroom.shared.ImWorkingRequest;
import org.pocketcampus.plugin.freeroom.shared.Occupancy;
import org.pocketcampus.plugin.freeroom.shared.WorkingOccupancy;
import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.Toast;
import com.markupartist.android.widget.ActionBar.Action;
/**
* <code>FreeRoomHomeView</code> is the main <code>View</code>, it's the entry
* of the plugin. It displays the availabilities for the search given, and for
* your favorites NOW at the start.
* <p>
* All others views are supposed to be dialog windows, therefore it's always
* visible.
* <p>
* <code>AlertDialog</code> that exists are the following:
* <p>
* INFO ROOM display detailed information and occupancy about a room, and give
* the ability to share the location.
* <p>
* SEARCH enables the user to enter a customized search, and retrieves
* previously entered searches.
* <p>
* FAVORITES show the current favorites, with the possibility to remove them one
* by one. Adding is done by the ADD ROOM dialog.
* <p>
* ADD ROOM gives the possibility to construct an user-defined list of selected
* rooms, with auto-complete capabilities. It can be user to add favorites or a
* custom search.
* <p>
* SHARE give the possibility to share the location with friends through a share
* Intent. The server will also be notified, such that approximately occupancies
* continues to be as accurate as possible.
* <p>
*
* @author FreeRoom Project Team (2014/05)
* @author Julien WEBER <[email protected]>
* @author Valentin MINDER <[email protected]>
*/
public class FreeRoomHomeView extends FreeRoomAbstractView implements
IFreeRoomView {
/* MVC STRUCTURE */
/**
* FreeRoom controller in MVC scheme.
*/
private FreeRoomController mController;
/**
* FreeRoom model in MVC scheme.
*/
private FreeRoomModel mModel;
/* COMMON SHARED VALUES */
/**
* Width of the main Activity.
*/
private int activityWidth;
/**
* Height of the main Activity.
*/
private int activityHeight;
/**
* Common LayoutInflater for all Layout inflated from xml.
*/
private LayoutInflater mLayoutInflater;
/* UI OF MAIN ACTIVITY */
/**
* Titled layout that holds the title and the main layout.
*/
private StandardTitledLayout titleLayout;
/**
* Main layout that hold all UI components.
*/
private LinearLayout mainLayout;
/**
* TextView to display a short message about what is currently displayed.
*/
private TextView mTextView;
/**
* ExpandableListView to display the results of occupancies building by
* building.
*/
private ExpandableListView mExpListView;
/**
* Adapter for the results (to display the occupancies).
*/
private ExpandableListViewAdapter<Occupancy> mExpListAdapter;
/* VIEW/DIALOGS FOR ALL ALERTDIALOG */
/**
* View that holds the INFO dialog content, defined in xml in layout folder.
*/
private View mInfoRoomView;
/**
* AlertDialog that holds the INFO dialog.
*/
private AlertDialog mInfoRoomDialog;
/**
* View that holds the SEARCH dialog content, defined in xml in layout
* folder.
*/
private View mSearchView;
/**
* Dialog that holds the SEARCH Dialog.
*/
private AlertDialog mSearchDialog;
/**
* View that holds the FAVORITES dialog content, defined in xml in layout
* folder.
*/
private View mFavoritesView;
/**
* AlertDialog that holds the FAVORITES dialog.
*/
private AlertDialog mFavoritesDialog;
/**
* View that holds the ADDROOM dialog content, defined in xml in layout
* folder.
*/
private View mAddRoomView;
/**
* AlertDialog that holds the ADDROOM dialog.
*/
private AlertDialog mAddRoomDialog;
/**
* View that holds the SHARE dialog content, defined in xml in layout
* folder.
*/
private View mShareView;
/**
* Dialog that holds the SHARE Dialog.
*/
private AlertDialog mShareDialog;
/**
* Dialog that holds the WARNING Dialog.
*/
private AlertDialog mWarningDialog;
/* UI ELEMENTS FOR ALL DIALOGS */
/* UI ELEMENTS FOR DIALOGS - INFO ROOM */
/* UI ELEMENTS FOR DIALOGS - SEARCH */
/**
* ListView that holds previous searches.
* <P>
* TODO: NOT USED SO FAR
*/
private ListView mSearchPreviousListView;
/* UI ELEMENTS FOR DIALOGS - FAVORITES */
/* UI ELEMENTS FOR DIALOGS - ADDROOM */
/* UI ELEMENTS FOR DIALOGS - SHARE */
/* OTHER UTILS */
/**
* Enum to have types and store the last caller of the "Add" dialog.
*
*/
private enum AddRoomCaller {
FAVORITES, SEARCH;
}
/**
* Stores the last caller of the ADDROOM dialog.
*/
private AddRoomCaller lastCaller = null;
/* ACTIONS FOR THE ACTION BAR */
/**
* Action to perform a customized search, by showing the search dialog.
*/
private Action search = new Action() {
public void performAction(View view) {
fillSearchDialog();
mSearchDialog.show();
}
public int getDrawable() {
return R.drawable.magnify2x06;
}
};
/**
* Action to edit the user's favorites, by showing the favorites dialog.
*/
private Action editFavorites = new Action() {
public void performAction(View view) {
mFavoritesAdapter.notifyDataSetChanged();
mFavoritesDialog.show();
}
public int getDrawable() {
return R.drawable.star2x28;
}
};
/**
* Action to refresh the view (it sends the same stored request again).
* <p>
* TODO: useful? useless ? delete !
*/
private Action refresh = new Action() {
public void performAction(View view) {
refresh();
}
public int getDrawable() {
return R.drawable.refresh2x01;
}
};
/* MAIN ACTIVITY - OVERRIDEN METHODS */
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return FreeRoomController.class;
}
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
// Tracker
Tracker.getInstance().trackPageView("freeroom");
// Get and cast the controller and model
mController = (FreeRoomController) controller;
mModel = (FreeRoomModel) controller.getModel();
// Setup the layout
mLayoutInflater = this.getLayoutInflater();
titleLayout = (StandardTitledLayout) mLayoutInflater.inflate(
R.layout.freeroom_layout_home, null);
mainLayout = (LinearLayout) titleLayout
.findViewById(R.id.freeroom_layout_home_main_layout);
// The ActionBar is added automatically when you call setContentView
setContentView(titleLayout);
titleLayout.setTitle(getString(R.string.freeroom_title_main_title));
mExpListView = (ExpandableListView) titleLayout
.findViewById(R.id.freeroom_layout_home_list);
mTextView = (TextView) titleLayout
.findViewById(R.id.freeroom_layout_home_text_summary);
setTextSummary(getString(R.string.freeroom_home_init_please_wait));
initializeView();
// This is necessary: xml definition don't support affFillerView!!
titleLayout.removeView(mainLayout);
titleLayout.addFillerView(mainLayout);
initDefaultRequest();
refresh();
// TODO: NOT the right call to handle the intent
handleIntent(getIntent());
}
/**
* This is called when the Activity is resumed.
*
* If the user presses back on the Authentication window, This Activity is
* resumed but we do not have the freeroomCookie. In this case we close the
* Activity.
*/
@Override
protected void onResume() {
super.onResume();
/*
* if(mModel != null && mModel.getFreeRoomCookie() == null) { // Resumed
* and lot logged in? go back finish(); }
*/
if (mController != null) {
mController.sendFRRequest(this);
}
}
/**
* Handles an intent for a search coming from outside.
* <p>
* // TODO: handles occupancy.epfl.ch + pockecampus://
*
* @param intent
* the intent to handle
*/
private void handleSearchIntent(Intent intent) {
// TODO: if search launched by other plugin.
}
/* MAIN ACTIVITY - INITIALIZATION */
@Override
public void initializeView() {
// retrieve display dimensions
Rect displayRectangle = new Rect();
Window window = this.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
activityWidth = displayRectangle.width();
activityHeight = displayRectangle.height();
mExpListAdapter = new ExpandableListViewAdapter<Occupancy>(
getApplicationContext(), mModel.getOccupancyResults(),
mController, this);
mExpListView.setAdapter(mExpListAdapter);
addActionToActionBar(refresh);
addActionToActionBar(editFavorites);
addActionToActionBar(search);
initInfoDialog();
initSearchDialog();
initFavoritesDialog();
initAddRoomDialog();
initShareDialog();
initWarningDialog();
}
/**
* Inits the dialog to diplay the information about a room.
*/
private void initInfoDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("room name");
builder.setIcon(R.drawable.details_white_50);
builder.setPositiveButton(
getString(R.string.freeroom_dialog_info_share), null);
builder.setNegativeButton(
getString(R.string.freeroom_dialog_fav_close), null);
// Get the AlertDialog from create()
mInfoRoomDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mInfoRoomDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mInfoRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mInfoRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mInfoRoomDialog.getWindow().setAttributes(lp);
mInfoRoomView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_info, null);
// these work perfectly
mInfoRoomView.setMinimumWidth((int) (activityWidth * 0.9f));
mInfoRoomView.setMinimumHeight((int) (activityHeight * 0.8f));
mInfoRoomDialog.setView(mInfoRoomView);
mInfoRoomDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
}
});
}
/**
* Inits the dialog to diplay the favorites.
*/
private ExpandableListViewFavoriteAdapter mFavoritesAdapter;
private void initFavoritesDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_fav_title));
builder.setIcon(R.drawable.star2x28);
builder.setPositiveButton(getString(R.string.freeroom_dialog_fav_add),
null);
builder.setNegativeButton(
getString(R.string.freeroom_dialog_fav_close), null);
builder.setNeutralButton(getString(R.string.freeroom_dialog_fav_reset),
null);
// Get the AlertDialog from create()
mFavoritesDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mFavoritesDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mFavoritesDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mFavoritesDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mFavoritesDialog.getWindow().setAttributes(lp);
mFavoritesView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_fav, null);
// these work perfectly
mFavoritesView.setMinimumWidth((int) (activityWidth * 0.9f));
mFavoritesView.setMinimumHeight((int) (activityHeight * 0.8f));
mFavoritesDialog.setView(mFavoritesView);
mFavoritesDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
mFavoritesAdapter.notifyDataSetChanged();
}
});
mFavoritesDialog.hide();
mFavoritesDialog.show();
mFavoritesDialog.dismiss();
Button tv = mFavoritesDialog.getButton(DialogInterface.BUTTON_POSITIVE);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mAddRoomDialog.isShowing()) {
displayAddRoomDialog(AddRoomCaller.FAVORITES);
}
}
});
Button bt = mFavoritesDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mWarningDialog.show();
}
});
ExpandableListView lv = (ExpandableListView) mFavoritesView
.findViewById(R.id.freeroom_layout_dialog_fav_list);
mFavoritesAdapter = new ExpandableListViewFavoriteAdapter(this, mModel
.getFavorites().keySetOrdered(), mModel.getFavorites(), mModel);
lv.setAdapter(mFavoritesAdapter);
mFavoritesAdapter.notifyDataSetChanged();
}
private void displayAddRoomDialog(AddRoomCaller calling) {
mAddRoomDialog.show();
// TODO: reset the data ? the text input, the selected room ?
lastCaller = calling;
}
private void dimissAddRoomDialog() {
if (lastCaller.equals(AddRoomCaller.FAVORITES)) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom mRoom = iter.next();
// TODO: add all in batch!
mModel.addFavorite(mRoom);
}
mFavoritesAdapter.notifyDataSetChanged();
resetUserDefined();
} else if (lastCaller.equals(AddRoomCaller.SEARCH)) {
// we do nothing: reset will be done at search time
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
}
}
private void initAddRoomDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_add_room_title));
builder.setIcon(R.drawable.adding_white_50);
// Get the AlertDialog from create()
mAddRoomDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mAddRoomDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mAddRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mAddRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mAddRoomDialog.getWindow().setAttributes(lp);
mAddRoomView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_add_room, null);
// these work perfectly
mAddRoomView.setMinimumWidth((int) (activityWidth * 0.9f));
// mAddRoomView.setMinimumHeight((int) (activityHeight * 0.8f));
mAddRoomDialog.setView(mAddRoomView);
mAddRoomDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
// searchButton.setEnabled(auditSubmit() == 0);
}
});
Button bt_done = (Button) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_room_done);
bt_done.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismissSoftKeyBoard(v);
mAddRoomDialog.dismiss();
dimissAddRoomDialog();
}
});
mSummarySelectedRoomsTextView = (TextView) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_room_summary);
UIConstructInputBar();
LinearLayout ll = (LinearLayout) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_layout_main);
ll.addView(mAutoCompleteSuggestionInputBarElement);
createSuggestionsList();
}
private void initShareDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_share_title));
builder.setPositiveButton(
getString(R.string.freeroom_dialog_share_button_friends), null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(
getString(R.string.freeroom_dialog_share_button_server), null);
builder.setIcon(R.drawable.share_white_50);
// Get the AlertDialog from create()
mShareDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mShareDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
mShareDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mShareDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mShareDialog.getWindow().setAttributes(lp);
mShareView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_share, null);
// these work perfectly
mShareView.setMinimumWidth((int) (activityWidth * 0.95f));
// mShareView.setMinimumHeight((int) (activityHeight * 0.8f));
mShareDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
dismissSoftKeyBoard(mShareView);
}
});
mShareDialog.setView(mShareView);
}
public void displayShareDialog(final FRPeriod mPeriod, final FRRoom mRoom) {
mShareDialog.hide();
mShareDialog.show();
final TextView tv = (TextView) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_textBasic);
tv.setText(wantToShare(mPeriod, mRoom, ""));
final EditText ed = (EditText) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_text_edit);
ed.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
tv.setText(wantToShare(mPeriod, mRoom, ed.getText().toString()));
dismissSoftKeyBoard(arg0);
return true;
}
});
Button shareWithServer = mShareDialog
.getButton(DialogInterface.BUTTON_NEUTRAL);
shareWithServer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, false, ed.getText().toString());
mShareDialog.dismiss();
}
});
Button shareWithFriends = mShareDialog
.getButton(DialogInterface.BUTTON_POSITIVE);
shareWithFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, true, ed.getText().toString());
mShareDialog.dismiss();
}
});
Spinner spinner = (Spinner) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_spinner_course);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the mFavoritesAdapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO do something with that
System.out.println("selected" + arg0.getItemAtPosition(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO find out how is this relevant
System.out.println("nothing selected!");
}
});
// it's automatically in center of screen!
mShareDialog.show();
}
/**
* Dismiss the keyboard associated with the view.
*
* @param v
*/
private void dismissSoftKeyBoard(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
/**
* Inits the dialog to diplay the information about a room.
*/
private void initSearchDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Various setter methods to set the searchDialog characteristics
builder.setTitle(getString(R.string.freeroom_search_title));
builder.setPositiveButton(getString(R.string.freeroom_search_search),
null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(getString(R.string.freeroom_search_reset),
null);
builder.setIcon(R.drawable.magnify2x06);
// Get the AlertDialog from create()
mSearchDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mSearchDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
mSearchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mSearchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mSearchDialog.getWindow().setAttributes(lp);
mSearchView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_search, null);
// these work perfectly
mSearchView.setMinimumWidth((int) (activityWidth * 0.9f));
mSearchView.setMinimumHeight((int) (activityHeight * 0.8f));
mSearchDialog.setView(mSearchView);
mSearchDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
searchButton.setEnabled(auditSubmit() == 0);
}
});
// this is necessary o/w buttons don't exists!
mSearchDialog.hide();
mSearchDialog.show();
mSearchDialog.dismiss();
resetButton = mSearchDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
searchButton = mSearchDialog.getButton(DialogInterface.BUTTON_POSITIVE);
mSummarySelectedRoomsTextViewSearchMenu = (TextView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_text_summary);
// the view will be removed or the text changed, no worry
mSummarySelectedRoomsTextViewSearchMenu.setText("empty");
mSearchPreviousListView = (ListView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_prev_search);
// TODO: previous search
// mSearchPreviousListView.setAdapter();
initSearch();
}
private void initWarningDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_warn_title));
builder.setMessage(getString(R.string.freeroom_dialog_warn_text));
builder.setIcon(R.drawable.warning_white_50);
builder.setPositiveButton(
getString(R.string.freeroom_dialog_warn_reset),
new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mModel.resetFavorites();
mFavoritesAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton(
getString(R.string.freeroom_dialog_warn_cancel), null);
// Get the AlertDialog from create()
mWarningDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mWarningDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.WRAP_CONTENT;
lp.height = LayoutParams.WRAP_CONTENT;
mWarningDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mWarningDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mWarningDialog.getWindow().setAttributes(lp);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
System.out
.println("TOuch outside the dialog ******************** ");
mSearchDialog.dismiss();
}
return false;
}
/**
* Overrides the legacy <code>onKeyDown</code> method in order to close the
* dialog if one was opened. TODO: test if really needed.
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Override back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
boolean flag = false;
if (mInfoRoomDialog.isShowing()) {
mInfoRoomDialog.dismiss();
flag = true;
}
if (mSearchDialog.isShowing()) {
mSearchDialog.dismiss();
flag = true;
}
if (mFavoritesDialog.isShowing()) {
mFavoritesDialog.dismiss();
flag = true;
}
selectedRooms.clear();
if (flag) {
resetUserDefined();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void anyError() {
setTextSummary(getString(R.string.freeroom_home_error_sorry));
}
/**
* Sets the summary text box to the specified text.
*
* @param text
* the new summary to be displayed.
*/
private void setTextSummary(String text) {
mTextView.setText(text);
}
/**
* Constructs the default request (check all the favorites for the next
* valid period) and sets it in the model for future use. You may call
* <code>refresh</code> in order to send it to the server.
*/
private void initDefaultRequest() {
mModel.setFRRequestDetails(validRequest());
}
private FRRequestDetails validRequest() {
OrderMapListFew<String, List<FRRoom>, FRRoom> set = mModel
.getFavorites();
FRRequestDetails details = null;
if (set.isEmpty()) {
// NO FAV = check all free rooms
// TODO change group accordingly, set to 1 by default and for
// testing purpose
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), true,
new ArrayList<String>(1), true, false, false,
new SetArrayList<FRRoom>(), 1);
} else {
// FAV: check occupancy of ALL favs
ArrayList<String> array = new ArrayList<String>(set.size());
addAllFavoriteToCollection(array, AddCollectionCaller.SEARCH, true);
// TODO change group accordingly, set to 1 by default and for
// testing purpose
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), false,
array, false, true, false, new SetArrayList<FRRoom>(), 1);
}
return details;
}
/**
* Asks the controller to send again the request which was already set in
* the model.
*/
private void refresh() {
setTextSummary(getString(R.string.freeroom_home_please_wait));
mController.sendFRRequest(this);
}
@Override
public void occupancyResultsUpdated() {
StringBuilder build = new StringBuilder(50);
if (mModel.getOccupancyResults().isEmpty()) {
build.append(getString(R.string.freeroom_home_error_no_results));
} else {
FRRequest request = mModel.getFRRequestDetails();
if (request.isOnlyFreeRooms()) {
build.append(getString(R.string.freeroom_home_info_free_rooms));
} else {
build.append(getString(R.string.freeroom_home_info_rooms));
}
FRPeriod period = request.getPeriod();
build.append(generateFullTimeSummary(period));
// if the info dialog is opened, we update the CORRECT occupancy
// with the new data.
if (mInfoRoomDialog.isShowing()) {
FRRoom room = mModel.getDisplayedOccupancy().getRoom();
List<?> list = mModel.getOccupancyResults().get(
mModel.getKey(room));
Iterator<?> iter = list.iterator();
label: while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof Occupancy) {
if (((Occupancy) o).getRoom().getUid()
.equals(room.getUid())) {
mModel.setDisplayedOccupancy((Occupancy) o);
// doesn't work
mInfoActualOccupationAdapter.notifyDataSetChanged();
// works!
displayInfoDialog();
break label;
}
}
}
}
}
setTextSummary(build.toString());
mExpListAdapter.notifyDataSetChanged();
updateCollapse(mExpListView, mExpListAdapter);
}
/**
* Expands all the groups if there are no more than 4 groups or not more
* than 10 results.
* <p>
* TODO defines these consts somewhere else
*
* @param ev
*/
public void updateCollapse(ExpandableListView ev,
ExpandableListViewAdapter<Occupancy> ad) {
System.out.println("check: " + ad.getGroupCount() + "/"
+ ad.getChildrenTotalCount()); // TODO delete
if (ad.getGroupCount() <= 4 || ad.getChildrenTotalCount() <= 10) {
System.out.println("i wanted to expand");
// TODO: this cause troubles in performance when first launch
for (int i = 0; i < ad.getGroupCount(); i++) {
ev.expandGroup(i);
}
}
}
/**
* Generates a string summary of a given period of time.
* <p>
* eg: "Wednesday Apr 24 from 9am to 12pm"
*
* @param period
* the period of time
* @return a string summary of a given period of time.
*/
private String generateFullTimeSummary(FRPeriod period) {
StringBuilder build = new StringBuilder(100);
Date endDate = new Date(period.getTimeStampEnd());
Date startDate = new Date(period.getTimeStampStart());
SimpleDateFormat day_month = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format));
SimpleDateFormat hour_min = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
build.append(" ");
// TODO: if date is today, use "today" instead of specifying date
build.append(getString(R.string.freeroom_check_occupancy_result_onthe));
build.append(" ");
build.append(day_month.format(startDate));
build.append(" ");
build.append(getString(R.string.freeroom_check_occupancy_result_from));
build.append(" ");
build.append(hour_min.format(startDate));
build.append(" ");
build.append(getString(R.string.freeroom_check_occupancy_result_to));
build.append(" ");
build.append(hour_min.format(endDate));
return build.toString();
}
/**
* Generates a short string summary of a given period of time.
* <p>
* eg: "9:00\n12:00pm"
*
* @param period
* the period of time
* @return a string summary of a given period of time.
*/
private String generateShortTimeSummary(FRPeriod period) {
StringBuilder build = new StringBuilder(100);
Date endDate = new Date(period.getTimeStampEnd());
Date startDate = new Date(period.getTimeStampStart());
SimpleDateFormat hour_min = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
build.append(hour_min.format(startDate));
build.append(" - ");
build.append(hour_min.format(endDate));
return build.toString();
}
/**
* Put a onClickListener on an imageView in order to share the location and
* time when clicking share, if available.
*
* @param shareImageView
* the view on which to put the listener
* @param homeView
* reference to the home view
* @param mOccupancy
* the holder of data for location and time
*/
public void setShareClickListener(View shareImageView,
final FreeRoomHomeView homeView, final Occupancy mOccupancy) {
if (!mOccupancy.isIsAtLeastOccupiedOnce()
&& mOccupancy.isIsAtLeastFreeOnce()) {
shareImageView.setClickable(true);
shareImageView.setEnabled(true);
if (shareImageView instanceof ImageView) {
((ImageView) shareImageView).setImageResource(R.drawable.share);
}
shareImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
homeView.displayShareDialog(
getMaxPeriodFromList(mOccupancy.getOccupancy()),
mOccupancy.getRoom());
}
});
} else {
shareImageView.setClickable(false);
shareImageView.setEnabled(false);
if (shareImageView instanceof ImageView) {
((ImageView) shareImageView)
.setImageResource(R.drawable.share_disabled);
}
}
}
/**
* Finds the whole period covered by a list of contiguous and ordered of
* occupancies.
*
* @param listOccupations
* the list of occupancies.
* @return the period covered by the list
*/
private FRPeriod getMaxPeriodFromList(List<ActualOccupation> listOccupations) {
long tss = listOccupations.get(0).getPeriod().getTimeStampStart();
long tse = listOccupations.get(listOccupations.size() - 1).getPeriod()
.getTimeStampEnd();
return new FRPeriod(tss, tse, false);
}
private ActualOccupationArrayAdapter<ActualOccupation> mInfoActualOccupationAdapter;
/**
* Display the dialog that provides more info about the occupation of the
* selected room.
*/
public void displayInfoDialog() {
final Occupancy mOccupancy = mModel.getDisplayedOccupancy();
if (mOccupancy != null) {
mInfoRoomDialog.hide();
mInfoRoomDialog.show();
final FRRoom mRoom = mOccupancy.getRoom();
String text = mRoom.getDoorCode();
if (mRoom.isSetDoorCodeAlias()) {
// alias is displayed IN PLACE of the official name
// the official name can be found in bottom of dialog
text = mRoom.getDoorCodeAlias();
}
mInfoRoomDialog.setTitle(text);
TextView periodTextView = (TextView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_period);
periodTextView
.setText(generateFullTimeSummary(getMaxPeriodFromList(mOccupancy
.getOccupancy())));
ImageView iv = (ImageView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_share);
setShareClickListener(iv, this, mOccupancy);
Button share = mInfoRoomDialog
.getButton(AlertDialog.BUTTON_POSITIVE);
share.setEnabled(mOccupancy.isIsAtLeastFreeOnce()
&& !mOccupancy.isIsAtLeastOccupiedOnce());
setShareClickListener(share, this, mOccupancy);
ListView roomOccupancyListView = (ListView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_roomOccupancy);
mInfoActualOccupationAdapter = new ActualOccupationArrayAdapter<ActualOccupation>(
getApplicationContext(), mOccupancy.getOccupancy(),
mController, this);
roomOccupancyListView.setAdapter(mInfoActualOccupationAdapter);
TextView detailsTextView = (TextView) mInfoRoomView
.findViewById(R.id.freeroom_layout_dialog_info_details);
detailsTextView.setText(getInfoFRRoom(mOccupancy.getRoom()));
mInfoRoomDialog.show();
}
}
private void fillSearchDialog() {
final FRRequestDetails request = mModel.getFRRequestDetails();
if (request != null) {
fillSearchDialog(request);
}
}
private void fillSearchDialog(final FRRequestDetails request) {
resetTimes(request.getPeriod());
anyButton.setChecked(request.isAny());
specButton.setChecked(!request.isAny());
favButton.setChecked(request.isFav());
userDefButton.setChecked(request.isUser());
freeButton.setChecked(request.isOnlyFreeRooms());
searchButton.setEnabled(auditSubmit() == 0);
boolean enabled = !request.isAny();
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
if (enabled) {
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
if (request.isUser()) {
mOptionalLineLinearLayoutWrapper
.addView(mOptionalLineLinearLayoutWrapperIn);
selectedRooms.addAll(request.getUidNonFav());
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
}
}
public String wantToShare(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
// TODO: in case of "now" request (nextPeriodValid is now), just put
// "i am, now, " instead of
// time
StringBuilder textBuilder = new StringBuilder(100);
textBuilder.append(getString(R.string.freeroom_share_iwillbe) + " ");
textBuilder.append(getString(R.string.freeroom_share_in_room) + " ");
if (mRoom.isSetDoorCodeAlias()) {
textBuilder.append(mRoom.getDoorCodeAlias() + " ("
+ mRoom.getDoorCode() + ") ");
} else {
textBuilder.append(mRoom.getDoorCode() + " ");
}
// TODO: which period to use ?
// in case of specified in request, we should use the personalized
// period
textBuilder.append(generateFullTimeSummary(mPeriod) + ". ");
if (toShare.length() == 0) {
textBuilder.append(getString(R.string.freeroom_share_please_come));
} else {
textBuilder.append(toShare);
}
return textBuilder.toString();
}
private void share(FRPeriod mPeriod, FRRoom mRoom, boolean withFriends,
String toShare) {
WorkingOccupancy work = new WorkingOccupancy(mPeriod, mRoom);
ImWorkingRequest request = new ImWorkingRequest(work,
mModel.getAnonymID());
mController.prepareImWorking(request);
mModel.setOnlyServer(!withFriends);
mController.ImWorking(this);
if (withFriends) {
shareWithFriends(mPeriod, mRoom, toShare);
}
}
/**
* Construct the Intent to share the location and time with friends. The
* same information is shared with the server at the same time
*
* @param mPeriod
* time period
* @param mRoom
* location
*/
private void shareWithFriends(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
String sharing = wantToShare(mPeriod, mRoom, toShare);
sharing += " \n" + getString(R.string.freeroom_share_ref_pocket);
Log.v(this.getClass().getName() + "-share", "sharing:" + sharing);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sharing);
// this ensure that our handler, that is handling home-made text types,
// will also work. But our won't work outside the app, which is needed,
// because it waits for this special type.
/**
* Converts a FRRoom to a String of only major properties, in order to
* display them. It includes name (with alias), type, capacity, surface and
* UID.
* <p>
* TODO: this method may be changed
*
* @param mFrRoom
* @return
*/
private String getInfoFRRoom(FRRoom mFrRoom) {
StringBuilder builder = new StringBuilder(50);
if (mFrRoom.isSetDoorCode()) {
if (mFrRoom.isSetDoorCodeAlias()) {
builder.append(mFrRoom.getDoorCode() + " (alias: "
+ mFrRoom.getDoorCodeAlias() + ")");
} else {
builder.append(mFrRoom.getDoorCode());
}
}
if (mFrRoom.isSetTypeFR() || mFrRoom.isSetTypeEN()) {
builder.append(" / "
+ getString(R.string.freeroom_dialog_info_type) + ": ");
if (mFrRoom.isSetTypeFR()) {
builder.append(mFrRoom.getTypeFR());
}
if (mFrRoom.isSetTypeFR() && mFrRoom.isSetTypeEN()) {
builder.append(" / ");
}
if (mFrRoom.isSetTypeFR()) {
builder.append(mFrRoom.getTypeEN());
}
}
if (mFrRoom.isSetCapacity()) {
builder.append(" / "
+ getString(R.string.freeroom_dialog_info_capacity) + ": "
+ mFrRoom.getCapacity() + " "
+ getString(R.string.freeroom_dialog_info_places));
}
if (mFrRoom.isSetSurface()) {
builder.append(" / "
+ getString(R.string.freeroom_dialog_info_surface) + ": "
+ mFrRoom.getSurface() + " "
+ getString(R.string.freeroom_dialog_info_sqm));
}
// TODO: for production, remove UID (it's useful for debugging for the
// moment)
if (mFrRoom.isSetUid()) {
// uniq UID must be 1201XXUID, with XX filled with 0 such that
// it has 10 digit
// the prefix "1201" indiquates that it's a EPFL room (not a phone,
// a computer)
String communUID = "1201";
String roomUID = mFrRoom.getUid();
for (int i = roomUID.length() + 1; i <= 6; i++) {
communUID += "0";
}
communUID += roomUID;
builder.append(" / "
+ getString(R.string.freeroom_dialog_info_uniqID) + ": "
+ communUID);
}
return builder.toString();
}
// ** REUSED FROM SCRATCH FROM FreeRoomSearchView ** //
private SetArrayList<FRRoom> selectedRooms;
private ListView mAutoCompleteSuggestionListView;
private List<FRRoom> mAutoCompleteSuggestionArrayListFRRoom;
/** The input bar to make the search */
private InputBarElement mAutoCompleteSuggestionInputBarElement;
/** Adapter for the <code>mListView</code> */
private FRRoomSuggestionArrayAdapter<FRRoom> mAdapter;
private DatePickerDialog mDatePickerDialog;
private TimePickerDialog mTimePickerStartDialog;
private TimePickerDialog mTimePickerEndDialog;
private Button showDatePicker;
private Button showStartTimePicker;
private Button showEndTimePicker;
private RadioButton specButton;
private RadioButton anyButton;
private CheckBox favButton;
private CheckBox userDefButton;
/**
* TRUE: "only free rooms" FALSE: "allow non-free rooms"
*/
private CheckBox freeButton;
private Button searchButton;
private Button resetButton;
private Button userDefEditButton;
private Button userDefResetButton;
private ImageButton addHourButton;
private ImageButton upToEndHourButton;
/**
* Stores if the "up to end" button has been trigged.
* <p>
* If yes, the endHour don't follow anymore the startHour when you change
* it. It will be disabled when you change manually the endHour to a value
* under the maximal hour.
*/
private boolean upToEndSelected = false;
private TextView mSummarySelectedRoomsTextView;
private TextView mSummarySelectedRoomsTextViewSearchMenu;
private int yearSelected = -1;
private int monthSelected = -1;
private int dayOfMonthSelected = -1;
private int startHourSelected = -1;
private int startMinSelected = -1;
private int endHourSelected = -1;
private int endMinSelected = -1;
private SimpleDateFormat dateFormat;
private SimpleDateFormat timeFormat;
private LinearLayout mOptionalLineLinearLayoutWrapper;
private LinearLayout mOptionalLineLinearLayoutWrapperIn;
private LinearLayout mOptionalLineLinearLayoutContainer;
private void initSearch() {
mOptionalLineLinearLayoutWrapper = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper);
mOptionalLineLinearLayoutContainer = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_container);
mOptionalLineLinearLayoutWrapperIn = (LinearLayout) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper_in);
selectedRooms = new SetArrayList<FRRoom>();
formatters();
// createSuggestionsList();
// addAllFavsToAutoComplete();
mAutoCompleteSuggestionArrayListFRRoom = new ArrayList<FRRoom>(10);
resetTimes();
UIConstructPickers();
UIConstructButton();
// UIConstructInputBar();
reset();
}
private void formatters() {
dateFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format));
timeFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
}
private void UIConstructPickers() {
// First allow the user to select a date
showDatePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_date);
mDatePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int nYear,
int nMonthOfYear, int nDayOfMonth) {
yearSelected = nYear;
monthSelected = nMonthOfYear;
dayOfMonthSelected = nDayOfMonth;
updateDatePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, yearSelected, monthSelected, dayOfMonthSelected);
showDatePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDatePickerDialog.show();
}
});
// Then the starting time of the period
showStartTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_start);
mTimePickerStartDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
int previous = startHourSelected;
startHourSelected = nHourOfDay;
startMinSelected = nMinute;
if (startHourSelected < FRTimes.FIRST_HOUR_CHECK) {
startHourSelected = FRTimes.FIRST_HOUR_CHECK;
startMinSelected = 0;
}
if (startHourSelected >= FRTimes.LAST_HOUR_CHECK) {
startHourSelected = FRTimes.LAST_HOUR_CHECK - 1;
startMinSelected = 0;
}
if (startHourSelected != -1 && !upToEndSelected) {
int shift = startHourSelected - previous;
int newEndHour = endHourSelected + shift;
if (newEndHour > FRTimes.LAST_HOUR_CHECK) {
newEndHour = FRTimes.LAST_HOUR_CHECK;
}
if (newEndHour < FRTimes.FIRST_HOUR_CHECK) {
newEndHour = FRTimes.FIRST_HOUR_CHECK + 1;
}
endHourSelected = newEndHour;
if (endHourSelected == FRTimes.LAST_HOUR_CHECK) {
endMinSelected = 0;
}
updateEndTimePickerAndButton();
}
updateStartTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, startHourSelected, startMinSelected, true);
showStartTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerStartDialog.show();
}
});
// Then the ending time of the period
showEndTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end);
mTimePickerEndDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
endHourSelected = nHourOfDay;
endMinSelected = nMinute;
if (endHourSelected < startHourSelected) {
endHourSelected = startHourSelected + 1;
}
if (endHourSelected < FRTimes.FIRST_HOUR_CHECK) {
endHourSelected = FRTimes.FIRST_HOUR_CHECK + 1;
endMinSelected = 0;
}
if (endHourSelected == FRTimes.FIRST_HOUR_CHECK
&& endMinSelected <= FRTimes.MIN_MINUTE_INTERVAL) {
endMinSelected = FRTimes.MIN_MINUTE_INTERVAL;
// TODO: if start is not 8h00 (eg 8h10 dont work)
}
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
}
if (endHourSelected != FRTimes.LAST_HOUR_CHECK) {
upToEndSelected = false;
upToEndHourButton.setEnabled(!upToEndSelected);
}
updateEndTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, endHourSelected, endMinSelected, true);
showEndTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerEndDialog.show();
}
});
}
private void resetUserDefined() {
// TODO: add/remove
// mGlobalSubLayout.removeView(mAutoCompleteSuggestionInputBarElement);
// mGlobalSubLayout.removeView(mSummarySelectedRoomsTextView);
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
selectedRooms.clear();
userDefButton.setChecked(false);
mSummarySelectedRoomsTextView
.setText(getSummaryTextFromCollection(selectedRooms));
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
mAutoCompleteSuggestionInputBarElement.setInputText("");
}
private void UIConstructButton() {
specButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_spec);
specButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (specButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(true);
anyButton.setChecked(false);
anyButton.setEnabled(true);
specButton.setChecked(true);
freeButton.setChecked(false);
boolean enabled = true;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// TODO: is this great ? this guarantees that search is always
// available, but requires two steps to remove the fav (ass
// user-def, remove fav)
favButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
anyButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_any);
anyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (anyButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(false);
resetUserDefined();
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
favButton.setChecked(false);
userDefButton.setChecked(false);
freeButton.setChecked(true);
anyButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
favButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_fav);
favButton.setEnabled(true);
favButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!userDefButton.isChecked()) {
favButton.setChecked(true);
}
anyButton.setChecked(false);
specButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
userDefButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user);
userDefButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (userDefButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
// TODO: init and use the data.
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
mOptionalLineLinearLayoutWrapper
.addView(mOptionalLineLinearLayoutWrapperIn);
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
displayAddRoomDialog(AddRoomCaller.SEARCH);
} else if (!favButton.isChecked()) {
userDefButton.setChecked(true);
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
} else {
resetUserDefined();
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
freeButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_non_free);
freeButton.setEnabled(true);
freeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!freeButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
searchButton.setEnabled(auditSubmit() == 0);
searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
prepareSearchQuery();
}
});
resetButton.setEnabled(true);
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
reset();
// addAllFavsToAutoComplete();
// we reset the input bar...
// TODO
// mAutoCompleteSuggestionInputBarElement.setInputText("");
}
});
addHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_plus);
addHourButton.setEnabled(true);
addHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (endHourSelected <= 18) {
endHourSelected += 1;
updateEndTimePickerAndButton();
mTimePickerEndDialog.updateTime(endHourSelected,
endMinSelected);
}
if (endHourSelected >= 19) {
addHourButton.setEnabled(false);
}
}
});
upToEndHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_toend);
upToEndHourButton.setEnabled(true);
upToEndHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
updateEndTimePickerAndButton();
mTimePickerEndDialog
.updateTime(endHourSelected, endMinSelected);
upToEndSelected = true;
upToEndHourButton.setEnabled(!upToEndSelected);
searchButton.setEnabled(auditSubmit() == 0);
}
});
// on vertical screens, choose fav and choose user-def are vertically
// aligned
// on horizontal screens, there are horizontally aligned.
if (activityHeight > activityWidth) {
LinearLayout mLinearLayout = (LinearLayout) mSearchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_semi);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
}
userDefEditButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_edit);
userDefEditButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
displayAddRoomDialog(AddRoomCaller.SEARCH);
}
});
userDefResetButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_reset);
userDefResetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
resetUserDefined();
}
});
}
// TODO: the InputBar is not used so far
private void UIConstructInputBar() {
final IFreeRoomView view = this;
mAutoCompleteSuggestionInputBarElement = new InputBarElement(
this,
null,
getString(R.string.freeroom_check_occupancy_search_inputbarhint));
mAutoCompleteSuggestionInputBarElement
.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
// click on magnify glass on the keyboard
mAutoCompleteSuggestionInputBarElement
.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
dismissSoftKeyBoard(v);
AutoCompleteRequest request = new AutoCompleteRequest(
query, 1);
mController.autoCompleteBuilding(view, request);
}
return true;
}
});
// click on BUTTON magnify glass on the inputbar
mAutoCompleteSuggestionInputBarElement
.setOnButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
if (query.length() >= 2) {
dismissSoftKeyBoard(v);
// TODO change group accordingly, set to 1 by
// default and for testing purpose
AutoCompleteRequest request = new AutoCompleteRequest(
query, 1);
mController.autoCompleteBuilding(view, request);
}
}
});
mAdapter = new FRRoomSuggestionArrayAdapter<FRRoom>(
getApplicationContext(),
mAutoCompleteSuggestionArrayListFRRoom, mModel);
mAutoCompleteSuggestionInputBarElement
.setOnKeyPressedListener(new OnKeyPressedListener() {
@Override
public void onKeyPressed(String text) {
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
mAutoCompleteSuggestionInputBarElement
.setButtonText(null);
mAutoCompleteSuggestionListView.invalidate();
addAllFavsToAutoComplete();
} else {
mAutoCompleteSuggestionInputBarElement
.setButtonText("");
if (text.length() >= 2) {
// TODO change group accordingly, set to 1 by
// default and for testing purpose
// remove this if you don't want auto-complete
// without pressing the button
AutoCompleteRequest request = new AutoCompleteRequest(
text, 1);
mController.autoCompleteBuilding(view, request);
}
}
}
});
}
private void addAllFavsToAutoComplete() {
mAutoCompleteSuggestionArrayListFRRoom.clear();
addAllFavoriteToCollection(mAutoCompleteSuggestionArrayListFRRoom,
AddCollectionCaller.ADDALLFAV, false);
mAdapter.notifyDataSetChanged();
}
private enum AddCollectionCaller {
ADDALLFAV, SEARCH;
}
/**
* Add all the favorites FRRoom to the collection. Caller is needed in order
* to have special condition depending on the caller. The collection will be
* cleared prior to any adding.
*
* @param collection
* collection in which you want the favorites to be added.
* @param caller
* identification of the caller, to provide conditions.
* @param addOnlyUID
* true to add UID, false to add fully FRRoom object.
*/
private void addAllFavoriteToCollection(Collection collection,
AddCollectionCaller caller, boolean addOnlyUID) {
collection.clear();
OrderMapListFew<String, List<FRRoom>, FRRoom> set = mModel
.getFavorites();
Iterator<String> iter = set.keySetOrdered().iterator();
while (iter.hasNext()) {
String key = iter.next();
Iterator<FRRoom> iter2 = set.get(key).iterator();
label: while (iter2.hasNext()) {
FRRoom mRoom = iter2.next();
// condition of adding depending on the caller
if (caller.equals(AddCollectionCaller.ADDALLFAV)) {
if (selectedRooms.contains(mRoom)) {
break label;
}
}
if (addOnlyUID) {
collection.add(mRoom.getUid());
} else {
collection.add(mRoom);
}
}
}
}
/**
* Initialize the autocomplete suggestion list
*/
private void createSuggestionsList() {
mAutoCompleteSuggestionListView = new LabeledListViewElement(this);
mAutoCompleteSuggestionInputBarElement
.addView(mAutoCompleteSuggestionListView);
mAutoCompleteSuggestionListView
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int pos, long id) {
FRRoom room = mAutoCompleteSuggestionArrayListFRRoom
.get(pos);
addRoomToCheck(room);
searchButton.setEnabled(auditSubmit() == 0);
// refresh the autocomplete, such that selected rooms
// are not displayed
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
addAllFavsToAutoComplete();
} else {
autoCompletedUpdated();
}
// WE DONT REMOVE the text in the input bar
// INTENTIONNALLY: user may want to select multiple
// rooms in the same building
}
});
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
}
private void addRoomToCheck(FRRoom room) {
// we only add if it already contains the room
if (!selectedRooms.contains(room)) {
selectedRooms.add(room);
mSummarySelectedRoomsTextView
.setText(getSummaryTextFromCollection(selectedRooms));
} else {
Log.e(this.getClass().toString(),
"room cannot be added: already added");
}
}
private String getSummaryTextFromCollection(Collection<FRRoom> collec) {
Iterator<FRRoom> iter = collec.iterator();
StringBuffer buffer = new StringBuffer(collec.size() * 5);
FRRoom room = null;
buffer.append(getString(R.string.freeroom_check_occupancy_search_text_selected_rooms)
+ " ");
boolean empty = true;
while (iter.hasNext()) {
empty = false;
room = iter.next();
buffer.append(room.getDoorCode() + ", ");
}
buffer.setLength(buffer.length() - 2);
int MAX = 100;
if (buffer.length() > MAX) {
buffer.setLength(MAX);
buffer.append("...");
}
String result = "";
if (empty) {
result = getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms);
} else {
result = buffer.toString();
}
return result;
}
/**
* Reset the year, month, day, hour_start, minute_start, hour_end,
* minute_end to their initial values. DONT forget to update the date/time
* pickers afterwards.
*/
private void resetTimes() {
FRPeriod mFrPeriod = FRTimes.getNextValidPeriod();
resetTimes(mFrPeriod);
}
private void resetTimes(FRPeriod mFrPeriod) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampStart());
yearSelected = mCalendar.get(Calendar.YEAR);
monthSelected = mCalendar.get(Calendar.MONTH);
dayOfMonthSelected = mCalendar.get(Calendar.DAY_OF_MONTH);
startHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
startMinSelected = mCalendar.get(Calendar.MINUTE);
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampEnd());
endHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
endMinSelected = mCalendar.get(Calendar.MINUTE);
}
private void reset() {
searchButton.setEnabled(false);
// // reset the list of selected rooms
selectedRooms.clear();
// mSummarySelectedRoomsTextView
// .setText(getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms));
mAutoCompleteSuggestionArrayListFRRoom.clear();
resetTimes();
anyButton.setChecked(true);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
specButton.setChecked(false);
favButton.setChecked(false);
userDefButton.setChecked(false);
// resetUserDefined(); TODO
freeButton.setChecked(true);
// verify the submit
searchButton.setEnabled(auditSubmit() == 0);
upToEndHourButton.setEnabled(true);
upToEndSelected = false;
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// show the buttons
updateDateTimePickersAndButtons();
}
/**
* Updates ALL the date and time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date/time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date/time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateDateTimePickersAndButtons() {
updateDatePickerAndButton();
updateStartTimePickerAndButton();
updateEndTimePickerAndButton();
}
/**
* Updates the date <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date has changed from somewhere else,
* the <code>PickerDialog</code> will reopen with the new value.
*
* <p>
* Instead of the usual format "Wed 24 May", the date is summarize to
* "today", "yesterday", "tomorrow" when relevant.
*/
private void updateDatePickerAndButton() {
// creating selected time
Calendar selected = Calendar.getInstance();
selected.setTimeInMillis(prepareFRFrPeriod().getTimeStampStart());
// creating now time reference
Calendar now = Calendar.getInstance();
// creating tomorrow time reference
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DAY_OF_MONTH, true);
// creating yesterday time reference
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DAY_OF_MONTH, false);
if (FRTimes.compareCalendars(now, selected)) {
showDatePicker.setText(getString(R.string.freeroom_search_today));
} else if (FRTimes.compareCalendars(tomorrow, selected)) {
showDatePicker
.setText(getString(R.string.freeroom_search_tomorrow));
} else if (FRTimes.compareCalendars(yesterday, selected)) {
showDatePicker
.setText(getString(R.string.freeroom_search_yesterday));
} else {
showDatePicker.setText(dateFormat.format(selected.getTime()));
}
mDatePickerDialog.updateDate(yearSelected, monthSelected,
dayOfMonthSelected);
}
/**
* Updates the START time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the START time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the START time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateStartTimePickerAndButton() {
showStartTimePicker
.setText(getString(R.string.freeroom_check_occupancy_search_start)
+ " "
+ timeFormat.format(new Date(prepareFRFrPeriod()
.getTimeStampStart())));
mTimePickerStartDialog.updateTime(startHourSelected, startMinSelected);
}
/**
* Updates the END time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the END time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the END time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateEndTimePickerAndButton() {
showEndTimePicker
.setText(getString(R.string.freeroom_check_occupancy_search_end)
+ " "
+ timeFormat.format(new Date(prepareFRFrPeriod()
.getTimeStampEnd())));
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK
|| (endHourSelected == FRTimes.LAST_HOUR_CHECK - 1 && endMinSelected != 0)) {
addHourButton.setEnabled(false);
} else {
addHourButton.setEnabled(true);
}
mTimePickerEndDialog.updateTime(endHourSelected, endMinSelected);
}
/**
* Construct the <code>FRPeriod</code> object asscociated with the current
* selected times.
*
* @return
*/
private FRPeriod prepareFRFrPeriod() {
Calendar start = Calendar.getInstance();
start.set(yearSelected, monthSelected, dayOfMonthSelected,
startHourSelected, startMinSelected, 0);
start.set(Calendar.MILLISECOND, 0);
Calendar end = Calendar.getInstance();
end.set(yearSelected, monthSelected, dayOfMonthSelected,
endHourSelected, endMinSelected, 0);
end.set(Calendar.MILLISECOND, 0);
// constructs the request
return new FRPeriod(start.getTimeInMillis(), end.getTimeInMillis(),
false);
}
/**
* Prepare the actual query to send and set it in the controller
*/
private void prepareSearchQuery() {
FRPeriod period = prepareFRFrPeriod();
List<String> mUIDList = new ArrayList<String>(selectedRooms.size());
if (favButton.isChecked()) {
addAllFavoriteToCollection(mUIDList, AddCollectionCaller.SEARCH,
true);
}
if (userDefButton.isChecked()) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom room = iter.next();
mUIDList.add(room.getUid());
}
}
boolean any = anyButton.isChecked();
boolean fav = favButton.isChecked();
boolean user = userDefButton.isChecked();
// TODO change group accordingly, set to 1 by default and for testing
// purpose
FRRequestDetails details = new FRRequestDetails(period,
freeButton.isChecked(), mUIDList, any, fav, user,
selectedRooms, 1);
mModel.setFRRequestDetails(details);
mController.sendFRRequest(this);
mSearchDialog.dismiss();
resetUserDefined(); // cleans the selectedRooms of userDefined
}
/**
* Check that the times set are valid, according to the shared definition.
*
* @return 0 if times are valids, positive integer otherwise
*/
private int auditTimes() {
// NOT EVEN SET, we don't bother checking
if (yearSelected == -1 || monthSelected == -1
|| dayOfMonthSelected == -1) {
return 1;
}
if (startHourSelected == -1 || endHourSelected == -1
|| startMinSelected == -1 || endMinSelected == -1) {
return 1;
}
// IF SET, we use the shared method checking the prepared period
String errors = FRTimes.validCalendarsString(prepareFRFrPeriod());
if (errors.equals("")) {
return 0;
}
Toast.makeText(
getApplicationContext(),
"Please review the time, should be between Mo-Fr 8am-7pm.\n"
+ "The end should also be after the start, and at least 5 minutes.",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Errors remaining: \n" + errors, Toast.LENGTH_LONG).show();
return 1;
}
/**
* This method check if the client is allowed to submit a request to the
* server.
*
* @return 0 if there is no error and the client can send the request,
* something else otherwise.
*/
private int auditSubmit() {
if (selectedRooms == null
|| (!anyButton.isChecked() && !favButton.isChecked()
&& userDefButton.isChecked() && selectedRooms.isEmpty())) {
return 1;
}
if (anyButton.isChecked()
&& (favButton.isChecked() || userDefButton.isChecked())) {
return 1;
}
if (!anyButton.isChecked() && !favButton.isChecked()
&& !userDefButton.isChecked()) {
return 1;
}
boolean isFavEmpty = mModel.getFavorites().isEmpty();
if (favButton.isChecked()
&& isFavEmpty
&& (!userDefButton.isChecked() || (userDefButton.isChecked() && selectedRooms
.isEmpty()))) {
return 1;
}
// we dont allow query all the room, including non-free
if (anyButton.isChecked() && !freeButton.isChecked()) {
return 1;
}
return auditTimes();
}
@Override
public void autoCompletedUpdated() {
mAdapter.notifyDataSetInvalidated();
mAutoCompleteSuggestionArrayListFRRoom.clear();
// TODO: adapt to use the new version of autocomplete mapped by building
Iterator<List<FRRoom>> iter = mModel.getAutoComplete().values()
.iterator();
System.out.println(mModel.getAutoComplete().values().size());
while (iter.hasNext()) {
List<FRRoom> list = iter.next();
System.out.println(list.size());
Iterator<FRRoom> iterroom = list.iterator();
while (iterroom.hasNext()) {
FRRoom room = iterroom.next();
// rooms that are already selected are not displayed...
if (!selectedRooms.contains(room)) {
mAutoCompleteSuggestionArrayListFRRoom.add(room);
}
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void refreshOccupancies() {
refresh();
}
}
|
package de.itemis.mosig.racecar.textconv;
import static org.junit.Assert.*;
import org.junit.Test;
public class HtmlTextConverterTest {
@Test
public void shouldConverAngelBracketsToHtmlCounterParts() {
HtmlTextConverter underTest = new HtmlTextConverter();
underTest.convertToHtml("<>");
}
}
|
package org.eclipse.mylyn.internal.hudson.core.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.eclipse.core.runtime.Assert;
import org.eclipse.mylyn.builds.core.spi.AbstractConfigurationCache;
import org.eclipse.mylyn.commons.core.IOperationMonitor;
import org.eclipse.mylyn.commons.http.CommonHttpClient;
import org.eclipse.mylyn.commons.http.CommonHttpMethod;
import org.eclipse.mylyn.commons.net.AbstractWebLocation;
import org.eclipse.mylyn.internal.commons.http.CommonPostMethod;
import org.eclipse.mylyn.internal.hudson.model.HudsonModelBuild;
import org.eclipse.mylyn.internal.hudson.model.HudsonModelHudson;
import org.eclipse.mylyn.internal.hudson.model.HudsonModelJob;
import org.eclipse.mylyn.internal.hudson.model.HudsonModelRun;
import org.eclipse.mylyn.internal.hudson.model.HudsonTasksJunitTestResult;
import org.eclipse.osgi.util.NLS;
import org.json.JSONException;
import org.json.JSONWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* Represents the Hudson repository that is accessed through REST.
*
* @author Markus Knittig
* @author Steffen Pingel
* @author Eike Stepper
*/
public class RestfulHudsonClient {
public enum BuildId {
LAST(-1, "lastBuild"), LAST_FAILED(-5, "lastFailedBuild"), LAST_STABLE(-2, "lastStableBuild"), LAST_SUCCESSFUL(
-3, "lastSuccessfulBuild"), LAST_UNSTABLE(-4, "lastUnstableBuild");
private HudsonModelBuild build;
private final int id;
private final String url;
BuildId(int id, String url) {
this.id = id;
this.url = url;
this.build = new HudsonModelBuild();
this.build.setNumber(id);
}
public HudsonModelBuild getBuild() {
return build;
}
};
private static final String URL_API = "/api/xml"; //$NON-NLS-1$
private AbstractConfigurationCache<HudsonConfiguration> cache;
private final CommonHttpClient client;
public RestfulHudsonClient(AbstractWebLocation location, HudsonConfigurationCache cache) {
client = new CommonHttpClient(location);
client.getHttpClient().getParams().setAuthenticationPreemptive(true);
setCache(cache);
}
protected void checkResponse(CommonHttpMethod method) throws HudsonException {
checkResponse(method, HttpStatus.SC_OK);
}
protected void checkResponse(CommonHttpMethod method, int expected) throws HudsonException {
int statusCode = method.getStatusCode();
if (statusCode != expected) {
if (statusCode == HttpStatus.SC_NOT_FOUND) {
throw new HudsonResourceNotFoundException(NLS.bind("Requested resource ''{0}'' does not exist", method
.getPath()));
}
throw new HudsonException(NLS.bind("Unexpected response from Hudson server for ''{0}'': {1}", method
.getPath(), HttpStatus.getStatusText(statusCode)));
}
}
public HudsonModelBuild getBuild(final HudsonModelJob job, final HudsonModelRun build,
final IOperationMonitor monitor) throws HudsonException {
return new HudsonOperation<HudsonModelBuild>(client) {
@Override
public HudsonModelBuild execute() throws IOException, HudsonException, JAXBException {
CommonHttpMethod method = createGetMethod(getBuildUrl(job, build) + URL_API);
try {
execute(method, monitor);
checkResponse(method);
InputStream in = method.getResponseBodyAsStream(monitor);
HudsonModelBuild hudsonBuild = unmarshal(parse(in), HudsonModelBuild.class);
return hudsonBuild;
} finally {
method.releaseConnection(monitor);
}
}
}.run();
}
public HudsonTasksJunitTestResult getTestReport(final HudsonModelJob job, final HudsonModelRun build,
final IOperationMonitor monitor) throws HudsonException {
return new HudsonOperation<HudsonTasksJunitTestResult>(client) {
@Override
public HudsonTasksJunitTestResult execute() throws IOException, HudsonException, JAXBException {
// String url = HudsonUrl.create(getBuildUrl(job, build) + "/testReport" + URL_API).exclude(
// "/testResult/suite/case/stdout").exclude("/testResult/suite/case/stderr").toUrl();
String url = HudsonUrl
.create(getBuildUrl(job, build) + "/testReport" + URL_API)
.tree("duration,failCount,passCount,skipCount,suites[cases[className,duration,errorDetails,errorStackTrace,failedSince,name,skipped,status],duration,name,stderr,stdout]")
.toUrl();
CommonHttpMethod method = createGetMethod(url);
try {
execute(method, monitor);
checkResponse(method);
InputStream in = method.getResponseBodyAsStream(monitor);
return unmarshal(parse(in), HudsonTasksJunitTestResult.class);
} finally {
method.releaseConnection(monitor);
}
}
}.run();
}
protected String getBuildUrl(final HudsonModelJob job, final HudsonModelRun build) throws HudsonException {
if (build.getNumber() == -1) {
return getJobUrl(job) + "/lastBuild";
} else {
return getJobUrl(job) + "/" + build.getNumber();
}
}
public AbstractConfigurationCache<HudsonConfiguration> getCache() {
return cache;
}
public HudsonConfiguration getConfiguration() {
return getCache().getConfiguration(client.getLocation().getUrl());
}
public Reader getConsole(final HudsonModelJob job, final HudsonModelBuild hudsonBuild,
final IOperationMonitor monitor) throws HudsonException {
return new HudsonOperation<Reader>(client) {
@Override
public Reader execute() throws IOException, HudsonException {
CommonHttpMethod method = createGetMethod(getBuildUrl(job, hudsonBuild) + "/consoleText");
execute(method, monitor);
checkResponse(method);
String charSet = method.getResponseCharSet();
if (charSet == null) {
charSet = "UTF-8";
}
return new InputStreamReader(method.getResponseBodyAsStream(monitor), charSet);
}
}.run();
}
private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
return DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
public List<HudsonModelJob> getJobs(final List<String> ids, final IOperationMonitor monitor) throws HudsonException {
return new HudsonOperation<List<HudsonModelJob>>(client) {
@Override
public List<HudsonModelJob> execute() throws IOException, HudsonException, JAXBException {
String url = HudsonUrl.create(client.getLocation().getUrl() + URL_API).depth(1).include("/hudson/job")
.match("name", ids).exclude("/hudson/job/build").toUrl();
CommonHttpMethod method = createGetMethod(url);
try {
execute(method, monitor);
checkResponse(method);
InputStream in = method.getResponseBodyAsStream(monitor);
Map<String, String> jobNameById = new HashMap<String, String>();
HudsonModelHudson hudson = unmarshal(parse(in), HudsonModelHudson.class);
List<HudsonModelJob> buildPlans = new ArrayList<HudsonModelJob>();
List<Object> jobsNodes = hudson.getJob();
for (Object jobNode : jobsNodes) {
Node node = (Node) jobNode;
HudsonModelJob job = unmarshal(node, HudsonModelJob.class);
if (job.getDisplayName() != null && job.getDisplayName().length() > 0) {
jobNameById.put(job.getName(), job.getDisplayName());
} else {
jobNameById.put(job.getName(), job.getName());
}
buildPlans.add(job);
}
HudsonConfiguration configuration = new HudsonConfiguration();
configuration.jobNameById = jobNameById;
setConfiguration(configuration);
return buildPlans;
} finally {
method.releaseConnection(monitor);
}
}
}.run();
}
private String getJobUrl(HudsonModelJob job) throws HudsonException {
String encodedJobname = "";
try {
encodedJobname = new URI(null, job.getName(), null).toASCIIString();
} catch (URISyntaxException e) {
throw new HudsonException(e);
}
return client.getLocation().getUrl() + "/job/" + encodedJobname;
}
Element parse(InputStream in) throws HudsonException {
try {
return getDocumentBuilder().parse(in).getDocumentElement();
} catch (SAXException e) {
throw new HudsonException(e);
} catch (Exception e) {
throw new HudsonException(e);
}
}
public Document getJobConfig(final HudsonModelJob job, final IOperationMonitor monitor) throws HudsonException {
return new HudsonOperation<Document>(client) {
@Override
public Document execute() throws IOException, HudsonException, JAXBException {
CommonHttpMethod method = createGetMethod(getJobUrl(job) + "/config.xml");
try {
execute(method, monitor);
checkResponse(method);
InputStream in = method.getResponseBodyAsStream(monitor);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder.parse(in); // TODO Enhance progress monitoring
} catch (ParserConfigurationException e) {
throw new HudsonException(e);
} catch (SAXException e) {
throw new HudsonException(e);
} finally {
method.releaseConnection(monitor);
}
}
}.run();
}
public void runBuild(final HudsonModelJob job, final Map<String, String> parameters, final IOperationMonitor monitor)
throws HudsonException {
new HudsonOperation<Object>(client) {
@Override
public Object execute() throws IOException, HudsonException {
CommonPostMethod method = (CommonPostMethod) createPostMethod(getJobUrl(job) + "/build");
method.setFollowRedirects(false);
method.setDoAuthentication(true);
if (parameters != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out);
try {
JSONWriter json = new JSONWriter(writer);
json.object().key("parameter").array();
for (Entry<String, String> entry : parameters.entrySet()) {
method.addParameter(new NameValuePair("name", entry.getKey()));
json.object().key("name").value(entry.getKey());
String value = entry.getValue();
if (value != null) {
method.addParameter(new NameValuePair("value", value));
json.key("value");
if (entry.getKey().equals("Boolean")) {
json.value(Boolean.parseBoolean(entry.getValue()));
} else {
json.value(entry.getValue());
}
}
json.endObject();
}
json.endArray().endObject();
writer.flush();
method.addParameter(new NameValuePair("json", out.toString()));
method.addParameter(new NameValuePair("Submit", "Build"));
} catch (JSONException e) {
throw new IOException("Error constructing request: " + e);
}
}
try {
execute(method, monitor);
checkResponse(method, 302);
return null;
} finally {
method.releaseConnection(monitor);
}
}
}.run();
}
public void setCache(AbstractConfigurationCache<HudsonConfiguration> cache) {
Assert.isNotNull(cache);
this.cache = cache;
}
protected void setConfiguration(HudsonConfiguration configuration) {
getCache().setConfiguration(client.getLocation().getUrl(), configuration);
}
private <T> T unmarshal(Node node, Class<T> clazz) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
JAXBElement<T> hudsonElement = unmarshaller.unmarshal(node, clazz);
return hudsonElement.getValue();
}
public HudsonServerInfo validate(final IOperationMonitor monitor) throws HudsonException {
return new HudsonOperation<HudsonServerInfo>(client) {
@Override
public HudsonServerInfo execute() throws IOException, HudsonException {
CommonHttpMethod method = createHeadMethod(client.getLocation().getUrl());
try {
execute(method, monitor);
checkResponse(method);
Header header = method.getResponseHeader("X-Hudson"); //$NON-NLS-1$
if (header == null) {
throw new HudsonException(NLS.bind("{0} does not appear to be a Hudson instance", client
.getLocation().getUrl()));
}
HudsonServerInfo info = new HudsonServerInfo(header.getValue());
return info;
} finally {
method.releaseConnection(monitor);
}
}
}.run();
}
}
|
package gov.nih.nci.caxchange.messaging;
import gov.nih.nci.integration.catissue.CaTissueParticipantClientIntegrationTest;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This is the TestClass for registerConsent flow.
*
* @author Rohit Gupta
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-mirth-deploy-test.xml")
public class RegisterConsentIntegrationTest {
@Value("${transcend.caxchange.service.url}")
private String transcendCaxchangeServiceUrl;
private final HttpClient httpclient = new DefaultHttpClient();
private static final String XMLTEXT = "text/xml";
private static final Logger LOG = LoggerFactory.getLogger(RegisterConsentIntegrationTest.class);
/**
* Testcase for registerConsents flow
*/
@Test
public void registerConsents() {
try {
final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl);
final StringEntity reqentity = new StringEntity(getRegisterConsentXMLStr());
httppost.setEntity(reqentity);
httppost.setHeader(HttpHeaders.CONTENT_TYPE, XMLTEXT);
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();
String createdXML = null;
if (entity != null) {
createdXML = EntityUtils.toString(entity);
Assert.assertEquals(true, createdXML.contains("<responseStatus>SUCCESS</responseStatus>"));
}
} catch (ClientProtocolException e) {
Assert.fail(e.getMessage());
} catch (IllegalStateException e) {
Assert.fail(e.getMessage());
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
/**
* Testcase for registerConsents when Specimen doesn't exist
*/
@Test
public void registerConsentsSpecimenNotExist() {
try {
final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl);
final StringEntity reqentity = new StringEntity(getRegisterConsentSpecimenNotExistXMLStr());
httppost.setEntity(reqentity);
httppost.setHeader(HttpHeaders.CONTENT_TYPE, XMLTEXT);
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();
String createdXML = null;
if (entity != null) {
createdXML = EntityUtils.toString(entity);
Assert.assertEquals(true, createdXML.contains("<errorCode>1090</errorCode>"));
}
} catch (ClientProtocolException e) {
Assert.fail(e.getMessage());
} catch (IllegalStateException e) {
Assert.fail(e.getMessage());
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
/**
* Testcase for registerConsents when Tier statement doesn't exist
*/
@Test
public void registerConsentsStatementNotExist() {
try {
final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl);
final StringEntity reqentity = new StringEntity(getRegisterConsentStatementNotExistXMLStr());
httppost.setEntity(reqentity);
httppost.setHeader(HttpHeaders.CONTENT_TYPE, XMLTEXT);
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();
String createdXML = null;
if (entity != null) {
createdXML = EntityUtils.toString(entity);
Assert.assertEquals(true, createdXML.contains("<errorCode>1092</errorCode>"));
}
} catch (ClientProtocolException e) {
Assert.fail(e.getMessage());
} catch (IllegalStateException e) {
Assert.fail(e.getMessage());
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
private String getRegisterConsentXMLStr() {
return getXMLString("RegisterConsent.xml");
}
private String getRegisterConsentSpecimenNotExistXMLStr() {
return getXMLString("RegisterConsentSpecimenNotExist.xml");
}
private String getRegisterConsentStatementNotExistXMLStr() {
return getXMLString("RegisterConsentStatementNotExist.xml");
}
private String getXMLString(String fileName) {
String contents = null;
final InputStream is = CaTissueParticipantClientIntegrationTest.class.getClassLoader().getResourceAsStream(
"payloads_consent/" + fileName);
try {
contents = org.apache.cxf.helpers.IOUtils.toString(is);
} catch (IOException e) {
LOG.error("Error while reading contents of file : " + fileName + ". " + e);
}
return contents;
}
}
|
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.globus.cog.abstraction.coaster.service;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.coaster.service.job.manager.Settings;
import org.globus.cog.abstraction.impl.execution.coaster.ServiceConfigurationCommand;
import org.globus.cog.karajan.workflow.service.ProtocolException;
import org.globus.cog.karajan.workflow.service.handlers.RequestHandler;
public class ServiceConfigurationHandler extends RequestHandler {
public static final Logger logger = Logger.getLogger(ServiceConfigurationHandler.class);
public static final String NAME = ServiceConfigurationCommand.NAME;
public void requestComplete() throws ProtocolException {
Settings settings =
((CoasterService) getChannel().getChannelContext().getService()).getJobQueue().getSettings();
logger.debug(settings);
try {
List l = getInDataChuncks();
if (l != null) {
Iterator i = l.iterator();
while (i.hasNext()) {
String s = new String((byte[]) i.next());
String[] p = s.split("=", 2);
settings.set(p[0], p[1]);
}
}
sendReply("OK");
}
catch (Exception e) {
logger.warn("Failed to set configuration", e);
sendError("Failed to set configuration: " + e.getMessage(), e);
}
}
}
|
package org.spongepowered.common.mixin.optimization.world.gen;
import net.minecraft.world.WorldServer;
import net.minecraft.world.gen.ChunkProviderServer;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.common.bridge.world.chunk.ChunkBridge;
@Mixin(value = ChunkProviderServer.class, priority = 1002)
public abstract class MixinChunkProviderServer_Async_Lighting {
@Shadow @Final public WorldServer world;
@Dynamic
@Redirect(method = "tick",
at = @At(
value = "INVOKE",
target = "Lorg/spongepowered/common/bridge/world/chunk/ChunkBridge;isPersistedChunk()Z",
remap = false))
private boolean asyncLighting$UsePendingLightUpdatesForAsyncChunk(ChunkBridge chunk) {
return chunk.isPersistedChunk()
|| chunk.getPendingLightUpdates().get() > 0
|| this.world.getTotalWorldTime() - chunk.getLightUpdateTime() < 20;
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.test.integration.project;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asAdmin;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asUser;
import static ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils.asSequencer;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiJdbcDataSourceConfig;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiPropertyPlaceholderConfig;
import ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestAuthUtils;
import ca.corefacility.bioinformatics.irida.web.controller.test.integration.util.ITestSystemProperties;
/**
* Integration tests for project samples.
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiJdbcDataSourceConfig.class,
IridaApiPropertyPlaceholderConfig.class })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class })
@ActiveProfiles("it")
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/web/controller/test/integration/project/ProjectSamplesIntegrationTest.xml")
@DatabaseTearDown("classpath:/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
public class ProjectSamplesIT {
private static final Logger logger = LoggerFactory.getLogger(ProjectSamplesIT.class);
@Test
public void testShareSampleToProject() {
final List<String> samples = Lists.newArrayList("1");
final String projectUri = "/api/projects/4";
final String projectJson = asUser().get(projectUri).asString();
final String samplesUri = from(projectJson).get("resource.links.find{it.rel == 'project/samples'}.href");
assertTrue("The samples URI should end with /api/projects/4/samples",
samplesUri.endsWith("/api/projects/4/samples"));
final Response r = asUser().contentType(ContentType.JSON).body(samples)
.header("Content-Type", "application/idcollection+json").expect().response()
.statusCode(HttpStatus.CREATED.value()).when().post(samplesUri);
final String location = r.getHeader(HttpHeaders.LOCATION);
assertNotNull("Location should not be null.", location);
assertEquals("The project/sample location uses the wrong sample ID.", ITestSystemProperties.BASE_URL
+ "/api/projects/4/samples/1", location);
}
@Test
public void testShareSampleToProjectWithSameId() {
final List<String> samples = Lists.newArrayList("3");
final String projectUri = "/api/projects/4";
final String projectJson = asUser().get(projectUri).asString();
final String samplesUri = from(projectJson).get("resource.links.find{it.rel == 'project/samples'}.href");
asUser().contentType(ContentType.JSON).body(samples).header("Content-Type", "application/idcollection+json")
.expect().response().statusCode(HttpStatus.CONFLICT.value()).when().post(samplesUri);
}
@Test
public void testAddMultithreadedSamplesToProject() throws InterruptedException {
final int numberOfThreads = 40;
final int numberOfSamples = 40;
final ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
// load a project
final String projectUri = "/api/projects/1";
// get the uri for creating samples associated with the project.
final String projectJson = asUser().get(projectUri).asString();
final String samplesUri = from(projectJson).get("resource.links.find{it.rel == 'project/samples'}.href");
final Callable<List<Integer>> task = () -> {
final List<Integer> responses = new CopyOnWriteArrayList<>();
final Random rand = new Random(Thread.currentThread().getId());
for (int i = 0; i < numberOfSamples; i++) {
final String sampleName = Thread.currentThread().getName() + "-" + rand.nextInt();
final HttpClient client = HttpClientBuilder.create().build();
final HttpPost request = new HttpPost(samplesUri);
request.addHeader("Authorization", "Bearer " + ITestAuthUtils.getTokenForRole("user"));
request.addHeader("Content-Type", "application/json");
final StringEntity content = new StringEntity("{\"sampleName\": \"" + sampleName + "\", \"sequencerSampleId\": \"" + sampleName + "\"}");
request.setEntity(content);
final HttpResponse response = client.execute(request);
// post that uri
responses.add(response.getStatusLine().getStatusCode());
}
return responses;
};
final List<Future<List<Integer>>> futures = new CopyOnWriteArrayList<>();
for (int i = 0 ; i < numberOfThreads; i++) {
futures.add(executorService.submit(task));
}
for (final Future<List<Integer>> f : futures) {
try {
final List<Integer> responses = f.get();
assertTrue("All responses should be created.", responses.stream().allMatch(r -> r == HttpStatus.CREATED.value()));
} catch (InterruptedException | ExecutionException e) {
logger.error("Failed to submit multiple samples simultaneously:", e);
fail("Failed to submit multiple samples simultaneously.");
}
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
}
@Test
public void testAddSampleToProject() {
Map<String, String> sample = new HashMap<>();
sample.put("sampleName", "sample_1");
sample.put("sequencerSampleId", "sample_1");
// load a project
String projectUri = "/api/projects/1";
// get the uri for creating samples associated with the project.
String projectJson = asUser().get(projectUri).asString();
String samplesUri = from(projectJson).get("resource.links.find{it.rel == 'project/samples'}.href");
// post that uri
Response r = asUser().body(sample).expect().response().statusCode(HttpStatus.CREATED.value()).when()
.post(samplesUri);
// check that the locations are set appropriately.
String location = r.getHeader(HttpHeaders.LOCATION);
assertNotNull(location);
assertTrue(location.matches("^" + ITestSystemProperties.BASE_URL + "/api/samples/[0-9]+$"));
}
@Test
public void testDeleteSampleFromProject() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/4";
// load the project
String projectJson = asUser().get(projectUri).asString();
String projectSamplesUri = from(projectJson).get("resource.links.find{it.rel=='project/samples'}.href");
String projectSamplesJson = asUser().get(projectSamplesUri).asString();
String sampleLabel = from(projectSamplesJson).get("resource.resources[0].sampleName");
// get the uri for a specific sample associated with a project
String sampleUri = from(projectSamplesJson).get("resource.resources[0].links.find{it.rel == 'project/sample'}.href");
// issue a delete against the service
Response r = asAdmin().expect().statusCode(HttpStatus.OK.value()).when().delete(sampleUri);
// check that the response body contains links to the project and
// samples collection
String responseBody = r.getBody().asString();
String projectUriRel = from(responseBody).get("resource.links.find{it.rel == 'project'}.href");
assertNotNull(projectUriRel);
assertEquals(projectUri, projectUriRel);
String samplesUri = from(responseBody).get("resource.links.find{it.rel == 'project/samples'}.href");
assertNotNull(samplesUri);
assertEquals(projectUri + "/samples", samplesUri);
// now confirm that the sample is not there anymore
asUser().expect().body("resource.resources.sampleName", not(hasItem(sampleLabel))).when()
.get(projectSamplesUri);
}
@Test
public void testUpdateProjectSample() {
String projectSampleUri = ITestSystemProperties.BASE_URL + "/api/samples/1";
Map<String, String> updatedFields = new HashMap<>();
String updatedName = "Totally-different-sample-name";
updatedFields.put("sampleName", updatedName);
asUser().and().body(updatedFields).expect()
.body("resource.links.rel", hasItems("self", "sample/sequenceFiles")).when()
.patch(projectSampleUri);
// now confirm that the sample name was updated
asUser().expect().body("resource.sampleName", is(updatedName)).when().get(projectSampleUri);
}
@Test
public void testReadSampleAsAdmin() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/5";
String projectSampleUri = projectUri + "/samples/1";
asAdmin().expect().body("resource.links.rel", hasItems("self", "sample/project", "sample/sequenceFiles"))
.when().get(projectSampleUri);
}
@Test
public void testReadSampleCollectionDate() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/5";
String projectSampleUri = projectUri + "/samples/1";
asAdmin().expect().body("resource.collectionDate", is("2019-01-24"))
.when().get(projectSampleUri);
}
@Test
public void testReadSampleCollectionDate2() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/5";
String projectSampleUri = projectUri + "/samples/3";
asAdmin().expect().body("resource.collectionDate", is("1999-12-05"))
.when().get(projectSampleUri);
}
@Test
public void testReadSampleAsAdminWithDoubledUpSlashes() {
String projectUri = ITestSystemProperties.BASE_URL + "/api//projects/5";
String projectSampleUri = projectUri + "/samples/1";
final Response r = asAdmin().expect().body("resource.links.rel", hasItems("self", "sample/project", "sample/sequenceFiles"))
.when().get(projectSampleUri);
final String responseBody = r.getBody().asString();
final String samplesUri = from(responseBody).get("resource.links.find{it.rel == 'sample/project'}.href");
// now verify that we can actually get this (so doubled slash should not have affected the link)
asAdmin().expect().statusCode(HttpStatus.OK.value()).when().get(samplesUri);
}
@Test
public void testReadSampleAsSequencer() {
String projectUri = ITestSystemProperties.BASE_URL + "/api/projects/5";
String projectSampleUri = projectUri + "/samples/1";
asSequencer().expect().body("resource.links.rel", hasItems("self", "sample/project", "sample/sequenceFiles"))
.when().get(projectSampleUri);
}
}
|
package org.apereo.cas.adaptors.u2f.storage;
import com.google.common.cache.LoadingCache;
import com.yubico.u2f.data.DeviceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;
/**
* This is {@link U2FJpaDeviceRepository}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@EnableTransactionManagement(proxyTargetClass = true)
@Transactional(transactionManager = "transactionManagerU2f")
public class U2FJpaDeviceRepository extends BaseU2FDeviceRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(U2FJpaDeviceRepository.class);
private static final String SELECT_QUERY = "SELECT r from U2FJpaDeviceRegistration r ";
@PersistenceContext(unitName = "u2fEntityManagerFactory")
private EntityManager entityManager;
public U2FJpaDeviceRepository(final LoadingCache<String, String> requestStorage) {
super(requestStorage);
}
@Override
public Collection<DeviceRegistration> getRegisteredDevices(final String username) {
try {
return this.entityManager.createQuery(
SELECT_QUERY.concat("where r.username = :username"), U2FJpaDeviceRegistration.class)
.setParameter("username", username)
.getResultList()
.stream()
.map(r -> DeviceRegistration.fromJson(r.getRecord()))
.collect(Collectors.toList());
} catch (final NoResultException e) {
LOGGER.debug("No device registration was found for [{}]", username);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return new ArrayList<>();
}
@Override
public void registerDevice(final String username, final DeviceRegistration registration) {
authenticateDevice(username, registration);
}
@Override
public void authenticateDevice(final String username, final DeviceRegistration registration) {
final U2FJpaDeviceRegistration jpa = new U2FJpaDeviceRegistration();
jpa.setUsername(username);
jpa.setRecord(registration.toJson());
this.entityManager.merge(jpa);
}
@Override
public boolean isDeviceRegisteredFor(final String username) {
return !getRegisteredDevices(username).isEmpty();
}
}
|
package org.arquillian.smart.testing.surefire.provider;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.surefire.providerapi.ProviderParameters;
import org.apache.maven.surefire.providerapi.SurefireProvider;
import org.apache.maven.surefire.report.ReporterException;
import org.apache.maven.surefire.suite.RunResult;
import org.apache.maven.surefire.testset.TestSetFailedException;
import org.apache.maven.surefire.util.TestsToRun;
import static java.lang.String.format;
public class SmartTestingSurefireProvider implements SurefireProvider {
private static final Logger logger = Logger.getLogger(SmartTestingSurefireProvider.class.getName());
private SurefireProvider surefireProvider;
private ProviderParametersParser paramParser;
private Class<SurefireProvider> providerClass;
private ProviderParameters bootParams;
public SmartTestingSurefireProvider(ProviderParameters bootParams) {
this.bootParams = bootParams;
this.paramParser = new ProviderParametersParser(this.bootParams);
this.providerClass = new ProviderList(this.paramParser).resolve();
this.surefireProvider = createSurefireProviderInstance();
}
private TestsToRun getTestsToRun() {
final TestsToRun testsToRun = (TestsToRun) getSuites();
final String strategiesParam = paramParser.getProperty("strategies");
logger.log(Level.INFO, format("Enabled strategies: %s", strategiesParam));
final String[] strategies = strategiesParam.split(",");
final JavaSPILoader spiLoader = new JavaSPILoader() {
@Override
public <S> Iterable<S> load(Class<S> service) {
return ServiceLoader.load(service);
}
};
final TestExecutionPlannerLoader testExecutionPlannerLoader =
new TestExecutionPlannerLoader(spiLoader, getGlobPatterns());
return new TestStrategyApplier(testsToRun, paramParser,
testExecutionPlannerLoader).apply(Arrays.asList(strategies));
}
private String[] getGlobPatterns() {
final List<String> globPatterns = paramParser.getIncludes();
// TODO question why exclusions are added too?
globPatterns.addAll(paramParser.getExcludes());
return globPatterns.toArray(new String[globPatterns.size()]);
}
public Iterable<Class<?>> getSuites() {
return surefireProvider.getSuites();
}
public RunResult invoke(Object forkTestSet)
throws TestSetFailedException, ReporterException, InvocationTargetException {
TestsToRun orderedTests = getTestsToRun();
surefireProvider = createSurefireProviderInstance();
return surefireProvider.invoke(orderedTests);
}
private SurefireProvider createSurefireProviderInstance(){
return SecurityUtils.newInstance(providerClass, new Class[] {ProviderParameters.class}, new Object[] {bootParams});
}
public void cancel() {
surefireProvider.cancel();
}
}
|
package org.jboss.as.test.integration.web.handlers;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests the use of undertow-handlers.conf
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ForwardedHandlerTestCase {
private static final String FORWARDED_HANDLER_NO_UT_HANDLERS = "forwarded-handler-no-ut-handlers";
private static final String FORWARDED_SERVLET = "forwarded-servlet";
private static final String FORWARDED_SERVLET_NO_UT_HANDLERS = "forwarded-servlet-no-ut-handlers";
private static final String FORWARDER_HANDLER_NAME = "forwarded";
private static final PathAddress FORWARDER_CONF_ADDR = PathAddress.pathAddress().append(SUBSYSTEM, "undertow")
.append("configuration", "filter").append("expression-filter", "ff");
private static final PathAddress FORWARDER_FILTER_REF_ADDR = PathAddress.pathAddress().append(SUBSYSTEM, "undertow")
.append("server", "default-server").append("host", "default-host").append("filter-ref", "ff");
private static final String JBOSS_WEB_TEXT = "<?xml version=\"1.0\"?>\n" +
"<jboss-web>\n" +
" <http-handler>\n" +
" <class-name>org.jboss.as.test.integration.web.handlers.ForwardedTestHelperHandler</class-name>\n" +
" </http-handler>\n" +
"</jboss-web>";
@ContainerResource
private ManagementClient managementClient;
@Deployment(name = FORWARDED_HANDLER_NO_UT_HANDLERS)
public static WebArchive deployWithoutUndertowHandlers() {
return ShrinkWrap.create(WebArchive.class, FORWARDED_HANDLER_NO_UT_HANDLERS + ".war")
.addPackage(ForwardedHandlerTestCase.class.getPackage())
.addAsWebInfResource(new StringAsset(JBOSS_WEB_TEXT), "jboss-web.xml")
.addAsWebResource(new StringAsset("A file"), "index.html");
}
@Deployment(name = FORWARDED_SERVLET)
public static WebArchive deploy_servlet() {
return ShrinkWrap.create(WebArchive.class, FORWARDED_SERVLET + ".war")
.addClass(ForwardedTestHelperServlet.class)
.addAsWebInfResource(new StringAsset(FORWARDER_HANDLER_NAME), "undertow-handlers.conf")
.addAsWebResource(new StringAsset("A file"), "index.html");
}
@Deployment(name = FORWARDED_SERVLET_NO_UT_HANDLERS)
public static WebArchive deployWithoutUndertowHandlers_servlet() {
return ShrinkWrap.create(WebArchive.class, FORWARDED_SERVLET_NO_UT_HANDLERS + ".war")
.addClass(ForwardedTestHelperServlet.class)
.addAsWebResource(new StringAsset("A file"), "index.html");
}
@Test
@OperateOnDeployment(FORWARDED_HANDLER_NO_UT_HANDLERS)
public void testRewriteGlobalSettings(@ArquillianResource URL url) throws Exception {
commonConfigureExpression(url, true);
}
@Test
@OperateOnDeployment(FORWARDED_SERVLET)
public void testRewriteWithUndertowHandlersServlet(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/forwarded"), false);
}
@Test
@OperateOnDeployment(FORWARDED_SERVLET_NO_UT_HANDLERS)
public void testRewriteGlobalSettingsServlet(@ArquillianResource URL url) throws Exception {
commonConfigureExpression(new URL(url + "/forwarded"), false);
}
private void commonConfigureExpression(URL url, boolean header) throws IOException, MgmtOperationException {
ModelNode op = Util.createAddOperation(FORWARDER_CONF_ADDR);
op.get("expression").set(FORWARDER_HANDLER_NAME);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = Util.createAddOperation(FORWARDER_FILTER_REF_ADDR);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
try {
commonTestPart(url, header);
} finally {
op = Util.createRemoveOperation(FORWARDER_FILTER_REF_ADDR);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = Util.createRemoveOperation(FORWARDER_CONF_ADDR);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
}
private void commonTestPart(URL url, boolean header) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final String proto = "https";
final String forAddrOnly = "192.121.210.60";
final String forAddr = forAddrOnly + ":455";
final String by = "203.0.113.43:777";
final InetAddress addr = InetAddress.getByName(url.getHost());
final String localAddrName = addr.getHostName();
final String localAddr = addr.getHostAddress() + ":" + url.getPort();
HttpGet httpget = new HttpGet(url.toExternalForm());
httpget.addHeader("Forwarded", "for=" + forAddr + ";proto=" + proto + ";by=" + by);
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
if (header) {
Header[] hdrs = response.getHeaders(ForwardedTestHelperHandler.FORWARD_TEST_HEADER);
Assert.assertEquals(1, hdrs.length);
Assert.assertEquals("/" + forAddr + "|" + proto + "|" + "/" + localAddr, hdrs[0].getValue());
} else {
String result = EntityUtils.toString(entity);
Assert.assertEquals(forAddrOnly + "|" + forAddr + "|" + proto + "|" + localAddrName + "|" + localAddr, result);
}
}
}
}
|
package org.nick.wwwjdic.history;
import java.util.ArrayList;
import java.util.List;
import org.nick.wwwjdic.R;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class FavoritesAndHistorySummaryView extends ListView implements
OnItemClickListener {
private static final int FAVORITES_ITEM_IDX = 0;
@SuppressWarnings("unused")
private static final int HISTORY_ITEM_IDX = 1;
private static final int FAVORITES_TAB_IDX = 0;
private static final int HISTORY_TAB_IDX = 1;
private Context context;
private HistoryFavoritesSummaryAdapter adapter;
private int favoritesFilterType;
private int historyFilterType;
public FavoritesAndHistorySummaryView(Context context) {
super(context);
init(context);
}
public FavoritesAndHistorySummaryView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
this.context = context;
setOnItemClickListener(this);
adapter = new HistoryFavoritesSummaryAdapter(context);
setAdapter(adapter);
}
public void setRecentEntries(long numAllFavorites,
List<String> recentFavorites, long numAllHistoryItems,
List<String> recentHistory) {
adapter.setRecentEntries(numAllFavorites, recentFavorites,
numAllHistoryItems, recentHistory);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
boolean isFavoritesTab = position == FAVORITES_ITEM_IDX;
int tabIdx = isFavoritesTab ? FAVORITES_TAB_IDX : HISTORY_TAB_IDX;
int filterType = isFavoritesTab ? favoritesFilterType
: historyFilterType;
// examples, only history
if (getAdapter().getCount() == 1) {
tabIdx = HISTORY_TAB_IDX;
filterType = historyFilterType;
}
Intent intent = new Intent(context, FavoritesAndHistory.class);
intent.putExtra(FavoritesAndHistory.EXTRA_SELECTED_TAB_IDX, tabIdx);
intent.putExtra(FavoritesAndHistory.EXTRA_FILTER_TYPE, filterType);
context.startActivity(intent);
}
public int getFavoritesFilterType() {
return favoritesFilterType;
}
public void setFavoritesFilterType(int favoritesFilterType) {
this.favoritesFilterType = favoritesFilterType;
}
public int getHistoryFilterType() {
return historyFilterType;
}
public void setHistoryFilterType(int historyFilterType) {
this.historyFilterType = historyFilterType;
}
static class HistoryFavoritesSummaryAdapter extends BaseAdapter {
private final Context context;
private long numAllFavorites;
private List<String> recentFavorites;
private long numAllHistoryItems;
private List<String> recentHistory;
public HistoryFavoritesSummaryAdapter(Context context) {
this.context = context;
this.numAllFavorites = 0;
this.recentFavorites = new ArrayList<String>();
this.numAllHistoryItems = 0;
this.recentHistory = new ArrayList<String>();
}
public HistoryFavoritesSummaryAdapter(Context context,
List<String> recentFavorites, List<String> recentHistory) {
this.context = context;
this.numAllFavorites = 0;
this.recentFavorites = recentFavorites;
this.numAllHistoryItems = 0;
this.recentHistory = recentHistory;
}
public void setRecentEntries(long numAllFavorites,
List<String> recentFavorites, long numAllHistoryItems,
List<String> recentHistory) {
this.numAllFavorites = numAllFavorites;
this.recentFavorites = recentFavorites;
this.numAllHistoryItems = numAllHistoryItems;
this.recentHistory = recentHistory;
notifyDataSetChanged();
}
@Override
public int getCount() {
if (recentFavorites == null) {
return 1;
}
return 2;
}
@Override
public Object getItem(int position) {
switch (position) {
case 0:
if (recentFavorites == null) {
return "history";
}
return "favorites";
case 1:
return "history";
default:
throw new IllegalArgumentException("Invalid position: "
+ position);
}
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
boolean isFavoritesEntry = position == 0;
List<String> recent = isFavoritesEntry ? recentFavorites
: recentHistory;
long numAllEntries = isFavoritesEntry ? numAllFavorites
: numAllHistoryItems;
if (recentFavorites == null) {
isFavoritesEntry = false;
recent = recentHistory;
numAllEntries = numAllHistoryItems;
}
if (convertView == null) {
convertView = new SummaryView(context);
}
((SummaryView) convertView).populate(numAllEntries, recent,
isFavoritesEntry);
return convertView;
}
static class SummaryView extends LinearLayout {
private TextView summary;
private TextView itemList;
SummaryView(Context context) {
super(context);
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.favorites_history_summary_item, this);
summary = (TextView) findViewById(R.id.summary);
itemList = (TextView) findViewById(R.id.item_list);
}
void populate(long numAllEntries, List<String> recentEntries,
boolean isFavoritesItem) {
if (isFavoritesItem) {
String message = getResources().getString(
R.string.favorties_summary);
summary.setText(String.format(message, numAllEntries));
} else {
String message = getResources().getString(
R.string.history_summary);
summary.setText(String.format(message, numAllEntries));
}
String itemsAsStr = TextUtils.join(", ", recentEntries);
if (numAllEntries > recentEntries.size()) {
itemsAsStr = itemsAsStr + "...";
}
itemList.setText(itemsAsStr);
}
}
}
}
|
package org.codehaus.xfire.loom.java;
import javax.xml.namespace.QName;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.codehaus.xfire.java.DefaultJavaService;
import org.codehaus.xfire.java.JavaService;
import org.codehaus.xfire.java.mapping.TypeMapping;
import org.codehaus.xfire.java.mapping.TypeMappingRegistry;
import org.codehaus.xfire.java.type.Type;
import org.codehaus.xfire.java.wsdl.JavaWSDLBuilder;
import org.codehaus.xfire.loom.simple.SimpleServiceFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.transport.TransportManager;
/**
* Creates and configures java-bound services for Loom.
*
* @author <a href="mailto:[email protected]">Dan Diephouse</a>
* @author <a href="mailto:[email protected]">peter royal</a>
*/
public class JavaServiceFactory extends SimpleServiceFactory implements Serviceable
{
private TypeMappingRegistry m_typeMappingRegistry;
private TransportManager m_transportManager;
public void service( final ServiceManager manager ) throws ServiceException
{
m_typeMappingRegistry = (TypeMappingRegistry)manager.lookup( TypeMappingRegistry.ROLE );
m_transportManager = (TransportManager)manager.lookup( TransportManager.ROLE );
}
public String getType()
{
return "java";
}
public Service createService( final Object target, final Configuration configuration )
throws Exception
{
final DefaultJavaService s = new DefaultJavaService( getTypeMappingRegistry() );
configureService( configuration, s, target );
return s;
}
protected void configureService( final Configuration configuration,
final DefaultJavaService service,
final Object target )
throws ConfigurationException
{
super.configureService( configuration, service, target );
try
{
service.setServiceClass( configuration.getChild( JavaService.SERVICE_CLASS ).getValue() );
}
catch( ClassNotFoundException e )
{
final String msg = "Couldn't find service class at "
+ configuration.getChild( JavaService.SERVICE_CLASS ).getLocation();
throw new ConfigurationException( msg, e );
}
// TODO use allowed methods attribute
service.setProperty( JavaService.ALLOWED_METHODS,
configuration.getChild( JavaService.ALLOWED_METHODS ).getValue( "" ) );
service.setAutoTyped( configuration.getChild( "autoTyped" ).getValueAsBoolean( false ) );
service.initializeTypeMapping();
final Configuration[] types = configuration.getChild( "types" ).getChildren( "type" );
for( int i = 0; i < types.length; i++ )
{
initializeType( types[i], service.getTypeMapping() );
}
service.initializeOperations();
service.setWSDLBuilder( new JavaWSDLBuilder( getTransportManager() ) );
}
private void initializeType( final Configuration configuration,
final TypeMapping tm )
throws ConfigurationException
{
try
{
final String ns = configuration.getAttribute( "namespace", tm.getEncodingStyleURI() );
final String name = configuration.getAttribute( "name" );
tm.register( loadClass( configuration.getAttribute( "class" ) ),
new QName( ns, name ),
(Type)loadClass( configuration.getAttribute( "type" ) ).newInstance() );
}
catch( ConfigurationException e )
{
throw e;
}
catch( Exception e )
{
throw new ConfigurationException( "Could not configure type at " + configuration.getLocation(), e );
}
}
public TypeMappingRegistry getTypeMappingRegistry()
{
return m_typeMappingRegistry;
}
protected TransportManager getTransportManager()
{
return m_transportManager;
}
/**
* Load a class from the class loader.
*
* @param className The name of the class.
*
* @return The class.
*/
protected Class loadClass( String className )
throws Exception
{
// Handle array'd types.
if( className.endsWith( "[]" ) )
{
className = "[L" + className.substring( 0, className.length() - 2 ) + ";";
}
return getClass().getClassLoader().loadClass( className );
}
}
|
package org.zanata.adapter.po;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import org.zanata.common.LocaleId;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.TextFlow;
import org.zanata.rest.dto.resource.TextFlowTarget;
import org.zanata.rest.dto.resource.TranslationsResource;
@Test(groups = { "unit-tests" })
public class PoReader2Test
{
private static final Logger log = LoggerFactory.getLogger(PoReader2Test.class);
LocaleId ja = new LocaleId("ja-JP");
String testDir = "src/test/resources/";
PoReader2 poReader = new PoReader2();
private Resource getTemplate()
{
InputSource inputSource = new InputSource(new File(testDir, "pot/RPM.pot").toURI().toString());
inputSource.setEncoding("utf8");
System.out.println("parsing template");
Resource doc = poReader.extractTemplate(inputSource, LocaleId.EN_US, "doc1");
assertThat(doc.getTextFlows().size(), is(137));
return doc;
}
private void extractTarget(boolean useSrcOrder) throws IOException, JAXBException
{
InputSource inputSource;
Resource doc = getTemplate();
String locale = "ja-JP";
inputSource = new InputSource(new File(testDir, locale + "/RPM.po").toURI().toString());
inputSource.setEncoding("utf8");
System.out.println("extracting target: " + locale);
TranslationsResource targetDoc = poReader.extractTarget(inputSource, doc, useSrcOrder);
List<TextFlowTarget> textFlowTargets = targetDoc.getTextFlowTargets();
assertThat(textFlowTargets.size(), is(137));
TextFlowTarget target = textFlowTargets.iterator().next();
assertThat(target, notNullValue());
JAXBContext jaxbContext = JAXBContext.newInstance(Resource.class, TranslationsResource.class);
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
System.out.println("marshalling source doc");
{
StringWriter writer = new StringWriter();
m.marshal(doc, writer);
log.debug("{}", writer);
}
System.out.println("marshalling target doc");
{
StringWriter writer = new StringWriter();
m.marshal(targetDoc, writer);
log.debug("{}", writer);
}
List<TextFlow> resources = doc.getTextFlows();
TextFlow tf1 = resources.get(3);
assertThat(tf1.getContent(), equalTo("Important"));
TextFlowTarget tfTarget = textFlowTargets.get(3);
assertThat(tfTarget.getContent(), equalTo(""));
// TODO test PO headers and attributes
}
@Test
public void extractTemplate()
{
getTemplate();
}
@Test(expectedExceptions = { RuntimeException.class }, expectedExceptionsMessageRegExp = ".*unsupported charset.*")
public void extractInvalidTemplate() throws IOException, JAXBException
{
InputSource inputSource = new InputSource(new File(testDir, "pot/invalid.pot").toURI().toString());
inputSource.setEncoding("utf8");
poReader.extractTemplate(inputSource, LocaleId.EN_US, "doc1");
}
@Test
public void extractTargetWithSourceOrder() throws IOException, JAXBException
{
extractTarget(true);
}
@Test
public void extractTargetWithTargetOrder() throws IOException, JAXBException
{
extractTarget(false);
}
@Test(expectedExceptions = { RuntimeException.class }, expectedExceptionsMessageRegExp = ".*unsupported charset.*")
public void extractInvalidTarget() throws IOException, JAXBException
{
Resource srcDoc = getTemplate();
String locale = "ja-JP";
InputSource inputSource = new InputSource(new File(testDir, locale + "/invalid.po").toURI().toString());
inputSource.setEncoding("utf8");
System.out.println("extracting target: " + locale);
poReader.extractTarget(inputSource, srcDoc, false);
}
}
|
package org.elasticsearch.xpack.ml.inference.loadingservice;
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.breaker.CircuitBreakingException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.ingest.IngestMetadata;
import org.elasticsearch.ingest.PipelineConfiguration;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.ScalingExecutorBuilder;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.ml.inference.TrainedModelConfig;
import org.elasticsearch.xpack.core.ml.inference.TrainedModelInput;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ClassificationConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceStats;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.inference.InferenceDefinition;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.elasticsearch.xpack.ml.inference.TrainedModelStatsService;
import org.elasticsearch.xpack.ml.inference.ingest.InferenceProcessor;
import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider;
import org.elasticsearch.xpack.ml.notifications.InferenceAuditor;
import org.junit.After;
import org.junit.Before;
import org.mockito.ArgumentMatcher;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.xpack.ml.MachineLearning.UTILITY_THREAD_POOL_NAME;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ModelLoadingServiceTests extends ESTestCase {
private TrainedModelProvider trainedModelProvider;
private ThreadPool threadPool;
private ClusterService clusterService;
private InferenceAuditor auditor;
private TrainedModelStatsService trainedModelStatsService;
private CircuitBreaker circuitBreaker;
@Before
public void setUpComponents() {
threadPool = new TestThreadPool("ModelLoadingServiceTests", new ScalingExecutorBuilder(UTILITY_THREAD_POOL_NAME,
1, 4, TimeValue.timeValueMinutes(10), "xpack.ml.utility_thread_pool"));
trainedModelProvider = mock(TrainedModelProvider.class);
clusterService = mock(ClusterService.class);
auditor = mock(InferenceAuditor.class);
trainedModelStatsService = mock(TrainedModelStatsService.class);
doAnswer(a -> null).when(auditor).error(any(String.class), any(String.class));
doAnswer(a -> null).when(auditor).info(any(String.class), any(String.class));
doAnswer(a -> null).when(auditor).warning(any(String.class), any(String.class));
doAnswer((invocationOnMock) -> null).when(clusterService).addListener(any(ClusterStateListener.class));
when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("_name")).build());
circuitBreaker = new CustomCircuitBreaker(1000);
}
@After
public void terminateThreadPool() {
terminate(threadPool);
}
public void testGetCachedModels() throws Exception {
String model1 = "test-load-model-1";
String model2 = "test-load-model-2";
String model3 = "test-load-model-3";
withTrainedModel(model1, 1L);
withTrainedModel(model2, 1L);
withTrainedModel(model3, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
modelLoadingService.clusterChanged(ingestChangedEvent(model1, model2, model3));
String[] modelIds = new String[]{model1, model2, model3};
for(int i = 0; i < 10; i++) {
String model = modelIds[i%3];
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
assertThat(future.get(), is(not(nullValue())));
}
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model2), any());
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model3), any());
assertTrue(modelLoadingService.isModelCached(model1));
assertTrue(modelLoadingService.isModelCached(model2));
assertTrue(modelLoadingService.isModelCached(model3));
// Test invalidate cache for model3
modelLoadingService.clusterChanged(ingestChangedEvent(model1, model2));
for(int i = 0; i < 10; i++) {
String model = modelIds[i%3];
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
assertThat(future.get(), is(not(nullValue())));
}
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model2), any());
// It is not referenced, so called eagerly
verify(trainedModelProvider, times(4)).getTrainedModelForInference(eq(model3), any());
}
public void testMaxCachedLimitReached() throws Exception {
String model1 = "test-cached-limit-load-model-1";
String model2 = "test-cached-limit-load-model-2";
String model3 = "test-cached-limit-load-model-3";
String[] modelIds = new String[]{model1, model2, model3};
withTrainedModel(model1, 10L);
withTrainedModel(model2, 6L);
withTrainedModel(model3, 15L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.builder().put(ModelLoadingService.INFERENCE_MODEL_CACHE_SIZE.getKey(), new ByteSizeValue(20L)).build(),
"test-node",
circuitBreaker);
// We want to be notified when the models are loaded which happens in a background thread
ModelLoadedTracker loadedTracker = new ModelLoadedTracker(Arrays.asList(modelIds));
for (String modelId : modelIds) {
modelLoadingService.addModelLoadedListener(modelId, loadedTracker.actionListener());
}
modelLoadingService.clusterChanged(ingestChangedEvent(model1, model2, model3));
// Should have been loaded from the cluster change event but it is unknown in what order
// the loading occurred or which models are currently in the cache due to evictions.
// Verify that we have at least loaded all three
assertBusy(() -> {
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model2), any());
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model3), any());
});
// all models loaded put in the cache
assertBusy(() -> assertTrue(loadedTracker.allModelsLoaded()), 2, TimeUnit.SECONDS);
for(int i = 0; i < 10; i++) {
// Only reference models 1 and 2, so that cache is only invalidated once for model3 (after initial load)
String model = modelIds[i%2];
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
assertThat(future.get(), is(not(nullValue())));
}
// Depending on the order the models were first loaded in the first step
// models 1 & 2 may have been evicted by model 3 in which case they have
// been loaded at most twice
verify(trainedModelProvider, atMost(2)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelProvider, atMost(2)).getTrainedModelForInference(eq(model2), any());
// Only loaded requested once on the initial load from the change event
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model3), any());
// model 3 has been loaded and evicted exactly once
verify(trainedModelStatsService, times(1)).queueStats(argThat(new ArgumentMatcher<>() {
@Override
public boolean matches(final Object o) {
return ((InferenceStats)o).getModelId().equals(model3);
}
}), anyBoolean());
// Load model 3, should invalidate 1 and 2
for(int i = 0; i < 10; i++) {
PlainActionFuture<LocalModel> future3 = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model3, future3);
assertThat(future3.get(), is(not(nullValue())));
}
verify(trainedModelProvider, times(2)).getTrainedModelForInference(eq(model3), any());
verify(trainedModelStatsService, atMost(2)).queueStats(argThat(new ArgumentMatcher<>() {
@Override
public boolean matches(final Object o) {
return ((InferenceStats)o).getModelId().equals(model1);
}
}), anyBoolean());
verify(trainedModelStatsService, atMost(2)).queueStats(argThat(new ArgumentMatcher<>() {
@Override
public boolean matches(final Object o) {
return ((InferenceStats)o).getModelId().equals(model2);
}
}), anyBoolean());
// Load model 1, should invalidate 3
for(int i = 0; i < 10; i++) {
PlainActionFuture<LocalModel> future1 = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model1, future1);
assertThat(future1.get(), is(not(nullValue())));
}
verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelStatsService, times(2)).queueStats(argThat(new ArgumentMatcher<>() {
@Override
public boolean matches(final Object o) {
return ((InferenceStats)o).getModelId().equals(model3);
}
}), anyBoolean());
// Load model 2
for(int i = 0; i < 10; i++) {
PlainActionFuture<LocalModel> future2 = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model2, future2);
assertThat(future2.get(), is(not(nullValue())));
}
verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model2), any());
// Test invalidate cache for model3
// Now both model 1 and 2 should fit in cache without issues
modelLoadingService.clusterChanged(ingestChangedEvent(model1, model2));
for(int i = 0; i < 10; i++) {
String model = modelIds[i%3];
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
assertThat(future.get(), is(not(nullValue())));
}
verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model2), any());
verify(trainedModelProvider, times(5)).getTrainedModelForInference(eq(model3), any());
}
public void testWhenCacheEnabledButNotIngestNode() throws Exception {
String model1 = "test-uncached-not-ingest-model-1";
withTrainedModel(model1, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
modelLoadingService.clusterChanged(ingestChangedEvent(false, model1));
for(int i = 0; i < 10; i++) {
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model1, future);
assertThat(future.get(), is(not(nullValue())));
}
assertFalse(modelLoadingService.isModelCached(model1));
verify(trainedModelProvider, times(10)).getTrainedModelForInference(eq(model1), any());
verify(trainedModelStatsService, never()).queueStats(any(InferenceStats.class), anyBoolean());
}
public void testGetCachedMissingModel() throws Exception {
String model = "test-load-cached-missing-model";
withMissingModel(model);
ModelLoadingService modelLoadingService =new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
modelLoadingService.clusterChanged(ingestChangedEvent(model));
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
try {
future.get();
fail("Should not have succeeded in loaded model");
} catch (Exception ex) {
assertThat(ex.getCause().getMessage(), equalTo(Messages.getMessage(Messages.INFERENCE_NOT_FOUND, model)));
}
assertFalse(modelLoadingService.isModelCached(model));
verify(trainedModelProvider, atMost(2)).getTrainedModelForInference(eq(model), any());
verify(trainedModelStatsService, never()).queueStats(any(InferenceStats.class), anyBoolean());
}
public void testGetMissingModel() {
String model = "test-load-missing-model";
withMissingModel(model);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
try {
future.get();
fail("Should not have succeeded");
} catch (Exception ex) {
assertThat(ex.getCause().getMessage(), equalTo(Messages.getMessage(Messages.INFERENCE_NOT_FOUND, model)));
}
assertFalse(modelLoadingService.isModelCached(model));
}
public void testGetModelEagerly() throws Exception {
String model = "test-get-model-eagerly";
withTrainedModel(model, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
for(int i = 0; i < 3; i++) {
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(model, future);
assertThat(future.get(), is(not(nullValue())));
}
verify(trainedModelProvider, times(3)).getTrainedModelForInference(eq(model), any());
assertFalse(modelLoadingService.isModelCached(model));
verify(trainedModelStatsService, never()).queueStats(any(InferenceStats.class), anyBoolean());
}
public void testGetModelForSearch() throws Exception {
String modelId = "test-get-model-for-search";
withTrainedModel(modelId, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
for(int i = 0; i < 3; i++) {
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForSearch(modelId, future);
assertThat(future.get(), is(not(nullValue())));
}
assertTrue(modelLoadingService.isModelCached(modelId));
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(modelId), any());
verify(trainedModelStatsService, never()).queueStats(any(InferenceStats.class), anyBoolean());
}
public void testCircuitBreakerBreak() throws Exception {
String model1 = "test-circuit-break-model-1";
String model2 = "test-circuit-break-model-2";
String model3 = "test-circuit-break-model-3";
withTrainedModel(model1, 5L);
withTrainedModel(model2, 5L);
withTrainedModel(model3, 12L);
CircuitBreaker circuitBreaker = new CustomCircuitBreaker(11);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
modelLoadingService.addModelLoadedListener(model3, ActionListener.wrap(
r -> fail("Should not have succeeded to load model as breaker should be reached"),
e -> assertThat(e, instanceOf(CircuitBreakingException.class))
));
modelLoadingService.clusterChanged(ingestChangedEvent(model1, model2, model3));
// Should have been loaded from the cluster change event but it is unknown in what order
// the loading occurred or which models are currently in the cache due to evictions.
// Verify that we have at least loaded all three
assertBusy(() -> {
verify(trainedModelProvider, times(1)).getTrainedModel(eq(model1), eq(false), any());
verify(trainedModelProvider, times(1)).getTrainedModel(eq(model2), eq(false), any());
verify(trainedModelProvider, times(1)).getTrainedModel(eq(model3), eq(false), any());
});
assertBusy(() -> {
assertThat(circuitBreaker.getUsed(), equalTo(10L));
assertThat(circuitBreaker.getTrippedCount(), equalTo(1L));
});
modelLoadingService.clusterChanged(ingestChangedEvent(model1));
assertBusy(() -> {
assertThat(circuitBreaker.getUsed(), equalTo(5L));
});
}
public void testReferenceCounting() throws ExecutionException, InterruptedException, IOException {
String modelId = "test-reference-counting";
withTrainedModel(modelId, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
modelLoadingService.clusterChanged(ingestChangedEvent(modelId));
PlainActionFuture<LocalModel> forPipeline = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, forPipeline);
LocalModel model = forPipeline.get();
assertEquals(2, model.getReferenceCount());
PlainActionFuture<LocalModel> forSearch = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, forSearch);
model = forSearch.get();
assertEquals(3, model.getReferenceCount());
model.release();
assertEquals(2, model.getReferenceCount());
PlainActionFuture<LocalModel> forSearch2 = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, forSearch2);
model = forSearch2.get();
assertEquals(3, model.getReferenceCount());
}
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/59445")
public void testReferenceCountingForPipeline() throws ExecutionException, InterruptedException, IOException {
String modelId = "test-reference-counting-for-pipeline";
withTrainedModel(modelId, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
modelLoadingService.clusterChanged(ingestChangedEvent(modelId));
PlainActionFuture<LocalModel> forPipeline = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, forPipeline);
LocalModel model = forPipeline.get();
assertEquals(2, model.getReferenceCount());
PlainActionFuture<LocalModel> forPipeline2 = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, forPipeline2);
model = forPipeline2.get();
assertEquals(3, model.getReferenceCount());
// will cause the model to be evicted
modelLoadingService.clusterChanged(ingestChangedEvent());
assertEquals(2, model.getReferenceCount());
}
public void testReferenceCounting_ModelIsNotCached() throws ExecutionException, InterruptedException {
String modelId = "test-reference-counting-not-cached";
withTrainedModel(modelId, 1L);
ModelLoadingService modelLoadingService = new ModelLoadingService(trainedModelProvider,
auditor,
threadPool,
clusterService,
trainedModelStatsService,
Settings.EMPTY,
"test-node",
circuitBreaker);
PlainActionFuture<LocalModel> future = new PlainActionFuture<>();
modelLoadingService.getModelForPipeline(modelId, future);
LocalModel model = future.get();
assertEquals(1, model.getReferenceCount());
}
@SuppressWarnings("unchecked")
private void withTrainedModel(String modelId, long size) {
InferenceDefinition definition = mock(InferenceDefinition.class);
when(definition.ramBytesUsed()).thenReturn(size);
TrainedModelConfig trainedModelConfig = mock(TrainedModelConfig.class);
when(trainedModelConfig.getModelId()).thenReturn(modelId);
when(trainedModelConfig.getInferenceConfig()).thenReturn(ClassificationConfig.EMPTY_PARAMS);
when(trainedModelConfig.getInput()).thenReturn(new TrainedModelInput(Arrays.asList("foo", "bar", "baz")));
when(trainedModelConfig.getEstimatedHeapMemory()).thenReturn(size);
doAnswer(invocationOnMock -> {
@SuppressWarnings("rawtypes")
ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1];
listener.onResponse(definition);
return null;
}).when(trainedModelProvider).getTrainedModelForInference(eq(modelId), any());
doAnswer(invocationOnMock -> {
@SuppressWarnings("rawtypes")
ActionListener listener = (ActionListener) invocationOnMock.getArguments()[2];
listener.onResponse(trainedModelConfig);
return null;
}).when(trainedModelProvider).getTrainedModel(eq(modelId), eq(false), any());
}
@SuppressWarnings("unchecked")
private void withMissingModel(String modelId) {
if (randomBoolean()) {
doAnswer(invocationOnMock -> {
@SuppressWarnings("rawtypes")
ActionListener listener = (ActionListener) invocationOnMock.getArguments()[2];
listener.onFailure(new ResourceNotFoundException(
Messages.getMessage(Messages.INFERENCE_NOT_FOUND, modelId)));
return null;
}).when(trainedModelProvider).getTrainedModel(eq(modelId), eq(false), any());
} else {
TrainedModelConfig trainedModelConfig = mock(TrainedModelConfig.class);
when(trainedModelConfig.getEstimatedHeapMemory()).thenReturn(0L);
doAnswer(invocationOnMock -> {
@SuppressWarnings("rawtypes")
ActionListener listener = (ActionListener) invocationOnMock.getArguments()[2];
listener.onResponse(trainedModelConfig);
return null;
}).when(trainedModelProvider).getTrainedModel(eq(modelId), eq(false), any());
doAnswer(invocationOnMock -> {
@SuppressWarnings("rawtypes")
ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1];
listener.onFailure(new ResourceNotFoundException(
Messages.getMessage(Messages.MODEL_DEFINITION_NOT_FOUND, modelId)));
return null;
}).when(trainedModelProvider).getTrainedModelForInference(eq(modelId), any());
}
doAnswer(invocationOnMock -> {
@SuppressWarnings("rawtypes")
ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1];
listener.onFailure(new ResourceNotFoundException(
Messages.getMessage(Messages.INFERENCE_NOT_FOUND, modelId)));
return null;
}).when(trainedModelProvider).getTrainedModelForInference(eq(modelId), any());
}
private static ClusterChangedEvent ingestChangedEvent(String... modelId) throws IOException {
return ingestChangedEvent(true, modelId);
}
private static ClusterChangedEvent ingestChangedEvent(boolean isIngestNode, String... modelId) throws IOException {
ClusterChangedEvent event = mock(ClusterChangedEvent.class);
when(event.changedCustomMetadataSet()).thenReturn(Collections.singleton(IngestMetadata.TYPE));
when(event.state()).thenReturn(buildClusterStateWithModelReferences(isIngestNode, modelId));
return event;
}
private static ClusterState buildClusterStateWithModelReferences(boolean isIngestNode, String... modelId) throws IOException {
Map<String, PipelineConfiguration> configurations = new HashMap<>(modelId.length);
for (String id : modelId) {
configurations.put("pipeline_with_model_" + id, newConfigurationWithInferenceProcessor(id));
}
IngestMetadata ingestMetadata = new IngestMetadata(configurations);
return ClusterState.builder(new ClusterName("_name"))
.metadata(Metadata.builder().putCustom(IngestMetadata.TYPE, ingestMetadata))
.nodes(DiscoveryNodes.builder().add(
new DiscoveryNode("node_name",
"node_id",
new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
Collections.emptyMap(),
isIngestNode ? Collections.singleton(DiscoveryNodeRole.INGEST_ROLE) : Collections.emptySet(),
Version.CURRENT))
.localNodeId("node_id")
.build())
.build();
}
private static PipelineConfiguration newConfigurationWithInferenceProcessor(String modelId) throws IOException {
try(XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().map(Collections.singletonMap("processors",
Collections.singletonList(
Collections.singletonMap(InferenceProcessor.TYPE,
Collections.singletonMap(InferenceProcessor.MODEL_ID,
modelId)))))) {
return new PipelineConfiguration("pipeline_with_model_" + modelId, BytesReference.bytes(xContentBuilder), XContentType.JSON);
}
}
private static class CustomCircuitBreaker implements CircuitBreaker {
private final long maxBytes;
private long currentBytes = 0;
private long trippedCount = 0;
CustomCircuitBreaker(long maxBytes) {
this.maxBytes = maxBytes;
}
@Override
public void circuitBreak(String fieldName, long bytesNeeded) {
throw new CircuitBreakingException(fieldName, Durability.TRANSIENT);
}
@Override
public double addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException {
synchronized (this) {
if (bytes + currentBytes >= maxBytes) {
trippedCount++;
circuitBreak(label, bytes);
}
currentBytes += bytes;
return currentBytes;
}
}
@Override
public long addWithoutBreaking(long bytes) {
synchronized (this) {
currentBytes += bytes;
return currentBytes;
}
}
@Override
public long getUsed() {
return currentBytes;
}
@Override
public long getLimit() {
return maxBytes;
}
@Override
public double getOverhead() {
return 1.0;
}
@Override
public long getTrippedCount() {
synchronized (this) {
return trippedCount;
}
}
@Override
public String getName() {
return MachineLearning.TRAINED_MODEL_CIRCUIT_BREAKER_NAME;
}
@Override
public Durability getDurability() {
return Durability.TRANSIENT;
}
@Override
public void setLimitAndOverhead(long limit, double overhead) {
throw new UnsupportedOperationException("boom");
}
}
private static class ModelLoadedTracker {
private final Set<String> expectedModelIds;
ModelLoadedTracker(Collection<String> expectedModelIds) {
this.expectedModelIds = new HashSet<>(expectedModelIds);
}
private synchronized boolean allModelsLoaded() {
return expectedModelIds.isEmpty();
}
private synchronized void onModelLoaded(LocalModel model) {
expectedModelIds.remove(model.getModelId());
}
private void onFailure(Exception e) {
fail(e.getMessage());
}
ActionListener<LocalModel> actionListener() {
return ActionListener.wrap(this::onModelLoaded, this::onFailure);
}
}
}
|
package solutions.alterego.androidbound;
import com.alterego.advancedandroidlogger.implementations.NullAndroidLogger;
import com.alterego.advancedandroidlogger.interfaces.IAndroidLogger;
import android.app.Activity;
import android.os.Bundle;
import java.lang.ref.WeakReference;
import lombok.experimental.Accessors;
import rx.Observable;
import rx.subjects.PublishSubject;
import solutions.alterego.androidbound.binding.interfaces.INotifyPropertyChanged;
import solutions.alterego.androidbound.interfaces.IDisposable;
import solutions.alterego.androidbound.interfaces.INeedsLogger;
@Accessors(prefix = "m")
public abstract class ViewModel implements INeedsLogger, INotifyPropertyChanged, IDisposable {
protected transient IAndroidLogger mLogger = NullAndroidLogger.instance;
private transient PublishSubject<String> propertyChanges = PublishSubject.create();
protected transient WeakReference<Activity> mParentActivity;
protected void raisePropertyChanged(String property) {
try {
propertyChanges.onNext(property);
} catch (Exception e) {
mLogger.error("exception when raising property changes = " + e.getMessage());
}
}
@Override
public Observable<String> onPropertyChanged() {
return propertyChanges;
}
@Override
public void dispose() {
if (propertyChanges != null) {
propertyChanges.onCompleted();
propertyChanges = null;
}
if (mParentActivity != null && mParentActivity.get() != null) {
mParentActivity.clear();
}
}
@Override
public void setLogger(IAndroidLogger logger) {
mLogger = logger.getLogger(this);
}
public void setParentActivity(Activity activity) {
mParentActivity = new WeakReference<Activity>(activity);
}
public Activity getParentActivity() {
if (mParentActivity != null && mParentActivity.get() != null) {
return mParentActivity.get();
}
return null;
}
public abstract void onCreate(Bundle outState);
public abstract void onResume();
public abstract void onPause();
public abstract void onSaveInstanceState(Bundle outState);
}
|
package org.elasticsearch.xpack.security.authz;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.index.shard.SearchOperationListener;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.search.SearchContextMissingException;
import org.elasticsearch.search.internal.ReaderContext;
import org.elasticsearch.search.internal.ScrollContext;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.internal.ShardSearchContextId;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.xpack.core.security.SecurityContext;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authc.AuthenticationField;
import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.AuthorizationInfo;
import org.elasticsearch.xpack.core.security.authz.AuthorizationServiceField;
import org.elasticsearch.xpack.core.security.authz.accesscontrol.IndicesAccessControl;
import org.elasticsearch.xpack.security.audit.AuditTrailService;
import org.elasticsearch.xpack.security.audit.AuditUtil;
import static org.elasticsearch.xpack.security.authz.AuthorizationService.AUTHORIZATION_INFO_KEY;
import static org.elasticsearch.xpack.security.authz.AuthorizationService.ORIGINATING_ACTION_KEY;
/**
* A {@link SearchOperationListener} that is used to provide authorization for scroll requests.
* <p>
* In order to identify the user associated with a scroll request, we replace the {@link ReaderContext}
* on creation with a custom implementation that holds the {@link Authentication} object. When
* this context is accessed again in {@link SearchOperationListener#onPreQueryPhase(SearchContext)}
* the ScrollContext is inspected for the authentication, which is compared to the currently
* authentication.
*/
public final class SecuritySearchOperationListener implements SearchOperationListener {
private final SecurityContext securityContext;
private final XPackLicenseState licenseState;
private final AuditTrailService auditTrailService;
public SecuritySearchOperationListener(SecurityContext securityContext, XPackLicenseState licenseState, AuditTrailService auditTrail) {
this.securityContext = securityContext;
this.licenseState = licenseState;
this.auditTrailService = auditTrail;
}
/**
* Adds the {@link Authentication} to the {@link ScrollContext}
*/
@Override
public void onNewScrollContext(ReaderContext readerContext) {
if (licenseState.isSecurityEnabled()) {
readerContext.putInContext(AuthenticationField.AUTHENTICATION_KEY, securityContext.getAuthentication());
IndicesAccessControl indicesAccessControl =
securityContext.getThreadContext().getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
assert indicesAccessControl != null : "thread context does not contain index access control";
readerContext.putInContext(AuthorizationServiceField.INDICES_PERMISSIONS_KEY, indicesAccessControl);
}
}
/**
* Checks for the {@link ReaderContext} if it exists and compares the {@link Authentication}
* object from the scroll context with the current authentication context
*/
@Override
public void validateSearchContext(ReaderContext readerContext, TransportRequest request) {
if (licenseState.isSecurityEnabled()) {
if (readerContext.scrollContext() != null) {
final Authentication originalAuth = readerContext.getFromContext(AuthenticationField.AUTHENTICATION_KEY);
final Authentication current = securityContext.getAuthentication();
final ThreadContext threadContext = securityContext.getThreadContext();
final String action = threadContext.getTransient(ORIGINATING_ACTION_KEY);
ensureAuthenticatedUserIsSame(originalAuth, current, auditTrailService, readerContext.id(), action, request,
AuditUtil.extractRequestId(threadContext), threadContext.getTransient(AUTHORIZATION_INFO_KEY));
if (null == securityContext.getThreadContext().getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY)) {
IndicesAccessControl scrollIndicesAccessControl =
readerContext.getFromContext(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
assert scrollIndicesAccessControl != null : "scroll does not contain index access control";
securityContext.getThreadContext().putTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY,
scrollIndicesAccessControl);
}
}
}
}
@Override
public void onPreFetchPhase(SearchContext searchContext) {
ensureIndicesAccessControlForScrollThreadContext(searchContext);
}
@Override
public void onPreQueryPhase(SearchContext searchContext) {
ensureIndicesAccessControlForScrollThreadContext(searchContext);
}
void ensureIndicesAccessControlForScrollThreadContext(SearchContext searchContext) {
if (licenseState.isSecurityEnabled() && searchContext.readerContext().scrollContext() != null) {
IndicesAccessControl threadIndicesAccessControl =
securityContext.getThreadContext().getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
if (null == threadIndicesAccessControl) {
throw new ElasticsearchSecurityException("Unexpected null indices access control for search context [" +
searchContext.id() + "] for request [" + searchContext.request().getDescription() + "] with source [" +
searchContext.source() + "]");
}
}
}
/**
* Compares the {@link Authentication} that was stored in the {@link ReaderContext} with the
* current authentication. We cannot guarantee that all of the details of the authentication will
* be the same. Some things that could differ include the roles, the name of the authenticating
* (or lookup) realm. To work around this we compare the username and the originating realm type.
*/
static void ensureAuthenticatedUserIsSame(Authentication original, Authentication current, AuditTrailService auditTrailService,
ShardSearchContextId id, String action, TransportRequest request, String requestId,
AuthorizationInfo authorizationInfo) {
// this is really a best effort attempt since we cannot guarantee principal uniqueness
// and realm names can change between nodes.
final boolean samePrincipal = original.getUser().principal().equals(current.getUser().principal());
final boolean sameRealmType;
if (original.getUser().isRunAs()) {
if (current.getUser().isRunAs()) {
sameRealmType = original.getLookedUpBy().getType().equals(current.getLookedUpBy().getType());
} else {
sameRealmType = original.getLookedUpBy().getType().equals(current.getAuthenticatedBy().getType());
}
} else if (current.getUser().isRunAs()) {
sameRealmType = original.getAuthenticatedBy().getType().equals(current.getLookedUpBy().getType());
} else {
sameRealmType = original.getAuthenticatedBy().getType().equals(current.getAuthenticatedBy().getType());
}
final boolean sameUser = samePrincipal && sameRealmType;
if (sameUser == false) {
auditTrailService.get().accessDenied(requestId, current, action, request, authorizationInfo);
throw new SearchContextMissingException(id);
}
}
}
|
package ch.ethz.scu.obit.at.gui.viewers.openbis;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import ch.ethz.scu.obit.at.gui.pane.OutputPane;
import ch.ethz.scu.obit.at.gui.viewers.ObserverActionParameters;
import ch.ethz.scu.obit.at.gui.viewers.openbis.model.AbstractOpenBISNode;
import ch.ethz.scu.obit.at.gui.viewers.openbis.model.OpenBISExperimentNode;
import ch.ethz.scu.obit.at.gui.viewers.openbis.model.OpenBISProjectNode;
import ch.ethz.scu.obit.at.gui.viewers.openbis.model.OpenBISSampleListNode;
import ch.ethz.scu.obit.at.gui.viewers.openbis.model.OpenBISSpaceNode;
import ch.ethz.scu.obit.at.gui.viewers.openbis.model.OpenBISUserNode;
import ch.ethz.scu.obit.at.gui.viewers.openbis.view.OpenBISViewerTree;
import ch.ethz.scu.obit.common.settings.UserSettingsManager;
import ch.ethz.scu.obit.common.utils.QueryOS;
import ch.ethz.scu.obit.processors.openbis.OpenBISProcessor;
import ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.Experiment;
import ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.Project;
import ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.Sample;
import ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.SpaceWithProjectsAndRoleAssignments;
import ch.systemsx.cisd.openbis.plugin.query.shared.api.v1.dto.QueryTableModel;
/**
* Graphical user interface to log in to openBIS and choose where to store
* acquired datasets.
* @author Aaron Ponti
*/
public class OpenBISViewer extends Observable
implements ActionListener, TreeSelectionListener, TreeWillExpandListener {
protected JPanel panel;
protected JButton scanButton;
private OpenBISProcessor openBISProcessor;
private OpenBISUserNode userNode;
private OpenBISViewerTree tree;
private String defaultRootNodeString = "/";
// Keep track of the last visited TreePath to prevent multiple firing
// of treeWillExpand().
private TreePath lastVisitedPath = null;
private boolean isReady = false;
protected OutputPane outputPane;
String loginErrorMessage = "";
String loginErrorTitle = "";
boolean loginErrorRecoverable = true;
/**
* Constructor
*/
public OpenBISViewer(OpenBISProcessor openBISProcessor, OutputPane outputPane) {
// Store the OpenBISProcessor reference
this.openBISProcessor = openBISProcessor;
// Store the OutputPane reference
this.outputPane = outputPane;
// Create a panel
panel = new JPanel();
// Get the openBIS URL from the appProperties
UserSettingsManager manager = new UserSettingsManager();
if (! manager.load()) {
JOptionPane.showMessageDialog(null,
"Could not read application settings!\n" +
"Please contact your administrator. The application\n" +
"will now exit!",
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
// Set a grid bag layout
panel.setLayout(new GridBagLayout());
// Common constraints
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.NORTHWEST;
constraints.fill = GridBagConstraints.BOTH;
// Add a title JLabel
JLabel title = new JLabel("<html><b>openBIS viewer</b></html>");
// Add the tree viewer to the layout
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.weighty = 0.0;
constraints.insets = new Insets(0, 5, 5, 0);
panel.add(title, constraints);
// Create the root node for the tree
userNode = new OpenBISUserNode(defaultRootNodeString);
// Create a tree that allows one selection at a time.
tree = new OpenBISViewerTree(userNode);
// Listen for when the selection changes.
tree.addTreeSelectionListener(this);
// Listen for when a node is about to be opened (for lazy loading)
tree.addTreeWillExpandListener(this);
// Add a context menu
tree.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (QueryOS.isWindows()) {
return;
}
setListenerOnJTree(e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (QueryOS.isMac()) {
return;
}
setListenerOnJTree(e);
}
});
// Create the scroll pane and add the tree to it.
JScrollPane treeView = new JScrollPane(tree);
// Add the tree viewer to the layout
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(5, 5, 5, 0);
panel.add(treeView, constraints);
// Add a rescan button
scanButton = new JButton("Scan");
scanButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scan();
}
});
// Add to the layout
constraints.gridx = 0;
constraints.gridy = 2;
constraints.weightx = 1.0;
constraints.weighty = 0.0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.insets = new Insets(0, 5, 5, 0);
panel.add(scanButton, constraints);
// Set sizes
panel.setMinimumSize(new Dimension(400, 700));
panel.setPreferredSize(new Dimension(400, 700));
}
/**
* Return the OpenBISProcessor.
* @return the OpenBISProcessor.
*/
public OpenBISProcessor getOpenBISProcessor() {
return openBISProcessor;
}
/**
* Returns the user name if successfully logged in, empty string otherwise
* @return user name or empty String if log on was not successful
*/
public String getUserName() {
if (!openBISProcessor.isLoggedIn()) {
return "";
}
return openBISProcessor.getUserName();
}
/**
* Called when selection in the Tree View is changed.
* @param e A TreeSelectionEvent
*/
@Override
public void valueChanged(TreeSelectionEvent e) {
// Get the selected tree node
AbstractOpenBISNode node = (AbstractOpenBISNode)
tree.getLastSelectedPathComponent();
if (node == null) {
return;
}
// TODO Implement!
}
/**
* Return the Tree's data model.
*/
public TreeModel getDataModel() {
return tree.getModel();
}
/**
* Clear the tree view
*/
private void clearTree() {
// Is there already something in the tree?
if (tree == null) {
return;
}
// Clear the tree model
TreeModel model = tree.getModel();
if (model != null) {
DefaultMutableTreeNode rootNode =
(DefaultMutableTreeNode) model.getRoot();
if (rootNode != null) {
rootNode.removeAllChildren();
((DefaultTreeModel) model).reload();
rootNode = null;
}
}
// Create the root node
userNode = new OpenBISUserNode(defaultRootNodeString);
tree.setModel(new DefaultTreeModel(userNode));
// Listen for when the selection changes.
tree.addTreeSelectionListener(this);
// Listen for when a node is about to be opened (for lazy loading)
tree.addTreeWillExpandListener(this);
}
/**
* Fill the tree view with the data obtained from openBIS
*/
public void scan() {
OpenBISSpaceNode space;
OpenBISProjectNode project;
// Inform
outputPane.log("Retrieving openBIS structure...");
// Clear the tree
clearTree();
// Notify observers that the scanning is about to start
synchronized (this) {
setChanged();
notifyObservers(new ObserverActionParameters(
ObserverActionParameters.Action.ABOUT_TO_RESCAN, null));
}
// Do we have a connection with openBIS?
// We just need an active facade for scanning; the queryFacade
// should actually be on as well, but we do not need it here.
if (! openBISProcessor.isLoggedIn()) {
return;
}
// Check that the session is still open (we just check the
// facade, the queryFacade is not necessary
if (!openBISProcessor.checkSession()) {
JOptionPane.showMessageDialog(this.panel,
"The openBIS session is no longer valid!\n" +
"Please try logging in again.",
"Session error",
JOptionPane.ERROR_MESSAGE);
clearTree();
return;
}
// Disable the "scan" button
scanButton.setEnabled(false);
// Set the root of the tree
userNode = new OpenBISUserNode(openBISProcessor.getUserName());
// Get spaces
List<SpaceWithProjectsAndRoleAssignments> spaces =
openBISProcessor.getSpaces();
if (spaces.isEmpty()) {
JOptionPane.showMessageDialog(this.panel,
"Sorry, there are no (accessible) spaces.\n\n" +
"Please ask your administrator to create a " +
"space for you or to grant you access to an " +
"existing one.\nNo data registration will be " +
"possible until this issue is fixed.",
"Warning",
JOptionPane.WARNING_MESSAGE);
// We do not need to return, this case is treated below
}
// Keep a count of the usable projects
int nProjects = 0;
for (SpaceWithProjectsAndRoleAssignments s : spaces) {
// Add the space
space = new OpenBISSpaceNode(s);
userNode.add(space);
// Get the projects for current space
List<Project> projects = s.getProjects();
// We add the projects -- experiments and samples will be
// lazily loaded on node expansion
for (Project p : projects) {
// Add the project
project = new OpenBISProjectNode(p);
space.add(project);
nProjects++;
}
}
// Update the view
tree.setModel(new DefaultTreeModel(userNode));
// Listen for when the selection changes
tree.addTreeSelectionListener(this);
// Listen for when a node is about to be opened (for lazy loading)
tree.addTreeWillExpandListener(this);
if (nProjects > 0) {
// Set isReady to true
isReady = true;
// Notify observers that the scanning is done
synchronized (this) {
setChanged();
notifyObservers(new ObserverActionParameters(
ObserverActionParameters.Action.SCAN_COMPLETE, null));
}
} else {
JOptionPane.showMessageDialog(this.panel,
"Sorry, there are no (accessible) projects.\n\n" +
"You will need to create one yourself or " +
"ask your space administrator to do it " +
"for you.\nNo data registration will be " +
"possible until this issue is fixed.",
"Warning",
JOptionPane.WARNING_MESSAGE);
// We do not need to return, this case is treated below
}
// Re-enable the "scan" button
scanButton.setEnabled(true);
// Inform
outputPane.log("Retrieving openBIS structure completed.");
}
/**
* Returns true if the viewer has completed creation of the data model
* @return true if the data model is complete, false otherwise
*/
public boolean isReady() { return isReady; }
@Override
public void actionPerformed(ActionEvent e) {
// TODO Currently we do not do anything.
}
/**
* Return the reference to the JPanel to be added to a container component
* @return JPanel reference
*/
public JPanel getPanel() {
return panel;
}
/**
* Called when a node in the Tree is about to expand.
* @param event A TreeExpansionEvent.
* Required by TreeWillExpandListener interface.
*/
@Override
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
TreePath path = event.getPath();
if (path == lastVisitedPath) {
return;
} else {
lastVisitedPath = path;
}
loadLazyChildren(
(AbstractOpenBISNode) path.getLastPathComponent());
}
/**
* Called when a node in the Tree is about to collapse.
* @param event A TreeExpansionEvent.
* Required by TreeWillExpandListener interface.
*/
@Override
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException {
// We do nothing
}
/**
* Load the childen of the specified node if needed.
* @param node Node to query for children.
*/
private synchronized void loadLazyChildren(AbstractOpenBISNode node) {
// If the node children were loaded already, we just return
if (node.isLoaded()) {
return;
}
// Get the user object stored in the node
Object obj = node.getUserObject();
// Which openBIS object did we get?
String className = obj.getClass().getSimpleName();
// Proceed with the loading
if (className.equals("Project")) {
// If we have a Project, we load the contained Experiments
Project p = (Project) obj;
List<String> expId = new ArrayList<String>();
expId.add(p.getIdentifier());
// Then define and start the worker
class Worker extends SwingWorker<List<Experiment>, Void> {
final private OpenBISProcessor o;
final private List<String> eId;
final private AbstractOpenBISNode n;
final private Project p;
/**
* Constructor.
* @param o OpenBISProcessor reference.
* @param eId List of Experiment identifiers.
* @param n Node to which to add the Experiment nodes.
* @param p Project reference.
*/
public Worker(OpenBISProcessor o, List<String> eId,
AbstractOpenBISNode n, Project p) {
this.o = o;
this.eId = eId;
this.n = n;
this.p = p;
}
@Override
public List<Experiment> doInBackground() {
return (o.getExperimentsForProjects(eId));
}
@Override
public void done() {
// Initialize Sample list
List<Experiment> experiments = new ArrayList<Experiment>();
// Retrieve the result
try {
experiments = get();
} catch (InterruptedException | ExecutionException e) {
experiments = new ArrayList<Experiment>();
}
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
for (Experiment e : experiments) {
// Add the experiments
OpenBISExperimentNode experiment = new OpenBISExperimentNode(e);
model.insertNodeInto(experiment, n, n.getChildCount());
}
// Inform
outputPane.log("Retrieved list of experiments for project " +
p.getIdentifier() + ".");
// Mark the node as loaded
n.setLoaded();
}
};
// Run the worker!
(new Worker(openBISProcessor, expId, node, p)).execute();
} else if (className.equals("Experiment")) {
// If we have an Experiment, we load the contained Samples
Experiment e = (Experiment) obj;
List<String> experimentId = new ArrayList<String>();
experimentId.add(e.getIdentifier());
// To be restored -- and extended -- in the future.
//EnumSet<SampleFetchOption> opts = EnumSet.of(SampleFetchOption.PROPERTIES);
//List<Sample> samples =
// facade.listSamplesForExperiments(experimentID, opts);
//for (Sample sm : samples) {
// // Add the samples
// OpenBISSampleNode sample = new OpenBISSampleNode(sm);
// node.add(sample);
// Temporarily, we just display the number of contained
// samples in the Experiment. Later we could re-enable this
// if we decided to provided specialized versions of the
// openBIS Viewer/Processor.
// Then define and start the worker
class Worker extends SwingWorker<List<Sample>, Void> {
final private OpenBISProcessor o;
final private List<String> eId;
final private AbstractOpenBISNode n;
final private Experiment e;
/**
* Constructor.
* @param o OpenBISProcessor reference.
* @param eId List of Experiment identifiers.
* @param n Node to which to add the Sample nodes.
* @param e Experiment reference.
*/
public Worker(OpenBISProcessor o, List<String> eId,
AbstractOpenBISNode n, Experiment e) {
this.o = o;
this.eId = eId;
this.n = n;
this.e = e;
}
@Override
public List<Sample> doInBackground() {
return (o.getSamplesForExperiments(eId));
}
@Override
public void done() {
// Initialize Sample list
List<Sample> samples = new ArrayList<Sample>();
// Retrieve the result
try {
samples = get();
} catch (InterruptedException | ExecutionException e) {
samples = new ArrayList<Sample>();
}
int nSamples = samples.size();
String title = "";
if (nSamples == 0) {
title = "No samples";
} else if (nSamples == 1) {
title = "One sample";
} else {
title = nSamples + " samples";
}
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
model.insertNodeInto(new OpenBISSampleListNode(title),
n, n.getChildCount());
// Inform
outputPane.log("Retrieved number of samples for experiment " +
e.getIdentifier() + ".");
// Mark the node as loaded
n.setLoaded();
}
};
// Run the worker!
(new Worker(openBISProcessor, experimentId, node, e)).execute();
} else {
// Mark the node as loaded (in any case)
node.setLoaded();
}
}
/**
* Sets a mouse event listener on the JTree
* @param e Mouse event
*/
private void setListenerOnJTree(MouseEvent e) {
if (e.isPopupTrigger() &&
e.getComponent() instanceof OpenBISViewerTree) {
// Position of mouse click
int x = e.getPoint().x;
int y = e.getPoint().y;
// Get selected node
TreePath p = tree.getPathForLocation(x, y);
if (p == null) {
// There is nothing usable at that location
return;
}
AbstractOpenBISNode node =
(AbstractOpenBISNode) p.getLastPathComponent();
// Type of node
String nodeType = node.getClass().getSimpleName();
// Add relevant context menu
if (nodeType.equals("OpenBISSpaceNode")) {
JPopupMenu popup =
createSpacePopup((OpenBISSpaceNode) node);
popup.show(e.getComponent(), x, y);
}
}
}
/**
* Create a popup menu with actions for a space node
* @return a JPopupMenu for the passed item
*/
private JPopupMenu createSpacePopup(final OpenBISSpaceNode node) {
// Create the popup menu.
JPopupMenu popup = new JPopupMenu();
// Create new project
String menuEntry = "Create new project";
JMenuItem menuItem = new JMenuItem(menuEntry);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (createNewProject(node)) {
// Rescan
scan();
}
}
});
popup.add(menuItem);
return popup;
}
/**
* Asks the user to give a project name and will then try to create
* it as a child of the passed OpenBISSpaceNode
* @param node An OpenBISSpaceNode
* @return true if creation was successfull, false otherwise.
*/
private boolean createNewProject(final OpenBISSpaceNode node) {
// Retrieve and store the createProject service
if (!openBISProcessor.retrieveAndStoreServices()) {
// TODO Throw an exception to distinguish the case where
// the project could not be created.
return false;
}
// Get the space object from the openBIS node
SpaceWithProjectsAndRoleAssignments space =
(SpaceWithProjectsAndRoleAssignments)
node.getUserObject();
// Ask the user to specify a project name
String projectCode = JOptionPane.showInputDialog(
"Please enter new project name (code)");
if (projectCode == null || projectCode.equals("")) {
outputPane.warn("Creation of new project aborted by user.");
return false;
}
// Call the ingestion server and collect the output
QueryTableModel tableModel;
try {
tableModel = openBISProcessor.createProject(
space.getCode(), projectCode);
} catch (Exception e) {
outputPane.err("Could not create project /" + space.getCode() +
"/" + projectCode + "! Please contact your "
+ "openBIS administrator!");
return false;
}
// Display the output
String success= "";
String message = "";
List<Serializable[]> rows = tableModel.getRows();
for (Serializable[] row : rows) {
success = (String)row[0];
message = (String)row[1];
if (success.equals("true")) {
outputPane.log(message);
return true;
}
}
outputPane.err(message);
return false;
}
}
|
package com.salesforce.dva.argus.entity;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import java.text.MessageFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.salesforce.dva.argus.service.AlertService;
import static com.salesforce.dva.argus.system.SystemAssert.requireArgument;
/**
* Encapsulates information about an alert notification. When a condition is triggered, it sends one or more notifications. The interval over which
* the trigger conditions are evaluated is the entire interval specified by the alert expression.
*
* @author Tom Valine ([email protected]), Raj Sarkapally([email protected])
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "NOTIFICATION", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" }))
public class Notification extends JPAEntity implements Serializable {
public static class Serializer extends JsonSerializer<Notification> {
@Override
public void serialize(Notification notification, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("id", notification.getId().toString());
if(notification.getCreatedDate()!=null) {
jgen.writeNumberField("createdDate", notification.getCreatedDate().getTime());
}
if(notification.getModifiedDate()!=null) {
jgen.writeNumberField("modifiedDate", notification.getModifiedDate().getTime());
}
jgen.writeStringField("name", notification.getName());
jgen.writeStringField("notifier", notification.getNotifierName());
jgen.writeNumberField("cooldownPeriod", notification.getCooldownPeriod());
jgen.writeBooleanField("srActionable", notification.getSRActionable());
jgen.writeNumberField("severityLevel", notification.getSeverityLevel());
if(notification.getCustomText() != null) {
jgen.writeStringField("customText", notification.getCustomText());
}
jgen.writeArrayFieldStart("subscriptions");
for(String subscription : notification.getSubscriptions()) {
jgen.writeString(subscription);
}
jgen.writeEndArray();
jgen.writeArrayFieldStart("metricsToAnnotate");
for(String metricToAnnotate : notification.getMetricsToAnnotate()) {
jgen.writeString(metricToAnnotate);
}
jgen.writeEndArray();
jgen.writeArrayFieldStart("triggers");
for(Trigger trigger : notification.getTriggers()) {
jgen.writeString(trigger.getId().toString());
}
jgen.writeEndArray();
// Getting these values requires a lot of queries to rdbms at runtime, and so these are excluded for now
// as the current usecases do not need these values to be serialized
//jgen.writeObjectField("cooldownExpirationByTriggerAndMetric", notification.getCooldownExpirationMap());
//jgen.writeObjectField("activeStatusByTriggerAndMetric", notification.getActiveStatusMap());
jgen.writeEndObject();
}
}
public static class Deserializer extends JsonDeserializer<Notification> {
@Override
public Notification deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Notification notification = new Notification();
JsonNode rootNode = jp.getCodec().readTree(jp);
BigInteger id = new BigInteger(rootNode.get("id").asText());
notification.id = id;
if(rootNode.get("createdDate")!=null) {
notification.createdDate = Date.from(Instant.ofEpochMilli(rootNode.get("createdDate").asLong()));
}
if(rootNode.get("modifiedDate")!=null) {
notification.setModifiedDate(Date.from(Instant.ofEpochMilli(rootNode.get("modifiedDate").asLong())));
}
String name = rootNode.get("name").asText();
notification.setName(name);
String notifierName = rootNode.get("notifier").asText();
notification.setNotifierName(notifierName);
long cooldownPeriod = rootNode.get("cooldownPeriod").asLong();
notification.setCooldownPeriod(cooldownPeriod);
boolean srActionable = rootNode.get("srActionable").asBoolean();
notification.setSRActionable(srActionable);
int severity = rootNode.get("severityLevel").asInt();
notification.setSeverityLevel(severity);
if(rootNode.get("customText") != null) {
notification.setCustomText(rootNode.get("customText").asText());
}
List<String> subscriptions = new ArrayList<>();
JsonNode subscriptionsArrayNode = rootNode.get("subscriptions");
if(subscriptionsArrayNode.isArray()) {
for(JsonNode subscriptionNode : subscriptionsArrayNode) {
subscriptions.add(subscriptionNode.asText());
}
}
notification.setSubscriptions(subscriptions);
List<String> metricsToAnnotate = new ArrayList<>();
JsonNode metricsToAnnotateArrayNode = rootNode.get("metricsToAnnotate");
if(metricsToAnnotateArrayNode.isArray()) {
for(JsonNode metricToAnnotateNode : metricsToAnnotateArrayNode) {
metricsToAnnotate.add(metricToAnnotateNode.asText());
}
}
notification.setMetricsToAnnotate(metricsToAnnotate);
List<Trigger> triggers = new ArrayList<>();
JsonNode triggersArrayNode = rootNode.get("triggers");
if(triggersArrayNode.isArray()) {
for(JsonNode triggerNode : triggersArrayNode) {
BigInteger triggerId = new BigInteger(triggerNode.asText());
Trigger trigger = new Trigger();
trigger.id = triggerId;
triggers.add(trigger);
}
}
notification.setTriggers(triggers);
// Commenting this part out as these fields are not currently serialized
/*Map<String, Boolean> activeStatusByTriggerAndMetric = new HashMap<>();
JsonNode activeStatusByTriggerAndMetricNode = rootNode.get("activeStatusByTriggerAndMetric");
if(activeStatusByTriggerAndMetricNode.isObject()) {
Iterator<Entry<String, JsonNode>> fieldsIter = activeStatusByTriggerAndMetricNode.fields();
while(fieldsIter.hasNext()) {
Entry<String, JsonNode> field = fieldsIter.next();
activeStatusByTriggerAndMetric.put(field.getKey(), field.getValue().asBoolean());
}
}
notification.activeStatusByTriggerAndMetric = activeStatusByTriggerAndMetric;
Map<String, Long> cooldownExpirationByTriggerAndMetric = new HashMap<>();
JsonNode cooldownExpirationByTriggerAndMetricNode = rootNode.get("cooldownExpirationByTriggerAndMetric");
if(cooldownExpirationByTriggerAndMetricNode.isObject()) {
Iterator<Entry<String, JsonNode>> fieldsIter = cooldownExpirationByTriggerAndMetricNode.fields();
while(fieldsIter.hasNext()) {
Entry<String, JsonNode> field = fieldsIter.next();
cooldownExpirationByTriggerAndMetric.put(field.getKey(), field.getValue().asLong());
}
}
notification.cooldownExpirationByTriggerAndMetric = cooldownExpirationByTriggerAndMetric;*/
return notification;
}
}
// We allow a-zA-Z0-9-_+. in the name, then @ then a-zA-Z0-9- followed by . and a-zA-Z0-9.
// ToDo Consider email.contains("@") if we see more issues in future
private static final String EMAILREGEX = "[a-zA-Z0-9\\-\\_\\+\\.]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9]+";
@Basic(optional = false)
@Column(name = "name", nullable = false)
String name;
String notifierName;
@ElementCollection
@Column(length = 2048)
List<String> subscriptions = new ArrayList<>(0);
@ElementCollection
List<String> metricsToAnnotate = new ArrayList<>(0);
long cooldownPeriod;
@ManyToOne(optional = false, fetch=FetchType.LAZY)
@JoinColumn(name = "alert_id")
private Alert alert;
@ManyToMany
@JoinTable(
name = "NOTIFICATION_TRIGGER", joinColumns = @JoinColumn(name = "TRIGGER_ID"), inverseJoinColumns = @JoinColumn(name = "NOTIFICATION_ID")
)
List<Trigger> triggers = new ArrayList<>(0);
boolean isSRActionable = false;
int severityLevel = 5;
@Lob
private String customText;
@ElementCollection
private Map<String, Long> cooldownExpirationByTriggerAndMetric = new HashMap<>();
@ElementCollection
private Map<String, Boolean> activeStatusByTriggerAndMetric = new HashMap<>();
/**
* Creates a new Notification object with a cool down of one hour and having specified no metrics on which to create annotations.
*
* @param name The notification name. Cannot be null or empty.
* @param alert The alert with which the notification is associated.
* @param notifierName The notifier implementation class name.
* @param subscriptions The notifier specific list of subscriptions to which notification shall be sent.
* @param cooldownPeriod The cool down period of the notification
*/
public Notification(String name, Alert alert, String notifierName, List<String> subscriptions, long cooldownPeriod) {
super(alert.getOwner());
setAlert(alert);
setName(name);
setNotifierName(notifierName);
setSubscriptions(subscriptions);
setCooldownPeriod(cooldownPeriod);
}
/** Creates a new Notification object. */
protected Notification() {
super(null);
}
@SuppressWarnings("unchecked")
public static void updateActiveStatusAndCooldown(EntityManager em, List<Notification> notifications) {
requireArgument(em != null, "Entity manager can not be null.");
if(notifications.isEmpty()) return;
Map<BigInteger, Notification> notificationsByIds = new HashMap<>(notifications.size());
StringBuilder sb = new StringBuilder();
for(Notification n : notifications) {
notificationsByIds.put(n.getId(), n);
n.activeStatusByTriggerAndMetric.clear();
n.cooldownExpirationByTriggerAndMetric.clear();
sb.append(n.getId()).append(",");
}
String ids = sb.substring(0, sb.length()-1);
try {
Query q = em.createNativeQuery("select * from notification_cooldownexpirationbytriggerandmetric where notification_id IN (" + ids + ")");
List<Object[]> objects = q.getResultList();
for(Object[] object : objects) {
BigInteger notificationId = new BigInteger(String.valueOf(Long.class.cast(object[0])));
Long cooldownExpiration = Long.class.cast(object[1]);
String key = String.class.cast(object[2]);
notificationsByIds.get(notificationId).cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration);
}
q = em.createNativeQuery("select * from notification_activestatusbytriggerandmetric where notification_id IN (" + ids + ")");
objects = q.getResultList();
for(Object[] object : objects) {
BigInteger notificationId = new BigInteger(String.valueOf(Long.class.cast(object[0])));
Boolean isActive;
try {
isActive = Boolean.class.cast(object[1]);
} catch (ClassCastException e) {
// This is because Embedded Derby stores booleans as 0, 1.
isActive = Integer.class.cast(object[1]) == 0 ? Boolean.FALSE : Boolean.TRUE;
}
String key = String.class.cast(object[2]);
notificationsByIds.get(notificationId).activeStatusByTriggerAndMetric.put(key, isActive);
}
} catch(NoResultException ex) {
return;
}
}
/**
* Given a metric to annotate expression, return a corresponding metric object.
*
* @param metric The metric to annotate expression.
*
* @return The corresponding metric or null if the metric to annotate expression is invalid.
*/
public static Metric getMetricToAnnotate(String metric) {
Metric result = null;
if (metric != null && !metric.isEmpty()) {
Pattern pattern = Pattern.compile(
"([\\w,\\-,\\.,/]+):([\\w,\\-,\\.,/]+)(\\{(?:[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)(?:,[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)*\\})?:([\\w,\\-,\\.,/]+)");
Matcher matcher = pattern.matcher(metric.replaceAll("\\s", ""));
if (matcher.matches()) {
String scopeName = matcher.group(1);
String metricName = matcher.group(2);
String tagString = matcher.group(3);
Map<String, String> tags = new HashMap<>();
if (tagString != null) {
tagString = tagString.replaceAll("\\{", "").replaceAll("\\}", "");
for (String tag : tagString.split(",")) {
String[] entry = tag.split("=");
tags.put(entry[0], entry[1]);
}
}
result = new Metric(scopeName, metricName);
result.setTags(tags);
}
}
return result;
}
/**
* Returns the alert with which the notification is associated.
*
* @return The associated alert.
*/
public Alert getAlert() {
return alert;
}
/**
* Sets the alert with which the notification is associated.
*
* @param alert The associated alert. Cannot be null.
*/
public void setAlert(Alert alert) {
requireArgument(alert != null, "The alert with which the notification is associated cannot be null.");
this.alert = alert;
}
/**
* Returns the notifier implementation class name associated with the notification.
*
* @return The notifier implementation class name.
*/
public String getNotifierName() {
return notifierName;
}
/**
* Sets the notifier implementation class name.
*
* @param notifierName The notifier implementation class name. Cannot be null.
*/
public void setNotifierName(String notifierName) {
this.notifierName = notifierName;
}
/**
* Returns the subscriptions used by the notifier to send the notifications.
*
* @return The list of subscriptions.
*/
public List<String> getSubscriptions() {
return Collections.unmodifiableList(subscriptions);
}
/**
* Replaces the subscriptions used by the notifier to send the notifications.
*
* @param subscriptions The subscription list.
*/
public void setSubscriptions(List<String> subscriptions) {
this.subscriptions.clear();
if(subscriptions == null) return;
for(String currentSubscription: subscriptions) {
if (this.getNotifierName().equals(AlertService.SupportedNotifier.GUS.getName())) {
if (currentSubscription.length() < 10)
throw new IllegalArgumentException("GUS subjectId is incorrect.");
}
}
if (subscriptions != null && !subscriptions.isEmpty()) {
this.subscriptions.addAll(subscriptions);
}
}
/**
* Returns the cool down period of notification.
*
* @return cool down period in milliseconds
*/
public long getCooldownPeriod() {
return cooldownPeriod;
}
/**
* Sets the cool down period to notification.
*
* @param cooldownPeriod cool down period in milliseconds
*/
public void setCooldownPeriod(long cooldownPeriod) {
requireArgument(cooldownPeriod >= 0, "Cool down period cannot be negative.");
this.cooldownPeriod = cooldownPeriod;
}
/**
* Returns the cool down expiration time of the notification given a metric,trigger combination.
*
* @param trigger The trigger
* @param metric The metric
* @return cool down expiration time in milliseconds
*/
public long getCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric) {
String key = _hashTriggerAndMetric(trigger, metric);
return this.cooldownExpirationByTriggerAndMetric.containsKey(key) ? this.cooldownExpirationByTriggerAndMetric.get(key) : 0;
}
/**
* Sets the cool down expiration time of the notification given a metric,trigger combination.
*
* @param trigger The trigger
* @param metric The metric
* @param cooldownExpiration cool down expiration time in milliseconds
*/
public void setCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric, long cooldownExpiration) {
requireArgument(cooldownExpiration >= 0, "Cool down expiration time cannot be negative.");
String key = _hashTriggerAndMetric(trigger, metric);
this.cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration);
}
public Map<String, Long> getCooldownExpirationMap() {
return cooldownExpirationByTriggerAndMetric;
}
public void setCooldownExpirationMap(Map<String, Long> cooldownExpirationByTriggerAndMetric) {
this.cooldownExpirationByTriggerAndMetric = cooldownExpirationByTriggerAndMetric;
}
/**
* Returns all metrics to be annotated.
*
* @return list of metrics
*/
public List<String> getMetricsToAnnotate() {
return metricsToAnnotate;
}
/**
* Sets metrics to be annotated.
*
* @param metricsToAnnotate list of metrics.
*/
public void setMetricsToAnnotate(List<String> metricsToAnnotate) {
this.metricsToAnnotate.clear();
if (metricsToAnnotate != null && !metricsToAnnotate.isEmpty()) {
for (String metric : metricsToAnnotate) {
requireArgument(getMetricToAnnotate(metric) != null, "Metrics to annotate should be of the form 'scope:metric[{[tagk=tagv]+}]");
this.metricsToAnnotate.add(metric);
}
}
}
public boolean onCooldown(Trigger trigger, Metric metric) {
return getCooldownExpirationByTriggerAndMetric(trigger, metric) >= System.currentTimeMillis();
}
/**
* returns the notification name.
*
* @return notification name.
*/
public String getName() {
return name;
}
/**
* Sets the notification name.
*
* @param name Notification name. Cannot be null or empty.
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the triggers associated with the notification.
*
* @return The triggers associated with the notification.
*/
public List<Trigger> getTriggers() {
return Collections.unmodifiableList(triggers);
}
/**
* Replaces the triggers associated with the notification.
*
* @param triggers The triggers associated with the notification.
*/
public void setTriggers(List<Trigger> triggers) {
this.triggers.clear();
if (triggers != null) {
this.triggers.addAll(triggers);
}
}
/**
* Given a metric,notification combination, indicates whether a triggering condition associated with this notification is still in a triggering state.
*
* @param trigger The Trigger that caused this notification
* @param metric The metric that caused this notification
*
* @return True if the triggering condition is still in a triggering state.
*/
public boolean isActiveForTriggerAndMetric(Trigger trigger, Metric metric) {
String key = _hashTriggerAndMetric(trigger, metric);
return this.activeStatusByTriggerAndMetric.containsKey(key) ? activeStatusByTriggerAndMetric.get(key) : false;
}
/**
* When a notification is sent out when a metric violates the trigger threshold, set this notification active for that trigger,metric combination
*
* @param trigger The Trigger that caused this notification
* @param metric The metric that caused this notification
* @param active Whether to set the notification to active
*/
public void setActiveForTriggerAndMetric(Trigger trigger, Metric metric, boolean active) {
String key = _hashTriggerAndMetric(trigger, metric);
this.activeStatusByTriggerAndMetric.put(key, active);
}
/**
* Indicates whether the notification is monitored by SR
*
* @return True if notification is monitored by SR
*/
public boolean getSRActionable() {
return isSRActionable;
}
/**
* Specifies whether the notification should be monitored by SR (actionable by SR)
*
* @param isSRActionable True if SR should monitor the notification
*/
public void setSRActionable(boolean isSRActionable) {
this.isSRActionable = isSRActionable;
}
/**
* Gets the severity level of notification
*
* @return The severity level
*/
public int getSeverityLevel() {
return severityLevel;
}
/**
* Sets the severity level of notification
*
* @param severityLevel The severity level
*/
public void setSeverityLevel(int severityLevel) {
if (severityLevel < 1 || severityLevel > 5) {
throw new IllegalArgumentException("The severty level should be between 1-5");
}
this.severityLevel = severityLevel;
}
public Map<String, Boolean> getActiveStatusMap() {
return activeStatusByTriggerAndMetric;
}
public void setActiveStatusMap(Map<String, Boolean> activeStatusByTriggerAndMetric) {
this.activeStatusByTriggerAndMetric = activeStatusByTriggerAndMetric;
}
/**
* Return the custom text in order to include in the notification
* @return the customText is optional
*/
public String getCustomText() {
return customText;
}
/**
* Sets the custom text to the notification
* @param customText customText is optional
*/
public void setCustomText(String customText) {
this.customText = customText;
}
@Override
public int hashCode() {
int hash = 5;
hash = 29 * hash + Objects.hashCode(this.name);
hash = 29 * hash + Objects.hashCode(this.alert);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Notification other = (Notification) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.alert, other.alert)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Notification{" + "name=" + name + ", notifierName=" + notifierName + ", subscriptions=" + subscriptions + ", metricsToAnnotate=" +
metricsToAnnotate + ", cooldownPeriod=" + cooldownPeriod + ", triggers=" + triggers + ", severity=" + severityLevel + ", srActionable=" + isSRActionable + ", customText;" + customText + '}';
}
private String _hashTriggerAndMetric(Trigger trigger, Metric metric) {
requireArgument(trigger != null, "Trigger cannot be null.");
requireArgument(metric != null, "Metric cannot be null");
if(trigger.getId()!=null) {
return trigger.getId().toString() + "$$" + metric.getIdentifier().hashCode();
}else {
return "0$$" + metric.getIdentifier().hashCode();
}
}
}
|
package core.model;
import java.util.UUID;
public class StaticGameObject extends GameObject {
public static final String NAME = "statics";
private int turn;
public void setId(String id) {
this.id = id;
}
public void setTurn(int turn) {
this.turn = turn;
}
StaticGameObject(int turn, String id)
{
this.turn = turn;
this.id = id;
}
}
|
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
StatementContextBase<A, D, E> {
private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
private final StatementContextBase<?, ?, ?> parent;
private final A argument;
private volatile SchemaPath schemaPath;
SubstatementContext(final StatementContextBase<?, ?, ?> parent, final ContextBuilder<A, D, E> builder) {
super(builder);
this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
this.argument = builder.getDefinition().parseArgumentValue(this, builder.getRawArgument());
}
@SuppressWarnings("unchecked")
SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
super(original);
this.parent = newParent;
if (newQNameModule != null) {
final A originalArg = original.argument;
if (originalArg instanceof QName) {
final QName originalQName = (QName) originalArg;
this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
QName.create(newQNameModule, originalQName.getLocalName()));
} else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
(StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
} else {
this.argument = original.argument;
}
} else {
this.argument = original.argument;
}
}
@Override
public StatementContextBase<?, ?, ?> getParentContext() {
return parent;
}
@Override
public NamespaceStorageNode getParentNamespaceStorage() {
return parent;
}
@Override
public Registry getBehaviourRegistry() {
return parent.getBehaviourRegistry();
}
@Override
public RootStatementContext<?, ?, ?> getRoot() {
return parent.getRoot();
}
@Override
public A getStatementArgument() {
return argument;
}
@Override
public StatementContextBase<?, ?, ?> createCopy(final StatementContextBase<?, ?, ?> newParent,
final CopyType typeOfCopy) {
return createCopy(null, newParent, typeOfCopy);
}
@Override
public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
"Attempted to copy statement {} which has completed phase {}", this, getCompletedPhase());
final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
if (this.getOriginalCtx() != null) {
copy.setOriginalCtx(this.getOriginalCtx());
} else {
copy.setOriginalCtx(this);
}
definition().onStatementAdded(copy);
copy.copyStatements(this, newQNameModule, typeOfCopy);
return copy;
}
private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
final CopyType typeOfCopy) {
final Collection<StatementContextBase<?, ?, ?>> declared = original.declaredSubstatements();
final Collection<StatementContextBase<?, ?, ?>> effective = original.effectiveSubstatements();
final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
for (final StatementContextBase<?, ?, ?> stmtContext : declared) {
if (StmtContextUtils.areFeaturesSupported(stmtContext)) {
copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
}
}
for (final StatementContextBase<?, ?, ?> stmtContext : effective) {
copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
}
addEffectiveSubstatements(buffer);
}
private void copySubstatement(final StatementContextBase<?, ?, ?> stmtContext,
final QNameModule newQNameModule, final CopyType typeOfCopy,
final Collection<StatementContextBase<?, ?, ?>> buffer) {
if (needToCopyByUses(stmtContext)) {
final StatementContextBase<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
buffer.add(copy);
} else if (isReusedByUses(stmtContext)) {
LOG.debug("Reusing substatement {} for {}", stmtContext, this);
buffer.add(stmtContext);
} else {
LOG.debug("Skipping statement {}", stmtContext);
}
}
// FIXME: revise this, as it seems to be wrong
private static final Set<Rfc6020Mapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
Rfc6020Mapping.DESCRIPTION,
Rfc6020Mapping.REFERENCE,
Rfc6020Mapping.STATUS);
private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(
Rfc6020Mapping.TYPE,
Rfc6020Mapping.TYPEDEF,
Rfc6020Mapping.USES);
private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
final StatementDefinition def = stmtContext.getPublicDefinition();
if (REUSED_DEF_SET.contains(def)) {
LOG.debug("Will reuse {} statement {}", def, stmtContext);
return false;
}
if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
return !Rfc6020Mapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
}
LOG.debug("Will copy {} statement {}", def, stmtContext);
return true;
}
private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
}
private boolean isSupportedAsShorthandCase() {
final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
}
private SchemaPath createSchemaPath() {
final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
final SchemaPath parentPath = maybeParentPath.get();
if (argument instanceof QName) {
final QName qname = (QName) argument;
if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
return maybeParentPath.orNull();
}
final SchemaPath path;
if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
|| Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
&& isSupportedAsShorthandCase()) {
path = parentPath.createChild(qname);
} else {
path = parentPath;
}
return path.createChild(qname);
}
if (argument instanceof String) {
final StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx();
final QName qname = (originalCtx != null) ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils
.qNameFromArgument(this, (String) argument);
return parentPath.createChild(qname);
}
if (argument instanceof SchemaNodeIdentifier
&& (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils
.producesDeclared(this, RefineStatement.class))) {
return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
}
if (Utils.isUnknownNode(this)) {
return parentPath.createChild(getPublicDefinition().getStatementName());
}
// FIXME: this does not look right
return maybeParentPath.orNull();
}
@Override
public Optional<SchemaPath> getSchemaPath() {
SchemaPath local = schemaPath;
if (local == null) {
synchronized (this) {
local = schemaPath;
if (local == null) {
local = createSchemaPath();
schemaPath = local;
}
}
}
return Optional.fromNullable(local);
}
@Override
public boolean isRootContext() {
return false;
}
@Override
public boolean isConfiguration() {
final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
ConfigStatement.class);
/*
* If "config" statement is not specified, the default is the same as
* the parent schema node's "config" value.
*/
if (configStatement == null) {
return parent.isConfiguration();
}
/*
* If a parent node has "config" set to "true", the node underneath it
* can have "config" set to "true" or "false".
*/
if (parent.isConfiguration()) {
return configStatement.getStatementArgument();
}
/*
* If a parent node has "config" set to "false", no node underneath it
* can have "config" set to "true", therefore only "false" is permitted.
*/
if (!configStatement.getStatementArgument()) {
return false;
}
throw new InferenceException(
"Parent node has config statement set to false, therefore no node underneath it can have config set to true",
getStatementSourceReference());
}
@Override
public boolean isEnabledSemanticVersioning() {
return parent.isEnabledSemanticVersioning();
}
}
|
package com.example.madiskar.experiencesamplingapp;
import android.support.test.espresso.ViewInteraction;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
@RunWith(AndroidJUnit4.class)
public class Test2EventActivity {
@Rule
public ActivityTestRule<LoginActivity> mActivityTestRule = new ActivityTestRule<>(LoginActivity.class);
UiDevice mDevice;
@Before
public void setUp() throws Exception {
//super.setUp();
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
@Test
public void eventActivityTest() throws Exception {
/*ViewInteraction appCompatEditText = onView(
withId(R.id.email_input));
appCompatEditText.perform(scrollTo(), click());
ViewInteraction appCompatEditText2 = onView(
withId(R.id.email_input));
appCompatEditText2.perform(scrollTo(), replaceText("[email protected]"), closeSoftKeyboard());
ViewInteraction appCompatEditText3 = onView(
withId(R.id.password_input));
appCompatEditText3.perform(scrollTo(), replaceText("testing123"), closeSoftKeyboard());
ViewInteraction appCompatButton = onView(
allOf(withId(R.id.button_login), withText("Login")));
appCompatButton.perform(scrollTo(), click());
ViewInteraction appCompatImageButton = onView(
allOf(withContentDescription("Open"),
withParent(allOf(withId(R.id.action_bar),
withParent(withId(R.id.action_bar_container)))),
isDisplayed()));
appCompatImageButton.check(matches(isDisplayed()));*/
/*ViewInteraction appCompatButton2 = onView(
allOf(withId(R.id.event_button), withText("Event"),
withParent(childAtPosition(
withId(android.R.id.list),
0)),
isDisplayed()));
appCompatButton2.perform(click());
ViewInteraction appCompatCheckedTextView = onView(
allOf(withId(android.R.id.text1), withText("Running"),
isDisplayed()));
appCompatCheckedTextView.perform(click());
ViewInteraction appCompatButton3 = onView(
allOf(withId(android.R.id.button1), withText("Start")));
appCompatButton3.perform(click());
mDevice.openNotification();
mDevice.wait(Until.hasObject(By.pkg("com.android.systemui")), 10000);
UiObject eventText = mDevice.findObject(new UiSelector().text("Active Event"));
assertTrue("'Active Event' exists", eventText.exists());
UiObject eventName = mDevice.findObject(new UiSelector().text("Running"));
assertTrue("Event 'Running' is the active event", eventName.exists());
UiObject eventFalseName = mDevice.findObject(new UiSelector().text("Short Event"));
assertFalse("Event 'Short Event' is NOT the active event", eventFalseName.exists());
UiObject eventStopButton = mDevice.findObject(new UiSelector().textMatches("STOP|Stop|stop"));
assertTrue("Event stop button exists", eventStopButton.exists());
eventStopButton.click();*/
//Make sure that notifications are closed
/*if (mDevice.hasObject(By.pkg("com.android.systemui")))
mDevice.pressBack();*/
/*ViewInteraction appCompatImageButton3 = onView(
allOf(withContentDescription("Open"),
withParent(allOf(withId(R.id.action_bar),
withParent(withId(R.id.action_bar_container)))),
isDisplayed()));
appCompatImageButton3.perform(click());
ViewInteraction relativeLayout = onView(
allOf(childAtPosition(
allOf(withId(R.id.menuList),
withParent(withId(R.id.drawerPane))),
4),
isDisplayed()));
relativeLayout.perform(click());
ViewInteraction appCompatButton4 = onView(
allOf(withId(R.id.button_login), withText("Login")));
appCompatButton4.check(matches(isDisplayed()));*/
}
/*
* Removed for now, long waiting does not work in Greenhouse
*
*/
/*@Test
public void eventControlTimeTest() throws Exception{
ViewInteraction appCompatButton2 = onView(
allOf(withId(R.id.event_button), withText("Event"),
withParent(childAtPosition(
withId(android.R.id.list),
0)),
isDisplayed()));
appCompatButton2.perform(click());
ViewInteraction appCompatCheckedTextView = onView(
allOf(withId(android.R.id.text1), withText("Short Event"),
isDisplayed()));
appCompatCheckedTextView.perform(click());
ViewInteraction appCompatButton3 = onView(
allOf(withId(android.R.id.button1), withText("Start")));
appCompatButton3.perform(click());
mDevice.openNotification();
mDevice.wait(Until.hasObject(By.pkg("com.android.systemui")), 10000);
mDevice.wait(Until.hasObject(By.text("Controltime has passed")), 70000);
UiObject eventText = mDevice.findObject(new UiSelector().text("Controltime for event \"Short Event\" has passed"));
assertTrue(eventText.exists());
UiObject eventStopButton = mDevice.findObject(new UiSelector().textMatches("STOP|Stop|stop"));
if (!eventStopButton.exists()){
UiObject expandButton = mDevice.findObject(new UiSelector().textMatches(".*01.*"));
expandButton.click();
eventStopButton = mDevice.findObject(new UiSelector().textMatches("STOP|Stop|stop"));
eventStopButton.click();
} else {
eventStopButton.click();
}
}*/
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
|
package sistemapagoimpuestos.View.Admin.GestionarEmpresaAdherida;
import exceptions.Excepciones;
import java.awt.Component;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import sistemapagoimpuestos.Dto.DTOEmpresaTipoImpuesto;
import sistemapagoimpuestos.Controller.ControladorGestionarEmpresaAdherida;
import sistemapagoimpuestos.Entity.Empresa;
import sistemapagoimpuestos.Entity.EmpresaTipoImpuesto;
import sistemapagoimpuestos.Utils.MetodosPantalla;
import sistemapagoimpuestos.View.Admin.GestionarTipoImpuesto.IUGestionarTipoImpuestoItems;
public class IUGestionarEmpresaAdherida extends javax.swing.JFrame {
ControladorGestionarEmpresaAdherida controlador = new ControladorGestionarEmpresaAdherida();
public IUGestionarEmpresaAdherida() {
initComponents();
this.setLocationRelativeTo(null);
obtenerEmpresas();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
Button_Filtrar = new javax.swing.JButton();
Button_Crear = new javax.swing.JButton();
Button_Modificar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tabla_empresa = new javax.swing.JTable();
TextField_Filtrar = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
Button_Actualizar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Gestionar Empresa Adherida");
Button_Filtrar.setText("Filtrar");
Button_Filtrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button_FiltrarActionPerformed(evt);
}
});
Button_Crear.setText("Crear");
Button_Crear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button_CrearActionPerformed(evt);
}
});
Button_Modificar.setText("Modificar");
Button_Modificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button_ModificarActionPerformed(evt);
}
});
tabla_empresa.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
"Cuit", "Nombre", "Tipo de Impuesto", "Tipo de Empresa", "Frecuencia de Liquidación", "Dirección", "Deshabilitada el dia"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(tabla_empresa);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("EMPRESAS");
Button_Actualizar.setText("Actualizar");
Button_Actualizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button_ActualizarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(Button_Crear, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(Button_Modificar)
.addGap(34, 34, 34)
.addComponent(Button_Actualizar)
.addGap(42, 42, 42))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(TextField_Filtrar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Button_Filtrar)
.addGap(363, 363, 363))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(290, 290, 290)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 569, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(31, 31, 31))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(jLabel1)
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(TextField_Filtrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Button_Filtrar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button_Modificar)
.addComponent(Button_Crear)
.addComponent(Button_Actualizar))
.addGap(34, 34, 34))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void Button_FiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_FiltrarActionPerformed
// TODO add your handling code here:
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(((DefaultTableModel) tabla_empresa.getModel()));
sorter.setRowFilter(RowFilter.regexFilter(TextField_Filtrar.getText()));
tabla_empresa.setRowSorter(sorter);
}//GEN-LAST:event_Button_FiltrarActionPerformed
private void Button_CrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_CrearActionPerformed
// TODO add your handling code here:
controlador.crearEmpresa(evt, controlador);
}//GEN-LAST:event_Button_CrearActionPerformed
private void Button_ModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_ModificarActionPerformed
try {
int columnCode = 0;
int rowSelected = tabla_empresa.getSelectedRow();
String codigo = tabla_empresa.getModel().getValueAt(rowSelected, columnCode).toString();
Vector vct = new Vector();
vct.add(tabla_empresa.getValueAt(rowSelected, 0));
vct.add(tabla_empresa.getValueAt(rowSelected, 1));
vct.add(tabla_empresa.getValueAt(rowSelected, 2));
vct.add(tabla_empresa.getValueAt(rowSelected, 3));
vct.add(tabla_empresa.getValueAt(rowSelected, 4));
vct.add(tabla_empresa.getValueAt(rowSelected, 5));
vct.add(tabla_empresa.getValueAt(rowSelected, 6));
controlador.modificarEmpresa(vct, controlador);
} catch (ArrayIndexOutOfBoundsException e) {
//Excepciones.getInstance().camposRequerido(Arrays.asList("Codigo"));
Excepciones.getInstance().objetoNoSeleccionado();
}
}//GEN-LAST:event_Button_ModificarActionPerformed
private void Button_ActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_ActualizarActionPerformed
this.obtenerEmpresas();
}//GEN-LAST:event_Button_ActualizarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(IUGestionarEmpresaAdherida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(IUGestionarEmpresaAdherida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(IUGestionarEmpresaAdherida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(IUGestionarEmpresaAdherida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new IUGestionarEmpresaAdherida().setVisible(true);
}
});
}
public void iniciar() {
controlador.iniciar();
}
public void obtenerEmpresas(){
List<DTOEmpresaTipoImpuesto> listDtoEmpresaTipoImpuesto = controlador.consultarEmpresas();
String[] columnas = {"Cuit", "Nombre","Tipo de Impuesto","Tipo de Empresa","Frecuencia de Liquidacion", "Direccion", "Deshabilitada el dia"};
DefaultTableModel dtm = new DefaultTableModel(null, columnas) {
@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
public Class<?> getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return String.class;
case 4:
return Integer.class;
case 5:
return String.class;
case 6:
return String.class;
default:
return null;
}
}
};
for (DTOEmpresaTipoImpuesto dtoEmpresaTipoImpuesto : listDtoEmpresaTipoImpuesto) {
Vector<Object> vect = new Vector<>();
vect.add(dtoEmpresaTipoImpuesto.getEmpresa().getCuitEmpresa());
vect.add(dtoEmpresaTipoImpuesto.getEmpresa().getNombreEmpresa());
vect.add(dtoEmpresaTipoImpuesto.getTipoImpuesto().getNombreTipoImpuesto());
vect.add(dtoEmpresaTipoImpuesto.getTipoEmpresa().getNombreTipoEmpresa());
vect.add(dtoEmpresaTipoImpuesto.getFrecuenciaLiquidacionDTOEmpresaExistente());
vect.add(dtoEmpresaTipoImpuesto.getEmpresa().getDireccionEmpresa());
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");
if (dtoEmpresaTipoImpuesto.getEmpresa().getFechaHoraInhabilitacionEmpresa() != null) {
vect.add(sdf.format(dtoEmpresaTipoImpuesto.getEmpresa().getFechaHoraInhabilitacionEmpresa()));
} else {
vect.add("");
}
dtm.addRow(vect);
}
DefaultTableCellRenderer r = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
setHorizontalAlignment(JLabel.CENTER);
return this;
}
};
tabla_empresa.setAutoCreateRowSorter(true);
tabla_empresa.setModel(dtm);
tabla_empresa.getColumnModel().getColumn(0).setCellRenderer(r);
tabla_empresa.getColumnModel().getColumn(1).setCellRenderer(r);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Button_Actualizar;
private javax.swing.JButton Button_Crear;
private javax.swing.JButton Button_Filtrar;
private javax.swing.JButton Button_Modificar;
private javax.swing.JTextField TextField_Filtrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tabla_empresa;
// End of variables declaration//GEN-END:variables
}
|
package org.csstudio.opibuilder.widgetActions;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.opibuilder.properties.FilePathProperty;
import org.csstudio.opibuilder.properties.MacrosProperty;
import org.csstudio.opibuilder.properties.WidgetPropertyCategory;
import org.csstudio.opibuilder.util.ConsoleService;
import org.csstudio.opibuilder.util.MacrosInput;
import org.csstudio.opibuilder.util.ResourceUtil;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
/**
* The abstract action opening an OPI file. It can be subclassed to be opened in view or editor.
*
* @author Xihui Chen
*
*/
public abstract class AbstractOpenOPIAction extends AbstractWidgetAction {
public static final String PROP_PATH = "path";//$NON-NLS-1$
public static final String PROP_MACROS = "macros";//$NON-NLS-1$
protected boolean ctrlPressed = false;
protected boolean shiftPressed = false;
@Override
protected void configureProperties() {
addProperty(new FilePathProperty(PROP_PATH, "File Path",
WidgetPropertyCategory.Basic, new Path(""),
new String[] { "opi" }, false)); //$NON-NLS-1$
addProperty(new MacrosProperty(PROP_MACROS, "Macros",
WidgetPropertyCategory.Basic, new MacrosInput(
new LinkedHashMap<String, String>(), true)));
}
@Override
public void run() {
// read file
IPath absolutePath = getPath();
if (!absolutePath.isAbsolute()) {
absolutePath = ResourceUtil.buildAbsolutePath(getWidgetModel(),
getPath());
if(!ResourceUtil.isExsitingFile(absolutePath, true)){
//search from OPI search path
absolutePath = ResourceUtil.getFileOnSearchPath(getPath(), true);
}
}
if (absolutePath == null || !ResourceUtil.isExsitingFile(absolutePath, true)) {
try {
throw new FileNotFoundException(
NLS.bind("The file {0} does not exist.",
getPath().toString()));
} catch (FileNotFoundException e) {
MessageDialog.openError(Display.getDefault().getActiveShell(),
"File Open Error", e.getMessage());
ConsoleService.getInstance().writeError(e.toString());
return;
}
}
openOPI(absolutePath);
}
abstract protected void openOPI(IPath absolutePath);
protected IPath getPath() {
return (IPath) getPropertyValue(PROP_PATH);
}
protected MacrosInput getMacrosInput() {
MacrosInput result = new MacrosInput(
new LinkedHashMap<String, String>(), false);
MacrosInput macrosInput = ((MacrosInput) getPropertyValue(PROP_MACROS))
.getCopy();
if (macrosInput.isInclude_parent_macros()) {
Map<String, String> macrosMap = getWidgetModel() instanceof AbstractContainerModel ? ((AbstractContainerModel) getWidgetModel())
.getParentMacroMap() : getWidgetModel().getParent()
.getMacroMap();
result.getMacrosMap().putAll(macrosMap);
}
result.getMacrosMap().putAll(macrosInput.getMacrosMap());
return result;
}
/**
* @param ctrlPressed
* the ctrlPressed to set
*/
public final void setCtrlPressed(boolean ctrlPressed) {
this.ctrlPressed = ctrlPressed;
}
/**
* @param shiftPressed
* the shiftPressed to set
*/
public final void setShiftPressed(boolean shiftPressed) {
this.shiftPressed = shiftPressed;
}
@Override
public String getDefaultDescription() {
return "Open " + getPath();
}
}
|
package org.ovirt.engine.core.bll.gluster;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.gluster.ResetGlusterVolumeOptionsParameters;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeOptionEntity;
import org.ovirt.engine.core.common.constants.gluster.GlusterConstants;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.gluster.ResetGlusterVolumeOptionsVDSParameters;
/**
* BLL Command to Reset Gluster Volume Options
*/
@NonTransactiveCommandAttribute
public class ResetGlusterVolumeOptionsCommand extends GlusterVolumeCommandBase<ResetGlusterVolumeOptionsParameters> {
private boolean isResetAllOptions;
public ResetGlusterVolumeOptionsCommand(ResetGlusterVolumeOptionsParameters params) {
super(params);
}
@Override
protected LockProperties applyLockProperties(LockProperties lockProperties) {
return lockProperties.withScope(Scope.Execution).withWait(true);
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(EngineMessage.VAR__ACTION__RESET);
addCanDoActionMessage(EngineMessage.VAR__TYPE__GLUSTER_VOLUME_OPTION);
}
@Override
protected void executeCommand() {
VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResetGlusterVolumeOptions,
new ResetGlusterVolumeOptionsVDSParameters(upServer.getId(),
getGlusterVolumeName(), getParameters().getVolumeOption(), getParameters().isForceAction()));
setSucceeded(returnValue.getSucceeded());
if (getSucceeded()) {
if (getParameters().getVolumeOption() != null && !(getParameters().getVolumeOption().getKey().isEmpty())) {
GlusterVolumeOptionEntity entity = getGlusterVolume().getOption(getParameters().getVolumeOption().getKey());
isResetAllOptions = false;
if(entity != null) {
removeOptionInDb(entity);
String optionValue = entity.getValue();
getParameters().getVolumeOption().setValue(optionValue != null ? optionValue : "");
addCustomValue(GlusterConstants.OPTION_KEY, getParameters().getVolumeOption().getKey());
addCustomValue(GlusterConstants.OPTION_VALUE, getParameters().getVolumeOption().getValue());
}
} else {
for (GlusterVolumeOptionEntity option : getGlusterVolume().getOptions()) {
removeOptionInDb(option);
}
isResetAllOptions = true;
}
} else {
handleVdsError(AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_FAILED, returnValue.getVdsError().getMessage());
return;
}
}
/**
* Remove the volume option in DB. If the option with given key already exists for the volume, <br>
* it will be deleted.
*
* @param option
*/
private void removeOptionInDb(GlusterVolumeOptionEntity option) {
getGlusterOptionDao().removeVolumeOption(option.getId());
}
@Override
public AuditLogType getAuditLogTypeValue() {
if (getSucceeded()) {
return (isResetAllOptions) ? AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_ALL : AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET;
} else {
return errorType == null ? AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_FAILED : errorType;
}
}
}
|
package org.ovirt.engine.core.bll.scheduling.policyunits;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.bll.scheduling.PolicyUnitImpl;
import org.ovirt.engine.core.bll.scheduling.pending.PendingResourceManager;
import org.ovirt.engine.core.common.businessentities.MigrationSupport;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.scheduling.PerHostMessages;
import org.ovirt.engine.core.common.scheduling.PolicyUnit;
public class NonMigratableUnit extends PolicyUnitImpl {
public NonMigratableUnit(PolicyUnit policyUnit,
PendingResourceManager pendingResourceManager) {
super(policyUnit, pendingResourceManager);
}
@Override
public List<VDS> filter(VDSGroup cluster, List<VDS> hosts, VM vm, Map<String, String> parameters, PerHostMessages messages) {
if (vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST
|| (vm.getRunOnVds() == null && vm.getMigrationSupport() == MigrationSupport.IMPLICITLY_NON_MIGRATABLE)) {
// host has been specified for pin to host.
if(vm.getDedicatedVmForVdsList().size() > 0) {
List<VDS> dedicatedHostsList = new LinkedList<>();
for (VDS host : hosts) {
if (vm.getDedicatedVmForVdsList().contains(host.getId())) {
dedicatedHostsList.add(host);
}
}
return dedicatedHostsList;
} else {
// check pin to any (the VM should be down/ no migration allowed).
if (vm.getRunOnVds() == null) {
return hosts;
}
}
// if flow reaches here, the VM is pinned but there is no dedicated host.
return Collections.emptyList();
}
return hosts;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.