answer
stringlengths 17
10.2M
|
|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.kp.web.pages.ertekeles;
import hu.sch.kp.web.util.ListDataProviderCompoundPropertyModelImpl;
import hu.sch.domain.Ertekeles;
import hu.sch.domain.Felhasznalo;
import hu.sch.domain.PontIgeny;
import hu.sch.kp.services.ErtekelesManagerLocal;
import hu.sch.kp.services.UserManagerLocal;
import hu.sch.kp.web.pages.ertekeles.Ertekelesek;
import hu.sch.kp.web.session.VirSession;
import hu.sch.kp.web.templates.SecuredPageTemplate;
import java.util.List;
import javax.ejb.EJB;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
/**
*
* @author hege
*/
public class LeadottPontIgenyles extends SecuredPageTemplate {
@EJB(name = "ErtekelesManagerBean")
ErtekelesManagerLocal ertekelesManager;
@EJB(name = "UserManagerBean")
UserManagerLocal userManager;
public LeadottPontIgenyles(Ertekeles ert) {
setHeaderLabelText("Leadott pontigénylések megtekintése");
final Long ertekelesId = ert.getId();
final List<PontIgeny> igenylista = igenyeketElokeszit(ert);
setModel(new CompoundPropertyModel(ert));
add(new Label("csoport.nev"));
add(new Label("szemeszter"));
Form igform = new Form("igenyekform") {
@Override
protected void onSubmit() {
return;
}
};
IDataProvider provider = new ListDataProviderCompoundPropertyModelImpl(igenylista);
DataView dview = new DataView("igenyek", provider) {
@Override
protected void populateItem(Item item) {
item.add(new Label("felhasznalo.nev"));
item.add(new Label("felhasznalo.becenev"));
item.add(new Label("pont"));
}
};
igform.add(dview);
add(igform);
}
private List<PontIgeny> igenyeketElokeszit(Ertekeles ert) {
List<Felhasznalo> csoporttagok = userManager.getCsoporttagokWithoutOregtagok(ert.getCsoport().getId());
List<PontIgeny> igenyek = ertekelesManager.findPontIgenyekForErtekeles(ert.getId());
if (igenyek.size() == 0) {
for (Felhasznalo f : csoporttagok) {
igenyek.add(new PontIgeny(f, 0));
}
} else {
if (igenyek.size() != csoporttagok.size()) {
boolean bentvan;
for (Felhasznalo felh : csoporttagok) {
bentvan = false;
for (PontIgeny igeny : igenyek) {
if (felh.getId().equals( igeny.getFelhasznalo().getId())) {
bentvan = true;
break;
}
}
if (!bentvan) {
igenyek.add(new PontIgeny(felh, 0));
}
}
}
}
return igenyek;
}
}
|
package com.smartdevicelink.api.audio;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import java.io.File;
import java.nio.ByteBuffer;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
class AudioDecoderCompat extends BaseAudioDecoder {
private static final String TAG = AudioDecoderCompat.class.getSimpleName();
private static final int DEQUEUE_TIMEOUT = 3000;
AudioDecoderCompat(File audioFile, int sampleRate, SampleType sampleType, AudioDecoderListener listener) {
super(audioFile, sampleRate, sampleType, listener);
}
void start() {
try {
initMediaComponents();
decoder.start();
new DecodeAsync().execute(audioFile);
} catch (Exception e) {
e.printStackTrace();
this.listener.onDecoderError(e);
stop();
}
}
private class DecodeAsync extends AsyncTask<File, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listener.onDecoderFinish();
stop();
}
@Override
protected Void doInBackground(File... files) {
ByteBuffer[] inputBuffersArray = decoder.getInputBuffers();
ByteBuffer[] outputBuffersArray = decoder.getOutputBuffers();
MediaCodec.BufferInfo outputBufferInfo = new MediaCodec.BufferInfo();
while (true) {
int inputBuffersArrayIndex = 0;
while (inputBuffersArrayIndex != MediaCodec.INFO_TRY_AGAIN_LATER) {
inputBuffersArrayIndex = decoder.dequeueInputBuffer(DEQUEUE_TIMEOUT);
if (inputBuffersArrayIndex >= 0) {
ByteBuffer inputBuffer = inputBuffersArray[inputBuffersArrayIndex];
MediaCodec.BufferInfo inputBufferInfo = AudioDecoderCompat.super.onInputBufferAvailable(extractor, inputBuffer);
decoder.queueInputBuffer(inputBuffersArrayIndex, inputBufferInfo.offset, inputBufferInfo.size, inputBufferInfo.presentationTimeUs, inputBufferInfo.flags);
}
}
int outputBuffersArrayIndex = 0;
while (outputBuffersArrayIndex != MediaCodec.INFO_TRY_AGAIN_LATER) {
outputBuffersArrayIndex = decoder.dequeueOutputBuffer(outputBufferInfo, DEQUEUE_TIMEOUT);
if (outputBuffersArrayIndex >= 0) {
ByteBuffer outputBuffer = outputBuffersArray[outputBuffersArrayIndex];
if ((outputBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0 && outputBufferInfo.size != 0) {
decoder.releaseOutputBuffer(outputBuffersArrayIndex, false);
} else {
SampleBuffer buffer = AudioDecoderCompat.super.onOutputBufferAvailable(outputBuffer);
listener.onAudioDataAvailable(buffer);
decoder.releaseOutputBuffer(outputBuffersArrayIndex, false);
}
} else if (outputBuffersArrayIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
MediaFormat newFormat = decoder.getOutputFormat();
AudioDecoderCompat.super.onOutputFormatChanged(newFormat);
}
}
if (outputBufferInfo.flags == MediaCodec.BUFFER_FLAG_END_OF_STREAM) {
break;
}
}
return null;
}
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// 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 com.kyloth.serleena.presenters;
import android.os.AsyncTask;
import com.kyloth.serleena.common.GeoPoint;
import com.kyloth.serleena.model.ISerleenaDataSource;
import com.kyloth.serleena.model.IWeatherForecast;
import com.kyloth.serleena.common.NoSuchWeatherForecastException;
import com.kyloth.serleena.presentation.ISerleenaActivity;
import com.kyloth.serleena.presentation.IWeatherPresenter;
import com.kyloth.serleena.presentation.IWeatherView;
import com.kyloth.serleena.sensors.ILocationManager;
import com.kyloth.serleena.sensors.ILocationObserver;
import java.util.Calendar;
import java.util.Date;
/**
* Concretizza IWeatherPresenter.
*
* @use Viene utilizzata solamente dall'Activity, che ne mantiene un riferimento. Il Presenter, alla creazione, si registra alla sua Vista, passando se stesso come parametro dietro interfaccia.
* @field view : IWeatherView Vista associata al presenter
* @field activity : ISerleenaActivity Activity a cui il presenter appartiene
* @field daysPastNow : int Giorni successivi a quello corrente la cui data corrispondente deve essere visualizzata sulla vista
* @field locMan : ILocationManager Sensore di posizione
* @field ds : ISerleenaDataSource DAO dell'applicazione
* @field lastKnownLocation : GeoPoint Ultima posizione geografica nota dell'utente
* @author Filippo Sestini <sestini.filippo@gmail.com>
* @version 1.0.0
*/
public class WeatherPresenter implements IWeatherPresenter, ILocationObserver {
private static int LOCATION_UPDATE_INTERVAL_SECONDS = 60;
private IWeatherView view;
private ISerleenaActivity activity;
private int daysPastNow;
private ILocationManager locMan;
private ISerleenaDataSource ds;
private GeoPoint lastKnownLocation;
public WeatherPresenter(IWeatherView view, ISerleenaActivity activity)
throws IllegalArgumentException {
if (view == null)
throw new IllegalArgumentException("Illegal null view");
if (activity == null)
throw new IllegalArgumentException("Illegal null activity");
this.view = view;
this.activity = activity;
this.view.attachPresenter(this);
this.locMan = activity.getSensorManager().getLocationSource();
this.ds = activity.getDataSource();
daysPastNow = 0;
}
/**
* Implementa IWeatherPresenter.advanceDate().
*/
@Override
public synchronized void advanceDate() {
daysPastNow = (daysPastNow + 1) % 6;
if (lastKnownLocation != null) {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
present(daysPastNow, lastKnownLocation);
return null;
}
};
task.execute();
}
}
public void present(int daysPastNow, GeoPoint location) throws
IllegalArgumentException {
if (location == null)
throw new IllegalArgumentException("Illegal null location");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, daysPastNow);
Date d = c.getTime();
view.setDate(d);
try {
IWeatherForecast info =
ds.getWeatherInfo(location, d);
view.setDate(d);
view.setWeatherInfo(info);
} catch (NoSuchWeatherForecastException ex) {
view.clearWeatherInfo();
}
}
/**
* Implementa IPresenter.resume().
*/
@Override
public synchronized void resume() {
locMan.attachObserver(this, LOCATION_UPDATE_INTERVAL_SECONDS);
}
/**
* Implementa IPresenter.pause().
*/
@Override
public synchronized void pause() {
locMan.detachObserver(this);
}
/**
* Implementa ILocationObserver.onLocationUpdate().
*
* @param loc Valore di tipo GeoPoint che indica la posizione
* dell'Escursionista.
*/
@Override
public synchronized void onLocationUpdate(GeoPoint loc)
throws IllegalArgumentException {
if (loc == null)
throw new IllegalArgumentException("Illegal null location");
lastKnownLocation = loc;
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
present(daysPastNow, lastKnownLocation);
return null;
}
};
task.execute();
}
}
|
package org.spine3.server.storage.memory;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.protobuf.FieldMask;
import org.spine3.protobuf.TypeUrl;
import org.spine3.server.stand.AggregateStateId;
import org.spine3.server.storage.EntityStorageRecord;
import org.spine3.server.storage.StandStorage;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* In-memory implementation of {@link StandStorage}.
*
* <p>Uses a {@link ConcurrentMap} for internal storage.
*
* @author Alex Tymchenko
*/
public class InMemoryStandStorage extends StandStorage {
private final InMemoryRecordStorage<AggregateStateId> recordStorage;
private InMemoryStandStorage(Builder builder) {
super(builder.isMultitenant());
recordStorage = new InMemoryRecordStorage<>(builder.isMultitenant());
}
public static Builder newBuilder() {
return new Builder();
}
@Override
public ImmutableCollection<EntityStorageRecord> readAllByType(final TypeUrl type) {
return readAllByType(type, FieldMask.getDefaultInstance());
}
@Override
public ImmutableCollection<EntityStorageRecord> readAllByType(final TypeUrl type, FieldMask fieldMask) {
final Map<AggregateStateId, EntityStorageRecord> allRecords = readAll(fieldMask);
final Map<AggregateStateId, EntityStorageRecord> resultMap = Maps.filterKeys(allRecords, new Predicate<AggregateStateId>() {
@Override
public boolean apply(@Nullable AggregateStateId stateId) {
checkNotNull(stateId);
final boolean typeMatches = stateId.getStateType()
.equals(type);
return typeMatches;
}
});
final ImmutableList<EntityStorageRecord> result = ImmutableList.copyOf(resultMap.values());
return result;
}
@Nullable
@Override
protected EntityStorageRecord readRecord(AggregateStateId id) {
final EntityStorageRecord result = recordStorage.read(id);
return result;
}
@Override
protected Iterable<EntityStorageRecord> readMultipleRecords(Iterable<AggregateStateId> ids) {
final Iterable<EntityStorageRecord> result = recordStorage.readMultiple(ids);
return result;
}
@Override
protected Iterable<EntityStorageRecord> readMultipleRecords(Iterable<AggregateStateId> ids, FieldMask fieldMask) {
final Iterable<EntityStorageRecord> result = recordStorage.readMultiple(ids, fieldMask);
return result;
}
@Override
protected Map<AggregateStateId, EntityStorageRecord> readAllRecords() {
final Map<AggregateStateId, EntityStorageRecord> result = recordStorage.readAll();
return result;
}
@Override
protected Map<AggregateStateId, EntityStorageRecord> readAllRecords(FieldMask fieldMask) {
final Map<AggregateStateId, EntityStorageRecord> result = recordStorage.readAll(fieldMask);
return result;
}
@Override
protected void writeRecord(AggregateStateId id, EntityStorageRecord record) {
final TypeUrl recordType = TypeUrl.of(record.getState()
.getTypeUrl());
final TypeUrl recordTypeFromId = id.getStateType();
checkState(
recordTypeFromId.equals(recordType),
String.format("The typeUrl of the record (%s) does not correspond to id (for type %s)",
recordType, recordTypeFromId));
recordStorage.write(id, record);
}
public static class Builder {
private boolean multitenant;
public boolean isMultitenant() {
return multitenant;
}
public Builder setMultitenant(boolean multitenant) {
this.multitenant = multitenant;
return this;
}
/**
* Builds an instance of in-memory stand storage.
*
* @return an instance of in-memory storage
*/
public InMemoryStandStorage build() {
final InMemoryStandStorage result = new InMemoryStandStorage(this);
return result;
}
}
}
|
package com.opengamma.util.db;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Test DbUtils.
*/
public class DbHelperTest {
protected DbHelper _helper = new DbHelper() {};
@Test
public void test_isWildcard() {
assertEquals(true, _helper.isWildcard("a*"));
assertEquals(true, _helper.isWildcard("a?"));
assertEquals(true, _helper.isWildcard("a*b"));
assertEquals(true, _helper.isWildcard("a?b"));
assertEquals(true, _helper.isWildcard("*b"));
assertEquals(true, _helper.isWildcard("?b"));
assertEquals(false, _helper.isWildcard("a"));
assertEquals(false, _helper.isWildcard(""));
assertEquals(false, _helper.isWildcard(null));
}
@Test
public void test_sqlWildcardOperator() {
assertEquals("LIKE", _helper.sqlWildcardOperator("a*"));
assertEquals("LIKE", _helper.sqlWildcardOperator("a?"));
assertEquals("LIKE", _helper.sqlWildcardOperator("a*b"));
assertEquals("LIKE", _helper.sqlWildcardOperator("a?b"));
assertEquals("LIKE", _helper.sqlWildcardOperator("*b"));
assertEquals("LIKE", _helper.sqlWildcardOperator("?b"));
assertEquals("=", _helper.sqlWildcardOperator("a"));
assertEquals("=", _helper.sqlWildcardOperator(""));
assertEquals("=", _helper.sqlWildcardOperator(null));
}
@Test
public void test_sqlWildcardAdjustValue() {
assertEquals("a%", _helper.sqlWildcardAdjustValue("a*"));
assertEquals("a_", _helper.sqlWildcardAdjustValue("a?"));
assertEquals("a%b", _helper.sqlWildcardAdjustValue("a*b"));
assertEquals("a_b", _helper.sqlWildcardAdjustValue("a?b"));
assertEquals("%b", _helper.sqlWildcardAdjustValue("*b"));
assertEquals("_b", _helper.sqlWildcardAdjustValue("?b"));
assertEquals("a", _helper.sqlWildcardAdjustValue("a"));
assertEquals("", _helper.sqlWildcardAdjustValue(""));
assertEquals(null, _helper.sqlWildcardAdjustValue(null));
assertEquals("a%b\\%c", _helper.sqlWildcardAdjustValue("a*b%c"));
assertEquals("a_b\\_c", _helper.sqlWildcardAdjustValue("a?b_c"));
}
@Test
public void test_sqlWildcardQuery() {
assertEquals("AND col LIKE :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "a*"));
assertEquals("AND col LIKE :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "a?"));
assertEquals("AND col LIKE :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "a*b"));
assertEquals("AND col LIKE :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "a?b"));
assertEquals("AND col LIKE :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "*b"));
assertEquals("AND col LIKE :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "?b"));
assertEquals("AND col = :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", "a"));
assertEquals("AND col = :arg ", _helper.sqlWildcardQuery("AND col ", ":arg", ""));
assertEquals("", _helper.sqlWildcardQuery("AND col ", ":arg", null));
}
@Test
public void test_sqlApplyPaging_noPaging() {
assertEquals(
"SELECT foo FROM bar WHERE TRUE ORDER BY foo ",
_helper.sqlApplyPaging("SELECT foo FROM bar WHERE TRUE ", "ORDER BY foo ", null));
assertEquals(
"SELECT foo FROM bar WHERE TRUE ORDER BY foo ",
_helper.sqlApplyPaging("SELECT foo FROM bar WHERE TRUE ", "ORDER BY foo ", PagingRequest.ALL));
}
@Test
public void test_sqlApplyPaging_limit() {
assertEquals(
"SELECT foo FROM bar WHERE TRUE ORDER BY foo FETCH FIRST 20 ROWS ONLY ",
_helper.sqlApplyPaging("SELECT foo FROM bar WHERE TRUE ", "ORDER BY foo ", new PagingRequest(1, 20)));
}
@Test
public void test_sqlApplyPaging_offsetLimit() {
assertEquals(
"SELECT foo FROM bar WHERE TRUE ORDER BY foo OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY ",
_helper.sqlApplyPaging("SELECT foo FROM bar WHERE TRUE ", "ORDER BY foo ", new PagingRequest(3, 20)));
}
}
|
package se.sics.cooja;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.dialogs.CreateSimDialog;
/**
* A simulation consists of a number of motes and mote types.
*
* A simulation is observable:
* changed simulation state, added or deleted motes etc are observed.
* To track mote changes, observe the mote (interfaces) itself.
*
* @author Fredrik Osterlind
*/
public class Simulation extends Observable implements Runnable {
public static final long MICROSECOND = 1L;
public static final long MILLISECOND = 1000*MICROSECOND;
/*private static long EVENT_COUNTER = 0;*/
private Vector<Mote> motes = new Vector<Mote>();
private Vector<Mote> motesUninit = new Vector<Mote>();
private Vector<MoteType> moteTypes = new Vector<MoteType>();
/* If true, run simulation at full speed */
private boolean speedLimitNone = true;
/* Limit simulation speed to maxSpeed; if maxSpeed is 1.0 simulation is run at real-time speed */
private double speedLimit;
/* Used to restrict simulation speed */
private long speedLimitLastSimtime;
private long speedLimitLastRealtime;
private long currentSimulationTime = 0;
private String title = null;
private RadioMedium currentRadioMedium = null;
private static Logger logger = Logger.getLogger(Simulation.class);
private boolean isRunning = false;
private boolean stopSimulation = false;
private Thread simulationThread = null;
private GUI myGUI = null;
private long randomSeed = 123456;
private boolean randomSeedGenerated = false;
private long maxMoteStartupDelay = 1000*MILLISECOND;
private Random randomGenerator = new Random();
private boolean hasMillisecondObservers = false;
private MillisecondObservable millisecondObservable = new MillisecondObservable();
private class MillisecondObservable extends Observable {
private void newMillisecond(long time) {
setChanged();
notifyObservers(time);
}
}
/* Event queue */
private EventQueue eventQueue = new EventQueue();
/* Poll requests */
private boolean hasPollRequests = false;
private ArrayDeque<Runnable> pollRequests = new ArrayDeque<Runnable>();
/**
* Request poll from simulation thread.
* Poll requests are prioritized over simulation events, and are
* executed between each simulation event.
*
* @param r Simulation thread action
*/
public void invokeSimulationThread(Runnable r) {
synchronized (pollRequests) {
pollRequests.addLast(r);
hasPollRequests = true;
}
}
private Runnable popSimulationInvokes() {
Runnable r;
synchronized (pollRequests) {
r = pollRequests.pop();
hasPollRequests = !pollRequests.isEmpty();
}
return r;
}
/**
* Add millisecond observer.
* This observer is notified once every simulated millisecond.
*
* @see #deleteMillisecondObserver(Observer)
* @param newObserver Observer
*/
public void addMillisecondObserver(Observer newObserver) {
millisecondObservable.addObserver(newObserver);
hasMillisecondObservers = true;
invokeSimulationThread(new Runnable() {
public void run() {
if (!millisecondEvent.isScheduled()) {
scheduleEvent(
millisecondEvent,
currentSimulationTime - (currentSimulationTime % MILLISECOND) + MILLISECOND);
}
}
});
}
/**
* Delete millisecond observer.
*
* @see #addMillisecondObserver(Observer)
* @param observer Observer to delete
*/
public void deleteMillisecondObserver(Observer observer) {
millisecondObservable.deleteObserver(observer);
hasMillisecondObservers = millisecondObservable.countObservers() > 0;
}
/**
* @return True iff current thread is the simulation thread
*/
public boolean isSimulationThread() {
return simulationThread == Thread.currentThread();
}
/**
* Schedule simulation event for given time.
* Already scheduled events must be removed before they are rescheduled.
*
* If the simulation is running, this method may only be called from the simulation thread.
*
* @see #invokeSimulationThread(Runnable)
*
* @param e Event
* @param time Execution time
*/
public void scheduleEvent(final TimeEvent e, final long time) {
if (isRunning) {
/* TODO Strict scheduling from simulation thread */
assert isSimulationThread() : "Scheduling event from non-simulation thread: " + e;
}
eventQueue.addEvent(e, time);
}
private TimeEvent delayEvent = new TimeEvent(0) {
public void execute(long t) {
if (speedLimitNone) {
/* As fast as possible: no need to reschedule delay event */
return;
}
long diffSimtime = (getSimulationTime() - speedLimitLastSimtime)/1000;
long diffRealtime = System.currentTimeMillis() - speedLimitLastRealtime;
long expectedDiffRealtime = (long) (diffSimtime/speedLimit);
long sleep = expectedDiffRealtime - diffRealtime;
if (sleep >= 0) {
/* Slow down simulation */
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
scheduleEvent(this, t+MILLISECOND);
} else {
/* Reduce slow-down: execute this delay event less often */
scheduleEvent(this, t-sleep*MILLISECOND);
}
/* Update counters every second */
if (diffRealtime > 1000) {
speedLimitLastRealtime = System.currentTimeMillis();
speedLimitLastSimtime = getSimulationTime();
}
}
public String toString() {
return "DELAY";
}
};
private TimeEvent millisecondEvent = new TimeEvent(0) {
public void execute(long t) {
if (!hasMillisecondObservers) {
return;
}
millisecondObservable.newMillisecond(getSimulationTime());
scheduleEvent(this, t+MILLISECOND);
}
public String toString() {
return "MILLISECOND: " + millisecondObservable.countObservers();
}
};
public void clearEvents() {
eventQueue.removeAll();
pollRequests.clear();
}
public void run() {
long lastStartTime = System.currentTimeMillis();
logger.info("Simulation main loop started, system time: " + lastStartTime);
isRunning = true;
speedLimitLastRealtime = System.currentTimeMillis();
speedLimitLastSimtime = getSimulationTime();
/* Simulation starting */
this.setChanged();
this.notifyObservers(this);
TimeEvent nextEvent = null;
try {
while (isRunning) {
/* Handle all poll requests */
while (hasPollRequests) {
popSimulationInvokes().run();
}
/* Handle one simulation event, and update simulation time */
nextEvent = eventQueue.popFirst();
if (nextEvent == null) {
throw new RuntimeException("No more events");
}
if (nextEvent.time < currentSimulationTime) {
throw new RuntimeException("Next event is in the past: " + nextEvent.time + " < " + currentSimulationTime + ": " + nextEvent);
}
currentSimulationTime = nextEvent.time;
/*logger.info("Executing event #" + EVENT_COUNTER++ + " @ " + currentSimulationTime + ": " + nextEvent);*/
nextEvent.execute(currentSimulationTime);
if (stopSimulation) {
isRunning = false;
}
}
} catch (RuntimeException e) {
if ("MSPSim requested simulation stop".equals(e.getMessage())) {
/* XXX Should be*/
logger.info("Simulation stopped due to MSPSim breakpoint");
} else {
logger.fatal("Simulation stopped due to error: " + e.getMessage(), e);
if (!GUI.isVisualized()) {
/* Quit simulator if in test mode */
System.exit(1);
} else {
String title = "Simulation error";
if (nextEvent instanceof MoteTimeEvent) {
title += ": " + ((MoteTimeEvent)nextEvent).getMote();
}
GUI.showErrorDialog(GUI.getTopParentContainer(), title, e, false);
}
}
}
isRunning = false;
simulationThread = null;
stopSimulation = false;
this.setChanged();
this.notifyObservers(this);
logger.info("Simulation main loop stopped, system time: " + System.currentTimeMillis() +
"\tDuration: " + (System.currentTimeMillis() - lastStartTime) +
" ms" +
"\tSimulated time " + getSimulationTimeMillis() +
" ms\tRatio " +
((double)getSimulationTimeMillis() /
(double)(System.currentTimeMillis() - lastStartTime)));
}
/**
* Creates a new simulation
*/
public Simulation(GUI gui) {
myGUI = gui;
}
/**
* Starts this simulation (notifies observers).
*/
public void startSimulation() {
if (!isRunning()) {
isRunning = true;
simulationThread = new Thread(this);
simulationThread.setPriority(Thread.MIN_PRIORITY);
simulationThread.start();
}
}
/**
* Stop simulation
*
* @param block Block until simulation has stopped, with timeout (100ms)
*
* @see #stopSimulation()
*/
public void stopSimulation(boolean block) {
if (!isRunning()) {
return;
}
stopSimulation = true;
if (block) {
if (Thread.currentThread() == simulationThread) {
return;
}
/* Wait until simulation stops */
try {
Thread simThread = simulationThread;
if (simThread != null) {
simThread.join(100);
}
} catch (InterruptedException e) {
}
}
}
/**
* Stop simulation (blocks).
* Calls stopSimulation(true).
*
* @see #stopSimulation(boolean)
*/
public void stopSimulation() {
stopSimulation(true);
}
/**
* Starts simulation if stopped, executes one millisecond, and finally stops
* simulation again.
*/
public void stepMillisecondSimulation() {
if (isRunning()) {
return;
}
TimeEvent stopEvent = new TimeEvent(0) {
public void execute(long t) {
/* Stop simulation */
stopSimulation();
}
};
scheduleEvent(stopEvent, getSimulationTime()+Simulation.MILLISECOND);
startSimulation();
}
/**
* @return GUI holding this simulation
*/
public GUI getGUI() {
return myGUI;
}
/**
* @return Random seed
*/
public long getRandomSeed() {
return randomSeed;
}
/**
* @return Random seed (converted to a string)
*/
public String getRandomSeedString() {
return Long.toString(randomSeed);
}
/**
* @param randomSeed Random seed
*/
public void setRandomSeed(long randomSeed) {
this.randomSeed = randomSeed;
randomGenerator.setSeed(randomSeed);
logger.info("Simulation random seed: " + randomSeed);
}
/**
* @param generated Autogenerated random seed at simulation load
*/
public void setRandomSeedGenerated(boolean generated) {
this.randomSeedGenerated = generated;
}
/**
* @return Autogenerated random seed at simulation load
*/
public boolean getRandomSeedGenerated() {
return randomSeedGenerated;
}
public Random getRandomGenerator() {
return randomGenerator;
}
/**
* @return Maximum mote startup delay
*/
public long getDelayedMoteStartupTime() {
return maxMoteStartupDelay;
}
/**
* @param maxMoteStartupDelay Maximum mote startup delay
*/
public void setDelayedMoteStartupTime(long maxMoteStartupDelay) {
this.maxMoteStartupDelay = Math.max(0, maxMoteStartupDelay);
}
private SimEventCentral eventCentral = new SimEventCentral(this);
public SimEventCentral getEventCentral() {
return eventCentral;
}
/**
* Returns the current simulation config represented by XML elements. This
* config also includes the current radio medium, all mote types and motes.
*
* @return Current simulation config
*/
public Collection<Element> getConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
// Title
element = new Element("title");
element.setText(title);
config.add(element);
/* Max simulation speed */
if (!speedLimitNone) {
element = new Element("speedlimit");
element.setText("" + getSpeedLimit());
config.add(element);
}
// Random seed
element = new Element("randomseed");
if (randomSeedGenerated) {
element.setText("generated");
} else {
element.setText(Long.toString(getRandomSeed()));
}
config.add(element);
// Max mote startup delay
element = new Element("motedelay_us");
element.setText(Long.toString(maxMoteStartupDelay));
config.add(element);
// Radio Medium
element = new Element("radiomedium");
element.setText(currentRadioMedium.getClass().getName());
Collection<Element> radioMediumXML = currentRadioMedium.getConfigXML();
if (radioMediumXML != null) {
element.addContent(radioMediumXML);
}
config.add(element);
/* Event central */
element = new Element("events");
element.addContent(eventCentral.getConfigXML());
config.add(element);
// Mote types
for (MoteType moteType : getMoteTypes()) {
element = new Element("motetype");
element.setText(moteType.getClass().getName());
Collection<Element> moteTypeXML = moteType.getConfigXML(this);
if (moteTypeXML != null) {
element.addContent(moteTypeXML);
}
config.add(element);
}
// Motes
for (Mote mote : motes) {
element = new Element("mote");
Collection<Element> moteConfig = mote.getConfigXML();
if (moteConfig == null) {
moteConfig = new ArrayList<Element>();
}
/* Add mote type identifier */
Element typeIdentifier = new Element("motetype_identifier");
typeIdentifier.setText(mote.getType().getIdentifier());
moteConfig.add(typeIdentifier);
element.addContent(moteConfig);
config.add(element);
}
return config;
}
/**
* Sets the current simulation config depending on the given configuration.
*
* @param configXML Simulation configuration
* @param visAvailable True if simulation is allowed to show visualizers
* @param manualRandomSeed Simulation random seed. May be null, in which case the configuration is used
* @return True if simulation was configured successfully
* @throws Exception If configuration could not be loaded
*/
public boolean setConfigXML(Collection<Element> configXML,
boolean visAvailable, Long manualRandomSeed) throws Exception {
// Parse elements
for (Element element : configXML) {
// Title
if (element.getName().equals("title")) {
title = element.getText();
}
/* Max simulation speed */
if (element.getName().equals("speedlimit")) {
String text = element.getText();
if (text.equals("null")) {
setSpeedLimit(null);
} else {
setSpeedLimit(Double.parseDouble(text));
}
}
// Random seed
if (element.getName().equals("randomseed")) {
long newSeed;
if (element.getText().equals("generated")) {
randomSeedGenerated = true;
newSeed = new Random().nextLong();
} else {
newSeed = Long.parseLong(element.getText());
}
if (manualRandomSeed != null) {
newSeed = manualRandomSeed;
}
setRandomSeed(newSeed);
}
// Max mote startup delay
if (element.getName().equals("motedelay")) {
maxMoteStartupDelay = Integer.parseInt(element.getText())*MILLISECOND;
}
if (element.getName().equals("motedelay_us")) {
maxMoteStartupDelay = Integer.parseInt(element.getText());
}
// Radio medium
if (element.getName().equals("radiomedium")) {
String radioMediumClassName = element.getText().trim();
Class<? extends RadioMedium> radioMediumClass = myGUI.tryLoadClass(
this, RadioMedium.class, radioMediumClassName);
if (radioMediumClass != null) {
// Create radio medium specified in config
try {
currentRadioMedium = RadioMedium.generateRadioMedium(radioMediumClass, this);
} catch (Exception e) {
currentRadioMedium = null;
logger.warn("Could not load radio medium class: " + radioMediumClassName);
}
}
// Show configure simulation dialog
boolean createdOK = false;
if (visAvailable) {
createdOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), this);
} else {
createdOK = true;
}
if (!createdOK) {
logger.debug("Simulation not created, aborting");
throw new Exception("Load aborted by user");
}
// Check if radio medium specific config should be applied
if (radioMediumClassName.equals(currentRadioMedium.getClass().getName())) {
currentRadioMedium.setConfigXML(element.getChildren(), visAvailable);
} else {
logger.info("Radio Medium changed - ignoring radio medium specific config");
}
}
/* Event central */
if (element.getName().equals("events")) {
eventCentral.setConfigXML(this, element.getChildren(), visAvailable);
}
// Mote type
if (element.getName().equals("motetype")) {
String moteTypeClassName = element.getText().trim();
/* Try to recreate simulation using a different mote type */
if (visAvailable) {
String[] availableMoteTypes = getGUI().getProjectConfig().getStringArrayValue("se.sics.cooja.GUI.MOTETYPES");
String newClass = (String) JOptionPane.showInputDialog(
GUI.getTopParentContainer(),
"The simulation is about to load '" + moteTypeClassName + "'\n" +
"You may try to load the simulation using a different mote type.\n",
"Loading mote type",
JOptionPane.QUESTION_MESSAGE,
null,
availableMoteTypes,
moteTypeClassName
);
if (newClass != null && !newClass.equals(moteTypeClassName)) {
logger.warn("Changing mote type class: " + moteTypeClassName + " -> " + newClass);
moteTypeClassName = newClass;
}
}
Class<? extends MoteType> moteTypeClass = myGUI.tryLoadClass(this,
MoteType.class, moteTypeClassName);
if (moteTypeClass == null) {
logger.fatal("Could not load mote type class: " + moteTypeClassName);
throw new MoteType.MoteTypeCreationException("Could not load mote type class: " + moteTypeClassName);
}
MoteType moteType = moteTypeClass.getConstructor((Class[]) null).newInstance();
boolean createdOK = moteType.setConfigXML(this, element.getChildren(),
visAvailable);
if (createdOK) {
addMoteType(moteType);
} else {
logger
.fatal("Mote type was not created: " + element.getText().trim());
throw new Exception("All mote types were not recreated");
}
}
/* Mote */
if (element.getName().equals("mote")) {
/* Read mote type identifier */
MoteType moteType = null;
for (Element subElement: (Collection<Element>) element.getChildren()) {
if (subElement.getName().equals("motetype_identifier")) {
moteType = getMoteType(subElement.getText());
if (moteType == null) {
throw new Exception("No mote type '" + subElement.getText() + "' for mote");
}
break;
}
}
if (moteType == null) {
throw new Exception("No mote type specified for mote");
}
/* Create mote using mote type */
Mote mote = moteType.generateMote(this);
if (mote.setConfigXML(this, element.getChildren(), visAvailable)) {
if (getMoteWithID(mote.getID()) != null) {
logger.warn("Ignoring duplicate mote ID: " + mote.getID());
} else {
addMote(mote);
}
} else {
logger.fatal("Mote was not created: " + element.getText().trim());
throw new Exception("All motes were not recreated");
}
}
}
if (currentRadioMedium != null) {
currentRadioMedium.simulationFinishedLoading();
}
setChanged();
notifyObservers(this);
/* Execute simulation thread events now, before simulation starts */
while (hasPollRequests) {
popSimulationInvokes().run();
}
return true;
}
/**
* Removes a mote from this simulation
*
* @param mote
* Mote to remove
*/
public void removeMote(final Mote mote) {
/* Simulation is running, remove mote in simulation loop */
Runnable removeMote = new Runnable() {
public void run() {
motes.remove(mote);
currentRadioMedium.unregisterMote(mote, Simulation.this);
/* Dispose mote interface resources */
mote.removed();
for (MoteInterface i: mote.getInterfaces().getInterfaces()) {
i.removed();
}
setChanged();
notifyObservers(mote);
/* Loop through all scheduled events.
* Delete all events associated with deleted mote. */
TimeEvent ev = eventQueue.peekFirst();
while (ev != null) {
if (ev instanceof MoteTimeEvent) {
if (((MoteTimeEvent)ev).getMote() == mote) {
ev.remove();
}
}
ev = ev.nextEvent;
}
}
};
if (!isRunning()) {
/* Simulation is stopped, remove mote immediately */
removeMote.run();
} else {
/* Remove mote from simulation thread */
invokeSimulationThread(removeMote);
}
getGUI().closeMotePlugins(mote);
}
/**
* Called to free resources used by the simulation.
* This method is called just before the simulation is removed.
*/
public void removed() {
/* Remove radio medium */
if (currentRadioMedium != null) {
currentRadioMedium.removed();
}
/* Remove all motes */
Mote[] motes = getMotes();
for (Mote m: motes) {
removeMote(m);
}
}
/**
* Adds a mote to this simulation
*
* @param mote
* Mote to add
*/
public void addMote(final Mote mote) {
Runnable addMote = new Runnable() {
public void run() {
if (mote.getInterfaces().getClock() != null) {
if (maxMoteStartupDelay > 0) {
mote.getInterfaces().getClock().setDrift(
- getSimulationTime()
- randomGenerator.nextInt((int)maxMoteStartupDelay)
);
} else {
mote.getInterfaces().getClock().setDrift(-getSimulationTime());
}
}
motes.add(mote);
motesUninit.remove(mote);
currentRadioMedium.registerMote(mote, Simulation.this);
/* Notify mote interfaces that node was added */
for (MoteInterface i: mote.getInterfaces().getInterfaces()) {
i.added();
}
setChanged();
notifyObservers(mote);
}
};
if (!isRunning()) {
/* Simulation is stopped, add mote immediately */
addMote.run();
} else {
/* Add mote from simulation thread */
invokeSimulationThread(addMote);
}
//Add to list of uninitialized motes
motesUninit.add(mote);
}
/**
* Returns simulation mote at given list position.
*
* @param pos Internal list position of mote
* @return Mote
* @see #getMotesCount()
* @see #getMoteWithID(int)
*/
public Mote getMote(int pos) {
return motes.get(pos);
}
/**
* Returns simulation with with given ID.
*
* @param id ID
* @return Mote or null
* @see Mote#getID()
*/
public Mote getMoteWithID(int id) {
for (Mote m: motes) {
if (m.getID() == id) {
return m;
}
}
return null;
}
/**
* Returns uninitialised simulation mote with with given ID.
*
* @param id ID
* @return Mote or null
* @see Mote#getID()
*/
public Mote getMoteWithIDUninit(int id) {
for (Mote m: motesUninit) {
if (m.getID() == id) {
return m;
}
}
return null;
}
/**
* Returns number of motes in this simulation.
*
* @return Number of motes
*/
public int getMotesCount() {
return motes.size();
}
/**
* Returns all motes in this simulation.
*
* @return Motes
*/
public Mote[] getMotes() {
Mote[] arr = new Mote[motes.size()];
motes.toArray(arr);
return arr;
}
/**
* Returns uninitialised motes
*
* @return Motes
*/
public Mote[] getMotesUninit() {
return motesUninit.toArray(new Mote[motesUninit.size()]);
}
/**
* Returns all mote types in simulation.
*
* @return All mote types
*/
public MoteType[] getMoteTypes() {
MoteType[] types = new MoteType[moteTypes.size()];
moteTypes.toArray(types);
return types;
}
/**
* Returns mote type with given identifier.
*
* @param identifier
* Mote type identifier
* @return Mote type or null if not found
*/
public MoteType getMoteType(String identifier) {
for (MoteType moteType : getMoteTypes()) {
if (moteType.getIdentifier().equals(identifier)) {
return moteType;
}
}
return null;
}
/**
* Adds given mote type to simulation.
*
* @param newMoteType Mote type
*/
public void addMoteType(MoteType newMoteType) {
moteTypes.add(newMoteType);
this.setChanged();
this.notifyObservers(this);
}
/**
* Remove given mote type from simulation.
*
* @param type Mote type
*/
public void removeMoteType(MoteType type) {
if (!moteTypes.contains(type)) {
logger.fatal("Mote type is not registered: " + type);
return;
}
/* Remove motes */
for (Mote m: getMotes()) {
if (m.getType() == type) {
removeMote(m);
}
}
moteTypes.remove(type);
this.setChanged();
this.notifyObservers(this);
}
/**
* Limit simulation speed to given ratio.
* This method may be called from outside the simulation thread.
* @param newSpeedLimit
*/
public void setSpeedLimit(final Double newSpeedLimit) {
invokeSimulationThread(new Runnable() {
public void run() {
if (newSpeedLimit == null) {
speedLimitNone = true;
return;
}
speedLimitNone = false;
speedLimitLastRealtime = System.currentTimeMillis();
speedLimitLastSimtime = getSimulationTime();
speedLimit = newSpeedLimit.doubleValue();
if (delayEvent.isScheduled()) {
delayEvent.remove();
}
scheduleEvent(delayEvent, currentSimulationTime);
Simulation.this.setChanged();
Simulation.this.notifyObservers(this);
}
});
}
/**
* @return Max simulation speed ratio. Returns null if no limit.
*/
public Double getSpeedLimit() {
if (speedLimitNone) {
return null;
}
return new Double(speedLimit);
}
/**
* Set simulation time to simulationTime.
*
* @param simulationTime
* New simulation time (ms)
*/
public void setSimulationTime(long simulationTime) {
currentSimulationTime = simulationTime;
this.setChanged();
this.notifyObservers(this);
}
/**
* Returns current simulation time.
*
* @return Simulation time (microseconds)
*/
public long getSimulationTime() {
return currentSimulationTime;
}
/**
* Returns current simulation time rounded to milliseconds.
*
* @see #getSimulationTime()
* @return Time rounded to milliseconds
*/
public long getSimulationTimeMillis() {
return currentSimulationTime / MILLISECOND;
}
/**
* Changes radio medium of this simulation to the given.
*
* @param radioMedium
* New radio medium
*/
public void setRadioMedium(RadioMedium radioMedium) {
// Remove current radio medium from observing motes
if (currentRadioMedium != null) {
for (int i = 0; i < motes.size(); i++) {
currentRadioMedium.unregisterMote(motes.get(i), this);
}
}
// Change current radio medium to new one
if (radioMedium == null) {
logger.fatal("Radio medium could not be created.");
return;
}
this.currentRadioMedium = radioMedium;
// Add all current motes to the new radio medium
for (int i = 0; i < motes.size(); i++) {
currentRadioMedium.registerMote(motes.get(i), this);
}
}
/**
* Get currently used radio medium.
*
* @return Currently used radio medium
*/
public RadioMedium getRadioMedium() {
return currentRadioMedium;
}
/**
* Return true is simulation is running.
*
* @return True if simulation is running
*/
public boolean isRunning() {
return isRunning && simulationThread != null;
}
/**
* Return true is simulation is runnable.
*
* @return True if simulation is runnable
*/
public boolean isRunnable() {
return isRunning || hasPollRequests || eventQueue.peekFirst() != null;
}
/**
* Get current simulation title (short description).
*
* @return Title
*/
public String getTitle() {
return title;
}
/**
* Set simulation title.
*
* @param title
* New title
*/
public void setTitle(String title) {
this.title = title;
}
}
|
package ucar.nc2.iosp.grid;
import ucar.nc2.*;
import ucar.nc2.iosp.mcidas.McIDASLookup;
import ucar.nc2.iosp.gempak.GempakLookup;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.dt.fmr.FmrcCoordSys;
import ucar.nc2.units.DateFormatter;
import ucar.nc2.util.CancelTask;
import ucar.grib.grib2.Grib2GridTableLookup;
import ucar.grib.grib1.Grib1GridTableLookup;
import ucar.unidata.util.StringUtil;
import ucar.grid.*;
import java.io.*;
import java.util.*;
/**
* Create a Netcdf File from a GridIndex
*
* @author caron
*/
public class GridIndexToNC {
/**
* logger
*/
static private org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(GridIndexToNC.class);
/**
* map of horizontal coordinate systems
*/
private Map<String,GridHorizCoordSys> hcsHash = new HashMap<String,GridHorizCoordSys>(10); // GridHorizCoordSys
/**
* date formattter
*/
private DateFormatter formatter = new DateFormatter();
/**
* debug flag
*/
private boolean debug = false;
/**
* flag for using GridParameter description for variable names
*/
private boolean useDescriptionForVariableName = true;
/**
* Make the level name
*
* @param gr grid record
* @param lookup lookup table
* @return name for the level
*/
public static String makeLevelName(GridRecord gr, GridTableLookup lookup) {
// for grib2, we need to add the layer to disambiguate
if ( lookup instanceof Grib2GridTableLookup ) {
String vname = lookup.getLevelName(gr);
return lookup.isLayer(gr)
? vname + "_layer"
: vname;
} else {
return lookup.getLevelName(gr); // GEMPAK
}
}
/**
* Get suffix name of variable if it exists
*
* @param gr grid record
* @param lookup lookup table
* @return name of the suffix, ensemble, probability, error, etc
*/
public static String makeSuffixName(GridRecord gr, GridTableLookup lookup) {
if ( ! (lookup instanceof Grib2GridTableLookup) )
return "";
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
return g2lookup.makeSuffix( gr );
}
/**
* Make the variable name
*
* @param gr grid record
* @param lookup lookup table
* @return variable name
*/
public String makeVariableName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
String suffixName = makeSuffixName(gr, lookup);
String paramName = (useDescriptionForVariableName)
? param.getDescription()
: param.getName();
paramName = (suffixName.length() == 0)
? paramName : paramName + "_" + suffixName;
paramName = (levelName.length() == 0)
? paramName : paramName + "_" + levelName;
return paramName;
}
/**
* moved to GridVariable = made sense since it knows what it is
* Make a long name for the variable
*
* @param gr grid record
* @param lookup lookup table
*
* @return long variable name
public static String makeLongName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
return (levelName.length() == 0)
? param.getDescription()
: param.getDescription() + " @ " + makeLevelName(gr, lookup);
}
*/
/**
* Fill in the netCDF file
*
* @param index grid index
* @param lookup lookup table
* @param version version of data
* @param ncfile netCDF file to fill in
* @param fmrcCoordSys forecast model run CS
* @param cancelTask cancel task
* @throws IOException Problem reading from the file
*/
public void open(GridIndex index, GridTableLookup lookup, int version,
NetcdfFile ncfile, FmrcCoordSys fmrcCoordSys,
CancelTask cancelTask)
throws IOException {
// create the HorizCoord Systems : one for each gds
List<GridDefRecord> hcsList = index.getHorizCoordSys();
boolean needGroups = (hcsList.size() > 1);
for (GridDefRecord gds : hcsList) {
Group g = null;
if (needGroups) {
g = new Group(ncfile, null, gds.getGroupName());
ncfile.addGroup(null, g);
}
// (GridDefRecord gdsIndex, String grid_name, String shape_name, Group g)
GridHorizCoordSys hcs = new GridHorizCoordSys(gds, lookup, g);
hcsHash.put(gds.getParam(GridDefRecord.GDS_KEY), hcs);
}
// run through each record
GridRecord firstRecord = null;
List<GridRecord> records = index.getGridRecords();
if (GridServiceProvider.debugOpen) {
System.out.println(" number of products = " + records.size());
}
for (GridRecord gribRecord : records) {
if (firstRecord == null)
firstRecord = gribRecord;
GridHorizCoordSys hcs = hcsHash.get(gribRecord.getGridDefRecordId());
String name = makeVariableName(gribRecord, lookup);
// combo gds, param name and level name
GridVariable pv = (GridVariable) hcs.varHash.get(name);
if (null == pv) {
String pname = lookup.getParameter(gribRecord).getDescription();
pv = new GridVariable(name, pname, hcs, lookup);
hcs.varHash.put(name, pv);
//System.out.printf("Add name=%s pname=%s%n", name, pname);
// keep track of all products with same parameter name
List<GridVariable> plist = hcs.productHash.get(pname);
if (null == plist) {
plist = new ArrayList<GridVariable>();
hcs.productHash.put(pname, plist);
}
plist.add(pv);
}
pv.addProduct(gribRecord);
}
// global stuff
ncfile.addAttribute(null, new Attribute("Conventions", "CF-1.0"));
String creator = null;
if ( lookup instanceof Grib2GridTableLookup ) {
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
creator = g2lookup.getFirstCenterName()
+ " subcenter = " + g2lookup.getFirstSubcenterId();
if (creator != null)
ncfile.addAttribute(null, new Attribute("Originating_center", creator));
String genType = g2lookup.getTypeGenProcessName(firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType));
if (null != g2lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", g2lookup.getFirstProductStatusName()));
ncfile.addAttribute(null, new Attribute("Product_Type", g2lookup.getFirstProductTypeName()));
} else if ( lookup instanceof Grib1GridTableLookup ) {
Grib1GridTableLookup g1lookup = (Grib1GridTableLookup) lookup;
creator = g1lookup.getFirstCenterName()
+ " subcenter = " + g1lookup.getFirstSubcenterId();
if (creator != null)
ncfile.addAttribute(null, new Attribute("Originating_center", creator));
String genType = g1lookup.getTypeGenProcessName(firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType));
if (null != g1lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", g1lookup.getFirstProductStatusName()));
ncfile.addAttribute(null, new Attribute("Product_Type", g1lookup.getFirstProductTypeName()));
}
// dataset discovery
ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.GRID.toString()));
if ( creator != null)
ncfile.addAttribute(null, new Attribute("creator_name", creator));
ncfile.addAttribute(null, new Attribute("file_format", lookup.getGridType()));
ncfile.addAttribute(null,
new Attribute("location", ncfile.getLocation()));
ncfile.addAttribute(null, new Attribute(
"history", "Direct read of "+ lookup.getGridType() +" into NetCDF-Java 4.0 API"));
ncfile.addAttribute(
null,
new Attribute(
_Coordinate.ModelRunDate,
formatter.toDateTimeStringISO(lookup.getFirstBaseTime())));
if (fmrcCoordSys != null) {
makeDefinedCoordSys(ncfile, lookup, fmrcCoordSys);
} else {
makeDenseCoordSys(ncfile, lookup, cancelTask);
}
if (GridServiceProvider.debugMissing) {
int count = 0;
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
for (GridVariable gv : gribvars) {
count += gv.dumpMissingSummary();
}
}
System.out.println(" total missing= " + count);
}
if (GridServiceProvider.debugMissingDetails) {
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
System.out.println("******** Horiz Coordinate= " + hcs.getGridName());
String lastVertDesc = null;
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
Collections.sort(gribvars, new CompareGridVariableByVertName());
for (GridVariable gv : gribvars) {
String vertDesc = gv.getVertName();
if (!vertDesc.equals(lastVertDesc)) {
System.out.println("---Vertical Coordinate= " + vertDesc);
lastVertDesc = vertDesc;
}
gv.dumpMissing();
}
}
}
// clean out stuff we dont need anymore
//for (GridHorizCoordSys ghcs : hcsHash.values()) {
// ghcs.empty();
}
// debugging
public GridHorizCoordSys getHorizCoordSys(GridRecord gribRecord) {
return hcsHash.get(gribRecord.getGridDefRecordId());
}
public Map<String,GridHorizCoordSys> getHorizCoordSystems() {
return hcsHash;
}
/**
* Make coordinate system without missing data - means that we
* have to make a coordinate axis for each unique set
* of time or vertical levels.
*
* @param ncfile netCDF file
* @param lookup lookup table
* @param cancelTask cancel task
* @throws IOException problem reading file
*/
private void makeDenseCoordSys(NetcdfFile ncfile, GridTableLookup lookup, CancelTask cancelTask) throws IOException {
List<GridTimeCoord> timeCoords = new ArrayList<GridTimeCoord>();
List<GridVertCoord> vertCoords = new ArrayList<GridVertCoord>();
List<GridEnsembleCoord> ensembleCoords = new ArrayList<GridEnsembleCoord>();
// loop over HorizCoordSys
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
for (GridVariable pv : gribvars) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
List<GridRecord> recordList = pv.getRecords();
GridRecord record = recordList.get(0);
String vname = makeLevelName(record, lookup);
// look to see if vertical already exists
GridVertCoord useVertCoord = null;
for (GridVertCoord gvcs : vertCoords) {
if (vname.equals(gvcs.getLevelName())) {
if (gvcs.matchLevels(recordList)) { // must have the same levels
useVertCoord = gvcs;
}
}
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(recordList, vname, lookup, hcs);
vertCoords.add(useVertCoord);
}
pv.setVertCoord(useVertCoord);
// look to see if time coord already exists
GridTimeCoord useTimeCoord = null;
for (GridTimeCoord gtc : timeCoords) {
if (gtc.matchLevels(recordList)) { // must have the same levels
useTimeCoord = gtc;
}
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(recordList, lookup);
timeCoords.add(useTimeCoord);
}
pv.setTimeCoord(useTimeCoord);
// check for ensemble members
//System.out.println( pv.getName() +" "+ pv.getParamName() );
GridEnsembleCoord useEnsembleCoord = null;
GridEnsembleCoord ensembleCoord = new GridEnsembleCoord(recordList, lookup);
for (GridEnsembleCoord gec : ensembleCoords) {
if (ensembleCoord.getNEnsembles() == gec.getNEnsembles()) {
useEnsembleCoord = gec;
break;
}
}
if (useEnsembleCoord == null) {
//useEnsembleCoord = new GridEnsembleCoord(recordList, lookup);
useEnsembleCoord = ensembleCoord;
ensembleCoords.add(useEnsembleCoord);
}
// only add ensemble dimensions
if (useEnsembleCoord.getNEnsembles() > 1)
pv.setEnsembleCoord(useEnsembleCoord);
}
//// assign time coordinate names
// find time dimensions with largest length
GridTimeCoord tcs0 = null;
int maxTimes = 0;
for (GridTimeCoord tcs : timeCoords) {
if (tcs.getNTimes() > maxTimes) {
tcs0 = tcs;
maxTimes = tcs.getNTimes();
}
}
// add time dimensions, give time dimensions unique names
int seqno = 1;
for (GridTimeCoord tcs : timeCoords) {
if (tcs != tcs0) {
tcs.setSequence(seqno++);
}
tcs.addDimensionsToNetcdfFile(ncfile, hcs.getGroup());
}
// add Ensemble dimensions, give Ensemble dimensions unique names
seqno = 0;
for (GridEnsembleCoord gec : ensembleCoords) {
gec.setSequence(seqno++);
if (gec.getNEnsembles() > 1)
gec.addDimensionsToNetcdfFile(ncfile, hcs.getGroup());
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile(ncfile);
// add vertical dimensions, give them unique names
Collections.sort(vertCoords);
int vcIndex = 0;
String listName = null;
int start = 0;
for (vcIndex = 0; vcIndex < vertCoords.size(); vcIndex++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(vcIndex);
String vname = gvcs.getLevelName();
if (listName == null) {
listName = vname; // initial
}
if (!vname.equals(listName)) {
makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup());
listName = vname;
start = vcIndex;
}
}
makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup());
// create a variable for each entry, but check for other products with same desc
// to disambiguate by vertical coord
List<List<GridVariable>> products = new ArrayList<List<GridVariable>>(hcs.productHash.values());
Collections.sort( products, new CompareGridVariableListByName());
for (List<GridVariable> plist : products) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
if (plist.size() == 1) {
GridVariable pv = plist.get(0);
Variable v;
if ( (lookup instanceof GempakLookup) || (lookup instanceof McIDASLookup )) {
v = pv.makeVariable(ncfile, hcs.getGroup(), false );
} else {
v = pv.makeVariable(ncfile, hcs.getGroup(), true);
}
ncfile.addVariable(hcs.getGroup(), v);
} else {
Collections.sort(plist, new CompareGridVariableByNumberVertLevels());
boolean isGrib2 = false;
Grib2GridTableLookup g2lookup = null;
if ( (lookup instanceof Grib2GridTableLookup) ) {
g2lookup = (Grib2GridTableLookup) lookup;
isGrib2 = true;
}
// finally, add the variables
for (int k = 0; k < plist.size(); k++) {
GridVariable pv = plist.get(k);
if (isGrib2 && ( g2lookup.isEnsemble( pv.getFirstRecord()) ||
g2lookup.isProbability( pv.getFirstRecord() ) ) ||
(lookup instanceof GempakLookup) || (lookup instanceof McIDASLookup ) ) {
ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), false));
} else {
ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), (k == 0)));
}
}
} // multipe vertical levels
} // create variable
// add coordinate variables at the end
for (GridTimeCoord tcs : timeCoords) {
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
for (GridEnsembleCoord gec : ensembleCoords) {
if (gec.getNEnsembles() > 1)
gec.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile(ncfile);
for (GridVertCoord gvcs : vertCoords) {
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
// TODO: check this, in ToolsUI it caused problems
//for (GridVertCoord gvcs : vertCoords) {
// gvcs.empty();
}
/**
* Make a vertical dimensions
*
* @param vertCoordList vertCoords all with the same name
* @param ncfile netCDF file to add to
* @param group group in ncfile
*/
private void makeVerticalDimensions(List<GridVertCoord> vertCoordList, NetcdfFile ncfile, Group group) {
// find biggest vert coord
GridVertCoord gvcs0 = null;
int maxLevels = 0;
for (GridVertCoord gvcs : vertCoordList) {
if (gvcs.getNLevels() > maxLevels) {
gvcs0 = gvcs;
maxLevels = gvcs.getNLevels();
}
}
int seqno = 1;
for (GridVertCoord gvcs : vertCoordList) {
if (gvcs != gvcs0) {
gvcs.setSequence(seqno++);
}
gvcs.addDimensionsToNetcdfFile(ncfile, group);
}
}
/**
* Make coordinate system from a Definition object
*
* @param ncfile netCDF file to add to
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @throws IOException problem reading from file
*/
private void makeDefinedCoordSys(NetcdfFile ncfile,
GridTableLookup lookup, FmrcCoordSys fmr) throws IOException {
List<GridTimeCoord> timeCoords = new ArrayList<GridTimeCoord>();
List<GridVertCoord> vertCoords = new ArrayList<GridVertCoord>();
List<GridEnsembleCoord> ensembleCoords = new ArrayList<GridEnsembleCoord>();
List<String> removeVariables = new ArrayList<String>();
// loop over HorizCoordSys
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
Set<String> keys = hcs.varHash.keySet();
for (String key : keys) {
GridVariable pv = hcs.varHash.get(key);
GridRecord record = pv.getFirstRecord();
// we dont know the name for sure yet, so have to try several
String searchName = findVariableName(ncfile, record, lookup, fmr);
if (searchName == null) { // cant find - just remove
removeVariables.add(key); // cant remove (concurrentModException) so save for later
continue;
}
pv.setVarName( searchName);
// get the vertical coordinate for this variable, if it exists
FmrcCoordSys.VertCoord vc_def = fmr.findVertCoordForVariable( searchName);
if (vc_def != null) {
String vc_name = vc_def.getName();
// look to see if GridVertCoord already made
GridVertCoord useVertCoord = null;
for (GridVertCoord gvcs : vertCoords) {
if (vc_name.equals(gvcs.getLevelName()))
useVertCoord = gvcs;
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(record, vc_name, lookup, vc_def.getValues1(), vc_def.getValues2());
useVertCoord.addDimensionsToNetcdfFile( ncfile, hcs.getGroup());
vertCoords.add( useVertCoord);
}
pv.setVertCoord( useVertCoord);
} else {
pv.setVertCoord( new GridVertCoord(searchName)); // fake
}
// get the time coordinate for this variable
FmrcCoordSys.TimeCoord tc_def = fmr.findTimeCoordForVariable( searchName, lookup.getFirstBaseTime());
String tc_name = tc_def.getName();
// look to see if GridTimeCoord already made
GridTimeCoord useTimeCoord = null;
for (GridTimeCoord gtc : timeCoords) {
if (tc_name.equals(gtc.getName()))
useTimeCoord = gtc;
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(tc_name, tc_def.getOffsetHours(), lookup);
useTimeCoord.addDimensionsToNetcdfFile( ncfile, hcs.getGroup());
timeCoords.add( useTimeCoord);
}
pv.setTimeCoord( useTimeCoord);
// check for ensemble members
//System.out.println( pv.getName() +" "+ pv.getParamName() );
GridEnsembleCoord useEnsembleCoord = null;
GridEnsembleCoord ensembleCoord = new GridEnsembleCoord(record, lookup);
for (GridEnsembleCoord gec : ensembleCoords) {
if (ensembleCoord.getNEnsembles() == gec.getNEnsembles()) {
useEnsembleCoord = gec;
break;
}
}
if (useEnsembleCoord == null) {
useEnsembleCoord = ensembleCoord;
ensembleCoords.add(useEnsembleCoord);
}
// only add ensemble dimensions
if (useEnsembleCoord.getNEnsembles() > 1)
pv.setEnsembleCoord(useEnsembleCoord);
}
// any need to be removed?
for (String key : removeVariables) {
hcs.varHash.remove(key);
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile( ncfile);
// create a variable for each entry
Collection<GridVariable> vars = hcs.varHash.values();
for (GridVariable pv : vars) {
Group g = hcs.getGroup() == null ? ncfile.getRootGroup() : hcs.getGroup();
Variable v = pv.makeVariable(ncfile, g, true);
if (g.findVariable( v.getShortName()) != null) { // already got. can happen when a new vert level is added
logger.warn("GribGridServiceProvider.GridIndexToNC: FmrcCoordSys has 2 variables mapped to ="+v.getShortName()+
" for file "+ncfile.getLocation());
} else
g.addVariable( v);
}
// add coordinate variables at the end
for (GridTimeCoord tcs : timeCoords) {
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
for (GridEnsembleCoord gec : ensembleCoords) {
if (gec.getNEnsembles() > 1)
gec.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile( ncfile);
for (GridVertCoord gvcs : vertCoords) {
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
if (debug) System.out.println("GridIndexToNC.makeDefinedCoordSys for "+ncfile.getLocation());
}
/**
* Find the variable name for the grid
*
* @param ncfile netCDF file
* @param gr grid record
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @return name for the grid
*
private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) {
// first lookup with name & vert name
String name = AbstractIOServiceProvider.createValidNetcdfObjectName(makeVariableName(gr, lookup));
if (fmr.hasVariable(name)) {
return name;
}
// now try just the name
String pname = AbstractIOServiceProvider.createValidNetcdfObjectName( lookup.getParameter(gr).getDescription());
if (fmr.hasVariable(pname)) {
return pname;
}
logger.warn( "GridIndexToNC: FmrcCoordSys does not have the variable named ="
+ name + " or " + pname + " for file " + ncfile.getLocation());
return null;
} */
private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) {
// first lookup with name & vert name
String name = makeVariableName(gr, lookup);
if (debug)
System.out.println( "name ="+ name );
if (fmr.hasVariable( name))
return name;
// now try just the name
String pname = lookup.getParameter(gr).getDescription();
if (debug)
System.out.println( "pname ="+ pname );
if (fmr.hasVariable( pname))
return pname;
// try replacing the blanks
String nameWunder = StringUtil.replace(name, ' ', "_");
if (debug)
System.out.println( "nameWunder ="+ nameWunder );
if (fmr.hasVariable( nameWunder))
return nameWunder;
String pnameWunder = StringUtil.replace(pname, ' ', "_");
if (debug)
System.out.println( "pnameWunder ="+ pnameWunder );
if (fmr.hasVariable( pnameWunder))
return pnameWunder;
logger.warn("GridServiceProvider.GridIndexToNC: FmrcCoordSys does not have the variable named ="+name+" or "+pname+" or "+
nameWunder+" or "+pnameWunder+" for file "+ncfile.getLocation());
return null;
}
/**
* Comparable object for grid variable
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableListByName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
ArrayList list1 = (ArrayList) o1;
ArrayList list2 = (ArrayList) o2;
GridVariable gv1 = (GridVariable) list1.get(0);
GridVariable gv2 = (GridVariable) list2.get(0);
return gv1.getName().compareToIgnoreCase(gv2.getName());
}
}
/**
* Comparator for grids by vertical variable name
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByVertName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
return gv1.getVertName().compareToIgnoreCase(gv2.getVertName());
}
}
/**
* Comparator for grid variables by number of vertical levels
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByNumberVertLevels implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
int n1 = gv1.getVertCoord().getNLevels();
int n2 = gv2.getVertCoord().getNLevels();
if (n1 == n2) { // break ties for consistency
return gv1.getVertCoord().getLevelName().compareTo(
gv2.getVertCoord().getLevelName());
} else {
return n2 - n1; // highest number first
}
}
}
/**
* Should use the description for the variable name.
*
* @param value false to use name instead of description
*/
public void setUseDescriptionForVariableName(boolean value) {
useDescriptionForVariableName = value;
}
}
|
package ru.job4j.condition;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public boolean is(int a, int b) {
return this.y == this.x * a + b;
}
}
|
package ru.job4j.condition;
/**.
* Class for point and calculate point element of some function.
* @author dpopov93 (mailto:d.popov93@mail.ru)
* @since 04.05.2017
* @version 1.0
*/
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public boolean is(int a, int b) {
return (this.y == (a * this.x + b));
}
}
|
package ru.job4j;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
/**.
* Chapter_002
* Test for task 5.4
*
* @author Anton Vasilyuk
* @version 1.0
* @since 0.1
*/
public class ShapeTest {
/**.
* method for write print
* @param fileName name file
* @return string from file
*/
private static String readUsingScanner(String fileName) throws IOException {
Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());
String data = scanner.useDelimiter("\\A").next();
scanner.close();
return data;
}
/**.
* Test method pic for square
*/
@Test
public void whenNeedBuildSquareThenWeBuildSquare() {
int height = 3;
Square square = new Square(height);
String fact = square.pic();
String expect = "w w w \nw w w \nw w w \n";
assertThat(fact, is(expect));
}
/**.
* Test method pic for triangle
*/
@Test
public void whenNeedBuildTriangleThenWeBuildTriangle() {
int height = 3;
Triangle triangle = new Triangle(height);
String fact = triangle.pic();
String expect = "w \nw w \nw w w \n";
assertThat(fact, is(expect));
}
/**.
* Test method draw for square
*/
@Test
public void whenNeedPrintingSquareThenWePrintSquare() throws Exception {
int height = 3;
Paint paint = new Paint();
Square square = new Square(height);
FileOutputStream f = new FileOutputStream("file.txt") ;
System.setOut(new PrintStream(f));
paint.draw(square);
String fact = readUsingScanner("file.txt");
String expect = "w w w \nw w w \nw w w \n\r\n";
assertThat(fact, is(expect));
}
/**.
* Test method draw for Triangle
*/
@Test
public void whenNeedPrintingTriangleThenWePrintTriangle() throws Exception {
int height = 3;
Paint paint = new Paint();
Triangle triangle = new Triangle(height);
FileOutputStream f = new FileOutputStream("file.txt") ;
System.setOut(new PrintStream(f));
paint.draw(triangle);
String expect = "w \nw w \nw w w \n\r\n";
String fact = readUsingScanner("file.txt");
assertThat(fact, is(expect));
}
}
|
package ru.job4j.Users;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ThreadSafe
public class UserStore {
@GuardedBy("this")
private ConcurrentMap<Integer, User> users = new ConcurrentHashMap<>();
public void add(User user) {
users.putIfAbsent(user.getId(), user);
}
public void update(User user) {
users.putIfAbsent(user.getId(), user);
}
public void delete(User user) {
users.remove(user.getId());
}
public void transfer(int id1, int id2, int amount) {
User us1 = users.get(id1);
User us2 = users.get(id2);
synchronized (us1) {
synchronized (us2) {
us1.changeAmount(-amount);
us2.changeAmount(amount);
}
}
}
}
|
package com.opengamma.sesame.sabr;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.google.common.collect.ImmutableMap;
import com.opengamma.core.config.Config;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.util.result.FailureStatus;
import com.opengamma.util.result.Result;
import org.joda.beans.Bean;
import org.joda.beans.impl.direct.DirectMetaProperty;
/**
* Responsible for determining what SABR data is required for
* the trade/security that is passed. Contains a map from
* security to the SABR config to be used.
*/
@BeanDefinition
@Config(group = "SABR Params", description = "SABR Config Selector")
public class SabrConfigSelector implements ImmutableBean {
@PropertyDefinition
private final Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig> _configurations;
/**
* Get the SABR config to use for a particular security.
*
* @param security the security to find the config for
* @return Result containing the configuration to use
* if available, a FailureResult otherwise
*/
public Result<SabrParametersConfiguration> getSabrConfig(FinancialSecurity security) {
if (_configurations.containsKey(security.getClass())) {
SabrSwaptionConfig config = _configurations.get(security.getClass());
return config.createSABRParametersConfig((SwaptionSecurity) security);
} else {
return Result.failure(
FailureStatus.MISSING_DATA, "Unable to get SABR config for security of type: {}", security.getClass());
}
}
///CLOVER:OFF
/**
* The meta-bean for {@code SabrConfigSelector}.
* @return the meta-bean, not null
*/
public static SabrConfigSelector.Meta meta() {
return SabrConfigSelector.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(SabrConfigSelector.Meta.INSTANCE);
}
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static SabrConfigSelector.Builder builder() {
return new SabrConfigSelector.Builder();
}
/**
* Restricted constructor.
* @param builder the builder to copy from, not null
*/
protected SabrConfigSelector(SabrConfigSelector.Builder builder) {
this._configurations = (builder._configurations != null ? ImmutableMap.copyOf(builder._configurations) : null);
}
@Override
public SabrConfigSelector.Meta metaBean() {
return SabrConfigSelector.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
/**
* Gets the configurations.
* @return the value of the property
*/
public Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig> getConfigurations() {
return _configurations;
}
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
@Override
public SabrConfigSelector clone() {
return this;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
SabrConfigSelector other = (SabrConfigSelector) obj;
return JodaBeanUtils.equal(getConfigurations(), other.getConfigurations());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash += hash * 31 + JodaBeanUtils.hashCode(getConfigurations());
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(64);
buf.append("SabrConfigSelector{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
protected void toString(StringBuilder buf) {
buf.append("configurations").append('=').append(JodaBeanUtils.toString(getConfigurations())).append(',').append(' ');
}
/**
* The meta-bean for {@code SabrConfigSelector}.
*/
public static class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code configurations} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig>> _configurations = DirectMetaProperty.ofImmutable(
this, "configurations", SabrConfigSelector.class, (Class) Map.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"configurations");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -214226371: // configurations
return _configurations;
}
return super.metaPropertyGet(propertyName);
}
@Override
public SabrConfigSelector.Builder builder() {
return new SabrConfigSelector.Builder();
}
@Override
public Class<? extends SabrConfigSelector> beanType() {
return SabrConfigSelector.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
/**
* The meta-property for the {@code configurations} property.
* @return the meta-property, not null
*/
public final MetaProperty<Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig>> configurations() {
return _configurations;
}
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -214226371: // configurations
return ((SabrConfigSelector) bean).getConfigurations();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
/**
* The bean-builder for {@code SabrConfigSelector}.
*/
public static class Builder extends DirectFieldsBeanBuilder<SabrConfigSelector> {
private Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig> _configurations;
/**
* Restricted constructor.
*/
protected Builder() {
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
protected Builder(SabrConfigSelector beanToCopy) {
this._configurations = (beanToCopy.getConfigurations() != null ? new HashMap<Class<? extends FinancialSecurity>, SabrSwaptionConfig>(beanToCopy.getConfigurations()) : null);
}
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case -214226371: // configurations
return _configurations;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@SuppressWarnings("unchecked")
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case -214226371: // configurations
this._configurations = (Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig>) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.set(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public SabrConfigSelector build() {
return new SabrConfigSelector(this);
}
/**
* Sets the {@code configurations} property in the builder.
* @param configurations the new value
* @return this, for chaining, not null
*/
public Builder configurations(Map<Class<? extends FinancialSecurity>, SabrSwaptionConfig> configurations) {
this._configurations = configurations;
return this;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(64);
buf.append("SabrConfigSelector.Builder{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
protected void toString(StringBuilder buf) {
buf.append("configurations").append('=').append(JodaBeanUtils.toString(_configurations)).append(',').append(' ');
}
}
///CLOVER:ON
}
|
package com.shc.silenceengine.utils.functional;
/**
* @author Sri Harsha Chilakapati
*/
public class Promise<T>
{
public State state = State.PENDING;
public T value;
private Promise<T> next;
private Throwable throwable;
private UniCallback<T> onFulfilled;
private UniCallback<Throwable> onRejected;
public Promise()
{
this((resolve, reject) ->
{
});
}
public Promise(BiCallback<UniCallback<T>, UniCallback<Throwable>> function)
{
this((self, resolve, reject) -> function.invoke(resolve, reject));
}
public Promise(TriCallback<Promise<T>, UniCallback<T>, UniCallback<Throwable>> function)
{
try
{
function.invoke(this, this::resolve, this::reject);
}
catch (Throwable throwable)
{
reject(throwable);
}
}
private Promise(UniCallback<T> onFulfilled, UniCallback<Throwable> onRejected)
{
this.onFulfilled = onFulfilled;
this.onRejected = onRejected;
}
public static Promise<Void> all(Promise<?>... promises)
{
return new Promise<>((resolve, reject) ->
{
final int[] done = { 0 };
for (Promise<?> promise : promises)
promise.then(v ->
{
done[0]++;
if (done[0] == promises.length)
resolve.invoke(null);
}, reject);
});
}
public static Promise<Void> race(Promise<?>... promises)
{
return new Promise<>((self, resolve, reject) ->
{
for (Promise<?> promise : promises)
promise.then(v ->
{
if (self.state != State.REJECTED)
resolve.invoke(null);
}, reject);
});
}
public synchronized void resolve(T value)
{
if (state == State.FULFILLED)
throw new PromiseException("Cannot resolve more than once");
if (state == State.REJECTED)
throw new PromiseException("Cannot resolve an already rejected promise");
this.value = value;
this.state = State.FULFILLED;
if (onFulfilled != null)
onFulfilled.invoke(value);
if (next != null)
next.resolve(value);
}
public synchronized void reject(Throwable throwable)
{
if (state == State.REJECTED)
throw new PromiseException("Cannot reject more than once");
if (state == State.FULFILLED)
throw new PromiseException("Cannot resolve an already fulfilled promise");
this.value = null;
this.state = State.REJECTED;
this.throwable = throwable;
if (onRejected != null)
onRejected.invoke(throwable);
if (next != null)
next.reject(throwable);
}
public synchronized Promise<T> then(UniCallback<T> onFulfilled, UniCallback<Throwable> onRejected)
{
if (next != null)
return next.then(onFulfilled, onRejected);
next = new Promise<>(onFulfilled, onRejected);
switch (state)
{
case REJECTED:
next.reject(throwable);
break;
case FULFILLED:
next.resolve(value);
break;
}
return next;
}
public synchronized Promise<T> then(UniCallback<T> onFulfilled)
{
return then(onFulfilled, t ->
{
});
}
public synchronized Promise<T> whenThrown(UniCallback<Throwable> onThrown)
{
return then(v ->
{
}, onThrown);
}
public enum State
{
PENDING, FULFILLED, REJECTED
}
public static class PromiseException extends RuntimeException
{
public PromiseException(String message)
{
super(message);
}
public PromiseException()
{
}
}
}
|
package org.slc.sli.api.security.saml2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.KeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXParameters;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.xml.crypto.AlgorithmMethod;
import javax.xml.crypto.KeySelector;
import javax.xml.crypto.KeySelectorException;
import javax.xml.crypto.KeySelectorResult;
import javax.xml.crypto.MarshalException;
import javax.xml.crypto.XMLCryptoContext;
import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* A basic implementation of a SAML2 validator. This is based on OpenAM
* as it was configured on 2/16/2012.
*/
@Component
public class DefaultSAML2Validator implements SAML2Validator {
private static final Logger LOG = LoggerFactory.getLogger(DefaultSAML2Validator.class);
private DOMValidateContext valContext;
/**
* Pulls the <Signature> tag from the SAML assertion document.
*
* @param samlDocument
* Document containing SAML assertion.
* @return Node representing the Signature block from the SAML assertion.
*/
private Node getSignatureElement(Document samlDocument) {
return samlDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0);
}
/**
* Creates a DOM validator for the SAML assertion document.
*
* @param samlDocument
* Document containing SAML assertion.
*/
private void createContext(Document samlDocument) {
this.valContext = new DOMValidateContext(new KeyValueKeySelector(), getSignatureElement(samlDocument));
}
/**
* Unmarshals the XML signature from the SAML assertion document.
*
* @param samlDocument
* Document containing SAML assertion.
* @return XML Signature element.
* @throws MarshalException
* thrown if an issue occurs during unmarshalling process.
*/
private XMLSignature getSignature(Document samlDocument) throws MarshalException {
createContext(samlDocument);
XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
return factory.unmarshalXMLSignature(valContext);
}
/**
* Checks that the specified signature value maps to a trusted Certificate Authority (in
* ${JAVA_HOME}/lib/security/cacerts).
*
* @param signature
* xml signature (contains KeyInfo, SignatureValue, and SignedInfo)
* @return boolean indicating whether the signature corresponds to a trusted certificate
* authority
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
private boolean isSignatureTrusted(XMLSignature signature) throws KeyStoreException,
InvalidAlgorithmParameterException, CertificateException, NoSuchAlgorithmException {
boolean trusted = false;
X509Certificate certificate = null;
@SuppressWarnings("unchecked")
List<XMLStructure> keyInfoContext = signature.getKeyInfo().getContent();
for (XMLStructure xmlStructure : keyInfoContext) {
if (xmlStructure instanceof X509Data) {
X509Data xd = (X509Data) xmlStructure;
@SuppressWarnings("unchecked")
Iterator<Object> data = xd.getContent().iterator();
while (data.hasNext()) {
Object nextElement = data.next();
if (nextElement instanceof X509Certificate) {
certificate = (X509Certificate) nextElement;
break;
}
}
}
}
if (certificate != null) {
KeyStore cacerts = loadCaCerts();
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
CertPath certPath = certFactory.generateCertPath(Arrays.asList(certificate));
CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
try {
certPathValidator.validate(certPath, params);
trusted = true;
LOG.debug("X509 Certificate is trusted.");
} catch (CertPathValidatorException e) {
LOG.error("X509 Certificate is not trusted.");
}
} else {
LOG.error("X509 Certificate is null --> no trust can be established.");
}
return trusted;
}
/**
* Loads the 'cacerts' Certificate Authority keystore.
*
* @return KeyStore containing trusted certificate authorities.
*/
private KeyStore loadCaCerts() {
KeyStore cacerts = null;
FileInputStream fis = null;
try {
cacerts = KeyStore.getInstance("JKS");
fis = new FileInputStream(new File(System.getProperty("java.home"), "lib/security/cacerts"));
cacerts.load(fis, null);
} catch (NoSuchAlgorithmException e) {
LOG.warn("Requested cryptographic algorithm is invalid or unavailable in the current environment", e);
} catch (CertificateException e) {
LOG.warn("There is an issue with the X509 Certificate", e);
} catch (FileNotFoundException e) {
LOG.warn("Trusted Certificate Authority store was not found", e);
} catch (IOException e) {
LOG.warn("There was an issue opening the trusted Certificate Authority store", e);
} catch (KeyStoreException e) {
LOG.warn("There is an issue with the trusted Certificate Authority store", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
LOG.error("couldn't close stream", e);
}
}
}
return cacerts;
}
/**
* Checks that the SAML assertion is both trusted and valid.
*
* @param samlDocument
* Document containing SAML assertion.
* @return true if the SAML assertion has been signed by a trusted certificate authority, as
* well as passes validation. false, otherwise.
* @throws MarshalException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
*/
public boolean isDocumentTrustedAndValid(Document samlDocument) throws KeyStoreException,
InvalidAlgorithmParameterException, CertificateException, NoSuchAlgorithmException, MarshalException {
return isDocumentTrusted(samlDocument) && isDocumentValid(samlDocument);
}
/**
* Checks that the SAML assertion is trusted.
*
* @param samlDocument
* Document containing SAML assertion.
* @return true if the SAML assertion has been signed by a trusted certificate authority. false,
* otherwise.
* @throws MarshalException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
*/
public boolean isDocumentTrusted(Document samlDocument) throws KeyStoreException,
InvalidAlgorithmParameterException, CertificateException, NoSuchAlgorithmException, MarshalException {
return isSignatureTrusted(getSignature(samlDocument));
}
/**
* Checks that the SAML assertion is valid.
*/
@Override
public boolean isDocumentValid(Document samlDocument) {
try {
return getSignature(samlDocument).validate(valContext);
} catch (MarshalException e) {
LOG.warn("Couldn't validate Document", e);
} catch (XMLSignatureException e) {
LOG.warn("Couldn't extract XML Signature from Document", e);
}
return false;
}
@Override
public boolean isSignatureValid(Document samlDocument) {
try {
return getSignature(samlDocument).getSignatureValue().validate(valContext);
} catch (MarshalException e) {
LOG.warn("Couldn't validate signature", e);
} catch (XMLSignatureException e) {
LOG.warn("Couldn't validate signature", e);
}
return false;
}
@Override
public boolean isDigestValid(Document samlDocument) {
boolean valid = false;
try {
@SuppressWarnings("unchecked")
Iterator<Reference> iterator = getSignature(samlDocument).getSignedInfo().getReferences().iterator();
while (iterator.hasNext()) {
Reference ref = ((Reference) iterator.next());
valid = ref.validate(valContext);
}
} catch (XMLSignatureException e) {
LOG.warn("Couldn't validate digest", e);
} catch (MarshalException e) {
LOG.warn("Couldn't validate digest", e);
}
return valid;
}
/**
* Suggest deleting this --> functionality exists within XMLSignatureHelper class.
*/
@Override
public Document signDocumentWithSAMLSigner(Document samlDocument, SAML2Signer signer) {
return null;
}
private static class KeyValueKeySelector extends KeySelector {
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method,
XMLCryptoContext context) throws KeySelectorException {
if (keyInfo == null) {
throw new KeySelectorException("Null KeyInfo object!");
}
SignatureMethod sm = (SignatureMethod) method;
@SuppressWarnings("unchecked")
List<XMLStructure> list = keyInfo.getContent();
for (XMLStructure xmlStructure : list) {
if (xmlStructure instanceof KeyValue) {
PublicKey pk = null;
try {
pk = ((KeyValue) xmlStructure).getPublicKey();
} catch (KeyException ke) {
throw new KeySelectorException(ke);
}
// make sure algorithm is compatible with method
if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
return new SimpleKeySelectorResult(pk);
}
}
if (xmlStructure instanceof X509Data) {
X509Data xd = (X509Data) xmlStructure;
@SuppressWarnings("unchecked")
Iterator<Object> data = xd.getContent().iterator();
for (; data.hasNext();) {
Object o = data.next();
if (o instanceof X509Certificate) {
X509Certificate cert = (X509Certificate) o;
return new SimpleKeySelectorResult(cert.getPublicKey());
}
}
}
}
throw new KeySelectorException("No KeyValue element found!");
}
static boolean algEquals(String algURI, String algName) {
return (algName.equalsIgnoreCase("DSA") && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1))
|| (algName.equalsIgnoreCase("RSA") && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1));
}
public static class SimpleKeySelectorResult implements KeySelectorResult {
private Key k;
public SimpleKeySelectorResult(PublicKey k) {
this.k = k;
}
@Override
public Key getKey() {
return k;
}
}
}
}
|
package com.garpr.android.data;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.os.AsyncTask;
import com.garpr.android.App;
import com.garpr.android.misc.Utils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
abstract class AsyncReadFile<T> extends AsyncTask<Void, Void, ArrayList<T>> {
private final Callback<T> mCallback;
private Exception mException;
AsyncReadFile(final Callback<T> callback) {
mCallback = callback;
}
@Override
protected final ArrayList<T> doInBackground(final Void... params) {
InputStream stream = null;
InputStreamReader streamReader = null;
BufferedReader reader = null;
StringWriter writer = null;
ArrayList<T> list = null;
try {
final Resources resources = App.getContext().getResources();
stream = resources.openRawResource(getRawResourceId());
streamReader = new InputStreamReader(stream);
reader = new BufferedReader(streamReader);
writer = new StringWriter();
final char[] buffer = new char[4 * 1024];
int ch;
while ((ch = reader.read(buffer)) != -1) {
writer.write(buffer, 0, ch);
}
final String fileContents = writer.toString().trim();
final JSONObject json = new JSONObject(fileContents);
list = parseJSON(json);
} catch (final IOException e) {
mException = e;
} catch (final JSONException e) {
mException = e;
} catch (final NotFoundException e) {
mException = e;
} finally {
Utils.closeCloseables(writer, reader, streamReader, stream);
}
return list;
}
abstract int getRawResourceId();
abstract ArrayList<T> parseJSON(final JSONObject json);
@Override
protected final void onPostExecute(final ArrayList<T> result) {
super.onPostExecute(result);
if (!mCallback.isAlive()) {
return;
}
if (mException == null) {
if (result == null || result.isEmpty()) {
throw new IllegalStateException("AsyncReadFile had no Exception and there's no result!");
}
if (result.size() == 1) {
mCallback.response(result.get(0));
} else {
mCallback.response(result);
}
} else {
mCallback.error(mException);
}
}
final void setException(final Exception exception) {
mException = exception;
}
}
|
package com.garpr.android.data;
import com.garpr.android.misc.Console;
import com.garpr.android.misc.Heartbeat;
import com.garpr.android.misc.Utils;
import com.garpr.android.models.Region;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
public class RegionSetting extends Setting<Region> {
private static final String TAG = "RegionSetting";
private final JSONSetting mJSONSetting;
private final LinkedList<Attachment> mListeners;
RegionSetting(final String key) {
super(key);
mJSONSetting = new JSONSetting(key);
mListeners = new LinkedList<>();
}
public void attachListener(final Heartbeat heartbeat, final RegionListener listener) {
if (Utils.areAnyObjectsNull(heartbeat, listener)) {
throw new RuntimeException();
}
synchronized (mListeners) {
boolean attachListener = true;
for (int i = 0; i < mListeners.size(); ) {
final Attachment attachment = mListeners.get(i);
if (attachment.isAlive()) {
if (attachment.hasListener(listener)) {
attachListener = false;
}
++i;
} else {
mListeners.remove(i);
}
}
if (!heartbeat.isAlive()) {
Console.w(TAG, "Attempted to attach a listener with a dead heartbeat");
return;
}
if (attachListener) {
mListeners.add(new Attachment(heartbeat, listener));
}
Console.d(TAG, "There are now " + mListeners.size() + " region listener(s)");
}
}
public void detachListener(final RegionListener listener) {
synchronized (mListeners) {
for (int i = 0; i < mListeners.size(); ) {
final Attachment attachment = mListeners.get(i);
if (!attachment.isAlive() || attachment.hasListener(listener)) {
mListeners.remove(i);
} else {
++i;
}
}
Console.d(TAG, "There are now " + mListeners.size() + " region listener(s)");
}
}
@Override
public Region get() {
final JSONObject json = mJSONSetting.get();
final Region region;
if (json == null) {
region = null;
} else {
try {
region = new Region(json);
} catch (final JSONException e) {
throw new RuntimeException(e);
}
}
return region;
}
@Override
public void set(final Region newValue) {
if (newValue == null) {
throw new IllegalArgumentException("newValue can't be null");
}
final JSONObject json = newValue.toJSON();
final Region oldValue = get();
String consoleMsg = "Region is now " + json.toString();
if (oldValue != null) {
consoleMsg += " (old region was " + oldValue.toJSON().toString() + ')';
}
Console.d(TAG, consoleMsg);
mJSONSetting.set(json);
}
public void set(final Region newValue, final boolean notifyListeners) {
set(newValue);
if (notifyListeners) {
synchronized (mListeners) {
for (int i = 0; i < mListeners.size(); ) {
final Attachment attachment = mListeners.get(i);
if (attachment.isAlive()) {
attachment.onRegionChanged(newValue);
++i;
} else {
mListeners.remove(i);
}
}
}
}
}
private final static class Attachment implements Heartbeat, RegionListener {
private final WeakReference<Heartbeat> mHeartbeat;
private final WeakReference<RegionListener> mListener;
private Attachment(final Heartbeat heartbeat, final RegionListener listener) {
mHeartbeat = new WeakReference<>(heartbeat);
mListener = new WeakReference<>(listener);
}
private boolean hasListener(final RegionListener listener) {
return mListener.get() == listener;
}
@Override
public boolean isAlive() {
final Heartbeat heartbeat = mHeartbeat.get();
return heartbeat != null && heartbeat.isAlive() && mListener.get() != null;
}
@Override
public void onRegionChanged(final Region region) {
if (!isAlive()) {
return;
}
final RegionListener listener = mListener.get();
if (listener != null) {
listener.onRegionChanged(region);
}
}
}
public interface RegionListener {
void onRegionChanged(final Region region);
}
}
|
package com.intellij.testFramework.fixtures.impl;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.completion.CodeCompletionHandler;
import com.intellij.codeInsight.completion.LookupData;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.LocalInspectionsPass;
import com.intellij.codeInsight.daemon.impl.PostHighlightingPass;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.IntentionManager;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.InspectionToolProvider;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.ModifiableModel;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.InspectionTool;
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.mock.MockProgressIndicator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.RunResult;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
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.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.testFramework.ExpectedHighlightingData;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.TempDirTestFixture;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import junit.framework.TestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
* @author Dmitry Avdeev
*/
public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsightTestFixture {
@NonNls private static final String PROFILE = "Configurable";
private PsiManagerImpl myPsiManager;
private PsiFile myFile;
private Editor myEditor;
private String myTestDataPath;
private LocalInspectionTool[] myInspections;
private final Map<String, LocalInspectionTool> myAvailableTools = new THashMap<String, LocalInspectionTool>();
private final Map<String, LocalInspectionToolWrapper> myAvailableLocalTools = new THashMap<String, LocalInspectionToolWrapper>();
private final TempDirTestFixture myTempDirFixture = new TempDirTextFixtureImpl();
private final IdeaProjectTestFixture myProjectFixture;
@NonNls private static final String XXX = "XXX";
public CodeInsightTestFixtureImpl(IdeaProjectTestFixture projectFixture) {
myProjectFixture = projectFixture;
}
public void setTestDataPath(String dataPath) {
myTestDataPath = dataPath;
}
public String getTempDirPath() {
return myTempDirFixture.getTempDirPath();
}
public TempDirTestFixture getTempDirFixture() {
return myTempDirFixture;
}
public void enableInspections(LocalInspectionTool... inspections) {
myInspections = inspections;
}
public void disableInspections(LocalInspectionTool... inspections) {
myAvailableTools.clear();
myAvailableLocalTools.clear();
final ArrayList<LocalInspectionTool> tools = new ArrayList<LocalInspectionTool>(Arrays.asList(myInspections));
for (Iterator<LocalInspectionTool> i = tools.iterator(); i.hasNext();) {
final LocalInspectionTool tool = i.next();
for (LocalInspectionTool toRemove: inspections) {
if (tool.getShortName().equals(toRemove.getShortName())) {
i.remove();
break;
}
}
}
myInspections = tools.toArray(new LocalInspectionTool[tools.size()]);
configureInspections(myInspections);
}
public void enableInspections(InspectionToolProvider... providers) {
final ArrayList<LocalInspectionTool> tools = new ArrayList<LocalInspectionTool>();
for (InspectionToolProvider provider: providers) {
for (Class clazz: provider.getInspectionClasses()) {
try {
LocalInspectionTool inspection = (LocalInspectionTool)clazz.getConstructor().newInstance();
tools.add(inspection);
}
catch (Exception e) {
throw new RuntimeException("Cannot instantiate " + clazz);
}
}
}
myInspections = tools.toArray(new LocalInspectionTool[tools.size()]);
}
public long testHighlighting(final boolean checkWarnings,
final boolean checkInfos,
final boolean checkWeakWarnings,
final String... filePaths) throws Throwable {
final Ref<Long> duration = new Ref<Long>();
new WriteCommandAction.Simple(myProjectFixture.getProject()) {
protected void run() throws Throwable {
configureByFiles(filePaths);
collectAndCheckHighlightings(checkWarnings, checkInfos, checkWeakWarnings, duration);
}
}.execute().throwException();
return duration.get().longValue();
}
public long testHighlighting(final String... filePaths) throws Throwable {
return testHighlighting(true, true, true, filePaths);
}
@Nullable
public PsiReference getReferenceAtCaretPosition(final String filePath) throws Throwable {
final RunResult<PsiReference> runResult = new WriteCommandAction<PsiReference>(myProjectFixture.getProject()) {
protected void run(final Result<PsiReference> result) throws Throwable {
configureByFiles(filePath);
final int offset = myEditor.getCaretModel().getOffset();
final PsiReference psiReference = getFile().findReferenceAt(offset);
result.setResult(psiReference);
}
}.execute();
runResult.throwException();
return runResult.getResultObject();
}
@NotNull
public PsiReference getReferenceAtCaretPositionWithAssertion(final String filePath) throws Throwable {
final PsiReference reference = getReferenceAtCaretPosition(filePath);
assert reference != null: "no reference found at " + myEditor.getCaretModel().getLogicalPosition();
return reference;
}
@NotNull
public List<IntentionAction> getAvailableIntentions(final String... filePaths) throws Throwable {
final Project project = myProjectFixture.getProject();
return new WriteCommandAction<List<IntentionAction>>(project) {
protected void run(final Result<List<IntentionAction>> result) throws Throwable {
final int offset = configureByFiles(filePaths);
result.setResult(getAvailableIntentions(project, doHighlighting(), offset, myEditor, myFile));
}
}.execute().getResultObject();
}
public void launchAction(@NotNull final IntentionAction action) throws Throwable {
new WriteCommandAction(myProjectFixture.getProject()) {
protected void run(final Result result) throws Throwable {
action.invoke(getProject(), getEditor(), getFile());
}
}.execute().throwException();
}
public void testCompletion(final String[] filesBefore, final String fileAfter) throws Throwable {
new WriteCommandAction.Simple(myProjectFixture.getProject()) {
protected void run() throws Throwable {
configureByFiles(filesBefore);
new CodeCompletionHandler().invoke(getProject(), myEditor, myFile);
checkResultByFile(fileAfter, myFile, false);
}
}.execute().throwException();
}
public void testCompletion(String fileBefore, String fileAfter) throws Throwable {
testCompletion(new String[] { fileBefore }, fileAfter);
}
public void testCompletionVariants(final String fileBefore, final String... items) throws Throwable {
new WriteCommandAction.Simple(myProjectFixture.getProject()) {
protected void run() throws Throwable {
configureByFiles(fileBefore);
final Ref<LookupItem[]> myItems = Ref.create(null);
new CodeCompletionHandler(){
protected Lookup showLookup(Project project,
Editor editor,
LookupItem[] items,
String prefix,
LookupData data, PsiFile file) {
myItems.set(items);
return null;
}
}.invoke(getProject(), myEditor, myFile);
final LookupItem[] items1 = myItems.get();
UsefulTestCase.assertNotNull(items1);
UsefulTestCase.assertSameElements(ContainerUtil.map(items1, new Function<LookupItem, String>() {
public String fun(final LookupItem lookupItem) {
return lookupItem.getLookupString();
}
}), items);
}
}.execute().throwException();
}
public void testRename(final String fileBefore, final String fileAfter, final String newName) throws Throwable {
new WriteCommandAction.Simple(myProjectFixture.getProject()) {
protected void run() throws Throwable {
configureByFiles(fileBefore);
PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED);
assert element != null: "element not found at caret position, offset " + myEditor.getCaretModel().getOffset();
new RenameProcessor(myProjectFixture.getProject(), element, newName, false, false).run();
checkResultByFile(fileAfter, myFile, false);
}
}.execute().throwException();
}
@Nullable
public GutterIconRenderer findGutter(final String filePath) throws Throwable {
final Project project = myProjectFixture.getProject();
final Ref<GutterIconRenderer> result = new Ref<GutterIconRenderer>();
new WriteCommandAction.Simple(project) {
protected void run() throws Throwable {
final int offset = configureByFiles(filePath);
final Collection<HighlightInfo> infos = doHighlighting();
for (HighlightInfo info :infos) {
if (info.endOffset >= offset && info.startOffset <= offset) {
final GutterIconRenderer renderer = info.getGutterIconRenderer();
if (renderer != null) {
result.set(renderer);
return;
}
}
}
}
}.execute().throwException();
return result.get();
}
public void checkResultByFile(final String filePath) throws Throwable {
new WriteCommandAction.Simple(myProjectFixture.getProject()) {
protected void run() throws Throwable {
checkResultByFile(filePath, myFile, false);
}
}.execute().throwException();
}
public void checkResultByFile(final String filePath, final String expectedFile, final boolean ignoreWhitespaces) throws Throwable {
new WriteCommandAction.Simple(myProjectFixture.getProject()) {
protected void run() throws Throwable {
String fullPath = getTempDirPath() + "/" + filePath;
final VirtualFile copy = LocalFileSystem.getInstance().refreshAndFindFileByPath(fullPath.replace(File.separatorChar, '/'));
assert copy != null : "file not found: " + fullPath;
final PsiFile psiFile = myPsiManager.findFile(copy);
assert psiFile != null;
checkResultByFile(expectedFile, psiFile, ignoreWhitespaces);
}
}.execute().throwException();
}
public void setUp() throws Exception {
super.setUp();
final String testDataPath = getTestDataPath();
if (testDataPath != null) {
FileUtil.copyDir(new File(testDataPath), new File(getTempDirPath()), false);
}
myProjectFixture.setUp();
myPsiManager = (PsiManagerImpl)PsiManager.getInstance(getProject());
configureInspections(myInspections == null ? new LocalInspectionTool[0] : myInspections);
}
private void enableInspectionTool(LocalInspectionTool tool){
final String shortName = tool.getShortName();
final HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
if (key == null){
HighlightDisplayKey.register(shortName, tool.getDisplayName(), tool.getID());
}
myAvailableTools.put(shortName, tool);
myAvailableLocalTools.put(shortName, new LocalInspectionToolWrapper(tool));
}
private void configureInspections(final LocalInspectionTool[] tools) {
for (LocalInspectionTool tool : tools) {
enableInspectionTool(tool);
}
final InspectionProfileImpl profile = new InspectionProfileImpl(PROFILE) {
public ModifiableModel getModifiableModel() {
mySource = this;
return this;
}
public InspectionProfileEntry[] getInspectionTools() {
final Collection<LocalInspectionToolWrapper> tools = myAvailableLocalTools.values();
return tools.toArray(new LocalInspectionToolWrapper[tools.size()]);
}
public boolean isToolEnabled(HighlightDisplayKey key) {
return key != null && key.toString() != null && myAvailableTools != null && myAvailableTools.containsKey(key.toString());
}
public HighlightDisplayLevel getErrorLevel(HighlightDisplayKey key) {
final LocalInspectionTool localInspectionTool = myAvailableTools.get(key.toString());
return localInspectionTool != null ? localInspectionTool.getDefaultLevel() : HighlightDisplayLevel.WARNING;
}
public InspectionTool getInspectionTool(String shortName) {
return myAvailableLocalTools.get(shortName);
}
};
final InspectionProfileManager inspectionProfileManager = InspectionProfileManager.getInstance();
inspectionProfileManager.addProfile(profile);
Disposer.register(getProject(), new Disposable() {
public void dispose() {
inspectionProfileManager.deleteProfile(PROFILE);
}
});
inspectionProfileManager.setRootProfile(profile.getName());
InspectionProjectProfileManager.getInstance(getProject()).updateProfile(profile);
}
public void tearDown() throws Exception {
LookupManager.getInstance(getProject()).hideActiveLookup();
FileEditorManager editorManager = FileEditorManager.getInstance(getProject());
VirtualFile[] openFiles = editorManager.getOpenFiles();
for (VirtualFile openFile : openFiles) {
editorManager.closeFile(openFile);
}
myProjectFixture.tearDown();
myTempDirFixture.tearDown();
super.tearDown();
}
private int configureByFiles(@NonNls String... filePaths) throws IOException {
myFile = null;
myEditor = null;
int offset = -1;
for (String filePath : filePaths) {
int fileOffset = configureByFileInner(filePath);
if (fileOffset > 0) {
offset = fileOffset;
}
}
return offset;
}
public void configureByFile(final String file) throws IOException {
new WriteCommandAction.Simple(getProject()) {
protected void run() throws Throwable {
configureByFileInner(file);
}
}.execute();
}
/**
*
* @param filePath
* @return caret offset or -1 if caret marker does not present
* @throws IOException
*/
private int configureByFileInner(@NonNls String filePath) throws IOException {
String fullPath = getTempDirPath() + "/" + filePath;
final VirtualFile copy = LocalFileSystem.getInstance().refreshAndFindFileByPath(fullPath.replace(File.separatorChar, '/'));
assert copy != null: "file " + fullPath + " not found";
SelectionAndCaretMarkupLoader loader = new SelectionAndCaretMarkupLoader(copy.getPath());
try {
final OutputStream outputStream = copy.getOutputStream(null, 0, 0);
outputStream.write(loader.newFileText.getBytes());
outputStream.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
if (myFile == null) myFile = myPsiManager.findFile(copy);
int offset = -1;
if (myEditor == null) {
myEditor = createEditor(copy);
assert myEditor != null;
if (loader.caretMarker != null) {
offset = loader.caretMarker.getStartOffset();
myEditor.getCaretModel().moveToOffset(offset);
}
if (loader.selStartMarker != null && loader.selEndMarker != null) {
myEditor.getSelectionModel().setSelection(loader.selStartMarker.getStartOffset(), loader.selEndMarker.getStartOffset());
}
}
return offset;
}
@Nullable
private Editor createEditor(VirtualFile file) {
final Project project = getProject();
final FileEditorManager instance = FileEditorManager.getInstance(project);
if (file.getFileType().isBinary()) {
return null;
}
return instance.openTextEditor(new OpenFileDescriptor(project, file, 0), false);
}
private void collectAndCheckHighlightings(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, Ref<Long> duration)
throws Exception {
final Project project = getProject();
ExpectedHighlightingData data = new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, myFile);
PsiDocumentManager.getInstance(project).commitAllDocuments();
((PsiFileImpl)myFile).calcTreeElement(); //to load text
//to initialize caches
myPsiManager.getCacheManager().getFilesWithWord(XXX, UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(project), true);
VirtualFileFilter javaFilesFilter = new VirtualFileFilter() {
public boolean accept(VirtualFile file) {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFile(file);
return fileType == StdFileTypes.JAVA || fileType == StdFileTypes.CLASS;
}
};
myPsiManager.setAssertOnFileLoadingFilter(javaFilesFilter); // check repository work
final long start = System.currentTimeMillis();
// ProfilingUtil.startCPUProfiling();
Collection<HighlightInfo> infos = doHighlighting();
duration.set(System.currentTimeMillis() - start);
// ProfilingUtil.captureCPUSnapshot("testing");
myPsiManager.setAssertOnFileLoadingFilter(VirtualFileFilter.NONE);
data.checkResult(infos, myEditor.getDocument().getText());
}
@NotNull
private Collection<HighlightInfo> doHighlighting() {
final Project project = myProjectFixture.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
Document document = myEditor.getDocument();
GeneralHighlightingPass action1 = new GeneralHighlightingPass(project, myFile, document, 0, myFile.getTextLength(), true);
action1.doCollectInformation(new MockProgressIndicator());
Collection<HighlightInfo> highlights1 = action1.getHighlights();
PostHighlightingPass action2 = new PostHighlightingPass(project, myFile, myEditor, 0, myFile.getTextLength());
action2.doCollectInformation(new MockProgressIndicator());
Collection<HighlightInfo> highlights2 = action2.getHighlights();
Collection<HighlightInfo> highlights3 = null;
if (myAvailableTools.size() > 0) {
LocalInspectionsPass inspectionsPass = new LocalInspectionsPass(myFile, myEditor.getDocument(), 0, myFile.getTextLength());
inspectionsPass.doCollectInformation(new MockProgressIndicator());
highlights3 = inspectionsPass.getHighlights();
}
ArrayList<HighlightInfo> list = new ArrayList<HighlightInfo>();
for (HighlightInfo info : highlights1) {
list.add(info);
}
for (HighlightInfo info : highlights2) {
list.add(info);
}
if (highlights3 != null) {
for (HighlightInfo info : highlights3) {
list.add(info);
}
}
return list;
}
private String getTestDataPath() {
return myTestDataPath;
}
public Project getProject() {
return myProjectFixture.getProject();
}
public Editor getEditor() {
return myEditor;
}
public PsiFile getFile() {
return myFile;
}
public static List<IntentionAction> getAvailableIntentions(final Project project, final Collection<HighlightInfo> infos, final int offset,
final Editor editor, final PsiFile file) {
final List<IntentionAction> availableActions = new ArrayList<IntentionAction>();
for (HighlightInfo info :infos) {
if (info.quickFixActionRanges != null) {
for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) {
if (offset > 0 && !pair.getSecond().contains(offset)) {
continue;
}
final HighlightInfo.IntentionActionDescriptor actionDescriptor = pair.first;
final IntentionAction action = actionDescriptor.getAction();
if (action.isAvailable(project, editor, file)) {
availableActions.add(action);
final List<IntentionAction> actions = actionDescriptor.getOptions(file.findElementAt(editor.getCaretModel().getOffset()));
if (actions != null) {
for (IntentionAction intentionAction : actions) {
if (intentionAction.isAvailable(project, editor, file)) {
availableActions.add(intentionAction);
}
}
}
}
}
}
}
for (IntentionAction intentionAction : IntentionManager.getInstance().getIntentionActions()) {
if (intentionAction.isAvailable(project, editor, file)) {
availableActions.add(intentionAction);
}
}
return availableActions;
}
static class SelectionAndCaretMarkupLoader {
final String newFileText;
final RangeMarker caretMarker;
final RangeMarker selStartMarker;
final RangeMarker selEndMarker;
SelectionAndCaretMarkupLoader(String fullPath) throws IOException {
final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(fullPath.replace(File.separatorChar, '/'));
assert vFile != null: "Cannot find file " + fullPath;
vFile.refresh(false, false);
String fileText = StringUtil.convertLineSeparators(VfsUtil.loadText(vFile), "\n");
Document document = EditorFactory.getInstance().createDocument(fileText);
int caretIndex = fileText.indexOf(CARET_MARKER);
int selStartIndex = fileText.indexOf(SELECTION_START_MARKER);
int selEndIndex = fileText.indexOf(SELECTION_END_MARKER);
caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null;
selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null;
selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null;
if (caretMarker != null) {
document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length());
}
if (selStartMarker != null) {
document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length());
}
if (selEndMarker != null) {
document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length());
}
newFileText = document.getText();
}
}
private void checkResultByFile(@NonNls String expectedFile,
@NotNull PsiFile originalFile,
boolean stripTrailingSpaces) throws IOException {
Project project = myProjectFixture.getProject();
project.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
if (stripTrailingSpaces) {
((DocumentEx)myEditor.getDocument()).stripTrailingSpaces(false);
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
SelectionAndCaretMarkupLoader loader = new SelectionAndCaretMarkupLoader(getTestDataPath() + "/" + expectedFile);
String newFileText1 = loader.newFileText;
if (stripTrailingSpaces) {
Document document1 = EditorFactory.getInstance().createDocument(loader.newFileText);
((DocumentEx)document1).stripTrailingSpaces(false);
newFileText1 = document1.getText();
}
String text = originalFile.getText();
text = StringUtil.convertLineSeparators(text, "\n");
//noinspection HardCodedStringLiteral
TestCase.assertEquals( "Text mismatch in file " + expectedFile, newFileText1, text );
if (loader.caretMarker != null) {
int caretLine = StringUtil.offsetToLineNumber(loader.newFileText, loader.caretMarker.getStartOffset());
int caretCol = loader.caretMarker.getStartOffset() - StringUtil.lineColToOffset(loader.newFileText, caretLine, 0);
TestCase.assertEquals("caretLine", caretLine + 1, myEditor.getCaretModel().getLogicalPosition().line + 1);
TestCase.assertEquals("caretColumn", caretCol + 1, myEditor.getCaretModel().getLogicalPosition().column + 1);
}
if (loader.selStartMarker != null && loader.selEndMarker != null) {
int selStartLine = StringUtil.offsetToLineNumber(loader.newFileText, loader.selStartMarker.getStartOffset());
int selStartCol = loader.selStartMarker.getStartOffset() - StringUtil.lineColToOffset(loader.newFileText, selStartLine, 0);
int selEndLine = StringUtil.offsetToLineNumber(loader.newFileText, loader.selEndMarker.getEndOffset());
int selEndCol = loader.selEndMarker.getEndOffset() - StringUtil.lineColToOffset(loader.newFileText, selEndLine, 0);
TestCase.assertEquals("selectionStartLine", selStartLine + 1,
StringUtil.offsetToLineNumber(loader.newFileText, myEditor.getSelectionModel().getSelectionStart()) + 1);
TestCase.assertEquals("selectionStartCol", selStartCol + 1, myEditor.getSelectionModel().getSelectionStart() -
StringUtil.lineColToOffset(loader.newFileText, selStartLine, 0) + 1);
TestCase.assertEquals("selectionEndLine", selEndLine + 1,
StringUtil.offsetToLineNumber(loader.newFileText, myEditor.getSelectionModel().getSelectionEnd()) + 1);
TestCase.assertEquals("selectionEndCol", selEndCol + 1,
myEditor.getSelectionModel().getSelectionEnd() - StringUtil.lineColToOffset(loader.newFileText, selEndLine, 0) + 1);
}
else {
TestCase.assertTrue("has no selection", !myEditor.getSelectionModel().hasSelection());
}
}
}
|
package cz.cuni.mff.xrg.odcs.dpu.fusiontool;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextArea;
import cz.cuni.mff.xrg.odcs.commons.configuration.ConfigException;
import cz.cuni.mff.xrg.odcs.commons.module.dialog.BaseConfigDialog;
import cz.cuni.mff.xrg.odcs.dpu.fusiontool.config.ConfigReader;
import cz.cuni.mff.xrg.odcs.dpu.fusiontool.exceptions.InvalidInputException;
/**
* DPU's configuration dialog. User can use this dialog to configure DPU
* configuration.
* @author Jan Michelfeit
*/
public class FusionToolDialog extends
BaseConfigDialog<FusionToolConfig> {
private static final long serialVersionUID = 1L;
private GridLayout mainLayout;
private TextArea configTextArea;
private Label labelUpQuer;
private String lastValidationError = "";
/**
* Initializes a new instance of the class.
*/
public FusionToolDialog() {
super(FusionToolConfig.class);
buildMainLayout();
setCompositionRoot(mainLayout);
}
@Override
public void setConfiguration(FusionToolConfig conf)
throws ConfigException {
configTextArea.setValue(conf.getXmlConfig());
}
@Override
public FusionToolConfig getConfiguration() throws ConfigException {
if (!configTextArea.isValid()) {
throw new ConfigException("Invalid configuration: " + lastValidationError);
} else {
FusionToolConfig conf = new FusionToolConfig(configTextArea.getValue().trim());
return conf;
}
}
@Override
public String getToolTip() {
return super.getToolTip();
}
@Override
public String getDescription() {
return super.getDescription();
}
/**
* Builds main layout with all dialog components.
*
* @return mainLayout GridLayout with all components of configuration
* dialog.
*/
private GridLayout buildMainLayout() {
// common part: create layout
mainLayout = new GridLayout(2, 1);
mainLayout.setImmediate(false);
mainLayout.setWidth("100%");
mainLayout.setHeight("100%");
mainLayout.setMargin(false);
// top-level component properties
setWidth("100%");
setHeight("100%");
// labelUpQuer
labelUpQuer = new Label();
labelUpQuer.setImmediate(false);
labelUpQuer.setWidth("68px");
labelUpQuer.setHeight("-1px");
labelUpQuer.setValue("Configuration");
mainLayout.addComponent(labelUpQuer, 0, 0);
// SPARQL Update Query textArea
configTextArea = new TextArea();
configTextArea.addValidator(new com.vaadin.data.Validator() {
private static final long serialVersionUID = 1L;
@Override
public void validate(Object value) throws InvalidValueException {
try {
ConfigReader.parseConfigXml(value.toString());
} catch (InvalidInputException e) {
String message = "Invalid XML configuration: " + e.getMessage();
lastValidationError = message;
throw new InvalidValueException(message);
}
}
});
// configTextArea.setNullRepresentation("");
configTextArea.setImmediate(true);
configTextArea.setWidth("100%");
configTextArea.setHeight("211px");
configTextArea.setInputPrompt("<?xml version=\"1.0\"?>\n<config>\n</config>");
mainLayout.addComponent(configTextArea, 1, 0);
// CHECKSTYLE:OFF
mainLayout.setColumnExpandRatio(0, 0.00001f);
mainLayout.setColumnExpandRatio(1, 0.99999f);
// CHECKSTYLE:ON
return mainLayout;
}
}
|
package ibis.ipl.examples;
import ibis.ipl.Ibis;
import ibis.ipl.IbisCapabilities;
import ibis.ipl.IbisFactory;
import ibis.ipl.IbisIdentifier;
import ibis.ipl.MessageUpcall;
import ibis.ipl.PortType;
import ibis.ipl.ReadMessage;
import ibis.ipl.ReceivePort;
import ibis.ipl.ReceivePortIdentifier;
import ibis.ipl.SendPort;
import ibis.ipl.WriteMessage;
import java.io.IOException;
import java.util.Date;
/**
* Example of a client application. The server waits until a request comes in,
* and sends a reply (in this case the current time). This application shows a
* combination of two port types. One is a many-to-one port with upcalls, the
* other a one-to-one port with explicit receive.
*/
public class ClientServer implements MessageUpcall {
/**
* Port type used for sending a request to the server
*/
PortType requestPortType = new PortType(PortType.COMMUNICATION_RELIABLE,
PortType.SERIALIZATION_OBJECT, PortType.RECEIVE_AUTO_UPCALLS,
PortType.CONNECTION_MANY_TO_ONE);
/**
* Port type used for sending a reply back
*/
PortType replyPortType = new PortType(PortType.COMMUNICATION_RELIABLE,
PortType.SERIALIZATION_DATA, PortType.RECEIVE_EXPLICIT,
PortType.CONNECTION_ONE_TO_ONE);
IbisCapabilities ibisCapabilities = new IbisCapabilities(
IbisCapabilities.ELECTIONS_STRICT);
private final Ibis myIbis;
/**
* Constructor. Actually does all the work too :)
*/
private ClientServer() throws Exception {
// Create an ibis instance.
// Notice createIbis uses varargs for its parameters.
myIbis = IbisFactory.createIbis(ibisCapabilities, null,
requestPortType, replyPortType);
// Elect a server
IbisIdentifier server = myIbis.registry().elect("Server");
// If I am the server, run server, else run client.
if (server.equals(myIbis.identifier())) {
server();
} else {
client(server);
}
// End ibis.
myIbis.end();
}
/**
* Function called by Ibis to give us a newly arrived message. This message
* will contain the ReceivePortIdentifier of the receive port of the ibis
* that send the request. We connect to this receive port, and send the
* reply.
*/
public void upcall(ReadMessage message) throws IOException,
ClassNotFoundException {
ReceivePortIdentifier requestor = (ReceivePortIdentifier) message
.readObject();
System.err.println("received request from: " + requestor);
// finish the request message. This MUST be done before sending
// the reply message. It ALSO means Ibis may now call this upcall
// method agian with the next request message
message.finish();
// create a sendport for the reply
SendPort replyPort = myIbis.createSendPort(replyPortType);
// connect to the requestor's receive port
replyPort.connect(requestor);
// create a reply message
WriteMessage reply = replyPort.newMessage();
reply.writeString("the time is " + new Date());
reply.finish();
replyPort.close();
}
private void server() throws Exception {
// Create a receive port, pass ourselves as the message upcall
// handler
ReceivePort receiver = myIbis.createReceivePort(requestPortType,
"server", this);
// enable connections
receiver.enableConnections();
// enable upcalls
receiver.enableMessageUpcalls();
System.err.println("server started");
// do nothing for a minute (will get upcalls for messages
Thread.sleep(60000);
// Close receive port.
receiver.close();
System.err.println("server stopped");
}
private void client(IbisIdentifier server) throws IOException {
// Create a send port for sending the request and connect.
SendPort sendPort = myIbis.createSendPort(requestPortType);
sendPort.connect(server, "server");
// Create a receive port for receiving the reply from the server
// this receive port does not need a name, as we will send the
// ReceivePortIdentifier to the server directly
ReceivePort receivePort = myIbis.createReceivePort(replyPortType, null);
receivePort.enableConnections();
// Send the request message. This message contains the identifier of
// our receive port so the server knows where to send the reply
WriteMessage request = sendPort.newMessage();
request.writeObject(receivePort.identifier());
request.finish();
ReadMessage reply = receivePort.receive();
String result = reply.readString();
System.err.println("server replies: " + result);
// Close ports.
sendPort.close();
receivePort.close();
}
public static void main(String args[]) {
try {
new ClientServer();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
|
//FILE: LabelsPage.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
// CVS: $Id$
package org.micromanager.conf;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.prefs.Preferences;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import mmcorej.MMCoreJ;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.PropertyItem;
import org.micromanager.utils.ReportingUtils;
/**
* Wizard page to define labels for state devices.
*
*/
public class LabelsPage extends PagePanel {
private static final long serialVersionUID = 1L;
private boolean initialized_ = false;
private String labels_[] = new String[0];
private String deviceLabels_[][] = new String[0][0];
ArrayList<Device> devices_ = new ArrayList<Device>();
public class SelectionListener implements ListSelectionListener {
JTable table;
// It is necessary to keep the table since it is not possible
// to determine the table from the event's source
SelectionListener(JTable table) {
this.table = table;
}
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
LabelTableModel ltm = (LabelTableModel)labelTable_.getModel();
if (lsm.isSelectionEmpty()) {
ltm.setData(model_, null);
} else {
String devName = (String)table.getValueAt(lsm.getMinSelectionIndex(), 0);
ltm.setData(model_, devName);
}
ltm.fireTableStructureChanged();
labelTable_.getColumnModel().getColumn(0).setWidth(40);
}
}
class LabelTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
public final String[] COLUMN_NAMES = new String[] {
"State",
"Label"
};
private Device curDevice_;
public Device getCurrentDevice() {
return curDevice_;
}
public void setData(MicroscopeModel model, String selDevice) {
curDevice_ = model.findDevice(selDevice);
labels_ = new String[0];
if (curDevice_ == null) {
return;
}
PropertyItem p = curDevice_.findProperty(MMCoreJ.getG_Keyword_Label());
if (p == null)
return;
labels_ = new String[curDevice_.getNumberOfStates()];
for (int i= 0; i<labels_.length; i++)
labels_[i] = new String("State-" + i);
for (int i=0; i<curDevice_.getNumberOfSetupLabels(); i++) {
Label lab = curDevice_.getSetupLabel(i);
labels_[lab.state_] = lab.label_;
}
}
public int getRowCount() {
return labels_.length;
}
public int getColumnCount() {
return COLUMN_NAMES.length;
}
public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0)
return Integer.toString(rowIndex);
else
return labels_[rowIndex];
}
public boolean isCellEditable(int nRow, int nCol) {
if(nCol == 1)
return true;
else
return false;
}
public void setValueAt(Object value, int row, int col) {
if (col == 1) {
try {
labels_[row] = (String) value;
curDevice_.setSetupLabel(row, (String) value);
fireTableCellUpdated(row, col);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
}
}
class DevTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
public final String[] COLUMN_NAMES = new String[] {
"State devices"
};
public void setData(MicroscopeModel model) {
if (!initialized_) {
storeLabels();
initialized_ = true;
}
Device devs[] = model.getDevices();
devices_.clear();
for (int i=0; i<devs.length; i++) {
if (devs[i].isStateDevice()) {
devices_.add(devs[i]);
}
}
}
public int getRowCount() {
return devices_.size();
}
public int getColumnCount() {
return COLUMN_NAMES.length;
}
public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
public Object getValueAt(int rowIndex, int columnIndex) {
return devices_.get(rowIndex).getName();
}
}
private JTable devTable_;
private JTable labelTable_;
/**
* Create the panel
*/
public LabelsPage(Preferences prefs) {
super();
title_ = "Define position labels for state devices";
helpText_ = "State devices with discrete positions, such as filter changers or objective turrets, etc. can have mnemonic labels assigned for each position.\n\n" +
"Select the device in the left-hand list and edit corresponding position labels in the right-hand list.\n\n" +
"Use the 'Read' button to read label info from the hardware. This will override your changes!\n\n";
setHelpFileName("conf_labels_page.html");
prefs_ = prefs;
setLayout(null);
final JScrollPane labelsScrollPane = new JScrollPane();
labelsScrollPane.setBounds(186, 10, 269, 254);
add(labelsScrollPane);
labelTable_ = new JTable();
labelTable_.setModel(new LabelTableModel());
labelTable_.setAutoCreateColumnsFromModel(false);
labelTable_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
InputMap im = labelTable_.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ), "none" );
labelsScrollPane.setViewportView(labelTable_);
GUIUtils.setClickCountToStartEditing(labelTable_,1);
GUIUtils.stopEditingOnLosingFocus(labelTable_);
final JScrollPane devScrollPane = new JScrollPane();
devScrollPane.setBounds(10, 10, 162, 255);
add(devScrollPane);
devTable_ = new JTable();
DevTableModel m = new DevTableModel();
devTable_.setModel(m);
devTable_.getSelectionModel().addListSelectionListener(new SelectionListener(devTable_));
devTable_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
devScrollPane.setViewportView(devTable_);
final JButton readButton = new JButton();
readButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// read labels from hardware
readFromHardware();
}
});
readButton.setText("Read");
readButton.setBounds(469,10,93,23);
add(readButton);
final JButton resetButton = new JButton();
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// read labels from hardware
resetLabels();
}
});
resetButton.setText("Reset");
resetButton.setBounds(469,43,93,23);
add(resetButton);
}
public void readFromHardware() {
LabelTableModel labelTableModel = (LabelTableModel) labelTable_.getModel();
Device selectedDevice = labelTableModel.getCurrentDevice();
if (selectedDevice != null) {
try {
selectedDevice.getSetupLabelsFromHardware(core_);
labelTableModel.setData(model_, selectedDevice.getName());
labelTableModel.fireTableStructureChanged();
} catch (Exception e) {
ReportingUtils.logError(e);
}
}
}
public void resetLabels() {
LabelTableModel labelTableModel = (LabelTableModel) labelTable_.getModel();
Device selectedDevice = labelTableModel.getCurrentDevice();
if (selectedDevice != null) {
for (int j=0; j<devices_.size(); j++) {
if (selectedDevice == devices_.get(j)) {
labels_ = deviceLabels_[j];
for (int k=0; k<labels_.length; k++)
selectedDevice.setSetupLabel(k, labels_[k]);
labelTableModel.fireTableStructureChanged();
}
}
}
}
public void storeLabels() {
// Store the initial list of labels for the reset button
String labels[] = new String[0];
Device devs[] = model_.getDevices();
devices_.clear();
for (int i=0; i<devs.length; i++) {
if (devs[i].isStateDevice()) {
devices_.add(devs[i]);
}
}
deviceLabels_ = new String[devices_.size()][0];
for (int j=0; j<devices_.size(); j++) {
labels = new String[devices_.get(j).getNumberOfStates()];
for (int i= 0; i<labels.length; i++)
labels[i] = new String("State-" + i);
for (int i=0; i<devices_.get(j).getNumberOfSetupLabels(); i++) {
Label lab = devices_.get(j).getSetupLabel(i);
labels[lab.state_] = lab.label_;
}
deviceLabels_[j] = new String[labels.length];
for (int k=0; k<labels.length; k++)
deviceLabels_[j][k]=labels[k];
}
}
public boolean enterPage(boolean next) {
DevTableModel tm = (DevTableModel)devTable_.getModel();
tm.setData(model_);
try {
model_.loadStateLabelsFromHardware(core_);
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean exitPage(boolean next) {
// define labels in hardware and syhcronize device data with microscope model
try {
model_.applySetupLabelsToHardware(core_);
model_.loadDeviceDataFromHardware(core_);
} catch (Exception e) {
handleError(e.getMessage());
return false;
}
return true;
}
public void refresh() {
}
public void loadSettings() {
}
public void saveSettings() {
}
}
|
/**
* Task.
*/
package ru.job4j.Task;
/**
* package-info for Class Task
* @author Kirill Krohmal (mailto:krohmal_kirill@mail.ru)
* @since 17.11.2019
*/
|
package mods.railcraft.api.carts;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.items.IItemHandler;
import javax.annotation.Nullable;
import java.util.function.Predicate;
@SuppressWarnings("unused")
public interface ITrainTransferHelper {
// Items
/**
* Will attempt to push an ItemStack to the Train.
*
* @param requester the source EntityMinecart
* @param stack the ItemStack to be pushed
* @return the ItemStack that remains after any pushed items were removed, or null if it was fully pushed
* @see mods.railcraft.api.carts.IFluidCart
*/
@Nullable
ItemStack pushStack(EntityMinecart requester, ItemStack stack);
/**
* Will request an item from the Train.
*
* @param requester the source EntityMinecart
* @param filter aPredicate<ItemStack> that defines the requested item
* @return the ItemStack pulled from the Train, or null if the request cannot be met
* @see mods.railcraft.api.carts.IItemCart
*/
@Nullable
ItemStack pullStack(EntityMinecart requester, Predicate<ItemStack> filter);
/**
* Offers an item stack to the Train or drops it if no one wants it.
*
* @param requester the source EntityMinecart
* @param stack the ItemStack to be offered
*/
void offerOrDropItem(EntityMinecart requester, ItemStack stack);
/**
* Returns an IItemHandler with represents the entire train.
*
* @param cart a cart in the train
* @return IItemHandler
*/
IItemHandler getTrainItemHandler(EntityMinecart cart);
// Fluids
/**
* Will attempt to push fluid to the Train.
*
* @param requester the source EntityMinecart
* @param fluidStack the amount and type of Fluid to be pushed
* @return the FluidStack that remains after any pushed Fluid was removed, or null if it was fully pushed
* @see mods.railcraft.api.carts.IFluidCart
*/
@Nullable
FluidStack pushFluid(EntityMinecart requester, FluidStack fluidStack);
/**
* Will request fluid from the Train.
*
* @param requester the source EntityMinecart
* @param fluidStack the amount and type of Fluid requested
* @return the FluidStack pulled from the Train, or null if the request cannot be met
* @see mods.railcraft.api.carts.IFluidCart
*/
@Nullable
FluidStack pullFluid(EntityMinecart requester, FluidStack fluidStack);
/**
* Returns an IFluidHandler with represents the entire train.
*
* @param cart a cart in the train
* @return IFluidHandler
*/
IFluidHandler getTrainFluidHandler(EntityMinecart cart);
}
|
package org.postgresql.ds.common;
import javax.sql.*;
import java.sql.*;
import java.util.*;
import java.lang.reflect.*;
import org.postgresql.PGConnection;
import org.postgresql.util.GT;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
/**
* PostgreSQL implementation of the PooledConnection interface. This shouldn't
* be used directly, as the pooling client should just interact with the
* ConnectionPool instead.
* @see org.postgresql.ds.PGConnectionPoolDataSource
*
* @author Aaron Mulder (ammulder@chariotsolutions.com)
* @author Csaba Nagy (ncsaba@yahoo.com)
*/
public class PooledConnectionImpl implements PooledConnection
{
private List listeners = new LinkedList();
private Connection con;
private ConnectionHandler last;
private boolean autoCommit;
/**
* Creates a new PooledConnection representing the specified physical
* connection.
*/
public PooledConnectionImpl(Connection con, boolean autoCommit)
{
this.con = con;
this.autoCommit = autoCommit;
}
/**
* Adds a listener for close or fatal error events on the connection
* handed out to a client.
*/
public void addConnectionEventListener(ConnectionEventListener connectionEventListener)
{
listeners.add(connectionEventListener);
}
/**
* Removes a listener for close or fatal error events on the connection
* handed out to a client.
*/
public void removeConnectionEventListener(ConnectionEventListener connectionEventListener)
{
listeners.remove(connectionEventListener);
}
/**
* Closes the physical database connection represented by this
* PooledConnection. If any client has a connection based on
* this PooledConnection, it is forcibly closed as well.
*/
public void close() throws SQLException
{
if (last != null)
{
last.close();
if (!con.getAutoCommit())
{
try
{
con.rollback();
}
catch (SQLException e)
{
}
}
}
try
{
con.close();
}
finally
{
con = null;
}
}
/**
* Gets a handle for a client to use. This is a wrapper around the
* physical connection, so the client can call close and it will just
* return the connection to the pool without really closing the
* pgysical connection.
*
* <p>According to the JDBC 2.0 Optional Package spec (6.2.3), only one
* client may have an active handle to the connection at a time, so if
* there is a previous handle active when this is called, the previous
* one is forcibly closed and its work rolled back.</p>
*/
public Connection getConnection() throws SQLException
{
if (con == null)
{
// Before throwing the exception, let's notify the registered listeners about the error
PSQLException sqlException = new PSQLException(GT.tr("This PooledConnection has already been closed."),
PSQLState.CONNECTION_DOES_NOT_EXIST);
fireConnectionFatalError(sqlException);
throw sqlException;
}
// If any error occures while opening a new connection, the listeners
// have to be notified. This gives a chance to connection pools to
// elliminate bad pooled connections.
try
{
// Only one connection can be open at a time from this PooledConnection. See JDBC 2.0 Optional Package spec section 6.2.3
if (last != null)
{
last.close();
if (!con.getAutoCommit())
{
try
{
con.rollback();
}
catch (SQLException e)
{
}
}
con.clearWarnings();
}
con.setAutoCommit(autoCommit);
}
catch (SQLException sqlException)
{
fireConnectionFatalError(sqlException);
throw (SQLException)sqlException.fillInStackTrace();
}
ConnectionHandler handler = new ConnectionHandler(con);
last = handler;
Connection proxyCon = (Connection)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Connection.class, PGConnection.class}, handler);
last.setProxy(proxyCon);
return proxyCon;
}
/**
* Used to fire a connection closed event to all listeners.
*/
void fireConnectionClosed()
{
ConnectionEvent evt = null;
// Copy the listener list so the listener can remove itself during this method call
ConnectionEventListener[] local = (ConnectionEventListener[]) listeners.toArray(new ConnectionEventListener[listeners.size()]);
for (int i = 0; i < local.length; i++)
{
ConnectionEventListener listener = local[i];
if (evt == null)
{
evt = new ConnectionEvent(this);
}
listener.connectionClosed(evt);
}
}
/**
* Used to fire a connection error event to all listeners.
*/
void fireConnectionFatalError(SQLException e)
{
ConnectionEvent evt = null;
// Copy the listener list so the listener can remove itself during this method call
ConnectionEventListener[] local = (ConnectionEventListener[])listeners.toArray(new ConnectionEventListener[listeners.size()]);
for (int i = 0; i < local.length; i++)
{
ConnectionEventListener listener = local[i];
if (evt == null)
{
evt = new ConnectionEvent(this, e);
}
listener.connectionErrorOccurred(evt);
}
}
// Classes we consider fatal.
private static String[] fatalClasses = {
"08", // connection error
"53", // insufficient resources
// nb: not just "57" as that includes query cancel which is nonfatal
"57P01", // admin shutdown
"57P02", // crash shutdown
"57P03", // cannot connect now
"58", // system error (backend)
"60", // system error (driver)
"99", // unexpected error
"F0", // configuration file error (backend)
"XX", // internal error (backend)
};
private static boolean isFatalState(String state) {
if (state == null) // no info, assume fatal
return true;
if (state.length() < 2) // no class info, assume fatal
return true;
for (int i = 0; i < fatalClasses.length; ++i)
if (state.startsWith(fatalClasses[i]))
return true; // fatal
return false;
}
/**
* Fires a connection error event, but only if we
* think the exception is fatal.
*
* @param e the SQLException to consider
*/
private void fireConnectionError(SQLException e)
{
if (!isFatalState(e.getSQLState()))
return;
fireConnectionFatalError(e);
}
/**
* Instead of declaring a class implementing Connection, which would have
* to be updated for every JDK rev, use a dynamic proxy to handle all
* calls through the Connection interface. This is the part that
* requires JDK 1.3 or higher, though JDK 1.2 could be supported with a
* 3rd-party proxy package.
*/
private class ConnectionHandler implements InvocationHandler
{
private Connection con;
private Connection proxy; // the Connection the client is currently using, which is a proxy
private boolean automatic = false;
public ConnectionHandler(Connection con)
{
this.con = con;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
// From Object
if (method.getDeclaringClass().getName().equals("java.lang.Object"))
{
if (method.getName().equals("toString"))
{
return "Pooled connection wrapping physical connection " + con;
}
if (method.getName().equals("hashCode"))
{
return new Integer(con.hashCode());
}
if (method.getName().equals("equals"))
{
if (args[0] == null)
{
return Boolean.FALSE;
}
try
{
return Proxy.isProxyClass(args[0].getClass()) && ((ConnectionHandler) Proxy.getInvocationHandler(args[0])).con == con ? Boolean.TRUE : Boolean.FALSE;
}
catch (ClassCastException e)
{
return Boolean.FALSE;
}
}
try
{
return method.invoke(con, args);
}
catch (InvocationTargetException e)
{
throw e.getTargetException();
}
}
// All the rest is from the Connection or PGConnection interface
if (method.getName().equals("isClosed"))
{
return con == null ? Boolean.TRUE : Boolean.FALSE;
}
if (con == null && !method.getName().equals("close"))
{
throw new PSQLException(automatic ? GT.tr("Connection has been closed automatically because a new connection was opened for the same PooledConnection or the PooledConnection has been closed.") : GT.tr("Connection has been closed."),
PSQLState.CONNECTION_DOES_NOT_EXIST);
}
if (method.getName().equals("close"))
{
// we are already closed and a double close
// is not an error.
if (con == null)
return null;
SQLException ex = null;
if (!con.getAutoCommit())
{
try
{
con.rollback();
}
catch (SQLException e)
{
ex = e;
}
}
con.clearWarnings();
con = null;
proxy = null;
last = null;
fireConnectionClosed();
if (ex != null)
{
throw ex;
}
return null;
}
// From here on in, we invoke via reflection, catch exceptions,
// and check if they're fatal before rethrowing.
try {
if (method.getName().equals("createStatement"))
{
Statement st = (Statement)method.invoke(con, args);
return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Statement.class, org.postgresql.PGStatement.class}, new StatementHandler(this, st));
}
else if (method.getName().equals("prepareCall"))
{
Statement st = (Statement)method.invoke(con, args);
return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{CallableStatement.class, org.postgresql.PGStatement.class}, new StatementHandler(this, st));
}
else if (method.getName().equals("prepareStatement"))
{
Statement st = (Statement)method.invoke(con, args);
return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{PreparedStatement.class, org.postgresql.PGStatement.class}, new StatementHandler(this, st));
}
else
{
return method.invoke(con, args);
}
} catch (InvocationTargetException e) {
Throwable te = e.getTargetException();
if (te instanceof SQLException)
fireConnectionError((SQLException)te); // Tell listeners about exception if it's fatal
throw te;
}
}
Connection getProxy() {
return proxy;
}
void setProxy(Connection proxy) {
this.proxy = proxy;
}
public void close()
{
if (con != null)
{
automatic = true;
}
con = null;
proxy = null;
// No close event fired here: see JDBC 2.0 Optional Package spec section 6.3
}
public boolean isClosed() {
return con == null;
}
}
/**
* Instead of declaring classes implementing Statement, PreparedStatement,
* and CallableStatement, which would have to be updated for every JDK rev,
* use a dynamic proxy to handle all calls through the Statement
* interfaces. This is the part that requires JDK 1.3 or higher, though
* JDK 1.2 could be supported with a 3rd-party proxy package.
*
* The StatementHandler is required in order to return the proper
* Connection proxy for the getConnection method.
*/
private class StatementHandler implements InvocationHandler {
private PooledConnectionImpl.ConnectionHandler con;
private Statement st;
public StatementHandler(PooledConnectionImpl.ConnectionHandler con, Statement st) {
this.con = con;
this.st = st;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
// From Object
if (method.getDeclaringClass().getName().equals("java.lang.Object"))
{
if (method.getName().equals("toString"))
{
return "Pooled statement wrapping physical statement " + st;
}
if (method.getName().equals("hashCode"))
{
return new Integer(st.hashCode());
}
if (method.getName().equals("equals"))
{
if (args[0] == null)
{
return Boolean.FALSE;
}
try
{
return Proxy.isProxyClass(args[0].getClass()) && ((StatementHandler) Proxy.getInvocationHandler(args[0])).st == st ? Boolean.TRUE : Boolean.FALSE;
}
catch (ClassCastException e)
{
return Boolean.FALSE;
}
}
return method.invoke(st, args);
}
// All the rest is from the Statement interface
if (method.getName().equals("close"))
{
// closing an already closed object is a no-op
if (st == null || con.isClosed())
return null;
try
{
st.close();
}
finally
{
con = null;
st = null;
}
return null;
}
if (st == null || con.isClosed())
{
throw new PSQLException(GT.tr("Statement has been closed."),
PSQLState.OBJECT_NOT_IN_STATE);
}
if (method.getName().equals("getConnection"))
{
return con.getProxy(); // the proxied connection, not a physical connection
}
try
{
return method.invoke(st, args);
} catch (InvocationTargetException e) {
Throwable te = e.getTargetException();
if (te instanceof SQLException)
fireConnectionError((SQLException)te); // Tell listeners about exception if it's fatal
throw te;
}
}
}
}
|
/*
* $Id: CrawlRuleTester.java,v 1.17 2006-07-24 06:51:11 tlipkis Exp $
*/
package org.lockss.devtools;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.lockss.crawler.*;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.plugin.base.*;
import org.lockss.util.*;
import org.lockss.util.urlconn.*;
import org.lockss.config.*;
public class CrawlRuleTester extends Thread {
protected static Logger log = Logger.getLogger("CrawlRuleTester");
/** Proxy host */
public static final String PARAM_PROXY_HOST =
Configuration.PREFIX + "crawltest.proxy.host";
/** Proxy port */
public static final String PARAM_PROXY_PORT =
Configuration.PREFIX + "crawltest.proxy.port";
public static final int DEFAULT_PROXY_PORT = -1;
/* Message Types */
public static final int ERROR_MESSAGE = 0;
public static final int WARNING_MESSAGE = 1;
public static final int PLAIN_MESSAGE = 2;
public static final int URL_SUMMARY_MESSAGE = 3;
public static final int TEST_SUMMARY_MESSAGE = 4;
public static long MIN_DELAY = BaseArchivalUnit.MIN_FETCH_DELAY;
private String m_baseUrl;
private CrawlSpec m_crawlSpec;
private int m_crawlDepth;
private long m_crawlDelay;
private int m_curDepth;
private String m_outputFile = null;
private BufferedWriter m_outWriter = null;
private Deadline fetchDeadline = Deadline.in(0);
private boolean useLocalWriter = true;
private MessageHandler m_msgHandler;
private LockssUrlConnectionPool connectionPool =
new LockssUrlConnectionPool();
private String proxyHost;
private int proxyPort;
// our storage for extracted urls
private TreeSet m_extracted = new TreeSet();
private TreeSet m_incls = new TreeSet();
private TreeSet m_excls = new TreeSet();
private TreeSet m_reported = new TreeSet();
public CrawlRuleTester(int crawlDepth, long crawlDelay, String baseUrl,
CrawlSpec crawlSpec) {
super("crawlrule tester");
m_crawlDepth = crawlDepth;
m_crawlDelay = Math.max(crawlDelay, MIN_DELAY);
m_baseUrl = baseUrl;
m_crawlSpec = crawlSpec;
}
/**
* RuleTest
*
* @param outFile String
* @param crawlDepth int
* @param crawlDelay long
* @param baseUrl String
* @param crawlSpec CrawlSpec
*/
public CrawlRuleTester(String outFile, int crawlDepth, long crawlDelay,
String baseUrl, CrawlSpec crawlSpec) {
this(crawlDepth, crawlDelay,baseUrl,crawlSpec);
m_outputFile = outFile;
}
/**
* RuleTest
*
* @param outWriter BufferedWriter
* @param crawlDepth int
* @param crawlDelay long
* @param baseUrl String
* @param crawlSpec CrawlSpec
*/
public CrawlRuleTester(BufferedWriter outWriter, int crawlDepth,
long crawlDelay,
String baseUrl, CrawlSpec crawlSpec) {
this(crawlDepth, crawlDelay, baseUrl, crawlSpec);
m_outWriter = outWriter;
}
/**
* RuleTest
*
* @param msgHandler MessageHandler to take all output
* @param crawlDepth the crawl depth to use
* @param crawlDelay the type to wait between fetches
* @param baseUrl the url to start from
* @param crawlSpec a CrawlSpec to use for url checking.
*/
public CrawlRuleTester(MessageHandler msgHandler, int crawlDepth,
long crawlDelay,
String baseUrl, CrawlSpec crawlSpec) {
this(crawlDepth, crawlDelay, baseUrl, crawlSpec);
m_msgHandler = msgHandler;
}
public void run() {
try {
setConfig(ConfigManager.getCurrentConfig());
if(m_outWriter == null && m_msgHandler == null) {
useLocalWriter = true;
}
else {
useLocalWriter = false;
}
if(useLocalWriter) {
openOutputFile();
}
checkRules();
if(useLocalWriter) {
closeOutputFile();
}
}
finally {
if (m_msgHandler != null) {
m_msgHandler.close();
}
}
}
void setConfig(Configuration config) {
log.debug("config: " + config);
proxyHost = config.get(PARAM_PROXY_HOST);
proxyPort = config.getInt(PARAM_PROXY_PORT, DEFAULT_PROXY_PORT);
if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
proxyHost = null;
} else {
if (log.isDebug()) log.debug("Proxying through " + proxyHost
+ ":" + proxyPort);
}
}
private void openOutputFile() {
if (m_outputFile != null) {
try {
m_outWriter = new BufferedWriter(new FileWriter(m_outputFile, false));
return;
}
catch (Exception ex) {
System.err.println("Error opening output file, writing to stdout: "
+ ex);
}
}
m_outWriter = new BufferedWriter(new OutputStreamWriter(System.out));
}
private void closeOutputFile() {
try {
if (m_outWriter != null) {
m_outWriter.close();
}
}
catch (IOException ex) {
System.err.println("Error closing output file.");
}
}
int[] depth_incl;
int[] depth_fetched;
int[] depth_parsed;
private void checkRules() {
outputMessage("\nChecking " + m_baseUrl, TEST_SUMMARY_MESSAGE);
outputMessage("crawl depth: " + m_crawlDepth +
" crawl delay: " + m_crawlDelay + " ms.",
PLAIN_MESSAGE);
TreeSet crawlList = new TreeSet();
TreeSet fetched = new TreeSet();
// inialize with the baseUrl
crawlList.add(m_baseUrl);
depth_incl = new int[m_crawlDepth];
depth_fetched = new int[m_crawlDepth];
depth_parsed = new int[m_crawlDepth];
long start_time = TimeBase.nowMs();
for (int depth = 1; depth <= m_crawlDepth; depth++) {
if (isInterrupted()) { return; }
m_curDepth = depth;
if (crawlList.isEmpty() && depth <= m_crawlDepth) {
outputMessage("\nNothing left to crawl, exiting after depth " +
(depth - 1), PLAIN_MESSAGE);
break;
}
String[] urls = (String[]) crawlList.toArray(new String[0]);
crawlList.clear();
outputMessage("\nDepth " + depth, PLAIN_MESSAGE);
for (int ix = 0; ix < urls.length; ix++) {
if (isInterrupted()) { return; }
pauseBeforeFetch();
String urlstr = urls[ix];
m_incls.clear();
m_excls.clear();
// crawl the page
buildUrlSets(urlstr);
fetched.add(urlstr);
// output incl/excl results,
// add the new_incls to the crawlList for next crawl depth loop
crawlList.addAll(outputUrlResults(urlstr, m_incls, m_excls));
}
}
long elapsed_time = TimeBase.nowMs() - start_time;
outputSummary(m_baseUrl, fetched, crawlList, elapsed_time);
}
private void buildUrlSets(String url) {
try {
outputMessage("\nFetching " + url, TEST_SUMMARY_MESSAGE);
URL srcUrl = new URL(url);
// URLConnection conn = srcUrl.openConnection();
// String type = conn.getContentType();
// type = conn.getHeaderField("content-type");
// InputStream istr = conn.getInputStream();
LockssUrlConnection conn = UrlUtil.openConnection(url, connectionPool);
if (proxyHost != null) {
conn.setProxy(proxyHost, proxyPort);
}
try {
conn.execute();
int resp = conn.getResponseCode();
if (resp != 200) {
outputMessage("Resp: " + resp + ": " + conn.getResponseMessage(),
TEST_SUMMARY_MESSAGE);
return;
}
depth_fetched[m_curDepth - 1]++;
String cookies = conn.getResponseHeaderValue("Set-Cookie");
if (cookies != null) {
outputMessage("Cookies: " + cookies, PLAIN_MESSAGE);
}
String type = conn.getResponseContentType();
if (type == null || !type.toLowerCase().startsWith("text/html")) {
outputMessage("Type: " + type + ", not parsing",URL_SUMMARY_MESSAGE);
return;
}
outputMessage("Type: " + type + ", extracting Urls",
URL_SUMMARY_MESSAGE);
InputStream istr = conn.getResponseInputStream();
InputStreamReader reader = new InputStreamReader(istr);
// MyMockCachedUrl mcu = new MyMockCachedUrl(srcUrl.toString(), reader);
GoslingHtmlParser parser = new GoslingHtmlParser();
parser.parseForUrls(reader, srcUrl.toString() ,
new MyFoundUrlCallback());
istr.close();
depth_parsed[m_curDepth - 1]++;
} finally {
conn.release();
}
}
catch (MalformedURLException murle) {
murle.printStackTrace();
outputErrResults(url, "Malformed URL:" + murle.getMessage());
}
catch (IOException ex) {
ex.printStackTrace();
outputErrResults(url, "IOException: " + ex.getMessage());
}
}
private void pauseBeforeFetch() {
if (!fetchDeadline.expired()) {
try {
fetchDeadline.sleep();
}
catch (InterruptedException ie) {
// no action
}
}
fetchDeadline.expireIn(m_crawlDelay);
}
private void outputMessage(String msg, int msgType) {
if (isInterrupted()) { return; }
if(m_msgHandler != null) {
m_msgHandler.outputMessage(msg + "\n", msgType);
}
else {
try {
m_outWriter.write(msg);
m_outWriter.newLine();
}
catch (Exception ex) {
System.err.println(msg);
}
}
}
private void outputErrResults(String url, String errMsg) {
outputMessage("Error: " + errMsg + " occured while processing " + url,
ERROR_MESSAGE);
}
private Set outputUrlResults(String url, Set m_inclset, Set m_exclset) {
Set new_incls =
new TreeSet(CollectionUtils.subtract(m_inclset, m_reported));
Set new_excls =
new TreeSet(CollectionUtils.subtract(m_exclset, m_reported));
if (!m_inclset.isEmpty()) {
outputMessage("\nIncluded Urls: (" + new_incls.size() + " new, " +
(m_inclset.size() - new_incls.size()) + " old)",
URL_SUMMARY_MESSAGE);
depth_incl[m_curDepth - 1] += new_incls.size();
}
for (Iterator it = new_incls.iterator(); it.hasNext(); ) {
outputMessage(it.next().toString(), PLAIN_MESSAGE);
}
if (!m_exclset.isEmpty()) {
outputMessage("\nExcluded Urls: (" + new_excls.size() + " new, " +
(m_exclset.size() - new_excls.size()) + " old)",
URL_SUMMARY_MESSAGE);
}
for (Iterator it = new_excls.iterator(); it.hasNext(); ) {
outputMessage(it.next().toString(), PLAIN_MESSAGE);
}
m_reported.addAll(new_incls);
m_reported.addAll(new_excls);
if(m_outWriter != null) {
try {
m_outWriter.flush();
}
catch (IOException ex) {
}
}
return new_incls;
}
private void outputSummary(String baseUrl, Set fetched, Set toCrawl,
long elapsedTime) {
int fetchCount = fetched.size();
outputMessage("\n\nSummary for starting Url: " + baseUrl +
" and depth: " + m_crawlDepth, TEST_SUMMARY_MESSAGE);
outputMessage("\nUrls fetched: " + fetchCount +
" Urls extracted: " + m_extracted.size(), PLAIN_MESSAGE);
outputMessage("\nDepth Fetched Parsed New URLs", PLAIN_MESSAGE);
for (int depth = 1; depth <= m_crawlDepth; depth++) {
PrintfFormat pf = new PrintfFormat("%5d %7d %6d %8d");
Integer[] args = new Integer[]{
new Integer(depth),
new Integer(depth_fetched[depth - 1]),
new Integer(depth_parsed[depth - 1]),
new Integer(depth_incl[depth - 1]),
};
String s = pf.sprintf(args);
outputMessage(s, PLAIN_MESSAGE);
}
outputMessage("\nRemaining unfetched: " + toCrawl.size(), PLAIN_MESSAGE);
if (false) {
for (Iterator iter = toCrawl.iterator(); iter.hasNext(); ) {
String url = (String)iter.next();
outputMessage(url, PLAIN_MESSAGE);
}
}
long secs = elapsedTime / Constants.SECOND;
long fetchRate = 0;
if(secs > 0) {
fetchRate = fetchCount * 60 * Constants.SECOND / elapsedTime;
}
outputMessage("\nElapsed Time: " + secs + " secs." +
" Fetch Rate: " + fetchRate + " p/m", PLAIN_MESSAGE);
}
public interface MessageHandler {
void outputMessage(String message, int messageType);
void close();
}
private class MyFoundUrlCallback
implements ContentParser.FoundUrlCallback {
MyFoundUrlCallback() {
}
public void foundUrl(String url) {
m_extracted.add(url);
try {
String normUrl = UrlUtil.normalizeUrl(url);
if (BaseCrawler.isSupportedUrlProtocol(normUrl) &&
m_crawlSpec.isIncluded(normUrl)) {
m_incls.add(normUrl);
}
else {
m_excls.add(normUrl);
}
} catch (MalformedURLException e) {
m_excls.add(url);
}
}
}
class MyMockCachedUrl implements CachedUrl {
private String url;
private boolean doesExist = false;
private Reader reader = null;
public MyMockCachedUrl(String url, Reader reader) {
this.url = url;
this.reader = reader;
}
public ArchivalUnit getArchivalUnit() {
throw new UnsupportedOperationException("Not implemented");
}
public String getUrl() {
return url;
}
public CachedUrl getCuVersion(int version) {
throw new UnsupportedOperationException("Not implemented");
}
public CachedUrl[] getCuVersions() {
throw new UnsupportedOperationException("Not implemented");
}
public CachedUrl[] getCuVersions(int maxVersions) {
throw new UnsupportedOperationException("Not implemented");
}
public int getVersion() {
return 1;
}
public Reader openForReading() {
return reader;
}
/**
* getUnfilteredInputStream
*
* @return InputStream
*/
public InputStream getUnfilteredInputStream() {
throw new UnsupportedOperationException("Not implemented");
}
/**
* openForHashing
*
* @return InputStream
*/
public InputStream openForHashing() {
throw new UnsupportedOperationException("Not implemented");
}
/**
* getContentSize
*
* @return long
*/
public long getContentSize() {
throw new UnsupportedOperationException("Not implemented");
}
public boolean hasContent() {
return doesExist;
}
public boolean isLeaf() {
return true;
}
public int getType() {
return CachedUrlSetNode.TYPE_CACHED_URL;
}
public CIProperties getProperties() {
return null;
}
public void release() {
}
public String toString() {
StringBuffer sb = new StringBuffer(url.length() + 17);
sb.append("[MyMockCachedUrl: ");
sb.append(url);
sb.append("]");
return sb.toString();
}
}
}
|
package core.entities;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import core.util.Utils;
import core.Constants;
import core.Database;
import core.entities.settings.ServerSettingsManager;
import core.entities.timers.DCTimer;
import core.exceptions.InvalidUseException;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.managers.RoleManager;
// Server class; Controls bot actions for each server
public class Server {
private Guild guild;
private ServerSettingsManager settingsManager;
private QueueManager queueManager;
private ConcurrentHashMap<Member, Long> activityList = new ConcurrentHashMap<Member, Long>();
private ConcurrentHashMap<Member, DCTimer> disconnectList = new ConcurrentHashMap<>();
private java.util.Queue<Message> messageCache = new LinkedList<Message>();
private Set<Long> banList;
private Set<Long> adminList;
private HashMap<String, Role> groupDict = new HashMap<String, Role>();
private CommandManager commandManager;
public Server(Guild guild) {
this.guild = guild;
commandManager = new CommandManager(this);
// Insert guild into database
Database.insertDiscordServer(getId(), guild.getName());
// Insert members into database
for (Member m : guild.getMembers()) {
Database.insertPlayer(m.getUser().getIdLong(), m.getEffectiveName());
Database.insertPlayerServer(guild.getIdLong(), m.getUser().getIdLong());
}
settingsManager = new ServerSettingsManager(this);
banList = Database.queryGetBanList(guild.getIdLong());
adminList = Database.queryGetAdminList(guild.getIdLong());
queueManager = new QueueManager(this);
groupDict = Database.retrieveGroups(guild.getIdLong());
queueManager.getQueueList().forEach((q) -> q.getPlayersInQueue().forEach((u) -> updateActivityList(u)));
}
public long getId() {
return guild.getIdLong();
}
public QueueManager getQueueManager() {
return queueManager;
}
public ServerSettingsManager getSettingsManager() {
return settingsManager;
}
public TextChannel getPugChannel() {
TextChannel channel = settingsManager.getPUGChannel();
if(channel == null){
channel = guild.getDefaultChannel();
}
return channel;
}
protected void checkActivityList() {
boolean update = false;
for (Member member : activityList.keySet()) {
long time = activityList.get(member);
if (!queueManager.isPlayerInQueue(member)) {
activityList.remove(member);
continue;
}
long timeDiffMs = System.currentTimeMillis() - time;
long minutes = TimeUnit.MINUTES.convert(timeDiffMs, TimeUnit.MILLISECONDS);
if (minutes >= settingsManager.getAFKTimeout()) {
String msg = String.format("<@%s> has been removed from all queues after being inactive for %d minutes",
member.getUser().getId(), settingsManager.getAFKTimeout());
queueManager.purgeQueue(member);
getPugChannel().sendMessage(Utils.createMessage("", msg, false)).queue();
update = true;
}
}
if(update){
queueManager.updateTopic();
}
}
public void dcTimerEnd(Member member) {
if (member.getOnlineStatus().equals(OnlineStatus.OFFLINE)) {
queueManager.purgeQueue(member);
queueManager.updateTopic();
String msg = String.format("%s has been removed from all queues after being offline for %s minutes",
member.getEffectiveName(), settingsManager.getDCTimeout());
getPugChannel().sendMessage(Utils.createMessage("", msg, false)).queue();
}
disconnectList.remove(member);
}
public void updateActivityList(Member m) {
if (queueManager.isPlayerInQueue(m)) {
activityList.put(m, System.currentTimeMillis());
} else if (activityList.containsKey(m)) {
activityList.remove(m);
}
}
public void playerDisconnect(Member member) {
if (queueManager.isPlayerInQueue(member)) {
DCTimer timer = new DCTimer(this, member);
if(disconnectList.containsKey(member)){
disconnectList.get(member).interrupt();
}
disconnectList.put(member, timer);
timer.start();
}
}
public Guild getGuild() {
return guild;
}
public boolean isAdmin(Member m) {
if (adminList.contains(m.getUser().getIdLong()) || m.hasPermission(Permission.KICK_MEMBERS)
|| m.getUser().getId().equals(Constants.OWNER_ID)) {
return true;
}
return false;
}
public boolean isBanned(Member m) {
return banList.contains(m.getUser().getIdLong());
}
public Member getMember(String member) {
for (Member m : guild.getMembers()) {
if (m.getEffectiveName().equalsIgnoreCase(member) || m.getUser().getId().equals(member)) {
return m;
}
}
throw new InvalidUseException("Member does not exist");
}
public void banUser(long userId) {
if (banList.contains(userId)) {
throw new InvalidUseException("This user is already banned");
}
banList.add(userId);
Database.updateBanStatus(guild.getIdLong(), Long.valueOf(userId), true);
}
public void unbanUser(long userId) {
if (!banList.contains(userId)) {
throw new InvalidUseException("This user is not banned");
}
banList.remove(userId);
Database.updateBanStatus(getId(), Long.valueOf(userId), false);
}
public void unbanAll() {
for (long userId : banList) {
Database.updateBanStatus(getId(), userId, false);
}
banList.clear();
}
public void addAdmin(long userId) {
if (adminList.contains(userId)) {
throw new InvalidUseException("User is already an admin");
}
adminList.add(userId);
Database.updateAdminStatus(getId(), Long.valueOf(userId), true);
}
public void removeAdmin(long userId) {
if (!adminList.contains(userId)) {
throw new InvalidUseException("User is not an admin");
}
adminList.remove(userId);
Database.updateAdminStatus(getId(), Long.valueOf(userId), false);
}
/**
* Checks a message cache to see if the message sent is identical to any
* other within 3 seconds
*
* @param message
* @return
*/
public boolean isSpam(Message message) {
boolean spam = false;
for (Message m : messageCache) {
long timeDiff = message.getCreationTime().toEpochSecond() - m.getCreationTime().toEpochSecond();
if (timeDiff <= 3 && m.getAuthor().getIdLong() == message.getAuthor().getIdLong()
&& m.getContent().equals(message.getContent())) {
spam = true;
break;
}
}
if (messageCache.size() > 9) {
messageCache.remove();
}
messageCache.add(message);
return spam;
}
/**
* Creates a role, adds it to the group dictionary, and inserts the id into
* the database
*
* @throws InvalidUseException
* If a group with the same name already exists
*
* @param groupName
* The name of the group
*/
public void addGroup(String groupName) {
if (groupDict.containsKey(groupName)) {
throw new InvalidUseException("A group with this name already exists!");
}
Role role = guild.getController().createRole().complete();
RoleManager manager = role.getManager();
// TODO: Update with new syntax after JDA upgrade
manager.setMentionable(true).queue();
manager.setName(groupName).queue();
groupDict.put(groupName.toLowerCase(), role);
Database.insertGroup(getId(), role.getIdLong());
}
/**
* Deletes a specified group and associated role
*
* @throws InvalidUseException
* If groupName is not a valid group
*
* @param groupName
* The name of the group
*/
public void deleteGroup(String groupName) {
if (!groupDict.containsKey(groupName)) {
throw new InvalidUseException("A group with that name does not exist");
} else {
Role role = groupDict.get(groupName);
groupDict.remove(groupName);
Database.deleteGroup(getId(), role.getIdLong());
role.delete().queue();
}
}
/**
* Creates an array of all group names
*
* @return A String[] containing all group names
*/
public String[] getGroupNames() {
return groupDict.keySet().toArray(new String[0]);
}
/**
* Gets a group by its name
*
* @param groupName
* The name of the group
* @return The Role associated with the group
*/
public Role getGroup(String groupName) {
if (!groupDict.containsKey(groupName)) {
throw new InvalidUseException(String.format("The group %s does not exist", groupName));
}
return groupDict.get(groupName.toLowerCase());
}
public CommandManager getCommandManager(){
return commandManager;
}
}
|
package Client;
import java.util.ArrayList;
import Boutons.Bouton;
import Boutons.BoutonDestination;
import Boutons.BoutonInterne;
//Salut, je suis un comm
public class Ascenseur {
// quel tage se trouve l'ascenseur
private int etage;
private ArrayList<BoutonInterne> listeBoutons = new ArrayList<BoutonInterne>();
//l'ascenseur est-il en mouvement ou bien l'arrt
private boolean estEnMouvement;
//quel est le poids maximum en kg que l'ascenseur est cens pouvoir supporter
private int poidsMax;
//l'ascenseur est-il vide
private boolean estVide;
private Batiment bat;
//constructeur
public Ascenseur (Batiment bati){
etage = 0; //un nouvel ascenseur est assembl au rez-de-chausse (niveau 0)
estEnMouvement = false; //un nouvel ascenseur est immobile car n'a pas encore reu de requte
estVide = true; //un nouvel ascenseur ne contient aucun usager
poidsMax = 300; //paramtre par dfaut - changer ou rendre paramtrable par l'utilisateur
bat = bati;
listeBoutons.add(new BoutonDestination("Rez-de-chaussé", 0));
listeBoutons.add(new BoutonDestination("1er étage", 1));
for (int i = 2; i <= bat.getNbEtages(); ++i){
listeBoutons.add(new BoutonDestination(i+"e étage", i)); //i = numero de l'etage correspondant au bouton
} //initialisation des boutons
}
@Override
public String toString() {
return "Ascenseur [etage=" + etage + ", estArrete=" + estEnMouvement + ", poidsMax=" + poidsMax + ", estVide="
+ estVide + "]";
}
public void setEtage(int etage) {
this.etage = etage;
}
public ArrayList<BoutonInterne> getListeBoutons() {
return listeBoutons;
}
public void setListeBoutons(ArrayList<BoutonInterne> listeBoutons) {
this.listeBoutons = listeBoutons;
}
}
|
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AcronymTest {
@Test
public void fromTitleCasedPhrases() {
final String phrase = "Portable Network Graphics";
final String expected = "PNG";
assertEquals(expected, Acronym.generate(phrase));
}
@Test
public void fromOtherTitleCasedPhrases() {
final String phrase = "Ruby on Rails";
final String expected = "ROR";
assertEquals(expected, Acronym.generate(phrase));
}
@Test
public void fromInconsistentlyCasedPhrases() {
final String phrase = "HyperText Markup Language";
final String expected = "HTML";
assertEquals(expected, Acronym.generate(phrase));
}
@Test
public void fromPhrasesWithPunctuation() {
final String phrase = "First In, First Out";
final String expected = "FIFO";
assertEquals(expected, Acronym.generate(phrase));
}
@Test
public void fromOtherPhrasesWithPunctuation() {
final String phrase = "PHP: Hypertext Preprocessor";
final String expected = "PHP";
assertEquals(expected, Acronym.generate(phrase));
}
@Test
public void fromPhrasesWithPunctuationAndSentenceCasing() {
final String phrase = "Complementary metal-oxide semiconductor";
final String expected = "CMOS";
assertEquals(expected, Acronym.generate(phrase));
}
@Test
public void fromPhraseWithSingleLetterWord() {
final String phrase = "Cat in a Hat";
final String expected = "CIAH";
assertEquals(expected, Acronym.generate(phrase));
}
}
|
package lighthouse.controls;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.binding.StringExpression;
import javafx.beans.property.LongProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.*;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.FileChooser;
import lighthouse.LighthouseBackend;
import lighthouse.Main;
import lighthouse.protocol.Ex;
import lighthouse.protocol.LHProtos;
import lighthouse.protocol.LHUtils;
import lighthouse.protocol.Project;
import lighthouse.subwindows.*;
import lighthouse.threading.AffinityExecutor;
import lighthouse.utils.ConcatenatingList;
import lighthouse.utils.GuiUtils;
import lighthouse.utils.MappedList;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.params.TestNet3Params;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.file.Files;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static javafx.beans.binding.Bindings.*;
import static javafx.collections.FXCollections.singletonObservableList;
import static lighthouse.utils.GuiUtils.getResource;
import static lighthouse.utils.GuiUtils.informationalAlert;
import static lighthouse.utils.MoreBindings.bindSetToList;
import static lighthouse.utils.MoreBindings.mergeSets;
/**
* The main content area that shows project details, pledges, a pie chart, buttons etc.
*/
public class ProjectView extends HBox {
private static final Logger log = LoggerFactory.getLogger(ProjectView.class);
private static final String BLOCK_EXPLORER_SITE = "https:
private static final String BLOCK_EXPLORER_SITE_TESTNET = "https:
@FXML Label projectTitle;
@FXML Label goalAmountLabel;
@FXML Label raisedAmountLabel;
@FXML TextFlow description;
@FXML Label noPledgesLabel;
@FXML ListView<LHProtos.Pledge> pledgesList;
@FXML PieChart pieChart;
@FXML Button actionButton;
@FXML Pane coverImage;
@FXML Label numPledgersLabel;
@FXML Label percentFundedLabel;
@FXML Button editButton;
@FXML VBox pledgesListVBox;
public final ObjectProperty<Project> project = new SimpleObjectProperty<>();
public final ObjectProperty<EventHandler<ActionEvent>> onBackClickedProperty = new SimpleObjectProperty<>();
private PieChart.Data emptySlice;
private final KeyCombination backKey = KeyCombination.valueOf("Shortcut+LEFT");
private ObservableSet<LHProtos.Pledge> pledges;
private UIBindings bindings;
private LongProperty pledgedValue;
private ObjectBinding<LighthouseBackend.CheckStatus> checkStatus;
private ObservableMap<String, LighthouseBackend.ProjectStateInfo> projectStates; // project id -> status
@Nullable private NotificationBarPane.Item notifyBarItem;
@Nullable private Sha256Hash myPledgeHash;
private String goalAmountFormatStr;
private BooleanBinding isFullyFundedAndNotParticipating;
private enum Mode {
OPEN_FOR_PLEDGES,
PLEDGED,
CAN_CLAIM,
CLAIMED,
}
private SimpleObjectProperty<Mode> mode = new SimpleObjectProperty<>(Mode.OPEN_FOR_PLEDGES);
private Mode priorMode;
public ProjectView() {
// Don't try and access Main.backend here in case you race with startup.
setupFXML();
pledgesList.setCellFactory(pledgeListView -> new PledgeListCell());
project.addListener(x -> updateForProject());
}
// Holds together various bindings so we can disconnect them when we switch projects.
private class UIBindings {
private final ObservableList<LHProtos.Pledge> sortedByTime;
private final ConcatenatingList<PieChart.Data> slices;
public UIBindings() {
// Bind the project pledges from the backend to the UI components so they react appropriately.
projectStates = Main.backend.mirrorProjectStates(AffinityExecutor.UI_THREAD);
projectStates.addListener((javafx.beans.InvalidationListener) x -> {
setModeFor(project.get(), pledgedValue.get());
});
//pledges = fakePledges();
ObservableSet<LHProtos.Pledge> openPledges = Main.backend.mirrorOpenPledges(project.get(), AffinityExecutor.UI_THREAD);
ObservableSet<LHProtos.Pledge> claimedPledges = Main.backend.mirrorClaimedPledges(project.get(), AffinityExecutor.UI_THREAD);
pledges = mergeSets(openPledges, claimedPledges);
pledges.addListener((SetChangeListener<? super LHProtos.Pledge>) change -> {
if (change.wasAdded())
checkForMyPledge(project.get());
});
final long goalAmount = project.get().getGoalAmount().value;
// - Bind the amount pledged to the label.
pledgedValue = LighthouseBackend.bindTotalPledgedProperty(pledges);
raisedAmountLabel.textProperty().bind(createStringBinding(() -> Coin.valueOf(pledgedValue.get()).toPlainString(), pledgedValue));
numPledgersLabel.textProperty().bind(Bindings.size(pledges).asString());
StringExpression format = Bindings.format("%.0f%%", pledgedValue.divide(1.0 * goalAmount).multiply(100.0));
percentFundedLabel.textProperty().bind(format);
// - Make the action button update when the amount pledged changes.
isFullyFundedAndNotParticipating =
pledgedValue.isEqualTo(project.get().getGoalAmount().longValue()).and(
mode.isEqualTo(Mode.OPEN_FOR_PLEDGES)
);
pledgedValue.addListener(o -> pledgedValueChanged(goalAmount, pledgedValue));
pledgedValueChanged(goalAmount, pledgedValue);
actionButton.disableProperty().bind(isFullyFundedAndNotParticipating);
// - Put pledges into the list view.
ObservableList<LHProtos.Pledge> list1 = FXCollections.observableArrayList();
bindSetToList(pledges, list1);
sortedByTime = new SortedList<>(list1, (o1, o2) -> -Long.compareUnsigned(o1.getTimestamp(), o2.getTimestamp()));
bindContent(pledgesList.getItems(), sortedByTime);
// - Convert pledges into pie slices.
MappedList<PieChart.Data, LHProtos.Pledge> pledgeSlices = new MappedList<>(sortedByTime,
pledge -> new PieChart.Data("", pledge.getTotalInputValue()));
// - Stick an invisible padding slice on the end so we can see through the unpledged part.
slices = new ConcatenatingList<>(pledgeSlices, singletonObservableList(emptySlice));
// - Connect to the chart widget.
bindContent(pieChart.getData(), slices);
}
public void unbind() {
numPledgersLabel.textProperty().unbind();
percentFundedLabel.textProperty().unbind();
unbindContent(pledgesList.getItems(), sortedByTime);
unbindContent(pieChart.getData(), slices);
}
}
public void updateForVisibility(boolean visible, @Nullable ObservableMap<Project, LighthouseBackend.CheckStatus> statusMap) {
if (project.get() == null) return;
if (visible) {
// Put the back keyboard shortcut in later, because removing an accelerator whilst a callback is being
// processed causes a ConcurrentModificationException inside the framework before 8u20.
Platform.runLater(() -> Main.instance.scene.getAccelerators().put(backKey, () -> backClicked(null)));
// Make the info bar appear if there's an error
checkStatus = valueAt(statusMap, project);
checkStatus.addListener(o -> updateInfoBar());
// Don't let the user perform an action whilst loading or if there's an error.
actionButton.disableProperty().unbind();
actionButton.disableProperty().bind(isFullyFundedAndNotParticipating.or(checkStatus.isNotNull()));
updateInfoBar();
} else {
// Take the back keyboard shortcut out later, because removing an accelerator whilst its callback is being
// processed causes a ConcurrentModificationException inside the framework before 8u20.
Platform.runLater(() -> Main.instance.scene.getAccelerators().remove(backKey));
if (notifyBarItem != null) {
notifyBarItem.cancel();
notifyBarItem = null;
}
}
}
private void updateForProject() {
pieChart.getData().clear();
pledgesList.getItems().clear();
final Project p = project.get();
projectTitle.setText(p.getTitle());
goalAmountLabel.setText(String.format(goalAmountFormatStr, p.getGoalAmount().toPlainString()));
description.getChildren().setAll(new Text(project.get().getMemo()));
pledgesListVBox.visibleProperty().bind(not(isEmpty(pledgesList.getItems())));
noPledgesLabel.visibleProperty().bind(isEmpty(pledgesList.getItems()));
// Load and set up the cover image.
Image img = new Image(p.getCoverImage().newInput());
if (img.getException() != null)
Throwables.propagate(img.getException());
BackgroundSize cover = new BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, false, false, false, true);
BackgroundImage bimg = new BackgroundImage(img, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT, cover);
coverImage.setBackground(new Background(bimg));
// Configure the pie chart.
emptySlice = new PieChart.Data("", 0);
if (bindings != null)
bindings.unbind();
bindings = new UIBindings();
// This must be done after the binding because otherwise it has no node in the scene graph yet.
emptySlice.getNode().setOpacity(0.1);
emptySlice.getNode().setVisible(true);
checkForMyPledge(p);
editButton.setVisible(Main.wallet.isProjectMine(p));
// If a cloned wallet double spends our pledge, the backend can notice this before the wallet does.
// Because the decision on what the button action should be depends on whether the wallet thinks it's pledged,
// we have to watch out for this and update the mode here.
Main.wallet.addOnRevokeHandler(pledge -> setModeFor(p, pledgedValue.get()), Platform::runLater);
if (p.getPaymentURL() != null) {
Platform.runLater(() -> {
Main.instance.scene.getAccelerators().put(KeyCombination.keyCombination("Shortcut+R"), () -> Main.backend.refreshProjectStatusFromServer(p));
});
}
}
private void checkForMyPledge(Project p) {
LHProtos.Pledge myPledge = Main.wallet.getPledgeFor(p);
if (myPledge != null)
myPledgeHash = LHUtils.hashFromPledge(myPledge);
}
private void updateInfoBar() {
if (notifyBarItem != null)
notifyBarItem.cancel();
final LighthouseBackend.CheckStatus status = checkStatus.get();
if (status != null && status.error != null) {
String msg = status.error.getLocalizedMessage();
if (status.error instanceof FileNotFoundException)
msg = "Server error: 404 Not Found: project is not known";
else if (status.error instanceof Ex.InconsistentUTXOAnswers)
msg = "Bitcoin P2P network returned inconsistent answers, please contact support";
else //noinspection ConstantConditions
if (msg == null)
msg = "Internal error: " + status.error.getClass().getName();
else
msg = "Error: " + msg;
notifyBarItem = Main.instance.notificationBar.displayNewItem(msg);
}
}
private void pledgedValueChanged(long goalAmount, LongProperty pledgedValue) {
// Take the max so if we end up with more pledges than the goal in serverless mode, the pie chart is always
// full and doesn't go backwards due to a negative pie slice.
emptySlice.setPieValue(Math.max(0, goalAmount - pledgedValue.get()));
setModeFor(project.get(), pledgedValue.get());
}
private void updateGUIForState() {
coverImage.setEffect(null);
switch (mode.get()) {
case OPEN_FOR_PLEDGES:
if (isFullyFundedAndNotParticipating.get()) {
actionButton.setText("Fully funded");
// Disable state is handled by binding.
} else {
actionButton.setText("Pledge");
}
break;
case PLEDGED:
actionButton.setText("Revoke");
break;
case CAN_CLAIM:
actionButton.setText("Claim");
break;
case CLAIMED:
actionButton.setText("View claim transaction");
ColorAdjust effect = new ColorAdjust();
coverImage.setEffect(effect);
if (priorMode != Mode.CLAIMED) {
Timeline timeline = new Timeline(new KeyFrame(GuiUtils.UI_ANIMATION_TIME.multiply(3), new KeyValue(effect.saturationProperty(), -0.9)));
timeline.play();
} else {
effect.setSaturation(-0.9);
}
break;
}
}
private void setModeFor(Project project, long value) {
priorMode = mode.get();
Mode newMode = Mode.OPEN_FOR_PLEDGES;
if (projectStates.get(project.getID()).state == LighthouseBackend.ProjectState.CLAIMED) {
newMode = Mode.CLAIMED;
} else {
if (Main.wallet.getPledgedAmountFor(project) > 0)
newMode = Mode.PLEDGED;
if (value >= project.getGoalAmount().value && Main.wallet.isProjectMine(project))
newMode = Mode.CAN_CLAIM;
}
log.info("Mode is {}", newMode);
mode.set(newMode);
if (priorMode == null) priorMode = newMode;
updateGUIForState();
}
private ObservableSet<LHProtos.Pledge> fakePledges() {
ImmutableList.Builder<LHProtos.Pledge> list = ImmutableList.builder();
LHProtos.Pledge.Builder builder = LHProtos.Pledge.newBuilder();
builder.setProjectId("abc");
long now = Instant.now().getEpochSecond();
for (int i = 0; i < 1; i++) {
builder.setTotalInputValue(Coin.CENT.value * 70);
builder.setTimestamp(now++);
list.add(builder.build());
builder.setTotalInputValue(Coin.CENT.value * 20);
builder.setTimestamp(now++);
list.add(builder.build());
builder.setTotalInputValue(Coin.CENT.value * 10);
builder.setTimestamp(now++);
list.add(builder.build());
builder.setTotalInputValue(Coin.CENT.value * 30);
builder.setTimestamp(now++);
list.add(builder.build());
}
return FXCollections.observableSet(new HashSet<>(list.build()));
}
private void setupFXML() {
try {
FXMLLoader loader = new FXMLLoader(getResource("controls/project_view.fxml"));
loader.setRoot(this);
loader.setController(this);
// The following line is supposed to help Scene Builder, although it doesn't seem to be needed for me.
loader.setClassLoader(getClass().getClassLoader());
loader.load();
goalAmountFormatStr = goalAmountLabel.getText();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@FXML
private void backClicked(@Nullable ActionEvent event) {
if (onBackClickedProperty.get() != null)
onBackClickedProperty.get().handle(event);
}
@FXML
private void actionClicked(ActionEvent event) {
final Project p = project.get();
switch (mode.get()) {
case OPEN_FOR_PLEDGES:
makePledge(p);
break;
case PLEDGED:
revokePledge(p);
break;
case CAN_CLAIM:
claimPledges(p);
break;
case CLAIMED:
viewClaim(p);
break;
default:
throw new AssertionError(); // Unreachable.
}
}
private void viewClaim(Project p) {
LighthouseBackend.ProjectStateInfo info = projectStates.get(p.getID());
checkState(info.state == LighthouseBackend.ProjectState.CLAIMED);
String url = String.format(Main.params == TestNet3Params.get() ? BLOCK_EXPLORER_SITE_TESTNET : BLOCK_EXPLORER_SITE, info.claimedBy);
log.info("Opening {}", url);
Main.instance.getHostServices().showDocument(url);
}
private void makePledge(Project p) {
log.info("Invoking pledge screen");
PledgeWindow window = Main.instance.<PledgeWindow>overlayUI("subwindows/pledge.fxml", "Pledge").controller;
window.project = p;
window.setLimits(p.getGoalAmount().subtract(Coin.valueOf(pledgedValue.get())), p.getMinPledgeAmount());
window.onSuccess = () -> {
mode.set(Mode.PLEDGED);
updateGUIForState();
};
}
private void claimPledges(Project p) {
log.info("Claim button clicked for {}", p);
Main.OverlayUI<RevokeAndClaimWindow> overlay = RevokeAndClaimWindow.openForClaim(p, pledges);
overlay.controller.onSuccess = () -> {
mode.set(Mode.OPEN_FOR_PLEDGES);
updateGUIForState();
};
}
private void revokePledge(Project project) {
log.info("Revoke button clicked: {}", project.getTitle());
LHProtos.Pledge pledge = Main.wallet.getPledgeFor(project);
checkNotNull(pledge, "UI invariant violation"); // Otherwise our UI is really messed up.
Main.OverlayUI<RevokeAndClaimWindow> overlay = RevokeAndClaimWindow.openForRevoke(pledge);
overlay.controller.onSuccess = () -> {
mode.set(Mode.OPEN_FOR_PLEDGES);
updateGUIForState();
};
}
public void setProject(Project project) {
this.project.set(project);
}
public Project getProject() {
return this.project.get();
}
// TODO: Should we show revoked pledges crossed out?
private class PledgeListCell extends ListCell<LHProtos.Pledge> {
private Label status, email, memoSnippet, date;
private Label viewMore;
public PledgeListCell() {
Pane pane;
HBox hbox;
VBox vbox = new VBox(
(status = new Label()),
(hbox = new HBox(
(email = new Label()),
(pane = new Pane()),
(date = new Label())
)),
(memoSnippet = new Label()),
(viewMore = new Label("View more"))
);
vbox.getStyleClass().add("pledge-cell");
status.getStyleClass().add("pledge-cell-status");
email.getStyleClass().add("pledge-cell-email");
HBox.setHgrow(pane, Priority.ALWAYS);
vbox.setFillWidth(true);
hbox.maxWidthProperty().bind(vbox.widthProperty());
date.getStyleClass().add("pledge-cell-date");
date.setMinWidth(USE_PREF_SIZE); // Date is shown in preference to contact if contact data is too long
memoSnippet.getStyleClass().add("pledge-cell-memo");
memoSnippet.setWrapText(true);
memoSnippet.maxWidthProperty().bind(vbox.widthProperty());
memoSnippet.setMaxHeight(100);
viewMore.getStyleClass().add("hover-link");
viewMore.setOnMouseClicked(ev -> ShowPledgeWindow.open(project.get(), getItem()));
viewMore.setAlignment(Pos.CENTER_RIGHT);
viewMore.prefWidthProperty().bind(vbox.widthProperty());
vbox.setPrefHeight(0);
vbox.setMaxHeight(USE_PREF_SIZE);
setGraphic(vbox);
setOnMouseClicked(ev -> {
if (ev.getClickCount() == 2)
ShowPledgeWindow.open(project.get(), getItem());
});
}
@Override
protected void updateItem(LHProtos.Pledge pledge, boolean empty) {
super.updateItem(pledge, empty);
if (empty) {
getGraphic().setVisible(false);
return;
}
getGraphic().setVisible(true);
String msg = Coin.valueOf(pledge.getTotalInputValue()).toFriendlyString();
if (LHUtils.hashFromPledge(pledge).equals(myPledgeHash))
msg += " (yours)";
status.setText(msg);
email.setText(pledge.getPledgeDetails().getContactAddress());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime time = LocalDateTime.ofEpochSecond(pledge.getTimestamp(), 0, ZoneOffset.UTC);
date.setText(time.format(formatter));
memoSnippet.setText(pledge.getPledgeDetails().getMemo());
}
}
@FXML
public void edit(ActionEvent event) {
log.info("Edit button clicked");
if (pledgedValue.get() > 0) {
informationalAlert("Unable to edit",
"You cannot edit a project that has already started gathering pledges, as otherwise existing " +
"pledges could be invalidated and participants could get confused. If you would like to " +
"change this project either create a new one, or request revocation of existing pledges."
);
return;
}
EditProjectWindow.openForEdit(project.get());
}
@FXML
public void onViewTechDetailsClicked(MouseEvent event) {
log.info("View tech details of project clicked for {}", project.get().getTitle());
ProjectTechDetailsWindow.open(project.get());
}
@FXML
public void exportPledgesClicked(MouseEvent event) {
log.info("Export pledges clicked for {}", project.get().getTitle());
FileChooser chooser = new FileChooser();
chooser.setTitle("Export pledges to CSV file");
chooser.setInitialFileName("pledges.csv");
GuiUtils.platformFiddleChooser(chooser);
File file = chooser.showSaveDialog(Main.instance.mainStage);
if (file == null) {
log.info(" ... but user cancelled");
return;
}
log.info("Saving pledges as CSV to file {}", file);
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), Charsets.UTF_8)) {
writer.append(String.format("num_satoshis,time,email,message%n"));
for (LHProtos.Pledge pledge : pledgesList.getItems()) {
String time = Instant.ofEpochSecond(pledge.getTimestamp()).atZone(ZoneId.of("UTC")).format(DateTimeFormatter.RFC_1123_DATE_TIME).replace(",", "");
String memo = pledge.getPledgeDetails().getMemo().replace('\n', ' ').replace(",", "");
writer.append(String.format("%d,%s,%s,%s%n", pledge.getTotalInputValue(), time, pledge.getPledgeDetails().getContactAddress(), memo));
}
GuiUtils.informationalAlert("Export succeeded", "Pledges are stored in a CSV file, which can be loaded with any spreadsheet application. Amounts are specified in satoshis.");
} catch (IOException e) {
log.error("Failed to write to csv file", e);
GuiUtils.informationalAlert("Export failed", "Lighthouse was unable to save pledge data to the selected file: %s", e.getLocalizedMessage());
}
}
}
|
package org.jetel.ctl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import junit.framework.AssertionFailedError;
import org.jetel.component.CTLRecordTransform;
import org.jetel.component.RecordTransform;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.SetVal;
import org.jetel.data.lookup.LookupTable;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.primitive.Decimal;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.TransformException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.ContextProvider.Context;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldContainerType;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.test.CloverTestCase;
import org.jetel.util.MiscUtils;
import org.jetel.util.bytes.PackedDecimal;
import org.jetel.util.crypto.Base64;
import org.jetel.util.crypto.Digest;
import org.jetel.util.crypto.Digest.DigestType;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.string.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Years;
public abstract class CompilerTestCase extends CloverTestCase {
protected static final String INPUT_1 = "firstInput";
protected static final String INPUT_2 = "secondInput";
protected static final String INPUT_3 = "thirdInput";
protected static final String INPUT_4 = "multivalueInput";
protected static final String OUTPUT_1 = "firstOutput";
protected static final String OUTPUT_2 = "secondOutput";
protected static final String OUTPUT_3 = "thirdOutput";
protected static final String OUTPUT_4 = "fourthOutput";
protected static final String OUTPUT_5 = "firstMultivalueOutput";
protected static final String OUTPUT_6 = "secondMultivalueOutput";
protected static final String OUTPUT_7 = "thirdMultivalueOutput";
protected static final String LOOKUP = "lookupMetadata";
protected static final String NAME_VALUE = " HELLO ";
protected static final Double AGE_VALUE = 20.25;
protected static final String CITY_VALUE = "Chong'La";
protected static final Date BORN_VALUE;
protected static final Long BORN_MILLISEC_VALUE;
static {
Calendar c = Calendar.getInstance();
c.set(2008, 12, 25, 13, 25, 55);
c.set(Calendar.MILLISECOND, 333);
BORN_VALUE = c.getTime();
BORN_MILLISEC_VALUE = c.getTimeInMillis();
}
protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10;
protected static final Boolean FLAG_VALUE = true;
protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes();
protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525");
protected static final int DECIMAL_PRECISION = 7;
protected static final int DECIMAL_SCALE = 3;
protected static final int NORMALIZE_RETURN_OK = 0;
public static final int DECIMAL_MAX_PRECISION = 32;
public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN);
/** Flag to trigger Java compilation */
private boolean compileToJava;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected TransformationGraph graph;
public CompilerTestCase(boolean compileToJava) {
this.compileToJava = compileToJava;
}
/**
* Method to execute tested CTL code in a way specific to testing scenario.
*
* Assumes that
* {@link #graph}, {@link #inputRecords} and {@link #outputRecords}
* have already been set.
*
* @param compiler
*/
public abstract void executeCode(ITLCompiler compiler);
/**
* Method which provides access to specified global variable
*
* @param varName
* global variable to be accessed
* @return
*
*/
protected abstract Object getVariable(String varName);
protected void check(String varName, Object expectedResult) {
assertEquals(varName, expectedResult, getVariable(varName));
}
protected void checkEquals(String varName1, String varName2) {
assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2));
}
protected void checkNull(String varName) {
assertNull(getVariable(varName));
}
private void checkArray(String varName, byte[] expected) {
byte[] actual = (byte[]) getVariable(varName);
assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected));
}
private static String byteArrayAsString(byte[] array) {
final StringBuilder sb = new StringBuilder("[");
for (final byte b : array) {
sb.append(b);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append(']');
return sb.toString();
}
@Override
protected void setUp() {
// set default locale to English to prevent various parsing errors
Locale.setDefault(Locale.ENGLISH);
initEngine();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
inputRecords = null;
outputRecords = null;
graph = null;
}
protected TransformationGraph createEmptyGraph() {
return new TransformationGraph();
}
protected TransformationGraph createDefaultGraph() {
TransformationGraph g = createEmptyGraph();
// set the context URL, so that imports can be used
g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource("."));
final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>();
metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1));
metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2));
metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3));
metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4));
metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1));
metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2));
metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3));
metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4));
metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5));
metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6));
metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7));
metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP));
g.addDataRecordMetadata(metadataMap);
g.addSequence(createDefaultSequence(g, "TestSequence"));
g.addLookupTable(createDefaultLookup(g, "TestLookup"));
Properties properties = new Properties();
properties.put("PROJECT", ".");
properties.put("DATAIN_DIR", "${PROJECT}/data-in");
properties.put("COUNT", "`1+2`");
properties.put("NEWLINE", "\\n");
g.getGraphParameters().setProperties(properties);
initDefaultDictionary(g);
return g;
}
private void initDefaultDictionary(TransformationGraph g) {
try {
g.getDictionary().init();
g.getDictionary().setValue("s", "string", null);
g.getDictionary().setValue("i", "integer", null);
g.getDictionary().setValue("l", "long", null);
g.getDictionary().setValue("d", "decimal", null);
g.getDictionary().setValue("n", "number", null);
g.getDictionary().setValue("a", "date", null);
g.getDictionary().setValue("b", "boolean", null);
g.getDictionary().setValue("y", "byte", null);
g.getDictionary().setValue("i211", "integer", new Integer(211));
g.getDictionary().setValue("sVerdon", "string", "Verdon");
g.getDictionary().setValue("l452", "long", new Long(452));
g.getDictionary().setValue("d621", "decimal", new BigDecimal(621));
g.getDictionary().setValue("n9342", "number", new Double(934.2));
g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE);
g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} );
g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc"));
g.getDictionary().setContentType("stringList", "string");
g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
g.getDictionary().setContentType("dateList", "date");
g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
g.getDictionary().setContentType("byteList", "byte");
} catch (ComponentNotReadyException e) {
throw new RuntimeException("Error init default dictionary", e);
}
}
protected Sequence createDefaultSequence(TransformationGraph graph, String name) {
Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class });
try {
seq.checkConfig(new ConfigurationStatus());
seq.init();
} catch (ComponentNotReadyException e) {
throw new RuntimeException(e);
}
return seq;
}
/**
* Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite
* lookup key Name+Value. Use field City for testing response.
*
* @param graph
* @param name
* @return
*/
protected LookupTable createDefaultLookup(TransformationGraph graph, String name) {
final TypedProperties props = new TypedProperties();
props.setProperty("id", "LookupTable0");
props.setProperty("type", "simpleLookup");
props.setProperty("metadata", LOOKUP);
props.setProperty("key", "Name;Value");
props.setProperty("name", name);
props.setProperty("keyDuplicates", "true");
/*
* The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code
* below, however this will most probably break down test_lookup() because free() will wipe away all data and
* noone will restore them
*/
URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat");
if (dataFile == null) {
throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader");
}
props.setProperty("fileURL", dataFile.getFile());
LookupTableFactory.init();
LookupTable lkp = LookupTableFactory.createLookupTable(props);
lkp.setGraph(graph);
try {
lkp.checkConfig(new ConfigurationStatus());
lkp.init();
lkp.preExecute();
} catch (ComponentNotReadyException ex) {
throw new RuntimeException(ex);
}
/*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse"));
lkpRecord.getField("Name").setValue("Alpha");
lkpRecord.getField("Value").setValue(1);
lkpRecord.getField("City").setValue("Andorra la Vella");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Bravo");
lkpRecord.getField("Value").setValue(2);
lkpRecord.getField("City").setValue("Bruxelles");
lkp.put(lkpRecord);
// duplicate entry
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chamonix");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chomutov");
lkp.put(lkpRecord);*/
return lkp;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|");
dateField.setFormatStr("yyyy-MM-dd HH:mm:ss");
ret.addField(dateField);
ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|"));
ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|"));
ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|"));
ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|"));
DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n");
decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION));
decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE));
ret.addField(decimalField);
return ret;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefault1Metadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
return ret;
}
/**
* Creates records with default structure
* containing multivalue fields.
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMultivalueMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|");
stringListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(stringListField);
DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|");
ret.addField(dateField);
DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|");
ret.addField(byteField);
DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|");
dateListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(dateListField);
DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|");
byteListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(byteListField);
DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|");
ret.addField(stringField);
DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|");
integerMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(integerMapField);
DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|");
stringMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(stringMapField);
DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|");
dateMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(dateMapField);
DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|");
byteMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(byteMapField);
DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|");
integerListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(integerListField);
DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|");
decimalListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(decimalListField);
DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|");
decimalMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(decimalMapField);
return ret;
}
protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
DataField field = ret.getField(i);
DataFieldMetadata fieldMetadata = field.getMetadata();
switch (fieldMetadata.getContainerType()) {
case SINGLE:
switch (fieldMetadata.getDataType()) {
case STRING:
field.setValue("John");
break;
case DATE:
field.setValue(new Date(10000));
break;
case BYTE:
field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } );
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
break;
case LIST:
{
List<Object> value = new ArrayList<Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.addAll(Arrays.asList("John", "Doe", "Jersey"));
break;
case INTEGER:
value.addAll(Arrays.asList(123, 456, 789));
break;
case DATE:
value.addAll(Arrays.asList(new Date (12000), new Date(34000)));
break;
case BYTE:
value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78}));
break;
case DECIMAL:
value.addAll(Arrays.asList(12.34, 56.78));
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
case MAP:
{
Map<String, Object> value = new HashMap<String, Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.put("firstName", "John");
value.put("lastName", "Doe");
value.put("address", "Jersey");
break;
case INTEGER:
value.put("count", 123);
value.put("max", 456);
value.put("sum", 789);
break;
case DATE:
value.put("before", new Date (12000));
value.put("after", new Date(34000));
break;
case BYTE:
value.put("hash", new byte[] {0x12, 0x34});
value.put("checksum", new byte[] {0x56, 0x78});
break;
case DECIMAL:
value.put("asset", 12.34);
value.put("liability", 56.78);
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
default:
throw new IllegalArgumentException(fieldMetadata.getContainerType().toString());
}
}
return ret;
}
protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
SetVal.setString(ret, "Name", NAME_VALUE);
SetVal.setDouble(ret, "Age", AGE_VALUE);
SetVal.setString(ret, "City", CITY_VALUE);
SetVal.setDate(ret, "Born", BORN_VALUE);
SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE);
SetVal.setInt(ret, "Value", VALUE_VALUE);
SetVal.setValue(ret, "Flag", FLAG_VALUE);
SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE);
SetVal.setValue(ret, "Currency", CURRENCY_VALUE);
return ret;
}
/**
* Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code>
*
* @param metadata
* structure to use
* @return empty record
*/
protected DataRecord createEmptyRecord(DataRecordMetadata metadata) {
DataRecord ret = DataRecordFactory.newRecord(metadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
SetVal.setNull(ret, i);
}
return ret;
}
/**
* Executes the code using the default graph and records.
*/
protected void doCompile(String expStr, String testIdentifier) {
TransformationGraph graph = createDefaultGraph();
DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) };
DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) };
doCompile(expStr, testIdentifier, graph, inRecords, outRecords);
}
/**
* This method should be used to execute a test with a custom graph and custom input and output records.
*
* To execute a test with the default graph,
* use {@link #doCompile(String)}
* or {@link #doCompile(String, String)} instead.
*
* @param expStr
* @param testIdentifier
* @param graph
* @param inRecords
* @param outRecords
*/
protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) {
this.graph = graph;
this.inputRecords = inRecords;
this.outputRecords = outRecords;
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length];
for (int i = 0; i < inRecords.length; i++) {
inMetadata[i] = inRecords[i].getMetadata();
}
DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length];
for (int i = 0; i < outRecords.length; i++) {
outMetadata[i] = outRecords[i].getMetadata();
}
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
// try {
// System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier));
// } catch (ErrorMessageException e) {
// System.out.println("Error parsing CTL code. Unable to output Java translation.");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() > 0) {
throw new AssertionFailedError("Error in execution. Check standard output for details.");
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
executeCode(compiler);
}
protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) {
graph = createDefaultGraph();
DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) };
DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) };
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() == 0) {
throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors.");
}
if (compiler.errorCount() != errCodes.size()) {
throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors.");
}
Iterator<String> it = errCodes.iterator();
for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) {
String expectedError = it.next();
if (!expectedError.equals(errorMessage.getErrorMessage())) {
throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'");
}
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
// executeCode(compiler);
}
protected void doCompileExpectError(String testIdentifier, String errCode) {
doCompileExpectErrors(testIdentifier, Arrays.asList(errCode));
}
protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes);
}
/**
* Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected String loadSourceCode(String testIdentifier) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
return sourceCode.toString();
}
/**
* Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* The default graph and records are used for the execution.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected void doCompile(String testIdentifier) {
String sourceCode = loadSourceCode(testIdentifier);
doCompile(sourceCode, testIdentifier);
}
protected void printMessages(List<ErrorMessage> diagnosticMessages) {
for (ErrorMessage e : diagnosticMessages) {
System.out.println(e);
}
}
/**
* Compares two records if they have the same number of fields and identical values in their fields. Does not
* consider (or examine) metadata.
*
* @param lhs
* @param rhs
* @return true if records have the same number of fields and the same values in them
*/
protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) {
if (lhs == rhs)
return true;
if (rhs == null)
return false;
if (lhs == null) {
return false;
}
if (lhs.getNumFields() != rhs.getNumFields()) {
return false;
}
for (int i = 0; i < lhs.getNumFields(); i++) {
if (lhs.getField(i).isNull()) {
if (!rhs.getField(i).isNull()) {
return false;
}
} else if (!lhs.getField(i).equals(rhs.getField(i))) {
return false;
}
}
return true;
}
public void print_code(String text) {
String[] lines = text.split("\n");
System.out.println("\t: 1 2 3 4 5 ");
System.out.println("\t:12345678901234567890123456789012345678901234567890123456789");
for (int i = 0; i < lines.length; i++) {
System.out.println((i + 1) + "\t:" + lines[i]);
}
}
@SuppressWarnings("unchecked")
public void test_operators_unary_record_allowed() {
doCompile("test_operators_unary_record_allowed");
check("value", Arrays.asList(14, 16, 16, 65, 63, 63));
check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L));
List<Double> actualAge = (List<Double>) getVariable("age");
double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789};
for (int i = 0; i < actualAge.size(); i++) {
assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001);
}
check("currency", Arrays.asList(
new BigDecimal(BigInteger.valueOf(12500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(65432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3)
));
}
@SuppressWarnings("unchecked")
public void test_dynamic_compare() {
doCompile("test_dynamic_compare");
String varName = "compare";
List<Integer> compareResult = (List<Integer>) getVariable(varName);
for (int i = 0; i < compareResult.size(); i++) {
if ((i % 3) == 0) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0);
} else if ((i % 3) == 1) {
assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i));
} else if ((i % 3) == 2) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0);
}
}
varName = "compareBooleans";
compareResult = (List<Integer>) getVariable(varName);
assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0));
assertTrue(varName + "[1]", compareResult.get(1) > 0);
assertTrue(varName + "[2]", compareResult.get(2) < 0);
assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3));
}
public void test_dynamiclib_compare_expect_error(){
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 'Flagxx', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 'Flag', myRec2, 'Flagxx'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = null; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "$out.0.Flag = true; "
+ "$out.1.Age = 11;"
+ "integer i = compare($out.0, 'Flag', $out.1, 'Age'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, -1, myRec2, -1 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 2, myRec2, 2 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "$out.0.8 = 12.4d; "
+ "$out.1.8 = 12.5d;"
+ "integer i = compare($out.0, 9, $out.1, 9 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "$out.0.0 = null; "
+ "$out.1.0 = null;"
+ "integer i = compare($out.0, 0, $out.1, 0 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
private void test_dynamic_get_set_loop(String testIdentifier) {
doCompile(testIdentifier);
check("recordLength", 9);
check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233));
check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal"));
check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000"));
check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false));
check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
Integer[] indices = new Integer[9];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
check("fieldIndex", Arrays.asList(indices));
// check dynamic write and read with all data types
check("booleanVar", true);
assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar")));
check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3));
check("integerVar", 1000);
check("longVar", 1000000000000L);
check("numberVar", 1000.5);
check("stringVar", "hello");
check("dateVar", new Date(5000));
// null value
Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(someValue, Boolean.FALSE);
check("someValue", Arrays.asList(someValue));
Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(nullValue, Boolean.TRUE);
check("nullValue", Arrays.asList(nullValue));
String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
check("asString2", Arrays.asList(asString2));
Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(isNull2, Boolean.TRUE);
check("isNull2", Arrays.asList(isNull2));
}
public void test_dynamic_get_set_loop() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop");
}
public void test_dynamic_get_set_loop_alternative() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative");
}
public void test_dynamic_invalid() {
doCompileExpectErrors("test_dynamic_invalid", Arrays.asList(
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_dynamiclib_getBoolValue(){
doCompile("test_dynamiclib_getBoolValue");
check("ret1", true);
check("ret2", true);
check("ret3", false);
check("ret4", false);
check("ret5", null);
check("ret6", null);
}
public void test_dynamiclib_getBoolValue_expect_error(){
try {
doCompile("function integer transform(){boolean b = getBoolValue($in.0, 2);return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){boolean b = getBoolValue($in.0, 'Age');return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 6); return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 'Flag'); return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getByteValue(){
doCompile("test_dynamiclib_getByteValue");
checkArray("ret1",CompilerTestCase.BYTEARRAY_VALUE);
checkArray("ret2",CompilerTestCase.BYTEARRAY_VALUE);
check("ret3", null);
check("ret4", null);
}
public void test_dynamiclib_getByteValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; byte b = getByteValue(fi,7); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; byte b = fi.getByteValue('ByteArray'); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = $in.0.getByteValue('Age'); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = getByteValue($in.0, 0); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getDateValue(){
doCompile("test_dynamiclib_getDateValue");
check("ret1", CompilerTestCase.BORN_VALUE);
check("ret2", CompilerTestCase.BORN_VALUE);
check("ret3", null);
check("ret4", null);
}
public void test_dynamiclib_getDateValue_expect_error(){
try {
doCompile("function integer transform(){date d = getDateValue($in.0,1); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = getDateValue($in.0,'Age'); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,'Born'); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,3); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getDecimalValue(){
doCompile("test_dynamiclib_getDecimalValue");
check("ret1", CompilerTestCase.CURRENCY_VALUE);
check("ret2", CompilerTestCase.CURRENCY_VALUE);
check("ret3", null);
check("ret4", null);
}
public void test_dynamiclib_getDecimalValue_expect_error(){
try {
doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 1); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 'Age'); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,8); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,'Currency'); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldIndex(){
doCompile("test_dynamiclib_getFieldIndex");
check("ret1", 1);
check("ret2", 1);
check("ret3", -1);
}
public void test_dynamiclib_getFieldIndex_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; integer int = fi.getFieldIndex('Age'); return 0;}","test_dynamiclib_getFieldIndex_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldLabel(){
doCompile("test_dynamiclib_getFieldLabel");
check("ret1", "Age");
check("ret2", "Name");
check("ret3", "Age");
check("ret4", "Value");
}
public void test_dynamiclib_getFieldLable_expect_error(){
try {
doCompile("function integer transform(){string name = getFieldLabel($in.0, -5);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string name = getFieldLabel($in.0, 12);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel(2);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('Age');return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('');return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string name = getFieldLabel($in.0, 'Tristana');return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string name = getFieldLabel($in.0, '');return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldName(){
doCompile("test_dynamiclib_getFieldName");
check("ret1", "Age");
check("ret2", "Name");
}
public void test_dynamiclib_getFieldName_expect_error(){
try {
doCompile("function integer transform(){string str = getFieldName($in.0, -5); return 0;}","test_dynamiclib_getFieldName_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getFieldName($in.0, 15); return 0;}","test_dynamiclib_getFieldName_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldName(2); return 0;}","test_dynamiclib_getFieldName_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldType(){
doCompile("test_dynamiclib_getFieldType");
check("ret1", "string");
check("ret2", "number");
}
public void test_dynamiclib_getFieldType_expect_error(){
try {
doCompile("function integer transform(){string str = getFieldType($in.0, -5); return 0;}","test_dynamiclib_getFieldType_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getFieldType($in.0, 12); return 0;}","test_dynamiclib_getFieldType_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldType(5); return 0;}","test_dynamiclib_getFieldType_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getIntValue(){
doCompile("test_dynamiclib_getIntValue");
check("ret1", CompilerTestCase.VALUE_VALUE);
check("ret2", CompilerTestCase.VALUE_VALUE);
check("ret3", CompilerTestCase.VALUE_VALUE);
check("ret4", CompilerTestCase.VALUE_VALUE);
check("ret5", null);
}
public void test_dynamiclib_getIntValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; integer i = fi.getIntValue(5); return 0;}","test_dynamiclib_getIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getIntValue($in.0, 1); return 0;}","test_dynamiclib_getIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getIntValue($in.0, 'Born'); return 0;}","test_dynamiclib_getIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getLongValue(){
doCompile("test_dynamiclib_getLongValue");
check("ret1", CompilerTestCase.BORN_MILLISEC_VALUE);
check("ret2", CompilerTestCase.BORN_MILLISEC_VALUE);
check("ret3", null);
}
public void test_dynamiclib_getLongValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; long l = getLongValue(fi, 4);return 0;} ","test_dynamiclib_getLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long l = getLongValue($in.0, 7);return 0;} ","test_dynamiclib_getLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long l = getLongValue($in.0, 'Age');return 0;} ","test_dynamiclib_getLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getNumValue(){
doCompile("test_dynamiclib_getNumValue");
check("ret1", CompilerTestCase.AGE_VALUE);
check("ret2", CompilerTestCase.AGE_VALUE);
check("ret3", null);
}
public void test_dynamiclib_getNumValue_expectValue(){
try {
doCompile("function integer transform(){firstInput fi = null; number n = getNumValue(fi, 1); return 0;}","test_dynamiclib_getNumValue_expectValue");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number n = getNumValue($in.0, 4); return 0;}","test_dynamiclib_getNumValue_expectValue");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number n = $in.0.getNumValue('Name'); return 0;}","test_dynamiclib_getNumValue_expectValue");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getStringValue(){
doCompile("test_dynamiclib_getStringValue");
check("ret1", CompilerTestCase.NAME_VALUE);
check("ret2", CompilerTestCase.NAME_VALUE);
check("ret3", null);
}
public void test_dynamiclib_getStringValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; string str = getStringValue(fi, 0); return 0;}","test_dynamiclib_getStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getStringValue($in.0, 5); return 0;}","test_dynamiclib_getStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = $in.0.getStringValue('Age'); return 0;}","test_dynamiclib_getStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getValueAsString(){
doCompile("test_dynamiclib_getValueAsString");
check("ret1", " HELLO ");
check("ret2", "20.25");
check("ret3", "Chong'La");
check("ret4", "Sun Jan 25 13:25:55 CET 2009");
check("ret5", "1232886355333");
check("ret6", "2147483637");
check("ret7", "true");
check("ret8", "41626563656461207a65646c612064656461");
check("ret9", "133.525");
check("ret10", null);
}
public void test_dynamiclib_getValueAsString_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; string str = getValueAsString(fi, 1); return 0;}","test_dynamiclib_getValueAsString_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getValueAsString($in.0, -1); return 0;}","test_dynamiclib_getValueAsString_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = $in.0.getValueAsString(10); return 0;}","test_dynamiclib_getValueAsString_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_isNull(){
doCompile("test_dynamiclib_isNull");
check("ret1", false);
check("ret2", false);
check("ret3", true);
}
public void test_dynamiclib_isNull_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; boolean b = fi.isNull(1); return 0;}","test_dynamiclib_isNull_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){boolean b = $in.0.isNull(-5); return 0;}","test_dynamiclib_isNull_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){boolean b = isNull($in.0,12); return 0;}","test_dynamiclib_isNull_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setBoolValue(){
doCompile("test_dynamiclib_setBoolValue");
check("ret1", null);
check("ret2", true);
check("ret3", false);
}
public void test_dynamiclib_setBoolValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setBoolValue(fi,6,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setBoolValue($out.0,1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setBoolValue(15,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setBoolValue(-1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setByteValue() throws UnsupportedEncodingException{
doCompile("test_dynamiclib_setByteValue");
checkArray("ret1", "Urgot".getBytes("UTF-8"));
check("ret2", null);
}
public void test_dynamiclib_setByteValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi =null; setByteValue(fi,7,str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setByteValue($out.0, 1, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setByteValue($out.0, 12, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setByteValue(-2, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setDateValue(){
doCompile("test_dynamiclib_setDateValue");
Calendar cal = Calendar.getInstance();
cal.set(2006,10,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret1", cal.getTime());
check("ret2", null);
}
public void test_dynamiclib_setDateValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setDateValue(fi,'Born', null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setDateValue($out.0,1, null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setDateValue($out.0,-2, null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setDateValue(12, null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setDecimalValue(){
doCompile("test_dynamiclib_setDecimalValue");
check("ret1", new BigDecimal("12.300"));
check("ret2", null);
}
public void test_dynamiclib_setDecimalValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setDecimalValue(fi, 'Currency', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setDecimalValue($out.0, 'Name', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setDecimalValue(-1, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setDecimalValue(15, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setIntValue(){
doCompile("test_dynamiclib_setIntValue");
check("ret1", 90);
check("ret2", null);
}
public void test_dynamiclib_setIntValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi =null; setIntValue(fi,5,null);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setIntValue($out.0,4,90);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setIntValue($out.0,-2,90);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setIntValue(15,90);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setLongValue(){
doCompile("test_dynamiclib_setLongValue");
check("ret1", 1565486L);
check("ret2", null);
}
public void test_dynamiclib_setLongValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setLongValue(fi, 4, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setLongValue($out.0, 0, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setLongValue($out.0, -1, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setLongValue(12, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setNumValue(){
doCompile("test_dynamiclib_setNumValue");
check("ret1", 12.5d);
check("ret2", null);
}
public void test_dynamiclib_setNumValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setNumValue(fi, 'Age', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setNumValue($out.0, 'Name', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setNumValue($out.0, -1, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setNumValue(11, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setStringValue(){
doCompile("test_dynamiclib_setStringValue");
check("ret1", "Zac");
check("ret2", null);
}
public void test_dynamiclib_setStringValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setStringValue(fi, 'Name', 'Draven'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setStringValue($out.0, 'Age', 'Soraka'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setStringValue($out.0, -1, 'Rengar'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setStringValue(11, 'Vaigar'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_return_constants() {
// test case for issue 2257
System.out.println("Return constants test:");
doCompile("test_return_constants");
check("skip", RecordTransform.SKIP);
check("all", RecordTransform.ALL);
check("ok", NORMALIZE_RETURN_OK);
check("stop", RecordTransform.STOP);
}
public void test_ambiguous() {
// built-in toString function
doCompileExpectError("test_ambiguous_toString", "Function 'toString' is ambiguous");
// built-in join function
doCompileExpectError("test_ambiguous_join", "Function 'join' is ambiguous");
// locally defined functions
doCompileExpectError("test_ambiguous_localFunctions", "Function 'local' is ambiguous");
// locally overloaded built-in getUrlPath() function
doCompileExpectError("test_ambiguous_combined", "Function 'getUrlPath' is ambiguous");
// swapped arguments - non null ambiguity
doCompileExpectError("test_ambiguous_swapped", "Function 'swapped' is ambiguous");
// primitive type widening; the test depends on specific values of the type distance function, can be removed
doCompileExpectError("test_ambiguous_widening", "Function 'widening' is ambiguous");
}
public void test_raise_error_terminal() {
// test case for issue 2337
doCompile("test_raise_error_terminal");
}
public void test_raise_error_nonliteral() {
// test case for issue CL-2071
doCompile("test_raise_error_nonliteral");
}
public void test_case_unique_check() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check2() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check3() {
doCompileExpectError("test_case_unique_check3", "Default case is already defined");
}
public void test_rvalue_for_append() {
// test case for issue 3956
doCompile("test_rvalue_for_append");
check("a", Arrays.asList("1", "2"));
check("b", Arrays.asList("a", "b", "c"));
check("c", Arrays.asList("1", "2", "a", "b", "c"));
}
public void test_rvalue_for_map_append() {
// test case for issue 3960
doCompile("test_rvalue_for_map_append");
HashMap<Integer, String> map1instance = new HashMap<Integer, String>();
map1instance.put(1, "a");
map1instance.put(2, "b");
HashMap<Integer, String> map2instance = new HashMap<Integer, String>();
map2instance.put(3, "c");
map2instance.put(4, "d");
HashMap<Integer, String> map3instance = new HashMap<Integer, String>();
map3instance.put(1, "a");
map3instance.put(2, "b");
map3instance.put(3, "c");
map3instance.put(4, "d");
check("map1", map1instance);
check("map2", map2instance);
check("map3", map3instance);
}
public void test_global_field_access() {
// test case for issue 3957
doCompileExpectError("test_global_field_access", "Unable to access record field in global scope");
}
public void test_global_scope() {
// test case for issue 5006
doCompile("test_global_scope");
check("len", "Kokon".length());
}
//TODO Implement
/*public void test_new() {
doCompile("test_new");
}*/
public void test_parser() {
System.out.println("\nParser test:");
doCompile("test_parser");
}
public void test_ref_res_import() {
System.out.println("\nSpecial character resolving (import) test:");
URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl");
String expStr = "import '" + importLoc + "';\n";
doCompile(expStr, "test_ref_res_import");
}
public void test_ref_res_noimport() {
System.out.println("\nSpecial character resolving (no import) test:");
doCompile("test_ref_res");
}
public void test_import() {
System.out.println("\nImport test:");
URL importLoc = getClass().getSuperclass().getResource("import.ctl");
String expStr = "import '" + importLoc + "';\n";
importLoc = getClass().getSuperclass().getResource("other.ctl");
expStr += "import '" + importLoc + "';\n" +
"integer sumInt;\n" +
"function integer transform() {\n" +
" if (a == 3) {\n" +
" otherImportVar++;\n" +
" }\n" +
" sumInt = sum(a, otherImportVar);\n" +
" return 0;\n" +
"}\n";
doCompile(expStr, "test_import");
}
public void test_scope() throws ComponentNotReadyException, TransformException {
System.out.println("\nMapping test:");
// String expStr =
// "function string computeSomething(int n) {\n" +
// " string s = '';\n" +
// " do {\n" +
// " int i = n--;\n" +
// " s = s + '-' + i;\n" +
// " } while (n > 0)\n" +
// " return s;" +
// "function int transform() {\n" +
// " printErr(computeSomething(10));\n" +
// " return 0;\n" +
URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl");
String expStr = "import '" + importLoc + "';\n";
// "function int getIndexOfOffsetStart(string encodedDate) {\n" +
// "int offsetStart;\n" +
// "int actualLastMinus;\n" +
// "int lastMinus = -1;\n" +
// "if ( index_of(encodedDate, '+') != -1 )\n" +
// " return index_of(encodedDate, '+');\n" +
// "do {\n" +
// " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" +
// " if ( actualLastMinus != -1 )\n" +
// " lastMinus = actualLastMinus;\n" +
// "} while ( actualLastMinus != -1 )\n" +
// "return lastMinus;\n" +
// "function int transform() {\n" +
// " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" +
// " return 0;\n" +
doCompile(expStr, "test_scope");
}
public void test_type_void() {
doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'",
"Variable 'voidVar' is not declared",
"Variable 'voidVar' is not declared",
"Syntax error on token 'void'"));
}
public void test_type_integer() {
doCompile("test_type_integer");
check("i", 0);
check("j", -1);
check("field", VALUE_VALUE);
checkNull("nullValue");
check("varWithInitializer", 123);
checkNull("varWithNullInitializer");
}
public void test_type_integer_edge() {
String testExpression =
"integer minInt;\n"+
"integer maxInt;\n"+
"function integer transform() {\n" +
"minInt=" + Integer.MIN_VALUE + ";\n" +
"printErr(minInt, true);\n" +
"maxInt=" + Integer.MAX_VALUE + ";\n" +
"printErr(maxInt, true);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_int_edge");
check("minInt", Integer.MIN_VALUE);
check("maxInt", Integer.MAX_VALUE);
}
public void test_type_long() {
doCompile("test_type_long");
check("i", Long.valueOf(0));
check("j", Long.valueOf(-1));
check("field", BORN_MILLISEC_VALUE);
check("def", Long.valueOf(0));
checkNull("nullValue");
check("varWithInitializer", 123L);
checkNull("varWithNullInitializer");
}
public void test_type_long_edge() {
String expStr =
"long minLong;\n"+
"long maxLong;\n"+
"function integer transform() {\n" +
"minLong=" + (Long.MIN_VALUE) + "L;\n" +
"printErr(minLong);\n" +
"maxLong=" + (Long.MAX_VALUE) + "L;\n" +
"printErr(maxLong);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr,"test_long_edge");
check("minLong", Long.MIN_VALUE);
check("maxLong", Long.MAX_VALUE);
}
public void test_type_decimal() {
doCompile("test_type_decimal");
check("i", new BigDecimal(0, MAX_PRECISION));
check("j", new BigDecimal(-1, MAX_PRECISION));
check("field", CURRENCY_VALUE);
check("def", new BigDecimal(0, MAX_PRECISION));
checkNull("nullValue");
check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION));
checkNull("varWithNullInitializer");
check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION));
}
public void test_type_decimal_edge() {
String testExpression =
"decimal minLong;\n"+
"decimal maxLong;\n"+
"decimal minLongNoDist;\n"+
"decimal maxLongNoDist;\n"+
"decimal minDouble;\n"+
"decimal maxDouble;\n"+
"decimal minDoubleNoDist;\n"+
"decimal maxDoubleNoDist;\n"+
"function integer transform() {\n" +
"minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" +
"printErr(minLong);\n" +
"maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" +
"printErr(maxLong);\n" +
"minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" +
"printErr(minLongNoDist);\n" +
"maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" +
"printErr(maxLongNoDist);\n" +
// distincter will cause the double-string be parsed into exact representation within BigDecimal
"minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" +
"printErr(minDouble);\n" +
"maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" +
"printErr(maxDouble);\n" +
// no distincter will cause the double-string to be parsed into inexact representation within double
// then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits)
"minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" +
"printErr(minDoubleNoDist);\n" +
"maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" +
"printErr(maxDoubleNoDist);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_decimal_edge");
check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
// distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324)
check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION));
check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION));
// no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of
// MAX_PRECISION digits (i.e. 4.94065.....E-324)
check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION));
check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION));
}
public void test_type_number() {
doCompile("test_type_number");
check("i", Double.valueOf(0));
check("j", Double.valueOf(-1));
check("field", AGE_VALUE);
check("def", Double.valueOf(0));
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_number_edge() {
String testExpression =
"number minDouble;\n" +
"number maxDouble;\n"+
"function integer transform() {\n" +
"minDouble=" + Double.MIN_VALUE + ";\n" +
"printErr(minDouble);\n" +
"maxDouble=" + Double.MAX_VALUE + ";\n" +
"printErr(maxDouble);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_number_edge");
check("minDouble", Double.valueOf(Double.MIN_VALUE));
check("maxDouble", Double.valueOf(Double.MAX_VALUE));
}
public void test_type_string() {
doCompile("test_type_string");
check("i","0");
check("helloEscaped", "hello\\nworld");
check("helloExpanded", "hello\nworld");
check("fieldName", NAME_VALUE);
check("fieldCity", CITY_VALUE);
check("escapeChars", "a\u0101\u0102A");
check("doubleEscapeChars", "a\\u0101\\u0102A");
check("specialChars", "špeciálne značky s mäkčeňom môžu byť");
check("dQescapeChars", "a\u0101\u0102A");
//TODO:Is next test correct?
check("dQdoubleEscapeChars", "a\\u0101\\u0102A");
check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť");
check("empty", "");
check("def", "");
checkNull("varWithNullInitializer");
}
public void test_type_string_long() {
int length = 1000;
StringBuilder tmp = new StringBuilder(length);
for (int i = 0; i < length; i++) {
tmp.append(i % 10);
}
String testExpression =
"string longString;\n" +
"function integer transform() {\n" +
"longString=\"" + tmp + "\";\n" +
"printErr(longString);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_string_long");
check("longString", String.valueOf(tmp));
}
public void test_type_date() throws Exception {
doCompile("test_type_date");
check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime());
check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime());
check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime());
check("field", BORN_VALUE);
checkNull("nullValue");
check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime());
checkNull("varWithNullInitializer");
// test with a default time zone set on the GraphRuntimeContext
Context context = null;
try {
tearDown();
setUp();
TransformationGraph graph = new TransformationGraph();
graph.getRuntimeContext().setTimeZone("GMT+8");
context = ContextProvider.registerGraph(graph);
doCompile("test_type_date");
Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3);
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("d2", calendar.getTime());
calendar.set(2006, 0, 1, 1, 2, 3);
check("d1", calendar.getTime());
} finally {
ContextProvider.unregister(context);
}
}
public void test_type_boolean() {
doCompile("test_type_boolean");
check("b1", true);
check("b2", false);
check("b3", false);
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_boolean_compare() {
doCompileExpectErrors("test_type_boolean_compare", Arrays.asList(
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'"));
}
public void test_type_list() {
doCompile("test_type_list");
check("intList", Arrays.asList(1, 2, 3, 4, 5, 6));
check("intList2", Arrays.asList(1, 2, 3));
check("stringList", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
check("stringListCopy", Arrays.asList(
"first", "second", "third", "fourth",
"fifth", "seventh"));
check("stringListCopy2", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
assertTrue(getVariable("stringList") != getVariable("stringListCopy"));
assertEquals(getVariable("stringList"), getVariable("stringListCopy2"));
assertEquals(Arrays.asList(false, null, true), getVariable("booleanList"));
assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList"));
assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList"));
assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList"));
assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList"));
assertEquals(Arrays.asList(12, null, 34), getVariable("intList3"));
assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList"));
assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList"));
assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2"));
List<?> decimalList2 = (List<?>) getVariable("decimalList2");
for (Object o: decimalList2) {
assertTrue(o instanceof BigDecimal);
}
List<?> intList4 = (List<?>) getVariable("intList4");
Set<Object> intList4Set = new HashSet<Object>(intList4);
assertEquals(3, intList4Set.size());
}
public void test_type_list_field() {
doCompile("test_type_list_field");
check("copyByValueTest1", "2");
check("copyByValueTest2", "test");
}
public void test_type_map_field() {
doCompile("test_type_map_field");
Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1");
assertEquals(new Integer(2), copyByValueTest1);
Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2");
assertEquals(new Integer(100), copyByValueTest2);
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepCopy(Object o1, Object o2) {
if (o1 instanceof DataRecord) {
assertFalse(o1 == o2);
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
assertFalse(o1 == o2);
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
for (Object key: m1.keySet()) {
assertDeepCopy(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
assertFalse(o1 == o2);
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
for (int i = 0; i < l1.size(); i++) {
assertDeepCopy(l1.get(i), l2.get(i));
}
} else if (o1 instanceof Date) {
assertFalse(o1 == o2);
// } else if (o1 instanceof byte[]) { // not required anymore
// assertFalse(o1 == o2);
}
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepEquals(Object o1, Object o2) {
if ((o1 == null) && (o2 == null)) {
return;
}
assertTrue((o1 == null) == (o2 == null));
if (o1 instanceof DataRecord) {
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
assertEquals(r1.getNumFields(), r2.getNumFields());
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
assertTrue(m1.keySet().equals(m2.keySet()));
for (Object key: m1.keySet()) {
assertDeepEquals(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
assertEquals("size", l1.size(), l2.size());
for (int i = 0; i < l1.size(); i++) {
assertDeepEquals(l1.get(i), l2.get(i));
}
} else if (o1 instanceof byte[]) {
byte[] b1 = (byte[]) o1;
byte[] b2 = (byte[]) o2;
if (b1 != b2) {
if (b1 == null || b2 == null) {
assertEquals(b1, b2);
}
assertEquals("length", b1.length, b2.length);
for (int i = 0; i < b1.length; i++) {
assertEquals(String.format("[%d]", i), b1[i], b2[i]);
}
}
} else if (o1 instanceof CharSequence) {
String s1 = ((CharSequence) o1).toString();
String s2 = ((CharSequence) o2).toString();
assertEquals(s1, s2);
} else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) {
BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1;
BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2;
assertEquals(d1, d2);
} else {
assertEquals(o1, o2);
}
}
private void check_assignment_deepcopy_variable_declaration() {
Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1");
Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2");
byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1");
byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2");
assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2);
assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_array_access_expression() {
{
// JJTARRAYACCESSEXPRESSION - List
List<String> stringListField1 = (List<String>) getVariable("stringListField1");
DataRecord recordInList1 = (DataRecord) getVariable("recordInList1");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2");
assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepEquals(recordInList1, recordList1.get(0));
assertDeepEquals(recordList1, recordList2);
assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepCopy(recordInList1, recordList1.get(0));
assertDeepCopy(recordList1, recordList2);
}
{
// map of records
Date testDate1 = (Date) getVariable("testDate1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1");
DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2");
Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2");
assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepEquals(recordInMap1, recordMap1.get(0));
assertDeepEquals(recordInMap2, recordMap1.get(0));
assertDeepEquals(recordMap1, recordMap2);
assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepCopy(recordInMap1, recordMap1.get(0));
assertDeepCopy(recordInMap2, recordMap1.get(0));
assertDeepCopy(recordMap1, recordMap2);
}
{
// map of dates
Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1");
Date date1 = (Date) getVariable("date1");
Date date2 = (Date) getVariable("date2");
assertDeepCopy(date1, dateMap1.get(0));
assertDeepCopy(date2, dateMap1.get(1));
}
{
// map of byte arrays
Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1");
byte[] byte1 = (byte[]) getVariable("byte1");
byte[] byte2 = (byte[]) getVariable("byte2");
assertDeepCopy(byte1, byteMap1.get(0));
assertDeepCopy(byte2, byteMap1.get(1));
}
{
// JJTARRAYACCESSEXPRESSION - Function call
List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList");
DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall");
Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map");
Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue());
assertEquals(1, function_call_original_map.size());
assertEquals(2, function_call_copied_map.size());
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list);
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list);
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2));
}
// CLO-1210
{
check("stringListNull", Arrays.asList((Object) null));
Map<String, String> stringMapNull = new HashMap<String, String>();
stringMapNull.put("a", null);
check("stringMapNull", stringMapNull);
}
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_field_access_expression() {
// field access
Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1");
String testFieldAccessString1 = (String) getVariable("testFieldAccessString1");
List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1");
List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1");
Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1");
Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput);
assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_member_access_expression() {
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
}
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2);
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2);
// dictionary
Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue();
byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue();
List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1");
List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2");
List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList");
List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(dictionaryDate, testMemberAccessDate1);
assertDeepEquals(dictionaryByte, testMemberAccessByte1);
assertDeepEquals(dictionaryStringList, testMemberAccessStringList1);
assertDeepEquals(dictionaryDateList, testMemberAccessDateList2);
assertDeepEquals(dictionaryByteList, testMemberAccessByteList2);
assertDeepCopy(dictionaryDate, testMemberAccessDate1);
assertDeepCopy(dictionaryByte, testMemberAccessByte1);
assertDeepCopy(dictionaryStringList, testMemberAccessStringList1);
assertDeepCopy(dictionaryDateList, testMemberAccessDateList2);
assertDeepCopy(dictionaryByteList, testMemberAccessByteList2);
// member access - array of records
List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
// member access - map of records
Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
}
}
@SuppressWarnings("unchecked")
public void test_assignment_deepcopy() {
doCompile("test_assignment_deepcopy");
List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList");
assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString());
List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList");
assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString());
check_assignment_deepcopy_variable_declaration();
check_assignment_deepcopy_array_access_expression();
check_assignment_deepcopy_field_access_expression();
check_assignment_deepcopy_member_access_expression();
}
public void test_assignment_deepcopy_field_access_expression() {
doCompile("test_assignment_deepcopy_field_access_expression");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
DataRecord multivalueInput = inputRecords[3];
assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepEquals(secondMultivalueOutput, multivalueInput);
assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput);
assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepCopy(secondMultivalueOutput, multivalueInput);
assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput);
}
public void test_assignment_array_access_function_call() {
doCompile("test_assignment_array_access_function_call");
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("a", "b");
Map<String, String> copiedMap = new HashMap<String, String>(originalMap);
copiedMap.put("c", "d");
check("originalMap", originalMap);
check("copiedMap", copiedMap);
}
public void test_assignment_array_access_function_call_wrong_type() {
doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type",
Arrays.asList(
"Expression is not a composite type but is resolved to 'string'",
"Type mismatch: cannot convert from 'integer' to 'string'",
"Cannot convert from 'integer' to string"
));
}
@SuppressWarnings("unchecked")
public void test_assignment_returnvalue() {
doCompile("test_assignment_returnvalue");
{
List<String> stringList1 = (List<String>) getVariable("stringList1");
List<String> stringList2 = (List<String>) getVariable("stringList2");
List<String> stringList3 = (List<String>) getVariable("stringList3");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
List<String> stringList4 = (List<String>) getVariable("stringList4");
Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1");
DataRecord record1 = (DataRecord) getVariable("record1");
DataRecord record2 = (DataRecord) getVariable("record2");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
Date dictionaryDate1 = (Date) getVariable("dictionaryDate1");
Date dictionaryDate = (Date) graph.getDictionary().getValue("a");
Date zeroDate = new Date(0);
List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10");
DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11");
List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12");
List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13");
Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map");
Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map");
DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord");
// identifier
assertFalse(stringList1.isEmpty());
assertTrue(stringList2.isEmpty());
assertTrue(stringList3.isEmpty());
// array access expression - list
assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue());
// array access expression - map
assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue());
// array access expression - function call
assertDeepEquals(null, function_call_original_map.get(2));
assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField"));
assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list);
assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField"));
// field access expression
assertFalse(stringList4.isEmpty());
assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty());
assertFalse(integerMap1.isEmpty());
assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty());
assertDeepEquals("unmodified", record1.getField("stringField"));
assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue());
assertDeepEquals("unmodified", record2.getField("stringField"));
assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue());
// member access expression - dictionary
// There is no function that could modify a date
// assertEquals(zeroDate, dictionaryDate);
// assertFalse(zeroDate.equals(testReturnValueDictionary1));
assertFalse(testReturnValueDictionary2.isEmpty());
assertTrue(dictionaryStringList.isEmpty());
// member access expression - record
assertFalse(testReturnValue10.isEmpty());
assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty());
// member access expression - list of records
assertFalse(testReturnValue12.isEmpty());
assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty());
// member access expression - map of records
assertFalse(testReturnValue13.isEmpty());
assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty());
}
}
@SuppressWarnings("unchecked")
public void test_type_map() {
doCompile("test_type_map");
Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap");
assertEquals(Integer.valueOf(1), testMap.get("zero"));
assertEquals(Integer.valueOf(2), testMap.get("one"));
assertEquals(Integer.valueOf(3), testMap.get("two"));
assertEquals(Integer.valueOf(4), testMap.get("three"));
assertEquals(4, testMap.size());
Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek");
Calendar c = Calendar.getInstance();
c.set(2009, Calendar.MARCH, 2, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Monday", dayInWeek.get(c.getTime()));
Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy");
c.set(2009, Calendar.MARCH, 3, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime()));
assertEquals("Tuesday", dayInWeekCopy.get(c.getTime()));
c.set(2009, Calendar.MARCH, 4, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime()));
assertEquals("Wednesday", dayInWeekCopy.get(c.getTime()));
assertFalse(dayInWeek.equals(dayInWeekCopy));
{
Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder");
assertEquals(100, preservedOrder.size());
int i = 0;
for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) {
assertEquals("key" + i, entry.getKey());
assertEquals("value" + i, entry.getValue());
i++;
}
}
}
public void test_type_record_list() {
doCompile("test_type_record_list");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_list_global() {
doCompile("test_type_record_list_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map() {
doCompile("test_type_record_map");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map_global() {
doCompile("test_type_record_map_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record() {
doCompile("test_type_record");
// expected result
DataRecord expected = createDefaultRecord(createDefaultMetadata("expected"));
// simple copy
assertTrue(recordEquals(expected, inputRecords[0]));
assertTrue(recordEquals(expected, (DataRecord) getVariable("copy")));
// copy and modify
expected.getField("Name").setValue("empty");
expected.getField("Value").setValue(321);
Calendar c = Calendar.getInstance();
c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
expected.getField("Born").setValue(c.getTime());
assertTrue(recordEquals(expected, (DataRecord) getVariable("modified")));
// 2x modified copy
expected.getField("Name").setValue("not empty");
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2")));
// no modification by reference is possible
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3")));
expected.getField("Value").setValue(654321);
assertTrue(recordEquals(expected, (DataRecord)getVariable("reference")));
assertTrue(getVariable("modified3") != getVariable("reference"));
// output record
assertTrue(recordEquals(expected, outputRecords[1]));
// null record
expected.setToNull();
assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord")));
}
public void test_variables() {
doCompile("test_variables");
check("b1", true);
check("b2", true);
check("b4", "hi");
check("i", 2);
}
public void test_operator_plus() {
doCompile("test_operator_plus");
check("iplusj", 10 + 100);
check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10));
check("mplusl", getVariable("lplusm"));
check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10);
check("iplusm", getVariable("mplusi"));
check("nplusm1", Double.valueOf(0.1D + 0.001D));
check("nplusj", Double.valueOf(100 + 0.1D));
check("jplusn", getVariable("nplusj"));
check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d));
check("mplusm1", getVariable("m1plusm"));
check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("jplusd", getVariable("dplusj"));
check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("mplusd", getVariable("dplusm"));
check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION)));
check("nplusd", getVariable("dplusn"));
check("spluss1", "hello world");
check("splusj", "hello100");
check("jpluss", "100hello");
check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE));
check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello");
check("splusm1", "hello" + Double.valueOf(0.001D));
check("m1pluss", Double.valueOf(0.001D) + "hello");
check("splusd1", "hello" + new BigDecimal("0.0001"));
check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello");
}
public void test_operator_minus() {
doCompile("test_operator_minus");
check("iminusj", 10 - 100);
check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE));
check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10));
check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE));
check("nminusm1", Double.valueOf(0.1D - 0.001D));
check("nminusj", Double.valueOf(0.1D - 100));
check("jminusn", Double.valueOf(100 - 0.1D));
check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE)));
check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D));
check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_multiply() {
doCompile("test_operator_multiply");
check("itimesj", 10 * 100);
check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10)));
check("mtimesl", getVariable("ltimesm"));
check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10);
check("itimesm", getVariable("mtimesi"));
check("ntimesm1", Double.valueOf(0.1D * 0.001D));
check("ntimesj", Double.valueOf(0.1) * 100);
check("jtimesn", getVariable("ntimesj"));
check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE)));
check("mtimesm1", getVariable("m1timesm"));
check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION)));
check("jtimesd", getVariable("dtimesj"));
check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mtimesd", getVariable("dtimesm"));
check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION));
check("ntimesd", getVariable("dtimesn"));
}
public void test_operator_divide() {
doCompile("test_operator_divide");
check("idividej", 10 / 100);
check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE));
check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10));
check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE));
check("ndividem1", Double.valueOf(0.1D / 0.001D));
check("ndividej", Double.valueOf(0.1D / 100));
check("jdividen", Double.valueOf(100 / 0.1D));
check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE)));
check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D));
check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_modulus() {
doCompile("test_operator_modulus");
check("imoduloj", 10 % 100);
check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE));
check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10));
check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE));
check("nmodulom1", Double.valueOf(0.1D % 0.001D));
check("nmoduloj", Double.valueOf(0.1D % 100));
check("jmodulon", Double.valueOf(100 % 0.1D));
check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE)));
check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D));
check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operators_unary() {
doCompile("test_operators_unary");
// postfix operators
// int
check("intPlusOrig", Integer.valueOf(10));
check("intPlusPlus", Integer.valueOf(10));
check("intPlus", Integer.valueOf(11));
check("intMinusOrig", Integer.valueOf(10));
check("intMinusMinus", Integer.valueOf(10));
check("intMinus", Integer.valueOf(9));
// long
check("longPlusOrig", Long.valueOf(10));
check("longPlusPlus", Long.valueOf(10));
check("longPlus", Long.valueOf(11));
check("longMinusOrig", Long.valueOf(10));
check("longMinusMinus", Long.valueOf(10));
check("longMinus", Long.valueOf(9));
// double
check("numberPlusOrig", Double.valueOf(10.1));
check("numberPlusPlus", Double.valueOf(10.1));
check("numberPlus", Double.valueOf(11.1));
check("numberMinusOrig", Double.valueOf(10.1));
check("numberMinusMinus", Double.valueOf(10.1));
check("numberMinus", Double.valueOf(9.1));
// decimal
check("decimalPlusOrig", new BigDecimal("10.1"));
check("decimalPlusPlus", new BigDecimal("10.1"));
check("decimalPlus", new BigDecimal("11.1"));
check("decimalMinusOrig", new BigDecimal("10.1"));
check("decimalMinusMinus", new BigDecimal("10.1"));
check("decimalMinus", new BigDecimal("9.1"));
// prefix operators
// integer
check("plusIntOrig", Integer.valueOf(10));
check("plusPlusInt", Integer.valueOf(11));
check("plusInt", Integer.valueOf(11));
check("minusIntOrig", Integer.valueOf(10));
check("minusMinusInt", Integer.valueOf(9));
check("minusInt", Integer.valueOf(9));
check("unaryInt", Integer.valueOf(-10));
// long
check("plusLongOrig", Long.valueOf(10));
check("plusPlusLong", Long.valueOf(11));
check("plusLong", Long.valueOf(11));
check("minusLongOrig", Long.valueOf(10));
check("minusMinusLong", Long.valueOf(9));
check("minusLong", Long.valueOf(9));
check("unaryLong", Long.valueOf(-10));
// double
check("plusNumberOrig", Double.valueOf(10.1));
check("plusPlusNumber", Double.valueOf(11.1));
check("plusNumber", Double.valueOf(11.1));
check("minusNumberOrig", Double.valueOf(10.1));
check("minusMinusNumber", Double.valueOf(9.1));
check("minusNumber", Double.valueOf(9.1));
check("unaryNumber", Double.valueOf(-10.1));
// decimal
check("plusDecimalOrig", new BigDecimal("10.1"));
check("plusPlusDecimal", new BigDecimal("11.1"));
check("plusDecimal", new BigDecimal("11.1"));
check("minusDecimalOrig", new BigDecimal("10.1"));
check("minusMinusDecimal", new BigDecimal("9.1"));
check("minusDecimal", new BigDecimal("9.1"));
check("unaryDecimal", new BigDecimal("-10.1"));
// record values
assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue());
//record as parameter
assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue());
// logical not
check("booleanValue", true);
check("negation", false);
check("doubleNegation", true);
}
public void test_operators_unary_record() {
doCompileExpectErrors("test_operators_unary_record", Arrays.asList(
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_operator_equal() {
doCompile("test_operator_equal");
check("eq0", true);
check("eq1", true);
check("eq1a", true);
check("eq1b", true);
check("eq1c", false);
check("eq2", true);
check("eq3", true);
check("eq4", true);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", false);
check("eq9", true);
check("eq10", false);
check("eq11", true);
check("eq12", false);
check("eq13", true);
check("eq14", false);
check("eq15", false);
check("eq16", true);
check("eq17", false);
check("eq18", false);
check("eq19", false);
// byte
check("eq20", true);
check("eq21", true);
check("eq22", false);
check("eq23", false);
check("eq24", true);
check("eq25", false);
check("eq20c", true);
check("eq21c", true);
check("eq22c", false);
check("eq23c", false);
check("eq24c", true);
check("eq25c", false);
check("eq26", true);
check("eq27", true);
}
public void test_operator_non_equal(){
doCompile("test_operator_non_equal");
check("inei", false);
check("inej", true);
check("jnei", true);
check("jnej", false);
check("lnei", false);
check("inel", false);
check("lnej", true);
check("jnel", true);
check("lnel", false);
check("dnei", false);
check("ined", false);
check("dnej", true);
check("jned", true);
check("dnel", false);
check("lned", false);
check("dned", false);
check("dned_different_scale", false);
}
public void test_operator_in() {
doCompile("test_operator_in");
check("a", Integer.valueOf(1));
check("haystack", Collections.EMPTY_LIST);
check("needle", Integer.valueOf(2));
check("b1", true);
check("b2", false);
check("h2", Arrays.asList(2.1D, 2.0D, 2.2D));
check("b3", true);
check("h3", Arrays.asList("memento", "mori", "memento mori"));
check("n3", "memento mori");
check("b4", true);
}
public void test_operator_greater_less() {
doCompile("test_operator_greater_less");
check("eq1", true);
check("eq2", true);
check("eq3", true);
check("eq4", false);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", true);
check("eq9", true);
}
public void test_operator_ternary(){
doCompile("test_operator_ternary");
// simple use
check("trueValue", true);
check("falseValue", false);
check("res1", Integer.valueOf(1));
check("res2", Integer.valueOf(2));
// nesting in positive branch
check("res3", Integer.valueOf(1));
check("res4", Integer.valueOf(2));
check("res5", Integer.valueOf(3));
// nesting in negative branch
check("res6", Integer.valueOf(2));
check("res7", Integer.valueOf(3));
// nesting in both branches
check("res8", Integer.valueOf(1));
check("res9", Integer.valueOf(1));
check("res10", Integer.valueOf(2));
check("res11", Integer.valueOf(3));
check("res12", Integer.valueOf(2));
check("res13", Integer.valueOf(4));
check("res14", Integer.valueOf(3));
check("res15", Integer.valueOf(4));
}
public void test_operators_logical(){
doCompile("test_operators_logical");
//TODO: please double check this.
check("res1", false);
check("res2", false);
check("res3", true);
check("res4", true);
check("res5", false);
check("res6", false);
check("res7", true);
check("res8", false);
}
public void test_regex(){
doCompile("test_regex");
check("eq0", false);
check("eq1", true);
check("eq2", false);
check("eq3", true);
check("eq4", false);
check("eq5", true);
}
public void test_if() {
doCompile("test_if");
// if with single statement
check("cond1", true);
check("res1", true);
// if with mutliple statements (block)
check("cond2", true);
check("res21", true);
check("res22", true);
// else with single statement
check("cond3", false);
check("res31", false);
check("res32", true);
// else with multiple statements (block)
check("cond4", false);
check("res41", false);
check("res42", true);
check("res43", true);
// if with block, else with block
check("cond5", false);
check("res51", false);
check("res52", false);
check("res53", true);
check("res54", true);
// else-if with single statement
check("cond61", false);
check("cond62", true);
check("res61", false);
check("res62", true);
// else-if with multiple statements
check("cond71", false);
check("cond72", true);
check("res71", false);
check("res72", true);
check("res73", true);
// if-elseif-else test
check("cond81", false);
check("cond82", false);
check("res81", false);
check("res82", false);
check("res83", true);
// if with single statement + inactive else
check("cond9", true);
check("res91", true);
check("res92", false);
// if with multiple statements + inactive else with block
check("cond10", true);
check("res101", true);
check("res102", true);
check("res103", false);
check("res104", false);
// if with condition
check("i", 0);
check("j", 1);
check("res11", true);
}
public void test_switch() {
doCompile("test_switch");
// simple switch
check("cond1", 1);
check("res11", false);
check("res12", true);
check("res13", false);
// switch, no break
check("cond2", 1);
check("res21", false);
check("res22", true);
check("res23", true);
// default branch
check("cond3", 3);
check("res31", false);
check("res32", false);
check("res33", true);
// no default branch => no match
check("cond4", 3);
check("res41", false);
check("res42", false);
check("res43", false);
// multiple statements in a single case-branch
check("cond5", 1);
check("res51", false);
check("res52", true);
check("res53", true);
check("res54", false);
// single statement shared by several case labels
check("cond6", 1);
check("res61", false);
check("res62", true);
check("res63", true);
check("res64", false);
check("res71", "default case");
check("res72", "null case");
check("res73", "null case");
check("res74", "default case");
}
public void test_int_switch(){
doCompile("test_int_switch");
// simple switch
check("cond1", 1);
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", 1);
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", 12);
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", 11);
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", 11);
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", 16);
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_non_int_switch(){
doCompile("test_non_int_switch");
// simple switch
check("cond1", "1");
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", "1");
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", "12");
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", "11");
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", "11");
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", "16");
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_while() {
doCompile("test_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_do_while() {
doCompile("test_do_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, null, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_for() {
doCompile("test_for");
// simple loop
check("res1", Arrays.asList(0,1,2));
// continue
check("res2", Arrays.asList(0,null,2));
// break
check("res3", Arrays.asList(0));
// empty init
check("res4", Arrays.asList(0,1,2));
// empty update
check("res5", Arrays.asList(0,1,2));
// empty final condition
check("res6", Arrays.asList(0,1,2));
// all conditions empty
check("res7", Arrays.asList(0,1,2));
}
public void test_for1() {
//5125: CTL2: "for" cycle is EXTREMELY memory consuming
doCompile("test_for1");
checkEquals("counter", "COUNT");
}
@SuppressWarnings("unchecked")
public void test_foreach() {
doCompile("test_foreach");
check("intRes", Arrays.asList(VALUE_VALUE));
check("longRes", Arrays.asList(BORN_MILLISEC_VALUE));
check("doubleRes", Arrays.asList(AGE_VALUE));
check("decimalRes", Arrays.asList(CURRENCY_VALUE));
check("booleanRes", Arrays.asList(FLAG_VALUE));
check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE));
check("dateRes", Arrays.asList(BORN_VALUE));
List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes");
List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size());
for (Object o: integerStringMapResTmp) {
integerStringMapRes.add(String.valueOf(o));
}
List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes");
List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes");
Collections.sort(integerStringMapRes);
Collections.sort(stringIntegerMapRes);
assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes);
assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes);
final int N = 5;
assertEquals(N, stringRecordMapRes.size());
int equalRecords = 0;
for (int i = 0; i < N; i++) {
for (DataRecord r: stringRecordMapRes) {
if (Integer.valueOf(i).equals(r.getField("Value").getValue())
&& "A string".equals(String.valueOf(r.getField("Name").getValue()))) {
equalRecords++;
break;
}
}
}
assertEquals(N, equalRecords);
}
public void test_return(){
doCompile("test_return");
check("lhs", Integer.valueOf(1));
check("rhs", Integer.valueOf(2));
check("res", Integer.valueOf(3));
}
public void test_return_incorrect() {
doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'");
}
public void test_return_void() {
doCompile("test_return_void");
}
public void test_overloading() {
doCompile("test_overloading");
check("res1", Integer.valueOf(3));
check("res2", "Memento mori");
}
public void test_overloading_incorrect() {
doCompileExpectErrors("test_overloading_incorrect", Arrays.asList(
"Duplicate function 'integer sum(integer, integer)'",
"Duplicate function 'integer sum(integer, integer)'"));
}
//Test case for 4038
public void test_function_parameter_without_type() {
doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'");
}
public void test_duplicate_import() {
URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl");
String expStr = "import '" + importLoc + "';\n";
expStr += "import '" + importLoc + "';\n";
doCompile(expStr, "test_duplicate_import");
}
/*TODO:
* public void test_invalid_import() {
URL importLoc = getClass().getResource("test_duplicate_import.ctl");
String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n";
expStr += expStr;
doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error"));
//doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error"));
} */
public void test_built_in_functions(){
doCompile("test_built_in_functions");
check("notNullValue", Integer.valueOf(1));
checkNull("nullValue");
check("isNullRes1", false);
check("isNullRes2", true);
assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1"));
check("nvlRes2", Integer.valueOf(2));
assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1"));
check("nvl2Res2", Integer.valueOf(2));
check("iifRes1", Integer.valueOf(2));
check("iifRes2", Integer.valueOf(1));
}
public void test_local_functions() {
// CLO-1246
doCompile("test_local_functions");
}
public void test_mapping(){
doCompile("test_mapping");
// simple mappings
assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString());
assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString());
assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue());
// * mapping
assertTrue(recordEquals(inputRecords[1], outputRecords[1]));
check("len", 2);
}
public void test_mapping_null_values() {
doCompile("test_mapping_null_values");
assertTrue(recordEquals(inputRecords[2], outputRecords[0]));
}
public void test_copyByName() {
doCompile("test_copyByName");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment() {
doCompile("test_copyByName_assignment");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment1() {
doCompile("test_copyByName_assignment1");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", null, outputRecords[3].getField("Age").getValue());
assertEquals("City", null, outputRecords[3].getField("City").getValue());
}
public void test_sequence(){
doCompile("test_sequence");
check("intRes", Arrays.asList(0,1,2));
check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2)));
check("stringRes", Arrays.asList("0","1","2"));
check("intCurrent", Integer.valueOf(2));
check("longCurrent", Long.valueOf(2));
check("stringCurrent", "2");
}
//TODO: If this test fails please double check whether the test is correct?
public void test_lookup(){
doCompile("test_lookup");
check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella"));
check("bravoResult", Arrays.asList("Bruxelles","Bruxelles"));
check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov"));
check("countResult", Arrays.asList(3,3));
check("charlieUpdatedCount", 5);
check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim"));
check("putResult", true);
check("meta", null);
check("meta2", null);
check("meta3", null);
check("meta4", null);
check("strRet", "Bratislava");
check("strRet2","Andorra la Vella");
check("intRet", 0);
check("intRet2", 1);
check("meta7", null);
// CLO-1582
check("nonExistingKeyRecord", null);
check("nullKeyRecord", null);
check("unusedNext", getVariable("unusedNextExpected"));
}
public void test_lookup_expect_error(){
//CLO-1582
try {
doCompile("function integer transform(){string str = lookup(TestLookup).get('Alpha',2).City; return 0;}","test_lookup_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer count = lookup(TestLookup).count('Alpha',1); printErr(count); lookup(TestLookup).next(); string city = lookup(TestLookup).next().City; return 0;}","test_lookup_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){lookupMetadata meta = null; lookup(TestLookup).put(meta); return 0;}","test_lookup_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){lookup(TestLookup).put(null); return 0;}","test_lookup_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_append() {
doCompile("test_containerlib_append");
check("appendElem", Integer.valueOf(10));
check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10));
check("stringList", Arrays.asList("horse","is","pretty","scary"));
check("stringList2", Arrays.asList("horse", null));
check("stringList3", Arrays.asList("horse", ""));
check("integerList1", Arrays.asList(1,2,3,4));
check("integerList2", Arrays.asList(1,2,null));
check("numberList1", Arrays.asList(0.21,1.1,2.2));
check("numberList2", Arrays.asList(1.1,null));
check("longList1", Arrays.asList(1l,2l,3L));
check("longList2", Arrays.asList(9L,null));
check("decList1", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("4.5"),new BigDecimal("6.7")));
check("decList2",Arrays.asList(new BigDecimal("1.1"), null));
}
public void test_containerlib_append_expect_error(){
try {
doCompile("function integer transform(){string[] listInput = null; append(listInput,'aa'); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte[] listInput = null; append(listInput,str2byte('third', 'utf-8')); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long[] listInput = null; append(listInput,15L); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] listInput = null; append(listInput,12); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal[] listInput = null; append(listInput,12.5d); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number[] listInput = null; append(listInput,12.36); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
@SuppressWarnings("unchecked")
public void test_containerlib_clear() {
doCompile("test_containerlib_clear");
assertTrue(((List<Integer>) getVariable("integerList")).isEmpty());
assertTrue(((List<Integer>) getVariable("strList")).isEmpty());
assertTrue(((List<Integer>) getVariable("longList")).isEmpty());
assertTrue(((List<Integer>) getVariable("decList")).isEmpty());
assertTrue(((List<Integer>) getVariable("numList")).isEmpty());
assertTrue(((List<Integer>) getVariable("byteList")).isEmpty());
assertTrue(((List<Integer>) getVariable("dateList")).isEmpty());
assertTrue(((List<Integer>) getVariable("boolList")).isEmpty());
assertTrue(((List<Integer>) getVariable("emptyList")).isEmpty());
assertTrue(((Map<String,Integer>) getVariable("myMap")).isEmpty());
}
public void test_container_clear_expect_error(){
try {
doCompile("function integer transform(){boolean[] nullList = null; clear(nullList); return 0;}","test_container_clear_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[integer,string] myMap = null; clear(myMap); return 0;}","test_container_clear_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_copy() {
doCompile("test_containerlib_copy");
check("copyIntList", Arrays.asList(1, 2, 3, 4, 5));
check("returnedIntList", Arrays.asList(1, 2, 3, 4, 5));
check("copyLongList", Arrays.asList(21L,15L, null, 10L));
check("returnedLongList", Arrays.asList(21l, 15l, null, 10L));
check("copyBoolList", Arrays.asList(false,false,null,true));
check("returnedBoolList", Arrays.asList(false,false,null,true));
Calendar cal = Calendar.getInstance();
cal.set(2006, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2002, 03, 12, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("copyDateList",Arrays.asList(cal2.getTime(), null, cal.getTime()));
check("returnedDateList",Arrays.asList(cal2.getTime(), null, cal.getTime()));
check("copyStrList", Arrays.asList("Ashe", "Jax", null, "Rengar"));
check("returnedStrList", Arrays.asList("Ashe", "Jax", null, "Rengar"));
check("copyNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d));
check("returnedNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d));
check("copyDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3")));
check("returnedDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3")));
Map<String, String> expectedMap = new HashMap<String, String>();
expectedMap.put("a", "a");
expectedMap.put("b", "b");
expectedMap.put("c", "c");
expectedMap.put("d", "d");
check("copyStrMap", expectedMap);
check("returnedStrMap", expectedMap);
Map<Integer, Integer> intMap = new HashMap<Integer, Integer>();
intMap.put(1,12);
intMap.put(2,null);
intMap.put(3,15);
check("copyIntMap", intMap);
check("returnedIntMap", intMap);
Map<Long, Long> longMap = new HashMap<Long, Long>();
longMap.put(10L, 453L);
longMap.put(11L, null);
longMap.put(12L, 54755L);
check("copyLongMap", longMap);
check("returnedLongMap", longMap);
Map<BigDecimal, BigDecimal> decMap = new HashMap<BigDecimal, BigDecimal>();
decMap.put(new BigDecimal("2.2"), new BigDecimal("12.3"));
decMap.put(new BigDecimal("2.3"), new BigDecimal("45.6"));
check("copyDecMap", decMap);
check("returnedDecMap", decMap);
Map<Double, Double> doubleMap = new HashMap<Double, Double>();
doubleMap.put(new Double(12.3d), new Double(11.2d));
doubleMap.put(new Double(13.4d), new Double(78.9d));
check("copyNumMap",doubleMap);
check("returnedNumMap", doubleMap);
List<String> myList = new ArrayList<String>();
check("copyEmptyList", myList);
check("returnedEmptyList", myList);
assertTrue(((List<String>)(getVariable("copyEmptyList"))).isEmpty());
assertTrue(((List<String>)(getVariable("returnedEmptyList"))).isEmpty());
Map<String, String> emptyMap = new HashMap<String, String>();
check("copyEmptyMap", emptyMap);
check("returnedEmptyMap", emptyMap);
assertTrue(((HashMap<String,String>)(getVariable("copyEmptyMap"))).isEmpty());
assertTrue(((HashMap<String,String>)(getVariable("returnedEmptyMap"))).isEmpty());
}
public void test_containerlib_copy_expect_error(){
try {
doCompile("function integer transform(){string[] origList = null; string[] copyList; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] origList; string[] copyList = null; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] orig = null; map[string, string] copy; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] orig; map[string, string] copy = null; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_insert() {
doCompile("test_containerlib_insert");
check("copyStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV"));
check("retStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV"));
check("copyStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe"));
check("retStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe"));
Calendar cal = Calendar.getInstance();
cal.set(2009, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal1 = Calendar.getInstance();
cal1.set(2008, 2, 7, 0, 0, 0);
cal1.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003, 01, 1, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("copyDateList", Arrays.asList(cal1.getTime(),cal.getTime()));
check("retDateList", Arrays.asList(cal1.getTime(),cal.getTime()));
check("copyDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime()));
check("retDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime()));
check("copyIntList", Arrays.asList(1,2,3,12,4,5,6,7));
check("retIntList", Arrays.asList(1,2,3,12,4,5,6,7));
check("copyLongList", Arrays.asList(14L,15l,16l,17l));
check("retLongList", Arrays.asList(14L,15l,16l,17l));
check("copyLongList2", Arrays.asList(20L,21L,22L,23l));
check("retLongList2", Arrays.asList(20L,21L,22L,23l));
check("copyNumList", Arrays.asList(12.3d,11.1d,15.4d));
check("retNumList", Arrays.asList(12.3d,11.1d,15.4d));
check("copyNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d));
check("retNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d));
check("copyDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3")));
check("retDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3")));
check("copyDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2")));
check("retDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2")));
check("copyEmpty", Arrays.asList(11));
check("retEmpty", Arrays.asList(11));
check("copyEmpty2", Arrays.asList(12,13));
check("retEmpty2", Arrays.asList(12,13));
check("copyEmpty3", Arrays.asList());
check("retEmpty3", Arrays.asList());
}
public void test_containerlib_insert_expect_error(){
try {
doCompile("function integer transform(){integer[] tmp = null; integer[] ret = insert(tmp,0,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp; integer[] toAdd = null; integer[] ret = insert(tmp,0,toAdd); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,-1,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,10,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_isEmpty() {
doCompile("test_containerlib_isEmpty");
check("emptyMap", true);
check("emptyMap1", true);
check("fullMap", false);
check("fullMap1", false);
check("emptyList", true);
check("emptyList1", true);
check("fullList", false);
check("fullList1", false);
}
public void test_containerlib_isEmpty_expect_error(){
try {
doCompile("function integer transform(){integer[] i = null; boolean boo = i.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] m = null; boolean boo = m.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_length(){
doCompile("test_containerlib_length");
check("lengthByte", 18);
check("lengthByte2", 18);
check("recordLength", 9);
check("recordLength2", 9);
check("listLength", 3);
check("listLength2", 3);
check("emptyListLength", 0);
check("emptyListLength2", 0);
check("emptyMapLength", 0);
check("emptyMapLength2", 0);
check("nullLength1", 0);
check("nullLength2", 0);
check("nullLength3", 0);
check("nullLength4", 0);
check("nullLength5", 0);
check("nullLength6", 0);
}
public void test_containerlib_poll() throws UnsupportedEncodingException {
doCompile("test_containerlib_poll");
check("intElem", Integer.valueOf(1));
check("intElem1", 2);
check("intList", Arrays.asList(3, 4, 5));
check("strElem", "Zyra");
check("strElem2", "Tresh");
check("strList", Arrays.asList("Janna", "Wu Kong"));
Calendar cal = Calendar.getInstance();
cal.set(2002, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem", cal.getTime());
cal.clear();
cal.set(2003,5,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem2", cal.getTime());
cal.clear();
cal.set(2006,9,15,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime()));
checkArray("byteElem", "Maoki".getBytes("UTF-8"));
checkArray("byteElem2", "Nasus".getBytes("UTF-8"));
check("longElem", 12L);
check("longElem2", 15L);
check("longList", Arrays.asList(16L,23L));
check("numElem", 23.6d);
check("numElem2", 15.9d);
check("numList", Arrays.asList(78.8d, 57.2d));
check("decElem", new BigDecimal("12.3"));
check("decElem2", new BigDecimal("23.4"));
check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("emptyElem", null);
check("emptyElem2", null);
check("emptyList", Arrays.asList());
}
public void test_containerlib_poll_expect_error(){
try {
doCompile("function integer transform(){integer[] arr = null; integer i = poll(arr); return 0;}","test_containerlib_poll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] arr = null; integer i = arr.poll(); return 0;}","test_containerlib_poll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_pop() {
doCompile("test_containerlib_pop");
check("intElem", 5);
check("intElem2", 4);
check("intList", Arrays.asList(1, 2, 3));
check("longElem", 14L);
check("longElem2", 13L);
check("longList", Arrays.asList(11L,12L));
check("numElem", 11.5d);
check("numElem2", 11.4d);
check("numList", Arrays.asList(11.2d,11.3d));
check("decElem", new BigDecimal("22.5"));
check("decElem2", new BigDecimal("22.4"));
check("decList", Arrays.asList(new BigDecimal("22.2"), new BigDecimal("22.3")));
Calendar cal = Calendar.getInstance();
cal.set(2005, 8, 24, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem",cal.getTime());
cal.clear();
cal.set(2001, 6, 13, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem2", cal.getTime());
cal.clear();
cal.set(2010, 5, 11, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2011,3,3,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(),cal2.getTime()));
check("strElem", "Ezrael");
check("strElem2", null);
check("strList", Arrays.asList("Kha-Zix", "Xerath"));
check("emptyElem", null);
check("emptyElem2", null);
}
public void test_containerlib_pop_expect_error(){
try {
doCompile("function integer transform(){string[] arr = null; string str = pop(arr); return 0;}","test_containerlib_pop_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] arr = null; string str = arr.pop(); return 0;}","test_containerlib_pop_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
@SuppressWarnings("unchecked")
public void test_containerlib_push() {
doCompile("test_containerlib_push");
check("intCopy", Arrays.asList(1, 2, 3));
check("intRet", Arrays.asList(1, 2, 3));
check("longCopy", Arrays.asList(12l,13l,14l));
check("longRet", Arrays.asList(12l,13l,14l));
check("numCopy", Arrays.asList(11.1d,11.2d,11.3d));
check("numRet", Arrays.asList(11.1d,11.2d,11.3d));
check("decCopy", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4")));
check("decRet", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4")));
check("strCopy", Arrays.asList("Fiora", "Nunu", "Amumu"));
check("strRet", Arrays.asList("Fiora", "Nunu", "Amumu"));
Calendar cal = Calendar.getInstance();
cal.set(2001, 5, 9, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal1 = Calendar.getInstance();
cal1.set(2005, 5, 9, 0, 0, 0);
cal1.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2011, 5, 9, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateCopy", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime()));
check("dateRet", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime()));
String str = null;
check("emptyCopy", Arrays.asList(str));
check("emptyRet", Arrays.asList(str));
// there is hardly any way to get an instance of DataRecord
// hence we just check if the list has correct size
// and if its elements have correct metadata
List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList");
List<DataRecordMetadata> mdList = Arrays.asList(
graph.getDataRecordMetadata(OUTPUT_1),
graph.getDataRecordMetadata(INPUT_2),
graph.getDataRecordMetadata(INPUT_1)
);
assertEquals(mdList.size(), recordList.size());
for (int i = 0; i < mdList.size(); i++) {
assertEquals(mdList.get(i), recordList.get(i).getMetadata());
}
}
public void test_containerlib_push_expect_error(){
try {
doCompile("function integer transform(){string[] str = null; str.push('a'); return 0;}","test_containerlib_push_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] str = null; push(str, 'a'); return 0;}","test_containerlib_push_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_remove() {
doCompile("test_containerlib_remove");
check("intElem", 2);
check("intList", Arrays.asList(1, 3, 4, 5));
check("longElem", 13L);
check("longList", Arrays.asList(11l,12l,14l));
check("numElem", 11.3d);
check("numList", Arrays.asList(11.1d,11.2d,11.4d));
check("decElem", new BigDecimal("11.3"));
check("decList", Arrays.asList(new BigDecimal("11.1"),new BigDecimal("11.2"),new BigDecimal("11.4")));
Calendar cal = Calendar.getInstance();
cal.set(2002,10,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem", cal.getTime());
cal.clear();
cal.set(2001,10,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003,10,13,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(), cal2.getTime()));
check("strElem", "Shivana");
check("strList", Arrays.asList("Annie","Lux"));
}
public void test_containerlib_remove_expect_error(){
try {
doCompile("function integer transform(){string[] strList; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList; string str = strList.remove(0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,5); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,-1); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = null; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_reverse_expect_error(){
try {
doCompile("function integer transform(){long[] longList = null; reverse(longList); return 0;}","test_containerlib_reverse_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long[] longList = null; long[] reversed = longList.reverse(); return 0;}","test_containerlib_reverse_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_reverse() {
doCompile("test_containerlib_reverse");
check("intList", Arrays.asList(5, 4, 3, 2, 1));
check("intList2", Arrays.asList(5, 4, 3, 2, 1));
check("longList", Arrays.asList(14l,13l,12l,11l));
check("longList2", Arrays.asList(14l,13l,12l,11l));
check("numList", Arrays.asList(1.3d,1.2d,1.1d));
check("numList2", Arrays.asList(1.3d,1.2d,1.1d));
check("decList", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1")));
check("decList2", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1")));
check("strList", Arrays.asList(null,"Lulu","Kog Maw"));
check("strList2", Arrays.asList(null,"Lulu","Kog Maw"));
Calendar cal = Calendar.getInstance();
cal.set(2001,2,1,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2002,2,1,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal2.getTime(),cal.getTime()));
check("dateList2", Arrays.asList(cal2.getTime(),cal.getTime()));
}
public void test_containerlib_sort() {
doCompile("test_containerlib_sort");
check("intList", Arrays.asList(1, 1, 2, 3, 5));
check("intList2", Arrays.asList(1, 1, 2, 3, 5));
check("longList", Arrays.asList(21l,22l,23l,24l));
check("longList2", Arrays.asList(21l,22l,23l,24l));
check("decList", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4")));
check("decList2", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4")));
check("numList", Arrays.asList(1.1d,1.2d,1.3d,1.4d));
check("numList2", Arrays.asList(1.1d,1.2d,1.3d,1.4d));
Calendar cal = Calendar.getInstance();
cal.set(2002,5,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003,5,12,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
Calendar cal3 = Calendar.getInstance();
cal3.set(2004,5,12,0,0,0);
cal3.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime()));
check("dateList2", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime()));
check("strList", Arrays.asList("","Alistar", "Nocturne", "Soraka"));
check("strList2", Arrays.asList("","Alistar", "Nocturne", "Soraka"));
check("emptyList", Arrays.asList());
check("emptyList2", Arrays.asList());
}
public void test_containerlib_sort_expect_error(){
try {
doCompile("function integer transform(){string[] strList = ['Renektor', null, 'Jayce']; sort(strList); return 0;}","test_containerlib_sort_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = null; sort(strList); return 0;}","test_containerlib_sort_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsAll() {
doCompile("test_containerlib_containsAll");
check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false));
check("test1", true);
check("test2", true);
check("test3", true);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", true);
check("test8", false);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", false);
check("test13", false);
check("test14", true);
check("test15", false);
check("test16", false);
}
public void test_containerlib_containsAll_expect_error(){
try {
doCompile("function integer transform(){integer[] intList = null; boolean b =intList.containsAll([1]); return 0;}","test_containerlib_containsAll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsKey() {
doCompile("test_containerlib_containsKey");
check("results", Arrays.asList(false, true, false, true, false, true));
check("test1", true);
check("test2", false);
check("test3", true);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", true);
check("test8", true);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", true);
check("test13", false);
check("test14", true);
check("test15", true);
check("test16", false);
check("test17", true);
check("test18", true);
check("test19", false);
check("test20", false);
}
public void test_containerlib_containsKey_expect_error(){
try {
doCompile("function integer transform(){map[string, integer] emptyMap = null; boolean b = emptyMap.containsKey('a'); return 0;}","test_containerlib_containsKey_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsValue() {
doCompile("test_containerlib_containsValue");
check("results", Arrays.asList(true, false, false, true, false, false, true, false));
check("test1", true);
check("test2", true);
check("test3", false);
check("test4", true);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", true);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", true);
check("test13", false);
check("test14", true);
check("test15", true);
check("test16", false);
check("test17", true);
check("test18", true);
check("test19", false);
check("test20", true);
check("test21", true);
check("test22", false);
check("test23", true);
check("test24", true);
check("test25", false);
check("test26", false);
}
public void test_convertlib_containsValue_expect_error(){
try {
doCompile("function integer transform(){map[integer, long] nullMap = null; boolean b = nullMap.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_getKeys() {
doCompile("test_containerlib_getKeys");
check("stringList", Arrays.asList("a","b"));
check("stringList2", Arrays.asList("a","b"));
check("integerList", Arrays.asList(5,7,2));
check("integerList2", Arrays.asList(5,7,2));
List<Date> list = new ArrayList<Date>();
Calendar cal = Calendar.getInstance();
cal.set(2008, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2001, 5, 28, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
list.add(cal.getTime());
list.add(cal2.getTime());
check("dateList", list);
check("dateList2", list);
check("longList", Arrays.asList(14L, 45L));
check("longList2", Arrays.asList(14L, 45L));
check("numList", Arrays.asList(12.3d, 13.4d));
check("numList2", Arrays.asList(12.3d, 13.4d));
check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("decList2", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("emptyList", Arrays.asList());
check("emptyList2", Arrays.asList());
}
public void test_containerlib_getKeys_expect_error(){
try {
doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getKeys(); return 0;}","test_containerlib_getKeys_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getKeys(strMap); return 0;}","test_containerlib_getKeys_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cache() {
doCompile("test_stringlib_cache");
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "The cat says meow. All cats say meow.");
check("rep3", "The cat says meow. All cats say meow.");
check("find1", Arrays.asList("to", "to", "to", "tro", "to"));
check("find2", Arrays.asList("to", "to", "to", "tro", "to"));
check("find3", Arrays.asList("to", "to", "to", "tro", "to"));
check("split1", Arrays.asList("one", "two", "three", "four", "five"));
check("split2", Arrays.asList("one", "two", "three", "four", "five"));
check("split3", Arrays.asList("one", "two", "three", "four", "five"));
check("chop01", "ting soming choping function");
check("chop02", "ting soming choping function");
check("chop03", "ting soming choping function");
check("chop11", "testing end of lines cutting");
check("chop12", "testing end of lines cutting");
}
public void test_stringlib_charAt() {
doCompile("test_stringlib_charAt");
String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG ";
String[] expected = new String[input.length()];
for (int i = 0; i < expected.length; i++) {
expected[i] = String.valueOf(input.charAt(i));
}
check("chars", Arrays.asList(expected));
}
public void test_stringlib_charAt_error(){
//test: attempt to access char at position, which is out of bounds -> upper bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: attempt to access char at position, which is out of bounds -> lower bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: argument for position is null
try {
doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_concat() {
doCompile("test_stringlib_concat");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("concat", "");
check("concat1", "ello hi ELLO 2,today is " + format.format(new Date()));
check("concat2", "");
check("concat3", "clover");
check("test_null1", "null");
check("test_null2", "null");
check("test_null3","skynullisnullblue");
}
public void test_stringlib_countChar() {
doCompile("test_stringlib_countChar");
check("charCount", 3);
check("count2", 0);
}
public void test_stringlib_countChar_emptychar() {
// test: attempt to count empty chars in string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
// test: attempt to count empty chars in empty string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 1
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 2
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 3
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cut() {
doCompile("test_stringlib_cut");
check("cutInput", Arrays.asList("a", "1edf", "h3ijk"));
}
public void test_string_cut_expect_error() {
// test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and
// user attempt to cut out after position 8.
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from
// position
// 4 substring 4 characters long
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut a substring with negative length
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring from negative position. E.g cut([-3,3]).
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_editDistance() {
doCompile("test_stringlib_editDistance");
check("dist", 1);
check("dist1", 1);
check("dist2", 0);
check("dist5", 1);
check("dist3", 1);
check("dist4", 0);
check("dist6", 4);
check("dist7", 5);
check("dist8", 0);
check("dist9", 0);
}
public void test_stringlib_editDistance_expect_error(){
//test: input - empty string - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input- empty string - second arg
try {
doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - second argument
try {
doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both empty
try {
doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both null
try {
doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
}
public void test_stringlib_find() {
doCompile("test_stringlib_find");
check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g"));
check("findList2", Arrays.asList("mark.twain"));
check("findList3", Arrays.asList());
check("findList4", Arrays.asList("", "", "", "", ""));
check("findList5", Arrays.asList("twain"));
check("findList6", Arrays.asList(""));
}
public void test_stringlib_find_expect_error() {
//test: regexp group number higher then count of regexp groups
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: negative regexp group number
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test1
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test2
try {
doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 and arg2 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_join() {
doCompile("test_stringlib_join");
//check("joinedString", "Bagr,3,3.5641,-87L,CTL2");
check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1");
check("joinedString2", "5.054.6567.0231.0");
//check("joinedString3", "554656723180=5455.987-5=5455.9873=0.1CTL242");
check("test_empty1", "abc");
check("test_empty2", "");
check("test_empty3"," ");
check("test_empty4","anullb");
check("test_empty5","80=5455.987-5=5455.9873=0.1");
check("test_empty6","80=5455.987 -5=5455.987 3=0.1");
check("test_null1","abc");
check("test_null2","");
check("test_null3","anullb");
check("test_null4","80=5455.987-5=5455.9873=0.1");
//CLO-1210
check("test_empty7","a=xb=nullc=z");
check("test_empty8","a=x b=null c=z");
check("test_empty9","null=xeco=storm");
check("test_empty10","null=x eco=storm");
check("test_null5","a=xb=nullc=z");
check("test_null6","null=xeco=storm");
}
public void test_stringlib_join_expect_error(){
// CLO-1567 - join("", null) is ambiguous
// try {
// doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
try {
doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_left() {
//CLO - 1193
// doCompile("test_stringlib_left");
// check("test1", "aa");
// check("test2", "aaa");
// check("test3", "");
// check("test4", null);
// check("test5", "abc");
// check("test6", "ab ");
// check("test7", " ");
// check("test8", " ");
// check("test9", "abc");
// check("test10", "abc");
// check("test11", "");
// check("test12", null);
}
public void test_stringlib_length() {
doCompile("test_stringlib_length");
check("lenght1", new BigDecimal(50));
check("stringLength", 8);
check("length_empty", 0);
check("length_null1", 0);
}
public void test_stringlib_lowerCase() {
doCompile("test_stringlib_lowerCase");
check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr ");
check("lower_empty", "");
check("lower_null", null);
}
public void test_stringlib_matches() {
doCompile("test_stringlib_matches");
check("matches1", true);
check("matches2", true);
check("matches3", false);
check("matches4", true);
check("matches5", false);
check("matches6", false);
check("matches7", false);
check("matches8", false);
check("matches9", true);
check("matches10", true);
}
public void test_stringlib_matches_expect_error(){
//test: regexp param null - test 1
try {
doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 2
try {
doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 3
try {
doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups() {
doCompile("test_stringlib_matchGroups");
check("result1", null);
check("result2", Arrays.asList(
//"(([^:]*)([:])([\\(]))(.*)(\\))(((
"zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt",
"zip:(",
"zip",
":",
"(",
"zip:(/path/name?.zip)#innerfolder/file.zip",
")",
"#innermostfolder?/filename*.txt",
"#innermostfolder?/filename*.txt",
"
"innermostfolder?/filename*.txt",
null
)
);
check("result3", null);
check("test_empty1", null);
check("test_empty2", Arrays.asList(""));
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_matchGroups_expect_error(){
//test: regexp is null - test 1
try {
doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 2
try {
doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 3
try {
doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups_unmodifiable() {
try {
doCompile("test_stringlib_matchGroups_unmodifiable");
fail();
} catch (RuntimeException re) {
};
}
public void test_stringlib_metaphone() {
doCompile("test_stringlib_metaphone");
check("metaphone1", "XRS");
check("metaphone2", "KWNTLN");
check("metaphone3", "KWNT");
check("metaphone4", "");
check("metaphone5", "");
check("test_empty1", "");
check("test_empty2", "");
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_nysiis() {
doCompile("test_stringlib_nysiis");
check("nysiis1", "CAP");
check("nysiis2", "CAP");
check("nysiis3", "1234");
check("nysiis4", "C2 PRADACTAN");
check("nysiis_empty", "");
check("nysiis_null", null);
}
public void test_stringlib_replace() {
doCompile("test_stringlib_replace");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("rep", format.format(new Date()).replaceAll("[lL]", "t"));
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "intruders must die");
check("test_empty1", "a");
check("test_empty2", "");
check("test_null", null);
check("test_null2","");
check("test_null3","bbb");
check("test_null4",null);
}
public void test_stringlib_replace_expect_error(){
//test: regexp null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //test: arg3 null - test2
// try {
// doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
// //test: arg3 null - test3
// try {
// doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_right() {
doCompile("test_stringlib_right");
check("righ", "y dog");
check("rightNotPadded", "y dog");
check("rightPadded", "y dog");
check("padded", " y dog");
check("notPadded", "y dog");
check("short", "Dog");
check("shortNotPadded", "Dog");
check("shortPadded", " Dog");
check("simple", "milk");
check("test_null1", null);
check("test_null2", null);
check("test_null3", " ");
check("test_empty1", "");
check("test_empty2", "");
check("test_empty3"," ");
}
public void test_stringlib_soundex() {
doCompile("test_stringlib_soundex");
check("soundex1", "W630");
check("soundex2", "W643");
check("test_null", null);
check("test_empty", "");
}
public void test_stringlib_split() {
doCompile("test_stringlib_split");
check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g"));
check("test_empty", Arrays.asList(""));
check("test_empty2", Arrays.asList("","a","a"));
List<String> tmp = new ArrayList<String>();
tmp.add(null);
check("test_null", tmp);
}
public void test_stringlib_split_expect_error(){
//test: regexp null - test1
try {
doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_substring() {
doCompile("test_stringlib_substring");
check("subs", "UICk ");
check("test1", "");
check("test_empty", "");
}
public void test_stringlib_substring_expect_error(){
try {
doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_trim() {
doCompile("test_stringlib_trim");
check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG");
check("trim_empty", "");
check("trim_null", null);
}
public void test_stringlib_upperCase() {
doCompile("test_stringlib_upperCase");
check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_isFormat() {
doCompile("test_stringlib_isFormat");
check("test", "test");
check("isBlank", Boolean.FALSE);
check("blank", "");
checkNull("nullValue");
check("isBlank1", true);
check("isBlank2", true);
check("isAscii1", true);
check("isAscii2", false);
check("isAscii3", true);
check("isAscii4", true);
check("isNumber", false);
check("isNumber1", false);
check("isNumber2", true);
check("isNumber3", true);
check("isNumber4", false);
check("isNumber5", true);
check("isNumber6", true);
check("isNumber7", false);
check("isNumber8", false);
check("isInteger", false);
check("isInteger1", false);
check("isInteger2", false);
check("isInteger3", true);
check("isInteger4", false);
check("isInteger5", false);
check("isLong", true);
check("isLong1", false);
check("isLong2", false);
check("isLong3", false);
check("isLong4", false);
check("isDate", true);
check("isDate1", false);
// "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23)
check("isDate2", true);
check("isDate3", true);
check("isDate4", false);
check("isDate5", true);
check("isDate6", true);
check("isDate7", false);
check("isDate9", false);
check("isDate10", false);
check("isDate11", false);
check("isDate12", true);
check("isDate13", false);
check("isDate14", false);
// empty string: invalid
check("isDate15", false);
check("isDate16", false);
check("isDate17", true);
check("isDate18", true);
check("isDate19", false);
check("isDate20", false);
check("isDate21", false);
// CLO-1190
// check("isDate22", false);
// check("isDate23", false);
check("isDate24", true);
check("isDate25", false);
}
public void test_stringlib_empty_strings() {
String[] expressions = new String[] {
"isInteger(?)",
"isNumber(?)",
"isLong(?)",
"isAscii(?)",
"isBlank(?)",
"isDate(?, \"yyyy\")",
"isUrl(?)",
"string x = ?; length(x)",
"lowerCase(?)",
"matches(?, \"\")",
"NYSIIS(?)",
"removeBlankSpace(?)",
"removeDiacritic(?)",
"removeNonAscii(?)",
"removeNonPrintable(?)",
"replace(?, \"a\", \"a\")",
"translate(?, \"ab\", \"cd\")",
"trim(?)",
"upperCase(?)",
"chop(?)",
"concat(?)",
"getAlphanumericChars(?)",
};
StringBuilder sb = new StringBuilder();
for (String expr : expressions) {
String emptyString = expr.replace("?", "\"\"");
boolean crashesEmpty = test_expression_crashes(emptyString);
assertFalse("Function " + emptyString + " crashed", crashesEmpty);
String nullString = expr.replace("?", "null");
boolean crashesNull = test_expression_crashes(nullString);
sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok"));
}
System.out.println(sb.toString());
}
private boolean test_expression_crashes(String expr) {
String expStr = "function integer transform() { " + expr + "; return 0; }";
try {
doCompile(expStr, "test_stringlib_empty_null_strings");
return false;
} catch (RuntimeException e) {
return true;
}
}
public void test_stringlib_removeBlankSpace() {
String expStr =
"string r1;\n" +
"string str_empty;\n" +
"string str_null;\n" +
"function integer transform() {\n" +
"r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" +
"printErr(r1);\n" +
"str_empty = removeBlankSpace('');\n" +
"str_null = removeBlankSpace(null);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_removeBlankSpace");
check("r1", "abcdef");
check("str_empty", "");
check("str_null", null);
}
public void test_stringlib_removeNonPrintable() {
doCompile("test_stringlib_removeNonPrintable");
check("nonPrintableRemoved", "AHOJ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_getAlphanumericChars() {
String expStr =
"string an1;\n " +
"string an2;\n" +
"string an3;\n" +
"string an4;\n" +
"string an5;\n" +
"string an6;\n" +
"string an7;\n" +
"string an8;\n" +
"string an9;\n" +
"string an10;\n" +
"string an11;\n" +
"string an12;\n" +
"string an13;\n" +
"string an14;\n" +
"string an15;\n" +
"function integer transform() {\n" +
"an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" +
"an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" +
"an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" +
"an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" +
"an5=getAlphanumericChars(\"\");\n" +
"an6=getAlphanumericChars(\"\",true,true);\n"+
"an7=getAlphanumericChars(\"\",true,false);\n"+
"an8=getAlphanumericChars(\"\",false,true);\n"+
"an9=getAlphanumericChars(null);\n" +
"an10=getAlphanumericChars(null,false,false);\n" +
"an11=getAlphanumericChars(null,true,false);\n" +
"an12=getAlphanumericChars(null,false,true);\n" +
"an13=getAlphanumericChars(' 0 ľeškó11');\n" +
"an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" +
//CLO-1174
"an15=getAlphanumericChars('" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "',false,false);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_getAlphanumericChars");
check("an1", "a1bcde2f");
check("an2", "a1bcde2f");
check("an3", "abcdef");
check("an4", "12");
check("an5", "");
check("an6", "");
check("an7", "");
check("an8", "");
check("an9", null);
check("an10", null);
check("an11", null);
check("an12", null);
check("an13", "0ľeškó11");
check("an14"," 0 ľeškó11");
//CLO-1174
String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n");
check("an15", tmp);
}
public void test_stringlib_indexOf(){
doCompile("test_stringlib_indexOf");
check("index",2);
check("index1",9);
check("index2",0);
check("index3",-1);
check("index4",6);
check("index5",-1);
check("index6",0);
check("index7",4);
check("index8",4);
check("index9", -1);
check("index10", 2);
check("index_empty1", -1);
check("index_empty2", 0);
check("index_empty3", 0);
check("index_empty4", -1);
}
public void test_stringlib_indexOf_expect_error(){
//test: second arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: both args are null
try {
doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeDiacritic(){
doCompile("test_stringlib_removeDiacritic");
check("test","tescik");
check("test1","zabicka");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_translate(){
doCompile("test_stringlib_translate");
check("trans","hippi");
check("trans1","hipp");
check("trans2","hippi");
check("trans3","");
check("trans4","y lanuaX nXXd thX lXttXr X");
check("trans5", "hello");
check("test_empty1", "");
check("test_empty2", "");
check("test_null", null);
}
public void test_stringlib_translate_expect_error(){
try {
doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeNonAscii(){
doCompile("test_stringlib_removeNonAscii");
check("test1", "Sun is shining");
check("test2", "");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_chop() {
doCompile("test_stringlib_chop");
check("s1", "hello");
check("s6", "hello");
check("s5", "hello");
check("s2", "hello");
check("s7", "helloworld");
check("s3", "hello ");
check("s4", "hello");
check("s8", "hello");
check("s9", "world");
check("s10", "hello");
check("s11", "world");
check("s12", "mark.twain");
check("s13", "two words");
check("s14", "");
check("s15", "");
check("s16", "");
check("s17", "");
check("s18", "");
check("s19", "word");
check("s20", "");
check("s21", "");
check("s22", "mark.twain");
}
public void test_stringlib_chop_expect_error() {
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null
try {
doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null - test 2
try {
doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test2
try {
doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test3
try {
doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitSet(){
doCompile("test_bitwise_bitSet");
check("test1", 3);
check("test2", 15);
check("test3", 34);
check("test4", 3l);
check("test5", 15l);
check("test6", 34l);
}
public void test_bitwise_bitSet_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 3;"
+ "boolean var3 = false;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 512;"
+ "integer var2 = null;"
+ "boolean var3 = false;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 512;"
+ "integer var2 = 3;"
+ "boolean var3 = null;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 512l;"
+ "integer var2 = 3;"
+ "boolean var3 = null;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 512l;"
+ "integer var2 = null;"
+ "boolean var3 = true;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "integer var2 = 3;"
+ "boolean var3 = true;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitIsSet(){
doCompile("test_bitwise_bitIsSet");
check("test1", true);
check("test2", false);
check("test3", false);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", false);
}
public void test_bitwise_bitIsSet_expect_error(){
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_or() {
doCompile("test_bitwise_or");
check("resultInt1", 1);
check("resultInt2", 1);
check("resultInt3", 3);
check("resultInt4", 3);
check("resultLong1", 1l);
check("resultLong2", 1l);
check("resultLong3", 3l);
check("resultLong4", 3l);
check("resultMix1", 15L);
check("resultMix2", 15L);
}
public void test_bitwise_or_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer input1 = 12; "
+ "integer input2 = null; "
+ "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer input1 = null; "
+ "integer input2 = 13; "
+ "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long input1 = null; "
+ "long input2 = 13l; "
+ "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long input1 = 23l; "
+ "long input2 = null; "
+ "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_and() {
doCompile("test_bitwise_and");
check("resultInt1", 0);
check("resultInt2", 1);
check("resultInt3", 0);
check("resultInt4", 1);
check("resultLong1", 0l);
check("resultLong2", 1l);
check("resultLong3", 0l);
check("resultLong4", 1l);
check("test_mixed1", 4l);
check("test_mixed2", 4l);
}
public void test_bitwise_and_expect_error(){
try {
doCompile("function integer transform(){\n"
+ "integer a = null; integer b = 16;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "integer a = 16; integer b = null;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = 16l; long b = null;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = null; long b = 10l;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_xor() {
doCompile("test_bitwise_xor");
check("resultInt1", 1);
check("resultInt2", 0);
check("resultInt3", 3);
check("resultInt4", 2);
check("resultLong1", 1l);
check("resultLong2", 0l);
check("resultLong3", 3l);
check("resultLong4", 2l);
check("test_mixed1", 15L);
check("test_mixed2", 60L);
}
public void test_bitwise_xor_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 123;"
+ "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 23;"
+ "integer var2 = null;"
+ "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "long var2 = 123l;"
+ "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 2135l;"
+ "long var2 = null;"
+ "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_lshift() {
doCompile("test_bitwise_lshift");
check("resultInt1", 2);
check("resultInt2", 4);
check("resultInt3", 10);
check("resultInt4", 20);
check("resultInt5", -2147483648);
check("resultLong1", 2l);
check("resultLong2", 4l);
check("resultLong3", 10l);
check("resultLong4", 20l);
check("resultLong5",-9223372036854775808l);
}
public void test_bitwise_lshift_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_rshift() {
doCompile("test_bitwise_rshift");
check("resultInt1", 2);
check("resultInt2", 0);
check("resultInt3", 4);
check("resultInt4", 2);
check("resultLong1", 2l);
check("resultLong2", 0l);
check("resultLong3", 4l);
check("resultLong4", 2l);
check("test_neg1", 0);
check("test_neg2", 0);
check("test_neg3", 0l);
check("test_neg4", 0l);
// CLO-1399
// check("test_mix1", 2);
// check("test_mix2", 2);
}
public void test_bitwise_rshift_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = 23;"
+ "integer var2 = null;"
+ "integer i = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 78;"
+ "integer u = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "long var1 = 23l;"
+ "long var2 = null;"
+ "long l =bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "long var2 = 84l;"
+ "long l = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_bitwise_negate() {
doCompile("test_bitwise_negate");
check("resultInt", -59081717);
check("resultLong", -3321654987654105969L);
check("test_zero_int", -1);
check("test_zero_long", -1l);
}
public void test_bitwise_negate_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_set_bit() {
doCompile("test_set_bit");
check("resultInt1", 0x2FF);
check("resultInt2", 0xFB);
check("resultLong1", 0x4000000000000l);
check("resultLong2", 0xFFDFFFFFFFFFFFFl);
check("resultBool1", true);
check("resultBool2", false);
check("resultBool3", true);
check("resultBool4", false);
}
public void test_mathlib_abs() {
doCompile("test_mathlib_abs");
check("absIntegerPlus", new Integer(10));
check("absIntegerMinus", new Integer(1));
check("absLongPlus", new Long(10));
check("absLongMinus", new Long(1));
check("absDoublePlus", new Double(10.0));
check("absDoubleMinus", new Double(1.0));
check("absDecimalPlus", new BigDecimal(5.0));
check("absDecimalMinus", new BigDecimal(5.0));
}
public void test_mathlib_abs_expect_error(){
try {
doCompile("function integer transform(){ \n "
+ "integer tmp;\n "
+ "tmp = null; \n"
+ " integer i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "long tmp;\n "
+ "tmp = null; \n"
+ "long i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "double tmp;\n "
+ "tmp = null; \n"
+ "double i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "decimal tmp;\n "
+ "tmp = null; \n"
+ "decimal i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_ceil() {
doCompile("test_mathlib_ceil");
check("ceil1", -3.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(3.0, -3.0));
check("decimalResult", Arrays.asList(3.0, -3.0));
}
public void test_mathlib_ceil_expect_error(){
try {
doCompile("function integer transform(){integer var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_e() {
doCompile("test_mathlib_e");
check("varE", Math.E);
}
public void test_mathlib_exp() {
doCompile("test_mathlib_exp");
check("ex", Math.exp(1.123));
check("test1", Math.exp(2));
check("test2", Math.exp(22));
check("test3", Math.exp(23));
check("test4", Math.exp(94));
}
public void test_mathlib_exp_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_floor() {
doCompile("test_mathlib_floor");
check("floor1", -4.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(2.0, -4.0));
check("decimalResult", Arrays.asList(2.0, -4.0));
}
public void test_math_lib_floor_expect_error(){
try {
doCompile("function integer transform(){integer input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input= null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_log() {
doCompile("test_mathlib_log");
check("ln", Math.log(3));
check("test_int", Math.log(32));
check("test_long", Math.log(14l));
check("test_double", Math.log(12.9));
check("test_decimal", Math.log(23.7));
}
public void test_math_log_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){long input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){decimal input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){double input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_mathlib_log10() {
doCompile("test_mathlib_log10");
check("varLog10", Math.log10(3));
check("test_int", Math.log10(5));
check("test_long", Math.log10(90L));
check("test_decimal", Math.log10(32.1));
check("test_number", Math.log10(84.12));
}
public void test_mathlib_log10_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_pi() {
doCompile("test_mathlib_pi");
check("varPi", Math.PI);
}
public void test_mathlib_pow() {
doCompile("test_mathlib_pow");
check("power1", Math.pow(3,1.2));
check("power2", Double.NaN);
check("intResult", Arrays.asList(8d, 8d, 8d, 8d));
check("longResult", Arrays.asList(8d, 8d, 8d, 8d));
check("doubleResult", Arrays.asList(8d, 8d, 8d, 8d));
check("decimalResult", Arrays.asList(8d, 8d, 8d, 8d));
}
public void test_mathlib_pow_expect_error(){
try {
doCompile("function integer transform(){integer var1 = 12; integer var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer var1 = null; integer var2 = 2; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var1 = 12l; long var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var1 = null; long var2 = 12L; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number var1 = 12.2; number var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number var1 = null; number var2 = 2.1; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var1 = 12.2d; decimal var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var1 = null; decimal var2 = 45.3d; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_round() {
doCompile("test_mathlib_round");
check("round1", -4l);
check("intResult", Arrays.asList(2l, 3l));
check("longResult", Arrays.asList(2l, 3l));
check("doubleResult", Arrays.asList(2l, 4l));
check("decimalResult", Arrays.asList(2l, 4l));
}
public void test_mathlib_round_expect_error(){
try {
doCompile("function integer transform(){number input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_sqrt() {
doCompile("test_mathlib_sqrt");
check("sqrtPi", Math.sqrt(Math.PI));
check("sqrt9", Math.sqrt(9));
check("test_int", 2.0);
check("test_long", Math.sqrt(64L));
check("test_num", Math.sqrt(86.9));
check("test_dec", Math.sqrt(34.5));
}
public void test_mathlib_sqrt_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_randomInteger(){
doCompile("test_mathlib_randomInteger");
assertNotNull(getVariable("test1"));
check("test2", 2);
}
public void test_mathlib_randomInteger_expect_error(){
try {
doCompile("function integer transform(){integer i = randomInteger(1,null); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(null,null); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(null, -3); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(1,-7); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_randomLong(){
doCompile("test_mathlib_randomLong");
assertNotNull(getVariable("test1"));
check("test2", 15L);
}
public void test_mathlib_randomLong_expect_error(){
try {
doCompile("function integer transform(){long lo = randomLong(15L, null); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(null, null); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(null, 15L); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(15L, 10L); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_cache() {
doCompile("test_datelib_cache");
check("b11", true);
check("b12", true);
check("b21", true);
check("b22", true);
check("b31", true);
check("b32", true);
check("b41", true);
check("b42", true);
checkEquals("date3", "date3d");
checkEquals("date4", "date4d");
checkEquals("date7", "date7d");
checkEquals("date8", "date8d");
}
public void test_datelib_trunc() {
doCompile("test_datelib_trunc");
check("truncDate", new GregorianCalendar(2004, 00, 02).getTime());
}
public void test_datelib_truncDate() {
doCompile("test_datelib_truncDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("truncBornDate", cal.getTime());
}
public void test_datelib_today() {
doCompile("test_datelib_today");
Date expectedDate = new Date();
//the returned date does not need to be exactly the same date which is in expectedData variable
//let say 1000ms is tolerance for equality
assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000);
}
public void test_datelib_zeroDate() {
doCompile("test_datelib_zeroDate");
check("zeroDate", new Date(0));
}
public void test_datelib_dateDiff() {
doCompile("test_datelib_dateDiff");
long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears();
check("ddiff", diffYears);
long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L};
String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"};
for (int i = 0; i < results.length; i++) {
check(vars[i], results[i]);
}
}
public void test_datelib_dateDiff_epect_error(){
try {
doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_dateAdd() {
doCompile("test_datelib_dateAdd");
check("datum", new Date(BORN_MILLISEC_VALUE + 100));
}
public void test_datelib_dateAdd_expect_error(){
try {
doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractTime() {
doCompile("test_datelib_extractTime");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("bornExtractTime", cal.getTime());
check("originalDate", BORN_VALUE);
check("nullDate", null);
check("nullDate2", null);
}
public void test_datelib_extractDate() {
doCompile("test_datelib_extractDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)};
cal.clear();
cal.set(Calendar.DAY_OF_MONTH, portion[0]);
cal.set(Calendar.MONTH, portion[1]);
cal.set(Calendar.YEAR, portion[2]);
check("bornExtractDate", cal.getTime());
check("originalDate", BORN_VALUE);
check("nullDate", null);
check("nullDate2", null);
}
public void test_datelib_createDate() {
doCompile("test_datelib_createDate");
Calendar cal = Calendar.getInstance();
// no time zone
cal.clear();
cal.set(2013, 5, 11);
check("date1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis1", cal.getTime());
// literal
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
cal.clear();
cal.set(2013, 5, 11);
check("date2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis2", cal.getTime());
// variable
cal.clear();
cal.set(2013, 5, 11);
check("date3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis3", cal.getTime());
}
public void test_datelib_getPart() {
doCompile("test_datelib_getPart");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+1"));
cal.set(2013, 5, 11, 14, 46, 34);
cal.set(Calendar.MILLISECOND, 123);
Date date = cal.getTime();
cal = Calendar.getInstance();
cal.setTime(date);
// no time zone
check("year1", cal.get(Calendar.YEAR));
check("month1", cal.get(Calendar.MONTH) + 1);
check("day1", cal.get(Calendar.DAY_OF_MONTH));
check("hour1", cal.get(Calendar.HOUR_OF_DAY));
check("minute1", cal.get(Calendar.MINUTE));
check("second1", cal.get(Calendar.SECOND));
check("millisecond1", cal.get(Calendar.MILLISECOND));
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
// literal
check("year2", cal.get(Calendar.YEAR));
check("month2", cal.get(Calendar.MONTH) + 1);
check("day2", cal.get(Calendar.DAY_OF_MONTH));
check("hour2", cal.get(Calendar.HOUR_OF_DAY));
check("minute2", cal.get(Calendar.MINUTE));
check("second2", cal.get(Calendar.SECOND));
check("millisecond2", cal.get(Calendar.MILLISECOND));
// variable
check("year3", cal.get(Calendar.YEAR));
check("month3", cal.get(Calendar.MONTH) + 1);
check("day3", cal.get(Calendar.DAY_OF_MONTH));
check("hour3", cal.get(Calendar.HOUR_OF_DAY));
check("minute3", cal.get(Calendar.MINUTE));
check("second3", cal.get(Calendar.SECOND));
check("millisecond3", cal.get(Calendar.MILLISECOND));
check("year_null", 2013);
check("month_null", 6);
check("day_null", 11);
check("hour_null", 15);
check("minute_null", cal.get(Calendar.MINUTE));
check("second_null", cal.get(Calendar.SECOND));
check("milli_null", cal.get(Calendar.MILLISECOND));
check("year_null2", null);
check("month_null2", null);
check("day_null2", null);
check("hour_null2", null);
check("minute_null2", null);
check("second_null2", null);
check("milli_null2", null);
check("year_null3", null);
check("month_null3", null);
check("day_null3", null);
check("hour_null3", null);
check("minute_null3", null);
check("second_null3", null);
check("milli_null3", null);
}
public void test_datelib_randomDate() {
doCompile("test_datelib_randomDate");
final long HOUR = 60L * 60L * 1000L;
Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L);
check("noTimeZone1", BORN_VALUE);
check("noTimeZone2", BORN_VALUE_NO_MILLIS);
check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3
check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5
assertNotNull(getVariable("patt_null"));
}
public void test_datelib_randomDate_expect_error(){
try {
doCompile("function integer transform(){date a = null; date b = today(); "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = today(); date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = null; date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = 843484317231l; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = 12115641158l; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//wrong format
try {
doCompile("function integer transform(){"
+ "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//start date bigger then end date
try {
doCompile("function integer transform(){"
+ "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_json2xml(){
doCompile("test_convertlib_json2xml");
String xmlChunk =""
+ "<lastName>Smith</lastName>"
+ "<phoneNumber>"
+ "<number>212 555-1234</number>"
+ "<type>home</type>"
+ "</phoneNumber>"
+ "<phoneNumber>"
+ "<number>646 555-4567</number>"
+ "<type>fax</type>"
+ "</phoneNumber>"
+ "<address>"
+ "<streetAddress>21 2nd Street</streetAddress>"
+ "<postalCode>10021</postalCode>"
+ "<state>NY</state>"
+ "<city>New York</city>"
+ "</address>"
+ "<age>25</age>"
+ "<firstName>John</firstName>";
check("ret", xmlChunk);
check("ret2", "<name/>");
check("ret3", "<address></address>");
check("ret4", "</>");
check("ret5", "<
check("ret6", "</>/<
check("ret7","");
check("ret8", "<>Urgot</>");
}
public void test_convertlib_json2xml_expect_error(){
try {
doCompile("function integer transform(){string str = json2xml(''); return 0;}","test_convertlib_json2xml_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){string str = json2xml(null); return 0;}","test_convertlib_json2xml_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){string str = json2xml('{\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){string str = json2xml('{\"name\":}'); return 0;}","test_convertlib_json2xml_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){string str = json2xml('{:\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_xml2json(){
doCompile("test_convertlib_xml2json");
String json = "{\"lastName\":\"Smith\",\"phoneNumber\":[{\"number\":\"212 555-1234\",\"type\":\"home\"},{\"number\":\"646 555-4567\",\"type\":\"fax\"}],\"address\":{\"streetAddress\":\"21 2nd Street\",\"postalCode\":10021,\"state\":\"NY\",\"city\":\"New York\"},\"age\":25,\"firstName\":\"John\"}";
check("ret1", json);
check("ret2", "{\"name\":\"Renektor\"}");
check("ret3", "{}");
check("ret4", "{\"address\":\"\"}");
check("ret5", "{\"age\":32}");
check("ret6", "{\"b\":\"\"}");
check("ret7", "{\"char\":{\"name\":\"Anivia\",\"lane\":\"mid\"}}");
check("ret8", "{\"
}
public void test_convertlib_xml2json_expect_error(){
try {
doCompile("function integer transform(){string json = xml2json(null); return 0;}","test_convertlib_xml2json_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string json = xml2json('<></>'); return 0;}","test_convertlib_xml2json_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string json = xml2json('<#>/</>'); return 0;}","test_convertlib_xml2json_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_cache() {
// set default locale to en.US so the date is formatted uniformly on all systems
Locale.setDefault(Locale.US);
doCompile("test_convertlib_cache");
Calendar cal = Calendar.getInstance();
cal.set(2000, 6, 20, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("sdate1", format.format(new Date()));
check("sdate2", format.format(new Date()));
check("date01", checkDate);
check("date02", checkDate);
check("date03", checkDate);
check("date04", checkDate);
check("date11", checkDate);
check("date12", checkDate);
check("date13", checkDate);
}
public void test_convertlib_base64byte() {
doCompile("test_convertlib_base64byte");
assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog")));
}
public void test_convertlib_base64byte_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = base64byte(null); return 0;}","test_convertlib_base64byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = null; byte b = base64byte(s); return 0;}","test_convertlib_base64byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bits2str() {
doCompile("test_convertlib_bits2str");
check("bitsAsString1", "00000000");
check("bitsAsString2", "11111111");
check("bitsAsString3", "010100000100110110100000");
}
public void test_convertlib_bits2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = bits2str(null); return 0;}","test_convertlib_bits2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = null; string s = bits2str(b); return 0;}","test_convertlib_bits2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bool2num() {
doCompile("test_convertlib_bool2num");
check("resultTrue", 1);
check("resultFalse", 0);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_byte2base64() {
doCompile("test_convertlib_byte2base64");
check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes()));
}
public void test_convertlib_byte2base64_expect_error(){
try {
doCompile("function integer transform(){string s = byte2base64(null);return 0;}","test_convertlib_byte2base64_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = null; string s = byte2base64(b);return 0;}","test_convertlib_byte2base64_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2hex() {
doCompile("test_convertlib_byte2hex");
check("hexResult", "41626563656461207a65646c612064656461");
check("test_null1", null);
check("test_null2", null);
}
public void test_convertlib_date2long() {
doCompile("test_convertlib_date2long");
check("bornDate", BORN_MILLISEC_VALUE);
check("zeroDate", 0l);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_date2num() {
doCompile("test_convertlib_date2num");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
check("yearDate", 1987);
check("monthDate", 5);
check("secondDate", 0);
check("yearBorn", cal.get(Calendar.YEAR));
check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1;
check("secondBorn", cal.get(Calendar.SECOND));
check("yearMin", 1970);
check("monthMin", 1);
check("weekMin", 1);
check("weekMinCs", 1);
check("dayMin", 1);
check("hourMin", 1); //TODO: check!
check("minuteMin", 0);
check("secondMin", 0);
check("millisecMin", 0);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_date2num_expect_error(){
try {
doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){number num = date2num(1982-09-02,null,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,null,s); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,year,s); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_date2str() {
doCompile("test_convertlib_date2str");
check("inputDate", "1987:05:12");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd");
check("bornDate", sdf.format(BORN_VALUE));
SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ"));
check("czechBornDate", sdfCZ.format(BORN_VALUE));
SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en"));
check("englishBornDate", sdfEN.format(BORN_VALUE));
{
String[] locales = {"en", "pl", null, "cs.CZ", null};
List<String> expectedDates = new ArrayList<String>();
for (String locale: locales) {
expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE));
}
check("loopTest", expectedDates);
}
SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en"));
sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("timeZone", sdfGMT8.format(BORN_VALUE));
check("nullRet", null);
check("nullRet2", null);
}
public void test_convertlib_decimal2double() {
doCompile("test_convertlib_decimal2double");
check("toDouble", 0.007d);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_decimal2integer() {
doCompile("test_convertlib_decimal2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_decimal2long() {
doCompile("test_convertlib_decimal2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_double2integer() {
doCompile("test_convertlib_double2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_double2long() {
doCompile("test_convertlib_double2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_getFieldName() {
doCompile("test_convertlib_getFieldName");
check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
}
public void test_convertlib_getFieldType() {
doCompile("test_convertlib_getFieldType");
check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(),
DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(),
DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName()));
}
public void test_convertlib_hex2byte() {
doCompile("test_convertlib_hex2byte");
assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE));
check("test_null", null);
}
public void test_convertlib_long2date() {
doCompile("test_convertlib_long2date");
check("fromLong1", new Date(0));
check("fromLong2", new Date(50000000000L));
check("fromLong3", new Date(-5000L));
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_long2integer() {
doCompile("test_convertlib_long2integer");
check("fromLong1", 10);
check("fromLong2", -10);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_long2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = long2integer(200032132463123L); return 0;}","test_convertlib_long2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2packDecimal() {
doCompile("test_convertlib_long2packDecimal");
assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12}));
}
public void test_convertlib_long2packDecimal_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = long2packDecimal(null); return 0;}","test_convertlib_long2packDecimal_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_md5() {
doCompile("test_convertlib_md5");
assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, "")));
}
public void test_convertlib_md5_expect_error(){
//CLO-1254
try {
doCompile("function integer transform(){string s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_num2bool() {
doCompile("test_convertlib_num2bool");
check("integerTrue", true);
check("integerFalse", false);
check("longTrue", true);
check("longFalse", false);
check("doubleTrue", true);
check("doubleFalse", false);
check("decimalTrue", true);
check("decimalFalse", false);
}
public void test_convertlib_num2bool_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: decimal
try {
doCompile("decimal input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_num2str() {
System.out.println("num2str() test:");
doCompile("test_convertlib_num2str");
check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs"));
check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs"));
check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs"));
check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs"));
check("nullIntRet", Arrays.asList(null,null,null,null,"12","12",null,null));
check("nullLongRet", Arrays.asList(null,null,null,null,"12","12",null,null));
check("nullDoubleRet", Arrays.asList(null,null,null,null,"12.2","12.2",null,null));
check("nullDecRet", Arrays.asList(null,null,null,"12.2","12.2",null,null));
}
public void test_convertlib_num2str_expect_error(){
try {
doCompile("function integer transform(){integer var = null; string ret = num2str(12, var); return 0;}","test_convertlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer var = null; string ret = num2str(12L, var); return 0;}","test_convertlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer var = null; string ret = num2str(12.3, var); return 0;}","test_convertlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_packdecimal2long() {
doCompile("test_convertlib_packDecimal2long");
check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE));
}
public void test_convertlib_packdecimal2long_expect_error(){
try {
doCompile("function integer transform(){long l =packDecimal2long(null); return 0;}","test_convertlib_packdecimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_sha() {
doCompile("test_convertlib_sha");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, "")));
}
public void test_convertlib_sha_expect_error(){
// CLO-1258
try {
doCompile("function integer transform(){string s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_sha256() {
doCompile("test_convertlib_sha256");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, "")));
}
public void test_convertlib_sha256_expect_error(){
// CLO-1258
try {
doCompile("function integer transform(){string a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2bits() {
doCompile("test_convertlib_str2bits");
//TODO: uncomment -> test will pass, but is that correct?
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {}));
}
public void test_convertlib_str2bits_expect_error(){
try {
doCompile("function integer transform(){byte b = str2bits(null); return 0;}","test_convertlib_str2bits_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2bool() {
doCompile("test_convertlib_str2bool");
check("fromTrueString", true);
check("fromFalseString", false);
check("nullRet1", null);
check("nullRet2", null);
}
public void test_convertlib_str2bool_expect_error(){
try {
doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_str2date() {
doCompile("test_convertlib_str2date");
Calendar cal = Calendar.getInstance();
cal.set(2005,10,19,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("date1", cal.getTime());
cal.clear();
cal.set(2050, 4, 19, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
check("date2", checkDate);
check("date3", checkDate);
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone1", cal.getTime());
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone2", cal.getTime());
assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2")));
check("nullRet1", null);
check("nullRet2", null);
check("nullRet3", null);
check("nullRet4", null);
check("nullRet5", null);
check("nullRet6", null);
}
public void test_convertlib_str2date_expect_error(){
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', 'cs.CZ', null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2decimal() {
doCompile("test_convertlib_str2decimal");
check("parsedDecimal1", new BigDecimal("100.13"));
check("parsedDecimal2", new BigDecimal("123123123.123"));
check("parsedDecimal3", new BigDecimal("-350000.01"));
check("parsedDecimal4", new BigDecimal("1000000"));
check("parsedDecimal5", new BigDecimal("1000000.99"));
check("parsedDecimal6", new BigDecimal("123123123.123"));
check("parsedDecimal7", new BigDecimal("5.01"));
check("nullRet1", null);
check("nullRet2", null);
check("nullRet3", null);
check("nullRet4", null);
check("nullRet5", null);
check("nullRet6", null);
check("nullRet7", new BigDecimal("5.05"));
// CLO-1614
check("nullRet8", new BigDecimal("5.05"));
check("nullRet9", new BigDecimal("5.05"));
check("nullRet10", new BigDecimal("5.05"));
check("nullRet11", new BigDecimal("5.05"));
check("nullRet12", new BigDecimal("5.05"));
check("nullRet13", new BigDecimal("5.05"));
check("nullRet14", new BigDecimal("5.05"));
check("nullRet15", new BigDecimal("5.05"));
check("nullRet16", new BigDecimal("5.05"));
}
public void test_convertlib_str2decimal_expect_result(){
try {
doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
// CLO-1614
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null, null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2double() {
doCompile("test_convertlib_str2double");
check("parsedDouble1", 100.13);
check("parsedDouble2", 123123123.123);
check("parsedDouble3", -350000.01);
check("nullRet1", null);
check("nullRet2", null);
check("nullRet3", null);
check("nullRet4", null);
check("nullRet5", null);
check("nullRet6", null);
check("nullRet7", 12.34d);
// CLO-1614
check("nullRet8", 12.34d);
check("nullRet9", 12.34d);
check("nullRet10", 12.34d);
check("nullRet11", 12.34d);
check("nullRet12", 12.34d);
check("nullRet13", 12.34d);
check("nullRet14", 12.34d);
check("nullRet15", 12.34d);
}
public void test_convertlib_str2double_expect_error(){
try {
doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// CLO-1614
try {
doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c', null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c', null, null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2integer() {
doCompile("test_convertlib_str2integer");
check("parsedInteger1", 123456789);
check("parsedInteger2", 123123);
check("parsedInteger3", -350000);
check("parsedInteger4", 419);
check("nullRet1", 123);
check("nullRet2", 123);
check("nullRet3", null);
check("nullRet4", null);
check("nullRet5", null);
check("nullRet6", null);
check("nullRet7", null);
check("nullRet8", null);
check("nullRet9", null);
// CLO-1614
// check("nullRet10", 123); // ambiguous
check("nullRet11", 123);
check("nullRet12", 123);
check("nullRet13", 123);
check("nullRet14", 123);
check("nullRet15", 123);
check("nullRet16", 123);
check("nullRet17", 123);
}
public void test_convertlib_str2integer_expect_error(){
try {
doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer('123 mil', '###mil'); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s, null); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2long() {
doCompile("test_convertlib_str2long");
check("parsedLong1", 1234567890123L);
check("parsedLong2", 123123123456789L);
check("parsedLong3", -350000L);
check("parsedLong4", 133L);
check("nullRet1", 123l);
check("nullRet2", 123l);
check("nullRet3", null);
check("nullRet4", null);
check("nullRet5", null);
check("nullRet6", null);
check("nullRet7", null);
check("nullRet8", null);
check("nullRet9", null);
// CLO-1614
// check("nullRet10", 123l); // ambiguous
check("nullRet11", 123l);
check("nullRet12", 123l);
check("nullRet13", 123l);
check("nullRet14", 123l);
check("nullRet15", 123l);
check("nullRet16", 123l);
check("nullRet17", 123l);
}
public void test_convertlib_str2long_expect_error(){
try {
doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long('13', '## bls'); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long('13', '## bls' , null); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long('13 L', null, 'cs.Cz'); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_toString() {
doCompile("test_convertlib_toString");
check("integerString", "10");
check("longString", "110654321874");
check("doubleString", "1.547874E-14");
check("decimalString", "-6847521431.1545874");
check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]");
check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}");
String byteMapString = getVariable("byteMapString").toString();
assertTrue(byteMapString.contains("1=value1"));
assertTrue(byteMapString.contains("2=value2"));
String fieldByteMapString = getVariable("fieldByteMapString").toString();
assertTrue(fieldByteMapString.contains("key1=value1"));
assertTrue(fieldByteMapString.contains("key2=value2"));
check("byteListString", "[firstElement, secondElement]");
check("fieldByteListString", "[firstElement, secondElement]");
// CLO-1262
check("test_null_l", "null");
check("test_null_dec", "null");
check("test_null_d", "null");
check("test_null_i", "null");
}
public void test_convertlib_str2byte() {
doCompile("test_convertlib_str2byte");
checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 });
checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 });
checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 });
checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 });
checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 });
checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 });
checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
}
public void test_convertlib_str2byte_expect_error(){
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-8'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-16'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'MacCentralEurope'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'ascii'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'iso-8859-2'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'windows-1250'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2str() {
doCompile("test_convertlib_byte2str");
String hello = "Hello World!";
String horse = "Příliš žluťoučký kůň pěl ďáblské ódy";
String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω";
check("utf8Hello", hello);
check("utf8Horse", horse);
check("utf8Math", math);
check("utf16Hello", hello);
check("utf16Horse", horse);
check("utf16Math", math);
check("macHello", hello);
check("macHorse", horse);
check("asciiHello", hello);
check("isoHello", hello);
check("isoHorse", horse);
check("cpHello", hello);
check("cpHorse", horse);
}
public void test_convertlib_byte2str_expect_error(){
try {
doCompile("function integer transform(){string s = byte2str(null,'utf-8'); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_conditional_fail() {
doCompile("test_conditional_fail");
check("result", 3);
}
public void test_expression_statement(){
// test case for issue 4174
doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected"));
}
public void test_dictionary_read() {
doCompile("test_dictionary_read");
check("s", "Verdon");
check("i", Integer.valueOf(211));
check("l", Long.valueOf(226));
check("d", BigDecimal.valueOf(239483061));
check("n", Double.valueOf(934.2));
check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
check("b", true);
byte[] y = (byte[]) getVariable("y");
assertEquals(10, y.length);
assertEquals(89, y[9]);
check("sNull", null);
check("iNull", null);
check("lNull", null);
check("dNull", null);
check("nNull", null);
check("aNull", null);
check("bNull", null);
check("yNull", null);
check("stringList", Arrays.asList("aa", "bb", null, "cc"));
check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) getVariable("byteList");
assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
}
public void test_dictionary_write() {
doCompile("test_dictionary_write");
assertEquals(832, graph.getDictionary().getValue("i") );
assertEquals("Guil", graph.getDictionary().getValue("s"));
assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l"));
assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d"));
assertEquals(934.2, graph.getDictionary().getValue("n"));
assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a"));
assertEquals(true, graph.getDictionary().getValue("b"));
byte[] y = (byte[]) graph.getDictionary().getValue("y");
assertEquals(2, y.length);
assertEquals(18, y[0]);
assertEquals(-94, y[1]);
assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList"));
assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList"));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF}));
check("assignmentReturnValue", "Guil");
}
public void test_dictionary_write_null() {
doCompile("test_dictionary_write_null");
assertEquals(null, graph.getDictionary().getValue("s"));
assertEquals(null, graph.getDictionary().getValue("sVerdon"));
assertEquals(null, graph.getDictionary().getValue("i") );
assertEquals(null, graph.getDictionary().getValue("i211") );
assertEquals(null, graph.getDictionary().getValue("l"));
assertEquals(null, graph.getDictionary().getValue("l452"));
assertEquals(null, graph.getDictionary().getValue("d"));
assertEquals(null, graph.getDictionary().getValue("d621"));
assertEquals(null, graph.getDictionary().getValue("n"));
assertEquals(null, graph.getDictionary().getValue("n9342"));
assertEquals(null, graph.getDictionary().getValue("a"));
assertEquals(null, graph.getDictionary().getValue("a1992"));
assertEquals(null, graph.getDictionary().getValue("b"));
assertEquals(null, graph.getDictionary().getValue("bTrue"));
assertEquals(null, graph.getDictionary().getValue("y"));
assertEquals(null, graph.getDictionary().getValue("yFib"));
}
public void test_dictionary_invalid_key(){
doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist"));
}
public void test_dictionary_string_to_int(){
doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'"));
}
public void test_utillib_sleep() {
long time = System.currentTimeMillis();
doCompile("test_utillib_sleep");
long tmp = System.currentTimeMillis() - time;
assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000);
}
public void test_utillib_random_uuid() {
doCompile("test_utillib_random_uuid");
assertNotNull(getVariable("uuid"));
}
public void test_stringlib_randomString(){
doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString");
assertNotNull(getVariable("test"));
}
public void test_stringlib_validUrl() {
doCompile("test_stringlib_url");
check("urlValid", Arrays.asList(true, true, false, true, false, true));
check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip"));
check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, ""));
check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, ""));
check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1));
check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)"));
check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, ""));
check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt"));
}
public void test_stringlib_escapeUrl() {
doCompile("test_stringlib_escapeUrl");
check("escaped", "http://example.com/foo%20bar%5E");
check("unescaped", "http://example.com/foo bar^");
}
public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){
//test: escape - empty string
try {
doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - null string
try {
doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - empty string
try {
doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - null
try {
doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - invalid URL
try {
doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescpae - invalid URL
try {
doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_resolveParams() {
doCompile("test_stringlib_resolveParams");
check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
}
public void test_utillib_getEnvironmentVariables() {
doCompile("test_utillib_getEnvironmentVariables");
check("empty", false);
}
public void test_utillib_getJavaProperties() {
String key1 = "my.testing.property";
String key2 = "my.testing.property2";
String value = "my value";
String value2;
assertNull(System.getProperty(key1));
assertNull(System.getProperty(key2));
System.setProperty(key1, value);
try {
doCompile("test_utillib_getJavaProperties");
value2 = System.getProperty(key2);
} finally {
System.clearProperty(key1);
assertNull(System.getProperty(key1));
System.clearProperty(key2);
assertNull(System.getProperty(key2));
}
check("java_specification_name", "Java Platform API Specification");
check("my_testing_property", value);
assertEquals("my value 2", value2);
}
public void test_utillib_getParamValues() {
doCompile("test_utillib_getParamValues");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
check("params", params);
}
public void test_utillib_getParamValue() {
doCompile("test_utillib_getParamValue");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
params.put("NONEXISTING", null);
check("params", params);
}
public void test_stringlib_getUrlParts() {
doCompile("test_stringlib_getUrlParts");
List<Boolean> isUrl = Arrays.asList(true, true, true, true, false);
List<String> path = Arrays.asList(
"/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt",
"/data-in/fileOperation/input.txt",
"/data/file.txt",
"/data/file.txt",
null);
List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null);
List<String> host = Arrays.asList(
"ava-fileManipulator1-devel.getgooddata.com",
"cloveretl.test.scenarios",
"ftp.test.com",
"www.test.com",
null);
List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2);
List<String> userInfo = Arrays.asList(
"user%40gooddata.com:password",
"",
"test:test",
"test:test",
null);
List<String> ref = Arrays.asList("", "", "", "", null);
List<String> query = Arrays.asList("", "", "", "", null);
check("isUrl", isUrl);
check("path", path);
check("protocol", protocol);
check("host", host);
check("port", port);
check("userInfo", userInfo);
check("ref", ref);
check("query", query);
check("isURL_empty", false);
check("path_empty", null);
check("protocol_empty", null);
check("host_empty", null);
check("port_empty", -2);
check("userInfo_empty", null);
check("ref_empty", null);
check("query_empty", null);
check("isURL_null", false);
check("path_null", null);
check("protocol_null", null);
check("host_null", null);
check("port_null", -2);
check("userInfo_null", null);
check("ref_null", null);
check("query_empty", null);
}
public void test_utillib_iif() throws UnsupportedEncodingException{
doCompile("test_utillib_iif");
check("ret1", "Renektor");
Calendar cal = Calendar.getInstance();
cal.set(2005,10,12,0,0,0);
cal.set(Calendar.MILLISECOND,0);
check("ret2", cal.getTime());
checkArray("ret3", "Akali".getBytes("UTF-8"));
check("ret4", 236);
check("ret5", 78L);
check("ret6", 78.2d);
check("ret7", new BigDecimal("87.69"));
check("ret8", true);
}
public void test_utillib_iif_expect_error(){
try {
doCompile("function integer transform(){boolean b = null; string str = iif(b, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_utillib_isnull(){
doCompile("test_utillib_isnull");
check("ret1", false);
check("ret2", true);
check("ret3", false);
check("ret4", true);
check("ret5", false);
check("ret6", true);
check("ret7", false);
check("ret8", true);
check("ret9", false);
check("ret10", true);
check("ret11", false);
check("ret12", true);
check("ret13", false);
check("ret14", true);
check("ret15", false);
check("ret16", true);
check("ret17", false);
check("ret18", true);
check("ret19", true);
}
public void test_utillib_nvl() throws UnsupportedEncodingException{
doCompile("test_utillib_nvl");
check("ret1", "Fiora");
check("ret2", "Olaf");
checkArray("ret3", "Elise".getBytes("UTF-8"));
checkArray("ret4", "Diana".getBytes("UTF-8"));
Calendar cal = Calendar.getInstance();
cal.set(2005,4,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret5", cal.getTime());
cal.clear();
cal.set(2004,2,14,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret6", cal.getTime());
check("ret7", 7);
check("ret8", 8);
check("ret9", 111l);
check("ret10", 112l);
check("ret11", 10.1d);
check("ret12", 10.2d);
check("ret13", new BigDecimal("12.2"));
check("ret14", new BigDecimal("12.3"));
// check("ret15", null);
}
public void test_utillib_nvl2() throws UnsupportedEncodingException{
doCompile("test_utillib_nvl2");
check("ret1", "Ahri");
check("ret2", "Galio");
checkArray("ret3", "Mordekaiser".getBytes("UTF-8"));
checkArray("ret4", "Zed".getBytes("UTF-8"));
Calendar cal = Calendar.getInstance();
cal.set(2010,4,18,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret5", cal.getTime());
cal.clear();
cal.set(2008,7,9,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret6", cal.getTime());
check("ret7", 11);
check("ret8", 18);
check("ret9", 20L);
check("ret10", 23L);
check("ret11", 15.2d);
check("ret12", 89.3d);
check("ret13", new BigDecimal("22.2"));
check("ret14", new BigDecimal("55.5"));
check("ret15", null);
check("ret16", null);
}
}
|
package org.jetel.ctl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import junit.framework.AssertionFailedError;
import org.jetel.component.CTLRecordTransform;
import org.jetel.component.RecordTransform;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.SetVal;
import org.jetel.data.lookup.LookupTable;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.primitive.Decimal;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.TransformException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.ContextProvider.Context;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldContainerType;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.test.CloverTestCase;
import org.jetel.util.MiscUtils;
import org.jetel.util.bytes.PackedDecimal;
import org.jetel.util.crypto.Base64;
import org.jetel.util.crypto.Digest;
import org.jetel.util.crypto.Digest.DigestType;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.string.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Years;
public abstract class CompilerTestCase extends CloverTestCase {
protected static final String INPUT_1 = "firstInput";
protected static final String INPUT_2 = "secondInput";
protected static final String INPUT_3 = "thirdInput";
protected static final String INPUT_4 = "multivalueInput";
protected static final String OUTPUT_1 = "firstOutput";
protected static final String OUTPUT_2 = "secondOutput";
protected static final String OUTPUT_3 = "thirdOutput";
protected static final String OUTPUT_4 = "fourthOutput";
protected static final String OUTPUT_5 = "firstMultivalueOutput";
protected static final String OUTPUT_6 = "secondMultivalueOutput";
protected static final String OUTPUT_7 = "thirdMultivalueOutput";
protected static final String LOOKUP = "lookupMetadata";
protected static final String NAME_VALUE = " HELLO ";
protected static final Double AGE_VALUE = 20.25;
protected static final String CITY_VALUE = "Chong'La";
protected static final Date BORN_VALUE;
protected static final Long BORN_MILLISEC_VALUE;
static {
Calendar c = Calendar.getInstance();
c.set(2008, 12, 25, 13, 25, 55);
c.set(Calendar.MILLISECOND, 333);
BORN_VALUE = c.getTime();
BORN_MILLISEC_VALUE = c.getTimeInMillis();
}
protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10;
protected static final Boolean FLAG_VALUE = true;
protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes();
protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525");
protected static final int DECIMAL_PRECISION = 7;
protected static final int DECIMAL_SCALE = 3;
protected static final int NORMALIZE_RETURN_OK = 0;
public static final int DECIMAL_MAX_PRECISION = 32;
public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN);
/** Flag to trigger Java compilation */
private boolean compileToJava;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected TransformationGraph graph;
public CompilerTestCase(boolean compileToJava) {
this.compileToJava = compileToJava;
}
/**
* Method to execute tested CTL code in a way specific to testing scenario.
*
* Assumes that
* {@link #graph}, {@link #inputRecords} and {@link #outputRecords}
* have already been set.
*
* @param compiler
*/
public abstract void executeCode(ITLCompiler compiler);
/**
* Method which provides access to specified global variable
*
* @param varName
* global variable to be accessed
* @return
*
*/
protected abstract Object getVariable(String varName);
protected void check(String varName, Object expectedResult) {
assertEquals(varName, expectedResult, getVariable(varName));
}
protected void checkEquals(String varName1, String varName2) {
assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2));
}
protected void checkNull(String varName) {
assertNull(getVariable(varName));
}
private void checkArray(String varName, byte[] expected) {
byte[] actual = (byte[]) getVariable(varName);
assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected));
}
private static String byteArrayAsString(byte[] array) {
final StringBuilder sb = new StringBuilder("[");
for (final byte b : array) {
sb.append(b);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append(']');
return sb.toString();
}
@Override
protected void setUp() {
// set default locale to English to prevent various parsing errors
Locale.setDefault(Locale.ENGLISH);
initEngine();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
inputRecords = null;
outputRecords = null;
graph = null;
}
protected TransformationGraph createEmptyGraph() {
return new TransformationGraph();
}
protected TransformationGraph createDefaultGraph() {
TransformationGraph g = createEmptyGraph();
// set the context URL, so that imports can be used
g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource("."));
final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>();
metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1));
metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2));
metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3));
metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4));
metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1));
metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2));
metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3));
metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4));
metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5));
metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6));
metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7));
metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP));
g.addDataRecordMetadata(metadataMap);
g.addSequence(createDefaultSequence(g, "TestSequence"));
g.addLookupTable(createDefaultLookup(g, "TestLookup"));
Properties properties = new Properties();
properties.put("PROJECT", ".");
properties.put("DATAIN_DIR", "${PROJECT}/data-in");
properties.put("COUNT", "`1+2`");
properties.put("NEWLINE", "\\n");
g.setGraphProperties(properties);
initDefaultDictionary(g);
return g;
}
private void initDefaultDictionary(TransformationGraph g) {
try {
g.getDictionary().init();
g.getDictionary().setValue("s", "string", null);
g.getDictionary().setValue("i", "integer", null);
g.getDictionary().setValue("l", "long", null);
g.getDictionary().setValue("d", "decimal", null);
g.getDictionary().setValue("n", "number", null);
g.getDictionary().setValue("a", "date", null);
g.getDictionary().setValue("b", "boolean", null);
g.getDictionary().setValue("y", "byte", null);
g.getDictionary().setValue("i211", "integer", new Integer(211));
g.getDictionary().setValue("sVerdon", "string", "Verdon");
g.getDictionary().setValue("l452", "long", new Long(452));
g.getDictionary().setValue("d621", "decimal", new BigDecimal(621));
g.getDictionary().setValue("n9342", "number", new Double(934.2));
g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE);
g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} );
g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc"));
g.getDictionary().setContentType("stringList", "string");
g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
g.getDictionary().setContentType("dateList", "date");
g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
g.getDictionary().setContentType("byteList", "byte");
} catch (ComponentNotReadyException e) {
throw new RuntimeException("Error init default dictionary", e);
}
}
protected Sequence createDefaultSequence(TransformationGraph graph, String name) {
Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class });
try {
seq.checkConfig(new ConfigurationStatus());
seq.init();
} catch (ComponentNotReadyException e) {
throw new RuntimeException(e);
}
return seq;
}
/**
* Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite
* lookup key Name+Value. Use field City for testing response.
*
* @param graph
* @param name
* @return
*/
protected LookupTable createDefaultLookup(TransformationGraph graph, String name) {
final TypedProperties props = new TypedProperties();
props.setProperty("id", "LookupTable0");
props.setProperty("type", "simpleLookup");
props.setProperty("metadata", LOOKUP);
props.setProperty("key", "Name;Value");
props.setProperty("name", name);
props.setProperty("keyDuplicates", "true");
/*
* The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code
* below, however this will most probably break down test_lookup() because free() will wipe away all data and
* noone will restore them
*/
URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat");
if (dataFile == null) {
throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader");
}
props.setProperty("fileURL", dataFile.getFile());
LookupTableFactory.init();
LookupTable lkp = LookupTableFactory.createLookupTable(props);
lkp.setGraph(graph);
try {
lkp.checkConfig(new ConfigurationStatus());
lkp.init();
lkp.preExecute();
} catch (ComponentNotReadyException ex) {
throw new RuntimeException(ex);
}
/*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse"));
lkpRecord.getField("Name").setValue("Alpha");
lkpRecord.getField("Value").setValue(1);
lkpRecord.getField("City").setValue("Andorra la Vella");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Bravo");
lkpRecord.getField("Value").setValue(2);
lkpRecord.getField("City").setValue("Bruxelles");
lkp.put(lkpRecord);
// duplicate entry
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chamonix");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chomutov");
lkp.put(lkpRecord);*/
return lkp;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|");
dateField.setFormatStr("yyyy-MM-dd HH:mm:ss");
ret.addField(dateField);
ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|"));
ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|"));
ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|"));
ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|"));
DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n");
decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION));
decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE));
ret.addField(decimalField);
return ret;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefault1Metadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
return ret;
}
/**
* Creates records with default structure
* containing multivalue fields.
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMultivalueMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|");
stringListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(stringListField);
DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|");
ret.addField(dateField);
DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|");
ret.addField(byteField);
DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|");
dateListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(dateListField);
DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|");
byteListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(byteListField);
DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|");
ret.addField(stringField);
DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|");
integerMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(integerMapField);
DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|");
stringMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(stringMapField);
DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|");
dateMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(dateMapField);
DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|");
byteMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(byteMapField);
DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|");
integerListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(integerListField);
DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|");
decimalListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(decimalListField);
DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|");
decimalMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(decimalMapField);
return ret;
}
protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
DataField field = ret.getField(i);
DataFieldMetadata fieldMetadata = field.getMetadata();
switch (fieldMetadata.getContainerType()) {
case SINGLE:
switch (fieldMetadata.getDataType()) {
case STRING:
field.setValue("John");
break;
case DATE:
field.setValue(new Date(10000));
break;
case BYTE:
field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } );
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
break;
case LIST:
{
List<Object> value = new ArrayList<Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.addAll(Arrays.asList("John", "Doe", "Jersey"));
break;
case INTEGER:
value.addAll(Arrays.asList(123, 456, 789));
break;
case DATE:
value.addAll(Arrays.asList(new Date (12000), new Date(34000)));
break;
case BYTE:
value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78}));
break;
case DECIMAL:
value.addAll(Arrays.asList(12.34, 56.78));
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
case MAP:
{
Map<String, Object> value = new HashMap<String, Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.put("firstName", "John");
value.put("lastName", "Doe");
value.put("address", "Jersey");
break;
case INTEGER:
value.put("count", 123);
value.put("max", 456);
value.put("sum", 789);
break;
case DATE:
value.put("before", new Date (12000));
value.put("after", new Date(34000));
break;
case BYTE:
value.put("hash", new byte[] {0x12, 0x34});
value.put("checksum", new byte[] {0x56, 0x78});
break;
case DECIMAL:
value.put("asset", 12.34);
value.put("liability", 56.78);
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
default:
throw new IllegalArgumentException(fieldMetadata.getContainerType().toString());
}
}
return ret;
}
protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
SetVal.setString(ret, "Name", NAME_VALUE);
SetVal.setDouble(ret, "Age", AGE_VALUE);
SetVal.setString(ret, "City", CITY_VALUE);
SetVal.setDate(ret, "Born", BORN_VALUE);
SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE);
SetVal.setInt(ret, "Value", VALUE_VALUE);
SetVal.setValue(ret, "Flag", FLAG_VALUE);
SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE);
SetVal.setValue(ret, "Currency", CURRENCY_VALUE);
return ret;
}
/**
* Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code>
*
* @param metadata
* structure to use
* @return empty record
*/
protected DataRecord createEmptyRecord(DataRecordMetadata metadata) {
DataRecord ret = DataRecordFactory.newRecord(metadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
SetVal.setNull(ret, i);
}
return ret;
}
/**
* Executes the code using the default graph and records.
*/
protected void doCompile(String expStr, String testIdentifier) {
TransformationGraph graph = createDefaultGraph();
DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) };
DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) };
doCompile(expStr, testIdentifier, graph, inRecords, outRecords);
}
/**
* This method should be used to execute a test with a custom graph and custom input and output records.
*
* To execute a test with the default graph,
* use {@link #doCompile(String)}
* or {@link #doCompile(String, String)} instead.
*
* @param expStr
* @param testIdentifier
* @param graph
* @param inRecords
* @param outRecords
*/
protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) {
this.graph = graph;
this.inputRecords = inRecords;
this.outputRecords = outRecords;
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length];
for (int i = 0; i < inRecords.length; i++) {
inMetadata[i] = inRecords[i].getMetadata();
}
DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length];
for (int i = 0; i < outRecords.length; i++) {
outMetadata[i] = outRecords[i].getMetadata();
}
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
// try {
// System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier));
// } catch (ErrorMessageException e) {
// System.out.println("Error parsing CTL code. Unable to output Java translation.");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() > 0) {
throw new AssertionFailedError("Error in execution. Check standard output for details.");
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
executeCode(compiler);
}
protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) {
graph = createDefaultGraph();
DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) };
DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) };
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() == 0) {
throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors.");
}
if (compiler.errorCount() != errCodes.size()) {
throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors.");
}
Iterator<String> it = errCodes.iterator();
for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) {
String expectedError = it.next();
if (!expectedError.equals(errorMessage.getErrorMessage())) {
throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'");
}
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
// executeCode(compiler);
}
protected void doCompileExpectError(String testIdentifier, String errCode) {
doCompileExpectErrors(testIdentifier, Arrays.asList(errCode));
}
protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes);
}
/**
* Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected String loadSourceCode(String testIdentifier) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
return sourceCode.toString();
}
/**
* Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* The default graph and records are used for the execution.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected void doCompile(String testIdentifier) {
String sourceCode = loadSourceCode(testIdentifier);
doCompile(sourceCode, testIdentifier);
}
protected void printMessages(List<ErrorMessage> diagnosticMessages) {
for (ErrorMessage e : diagnosticMessages) {
System.out.println(e);
}
}
/**
* Compares two records if they have the same number of fields and identical values in their fields. Does not
* consider (or examine) metadata.
*
* @param lhs
* @param rhs
* @return true if records have the same number of fields and the same values in them
*/
protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) {
if (lhs == rhs)
return true;
if (rhs == null)
return false;
if (lhs == null) {
return false;
}
if (lhs.getNumFields() != rhs.getNumFields()) {
return false;
}
for (int i = 0; i < lhs.getNumFields(); i++) {
if (lhs.getField(i).isNull()) {
if (!rhs.getField(i).isNull()) {
return false;
}
} else if (!lhs.getField(i).equals(rhs.getField(i))) {
return false;
}
}
return true;
}
public void print_code(String text) {
String[] lines = text.split("\n");
System.out.println("\t: 1 2 3 4 5 ");
System.out.println("\t:12345678901234567890123456789012345678901234567890123456789");
for (int i = 0; i < lines.length; i++) {
System.out.println((i + 1) + "\t:" + lines[i]);
}
}
@SuppressWarnings("unchecked")
public void test_operators_unary_record_allowed() {
doCompile("test_operators_unary_record_allowed");
check("value", Arrays.asList(14, 16, 16, 65, 63, 63));
check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L));
List<Double> actualAge = (List<Double>) getVariable("age");
double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789};
for (int i = 0; i < actualAge.size(); i++) {
assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001);
}
check("currency", Arrays.asList(
new BigDecimal(BigInteger.valueOf(12500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(65432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3)
));
}
@SuppressWarnings("unchecked")
public void test_dynamic_compare() {
doCompile("test_dynamic_compare");
String varName = "compare";
List<Integer> compareResult = (List<Integer>) getVariable(varName);
for (int i = 0; i < compareResult.size(); i++) {
if ((i % 3) == 0) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0);
} else if ((i % 3) == 1) {
assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i));
} else if ((i % 3) == 2) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0);
}
}
varName = "compareBooleans";
compareResult = (List<Integer>) getVariable(varName);
assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0));
assertTrue(varName + "[1]", compareResult.get(1) > 0);
assertTrue(varName + "[2]", compareResult.get(2) < 0);
assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3));
}
private void test_dynamic_get_set_loop(String testIdentifier) {
doCompile(testIdentifier);
check("recordLength", 9);
check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233));
check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal"));
check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000"));
check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false));
check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
Integer[] indices = new Integer[9];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
check("fieldIndex", Arrays.asList(indices));
// check dynamic write and read with all data types
check("booleanVar", true);
assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar")));
check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3));
check("integerVar", 1000);
check("longVar", 1000000000000L);
check("numberVar", 1000.5);
check("stringVar", "hello");
check("dateVar", new Date(5000));
// null value
Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(someValue, Boolean.FALSE);
check("someValue", Arrays.asList(someValue));
Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(nullValue, Boolean.TRUE);
check("nullValue", Arrays.asList(nullValue));
String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
check("asString2", Arrays.asList(asString2));
Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(isNull2, Boolean.TRUE);
check("isNull2", Arrays.asList(isNull2));
}
public void test_dynamic_get_set_loop() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop");
}
public void test_dynamic_get_set_loop_alternative() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative");
}
public void test_dynamic_invalid() {
doCompileExpectErrors("test_dynamic_invalid", Arrays.asList(
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_return_constants() {
// test case for issue 2257
System.out.println("Return constants test:");
doCompile("test_return_constants");
check("skip", RecordTransform.SKIP);
check("all", RecordTransform.ALL);
check("ok", NORMALIZE_RETURN_OK);
check("stop", RecordTransform.STOP);
}
public void test_raise_error_terminal() {
// test case for issue 2337
doCompile("test_raise_error_terminal");
}
public void test_raise_error_nonliteral() {
// test case for issue CL-2071
doCompile("test_raise_error_nonliteral");
}
public void test_case_unique_check() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check2() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check3() {
doCompileExpectError("test_case_unique_check3", "Default case is already defined");
}
public void test_rvalue_for_append() {
// test case for issue 3956
doCompile("test_rvalue_for_append");
check("a", Arrays.asList("1", "2"));
check("b", Arrays.asList("a", "b", "c"));
check("c", Arrays.asList("1", "2", "a", "b", "c"));
}
public void test_rvalue_for_map_append() {
// test case for issue 3960
doCompile("test_rvalue_for_map_append");
HashMap<Integer, String> map1instance = new HashMap<Integer, String>();
map1instance.put(1, "a");
map1instance.put(2, "b");
HashMap<Integer, String> map2instance = new HashMap<Integer, String>();
map2instance.put(3, "c");
map2instance.put(4, "d");
HashMap<Integer, String> map3instance = new HashMap<Integer, String>();
map3instance.put(1, "a");
map3instance.put(2, "b");
map3instance.put(3, "c");
map3instance.put(4, "d");
check("map1", map1instance);
check("map2", map2instance);
check("map3", map3instance);
}
public void test_global_field_access() {
// test case for issue 3957
doCompileExpectError("test_global_field_access", "Unable to access record field in global scope");
}
public void test_global_scope() {
// test case for issue 5006
doCompile("test_global_scope");
check("len", "Kokon".length());
}
//TODO Implement
/*public void test_new() {
doCompile("test_new");
}*/
public void test_parser() {
System.out.println("\nParser test:");
doCompile("test_parser");
}
public void test_ref_res_import() {
System.out.println("\nSpecial character resolving (import) test:");
URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl");
String expStr = "import '" + importLoc + "';\n";
doCompile(expStr, "test_ref_res_import");
}
public void test_ref_res_noimport() {
System.out.println("\nSpecial character resolving (no import) test:");
doCompile("test_ref_res");
}
public void test_import() {
System.out.println("\nImport test:");
URL importLoc = getClass().getSuperclass().getResource("import.ctl");
String expStr = "import '" + importLoc + "';\n";
importLoc = getClass().getSuperclass().getResource("other.ctl");
expStr += "import '" + importLoc + "';\n" +
"integer sumInt;\n" +
"function integer transform() {\n" +
" if (a == 3) {\n" +
" otherImportVar++;\n" +
" }\n" +
" sumInt = sum(a, otherImportVar);\n" +
" return 0;\n" +
"}\n";
doCompile(expStr, "test_import");
}
public void test_scope() throws ComponentNotReadyException, TransformException {
System.out.println("\nMapping test:");
// String expStr =
// "function string computeSomething(int n) {\n" +
// " string s = '';\n" +
// " do {\n" +
// " int i = n--;\n" +
// " s = s + '-' + i;\n" +
// " } while (n > 0)\n" +
// " return s;" +
// "function int transform() {\n" +
// " printErr(computeSomething(10));\n" +
// " return 0;\n" +
URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl");
String expStr = "import '" + importLoc + "';\n";
// "function int getIndexOfOffsetStart(string encodedDate) {\n" +
// "int offsetStart;\n" +
// "int actualLastMinus;\n" +
// "int lastMinus = -1;\n" +
// "if ( index_of(encodedDate, '+') != -1 )\n" +
// " return index_of(encodedDate, '+');\n" +
// "do {\n" +
// " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" +
// " if ( actualLastMinus != -1 )\n" +
// " lastMinus = actualLastMinus;\n" +
// "} while ( actualLastMinus != -1 )\n" +
// "return lastMinus;\n" +
// "function int transform() {\n" +
// " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" +
// " return 0;\n" +
doCompile(expStr, "test_scope");
}
public void test_type_void() {
doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'",
"Variable 'voidVar' is not declared",
"Variable 'voidVar' is not declared",
"Syntax error on token 'void'"));
}
public void test_type_integer() {
doCompile("test_type_integer");
check("i", 0);
check("j", -1);
check("field", VALUE_VALUE);
checkNull("nullValue");
check("varWithInitializer", 123);
checkNull("varWithNullInitializer");
}
public void test_type_integer_edge() {
String testExpression =
"integer minInt;\n"+
"integer maxInt;\n"+
"function integer transform() {\n" +
"minInt=" + Integer.MIN_VALUE + ";\n" +
"printErr(minInt, true);\n" +
"maxInt=" + Integer.MAX_VALUE + ";\n" +
"printErr(maxInt, true);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_int_edge");
check("minInt", Integer.MIN_VALUE);
check("maxInt", Integer.MAX_VALUE);
}
public void test_type_long() {
doCompile("test_type_long");
check("i", Long.valueOf(0));
check("j", Long.valueOf(-1));
check("field", BORN_MILLISEC_VALUE);
check("def", Long.valueOf(0));
checkNull("nullValue");
check("varWithInitializer", 123L);
checkNull("varWithNullInitializer");
}
public void test_type_long_edge() {
String expStr =
"long minLong;\n"+
"long maxLong;\n"+
"function integer transform() {\n" +
"minLong=" + (Long.MIN_VALUE) + "L;\n" +
"printErr(minLong);\n" +
"maxLong=" + (Long.MAX_VALUE) + "L;\n" +
"printErr(maxLong);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr,"test_long_edge");
check("minLong", Long.MIN_VALUE);
check("maxLong", Long.MAX_VALUE);
}
public void test_type_decimal() {
doCompile("test_type_decimal");
check("i", new BigDecimal(0, MAX_PRECISION));
check("j", new BigDecimal(-1, MAX_PRECISION));
check("field", CURRENCY_VALUE);
check("def", new BigDecimal(0, MAX_PRECISION));
checkNull("nullValue");
check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION));
checkNull("varWithNullInitializer");
check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION));
}
public void test_type_decimal_edge() {
String testExpression =
"decimal minLong;\n"+
"decimal maxLong;\n"+
"decimal minLongNoDist;\n"+
"decimal maxLongNoDist;\n"+
"decimal minDouble;\n"+
"decimal maxDouble;\n"+
"decimal minDoubleNoDist;\n"+
"decimal maxDoubleNoDist;\n"+
"function integer transform() {\n" +
"minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" +
"printErr(minLong);\n" +
"maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" +
"printErr(maxLong);\n" +
"minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" +
"printErr(minLongNoDist);\n" +
"maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" +
"printErr(maxLongNoDist);\n" +
// distincter will cause the double-string be parsed into exact representation within BigDecimal
"minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" +
"printErr(minDouble);\n" +
"maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" +
"printErr(maxDouble);\n" +
// no distincter will cause the double-string to be parsed into inexact representation within double
// then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits)
"minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" +
"printErr(minDoubleNoDist);\n" +
"maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" +
"printErr(maxDoubleNoDist);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_decimal_edge");
check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
// distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324)
check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION));
check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION));
// no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of
// MAX_PRECISION digits (i.e. 4.94065.....E-324)
check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION));
check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION));
}
public void test_type_number() {
doCompile("test_type_number");
check("i", Double.valueOf(0));
check("j", Double.valueOf(-1));
check("field", AGE_VALUE);
check("def", Double.valueOf(0));
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_number_edge() {
String testExpression =
"number minDouble;\n" +
"number maxDouble;\n"+
"function integer transform() {\n" +
"minDouble=" + Double.MIN_VALUE + ";\n" +
"printErr(minDouble);\n" +
"maxDouble=" + Double.MAX_VALUE + ";\n" +
"printErr(maxDouble);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_number_edge");
check("minDouble", Double.valueOf(Double.MIN_VALUE));
check("maxDouble", Double.valueOf(Double.MAX_VALUE));
}
public void test_type_string() {
doCompile("test_type_string");
check("i","0");
check("helloEscaped", "hello\\nworld");
check("helloExpanded", "hello\nworld");
check("fieldName", NAME_VALUE);
check("fieldCity", CITY_VALUE);
check("escapeChars", "a\u0101\u0102A");
check("doubleEscapeChars", "a\\u0101\\u0102A");
check("specialChars", "špeciálne značky s mäkčeňom môžu byť");
check("dQescapeChars", "a\u0101\u0102A");
//TODO:Is next test correct?
check("dQdoubleEscapeChars", "a\\u0101\\u0102A");
check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť");
check("empty", "");
check("def", "");
checkNull("varWithNullInitializer");
}
public void test_type_string_long() {
int length = 1000;
StringBuilder tmp = new StringBuilder(length);
for (int i = 0; i < length; i++) {
tmp.append(i % 10);
}
String testExpression =
"string longString;\n" +
"function integer transform() {\n" +
"longString=\"" + tmp + "\";\n" +
"printErr(longString);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_string_long");
check("longString", String.valueOf(tmp));
}
public void test_type_date() throws Exception {
doCompile("test_type_date");
check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime());
check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime());
check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime());
check("field", BORN_VALUE);
checkNull("nullValue");
check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime());
checkNull("varWithNullInitializer");
// test with a default time zone set on the GraphRuntimeContext
Context context = null;
try {
tearDown();
setUp();
TransformationGraph graph = new TransformationGraph();
graph.getRuntimeContext().setTimeZone("GMT+8");
context = ContextProvider.registerGraph(graph);
doCompile("test_type_date");
Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3);
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("d2", calendar.getTime());
calendar.set(2006, 0, 1, 1, 2, 3);
check("d1", calendar.getTime());
} finally {
ContextProvider.unregister(context);
}
}
public void test_type_boolean() {
doCompile("test_type_boolean");
check("b1", true);
check("b2", false);
check("b3", false);
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_boolean_compare() {
doCompileExpectErrors("test_type_boolean_compare", Arrays.asList(
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'"));
}
public void test_type_list() {
doCompile("test_type_list");
check("intList", Arrays.asList(1, 2, 3, 4, 5, 6));
check("intList2", Arrays.asList(1, 2, 3));
check("stringList", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
check("stringListCopy", Arrays.asList(
"first", "second", "third", "fourth",
"fifth", "seventh"));
check("stringListCopy2", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
assertTrue(getVariable("stringList") != getVariable("stringListCopy"));
assertEquals(getVariable("stringList"), getVariable("stringListCopy2"));
assertEquals(Arrays.asList(false, null, true), getVariable("booleanList"));
assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList"));
assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList"));
assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList"));
assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList"));
assertEquals(Arrays.asList(12, null, 34), getVariable("intList3"));
assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList"));
assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList"));
assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2"));
List<?> decimalList2 = (List<?>) getVariable("decimalList2");
for (Object o: decimalList2) {
assertTrue(o instanceof BigDecimal);
}
List<?> intList4 = (List<?>) getVariable("intList4");
Set<Object> intList4Set = new HashSet<Object>(intList4);
assertEquals(3, intList4Set.size());
}
public void test_type_list_field() {
doCompile("test_type_list_field");
check("copyByValueTest1", "2");
check("copyByValueTest2", "test");
}
public void test_type_map_field() {
doCompile("test_type_map_field");
Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1");
assertEquals(new Integer(2), copyByValueTest1);
Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2");
assertEquals(new Integer(100), copyByValueTest2);
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepCopy(Object o1, Object o2) {
if (o1 instanceof DataRecord) {
assertFalse(o1 == o2);
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
assertFalse(o1 == o2);
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
for (Object key: m1.keySet()) {
assertDeepCopy(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
assertFalse(o1 == o2);
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
for (int i = 0; i < l1.size(); i++) {
assertDeepCopy(l1.get(i), l2.get(i));
}
} else if (o1 instanceof Date) {
assertFalse(o1 == o2);
// } else if (o1 instanceof byte[]) { // not required anymore
// assertFalse(o1 == o2);
}
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepEquals(Object o1, Object o2) {
if ((o1 == null) && (o2 == null)) {
return;
}
assertTrue((o1 == null) == (o2 == null));
if (o1 instanceof DataRecord) {
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
assertEquals(r1.getNumFields(), r2.getNumFields());
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
assertTrue(m1.keySet().equals(m2.keySet()));
for (Object key: m1.keySet()) {
assertDeepEquals(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
assertEquals("size", l1.size(), l2.size());
for (int i = 0; i < l1.size(); i++) {
assertDeepEquals(l1.get(i), l2.get(i));
}
} else if (o1 instanceof byte[]) {
byte[] b1 = (byte[]) o1;
byte[] b2 = (byte[]) o2;
if (b1 != b2) {
if (b1 == null || b2 == null) {
assertEquals(b1, b2);
}
assertEquals("length", b1.length, b2.length);
for (int i = 0; i < b1.length; i++) {
assertEquals(String.format("[%d]", i), b1[i], b2[i]);
}
}
} else if (o1 instanceof CharSequence) {
String s1 = ((CharSequence) o1).toString();
String s2 = ((CharSequence) o2).toString();
assertEquals(s1, s2);
} else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) {
BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1;
BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2;
assertEquals(d1, d2);
} else {
assertEquals(o1, o2);
}
}
private void check_assignment_deepcopy_variable_declaration() {
Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1");
Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2");
byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1");
byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2");
assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2);
assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_array_access_expression() {
{
// JJTARRAYACCESSEXPRESSION - List
List<String> stringListField1 = (List<String>) getVariable("stringListField1");
DataRecord recordInList1 = (DataRecord) getVariable("recordInList1");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2");
assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepEquals(recordInList1, recordList1.get(0));
assertDeepEquals(recordList1, recordList2);
assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepCopy(recordInList1, recordList1.get(0));
assertDeepCopy(recordList1, recordList2);
}
{
// map of records
Date testDate1 = (Date) getVariable("testDate1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1");
DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2");
Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2");
assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepEquals(recordInMap1, recordMap1.get(0));
assertDeepEquals(recordInMap2, recordMap1.get(0));
assertDeepEquals(recordMap1, recordMap2);
assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepCopy(recordInMap1, recordMap1.get(0));
assertDeepCopy(recordInMap2, recordMap1.get(0));
assertDeepCopy(recordMap1, recordMap2);
}
{
// map of dates
Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1");
Date date1 = (Date) getVariable("date1");
Date date2 = (Date) getVariable("date2");
assertDeepCopy(date1, dateMap1.get(0));
assertDeepCopy(date2, dateMap1.get(1));
}
{
// map of byte arrays
Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1");
byte[] byte1 = (byte[]) getVariable("byte1");
byte[] byte2 = (byte[]) getVariable("byte2");
assertDeepCopy(byte1, byteMap1.get(0));
assertDeepCopy(byte2, byteMap1.get(1));
}
{
// JJTARRAYACCESSEXPRESSION - Function call
List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList");
DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall");
Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map");
Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue());
assertEquals(1, function_call_original_map.size());
assertEquals(2, function_call_copied_map.size());
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list);
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list);
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2));
}
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_field_access_expression() {
// field access
Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1");
String testFieldAccessString1 = (String) getVariable("testFieldAccessString1");
List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1");
List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1");
Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1");
Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput);
assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_member_access_expression() {
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
}
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2);
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2);
// dictionary
Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue();
byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue();
List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1");
List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2");
List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList");
List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(dictionaryDate, testMemberAccessDate1);
assertDeepEquals(dictionaryByte, testMemberAccessByte1);
assertDeepEquals(dictionaryStringList, testMemberAccessStringList1);
assertDeepEquals(dictionaryDateList, testMemberAccessDateList2);
assertDeepEquals(dictionaryByteList, testMemberAccessByteList2);
assertDeepCopy(dictionaryDate, testMemberAccessDate1);
assertDeepCopy(dictionaryByte, testMemberAccessByte1);
assertDeepCopy(dictionaryStringList, testMemberAccessStringList1);
assertDeepCopy(dictionaryDateList, testMemberAccessDateList2);
assertDeepCopy(dictionaryByteList, testMemberAccessByteList2);
// member access - array of records
List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
// member access - map of records
Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
}
}
@SuppressWarnings("unchecked")
public void test_assignment_deepcopy() {
doCompile("test_assignment_deepcopy");
List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList");
assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString());
List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList");
assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString());
check_assignment_deepcopy_variable_declaration();
check_assignment_deepcopy_array_access_expression();
check_assignment_deepcopy_field_access_expression();
check_assignment_deepcopy_member_access_expression();
}
public void test_assignment_deepcopy_field_access_expression() {
doCompile("test_assignment_deepcopy_field_access_expression");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
DataRecord multivalueInput = inputRecords[3];
assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepEquals(secondMultivalueOutput, multivalueInput);
assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput);
assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepCopy(secondMultivalueOutput, multivalueInput);
assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput);
}
public void test_assignment_array_access_function_call() {
doCompile("test_assignment_array_access_function_call");
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("a", "b");
Map<String, String> copiedMap = new HashMap<String, String>(originalMap);
copiedMap.put("c", "d");
check("originalMap", originalMap);
check("copiedMap", copiedMap);
}
public void test_assignment_array_access_function_call_wrong_type() {
doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type",
Arrays.asList(
"Expression is not a composite type but is resolved to 'string'",
"Type mismatch: cannot convert from 'integer' to 'string'",
"Cannot convert from 'integer' to string"
));
}
@SuppressWarnings("unchecked")
public void test_assignment_returnvalue() {
doCompile("test_assignment_returnvalue");
{
List<String> stringList1 = (List<String>) getVariable("stringList1");
List<String> stringList2 = (List<String>) getVariable("stringList2");
List<String> stringList3 = (List<String>) getVariable("stringList3");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
List<String> stringList4 = (List<String>) getVariable("stringList4");
Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1");
DataRecord record1 = (DataRecord) getVariable("record1");
DataRecord record2 = (DataRecord) getVariable("record2");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
Date dictionaryDate1 = (Date) getVariable("dictionaryDate1");
Date dictionaryDate = (Date) graph.getDictionary().getValue("a");
Date zeroDate = new Date(0);
List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10");
DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11");
List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12");
List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13");
Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map");
Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map");
DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord");
// identifier
assertFalse(stringList1.isEmpty());
assertTrue(stringList2.isEmpty());
assertTrue(stringList3.isEmpty());
// array access expression - list
assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue());
// array access expression - map
assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue());
// array access expression - function call
assertDeepEquals(null, function_call_original_map.get(2));
assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField"));
assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list);
assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField"));
// field access expression
assertFalse(stringList4.isEmpty());
assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty());
assertFalse(integerMap1.isEmpty());
assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty());
assertDeepEquals("unmodified", record1.getField("stringField"));
assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue());
assertDeepEquals("unmodified", record2.getField("stringField"));
assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue());
// member access expression - dictionary
// There is no function that could modify a date
// assertEquals(zeroDate, dictionaryDate);
// assertFalse(zeroDate.equals(testReturnValueDictionary1));
assertFalse(testReturnValueDictionary2.isEmpty());
assertTrue(dictionaryStringList.isEmpty());
// member access expression - record
assertFalse(testReturnValue10.isEmpty());
assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty());
// member access expression - list of records
assertFalse(testReturnValue12.isEmpty());
assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty());
// member access expression - map of records
assertFalse(testReturnValue13.isEmpty());
assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty());
}
}
@SuppressWarnings("unchecked")
public void test_type_map() {
doCompile("test_type_map");
Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap");
assertEquals(Integer.valueOf(1), testMap.get("zero"));
assertEquals(Integer.valueOf(2), testMap.get("one"));
assertEquals(Integer.valueOf(3), testMap.get("two"));
assertEquals(Integer.valueOf(4), testMap.get("three"));
assertEquals(4, testMap.size());
Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek");
Calendar c = Calendar.getInstance();
c.set(2009, Calendar.MARCH, 2, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Monday", dayInWeek.get(c.getTime()));
Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy");
c.set(2009, Calendar.MARCH, 3, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime()));
assertEquals("Tuesday", dayInWeekCopy.get(c.getTime()));
c.set(2009, Calendar.MARCH, 4, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime()));
assertEquals("Wednesday", dayInWeekCopy.get(c.getTime()));
assertFalse(dayInWeek.equals(dayInWeekCopy));
{
Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder");
assertEquals(100, preservedOrder.size());
int i = 0;
for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) {
assertEquals("key" + i, entry.getKey());
assertEquals("value" + i, entry.getValue());
i++;
}
}
}
public void test_type_record_list() {
doCompile("test_type_record_list");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_list_global() {
doCompile("test_type_record_list_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map() {
doCompile("test_type_record_map");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map_global() {
doCompile("test_type_record_map_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record() {
doCompile("test_type_record");
// expected result
DataRecord expected = createDefaultRecord(createDefaultMetadata("expected"));
// simple copy
assertTrue(recordEquals(expected, inputRecords[0]));
assertTrue(recordEquals(expected, (DataRecord) getVariable("copy")));
// copy and modify
expected.getField("Name").setValue("empty");
expected.getField("Value").setValue(321);
Calendar c = Calendar.getInstance();
c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
expected.getField("Born").setValue(c.getTime());
assertTrue(recordEquals(expected, (DataRecord) getVariable("modified")));
// 2x modified copy
expected.getField("Name").setValue("not empty");
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2")));
// no modification by reference is possible
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3")));
expected.getField("Value").setValue(654321);
assertTrue(recordEquals(expected, (DataRecord)getVariable("reference")));
assertTrue(getVariable("modified3") != getVariable("reference"));
// output record
assertTrue(recordEquals(expected, outputRecords[1]));
// null record
expected.setToNull();
assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord")));
}
public void test_variables() {
doCompile("test_variables");
check("b1", true);
check("b2", true);
check("b4", "hi");
check("i", 2);
}
public void test_operator_plus() {
doCompile("test_operator_plus");
check("iplusj", 10 + 100);
check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10));
check("mplusl", getVariable("lplusm"));
check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10);
check("iplusm", getVariable("mplusi"));
check("nplusm1", Double.valueOf(0.1D + 0.001D));
check("nplusj", Double.valueOf(100 + 0.1D));
check("jplusn", getVariable("nplusj"));
check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d));
check("mplusm1", getVariable("m1plusm"));
check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("jplusd", getVariable("dplusj"));
check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("mplusd", getVariable("dplusm"));
check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION)));
check("nplusd", getVariable("dplusn"));
check("spluss1", "hello world");
check("splusj", "hello100");
check("jpluss", "100hello");
check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE));
check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello");
check("splusm1", "hello" + Double.valueOf(0.001D));
check("m1pluss", Double.valueOf(0.001D) + "hello");
check("splusd1", "hello" + new BigDecimal("0.0001"));
check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello");
}
public void test_operator_minus() {
doCompile("test_operator_minus");
check("iminusj", 10 - 100);
check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE));
check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10));
check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE));
check("nminusm1", Double.valueOf(0.1D - 0.001D));
check("nminusj", Double.valueOf(0.1D - 100));
check("jminusn", Double.valueOf(100 - 0.1D));
check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE)));
check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D));
check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_multiply() {
doCompile("test_operator_multiply");
check("itimesj", 10 * 100);
check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10)));
check("mtimesl", getVariable("ltimesm"));
check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10);
check("itimesm", getVariable("mtimesi"));
check("ntimesm1", Double.valueOf(0.1D * 0.001D));
check("ntimesj", Double.valueOf(0.1) * 100);
check("jtimesn", getVariable("ntimesj"));
check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE)));
check("mtimesm1", getVariable("m1timesm"));
check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION)));
check("jtimesd", getVariable("dtimesj"));
check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mtimesd", getVariable("dtimesm"));
check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION));
check("ntimesd", getVariable("dtimesn"));
}
public void test_operator_divide() {
doCompile("test_operator_divide");
check("idividej", 10 / 100);
check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE));
check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10));
check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE));
check("ndividem1", Double.valueOf(0.1D / 0.001D));
check("ndividej", Double.valueOf(0.1D / 100));
check("jdividen", Double.valueOf(100 / 0.1D));
check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE)));
check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D));
check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_modulus() {
doCompile("test_operator_modulus");
check("imoduloj", 10 % 100);
check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE));
check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10));
check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE));
check("nmodulom1", Double.valueOf(0.1D % 0.001D));
check("nmoduloj", Double.valueOf(0.1D % 100));
check("jmodulon", Double.valueOf(100 % 0.1D));
check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE)));
check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D));
check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operators_unary() {
doCompile("test_operators_unary");
// postfix operators
// int
check("intPlusOrig", Integer.valueOf(10));
check("intPlusPlus", Integer.valueOf(10));
check("intPlus", Integer.valueOf(11));
check("intMinusOrig", Integer.valueOf(10));
check("intMinusMinus", Integer.valueOf(10));
check("intMinus", Integer.valueOf(9));
// long
check("longPlusOrig", Long.valueOf(10));
check("longPlusPlus", Long.valueOf(10));
check("longPlus", Long.valueOf(11));
check("longMinusOrig", Long.valueOf(10));
check("longMinusMinus", Long.valueOf(10));
check("longMinus", Long.valueOf(9));
// double
check("numberPlusOrig", Double.valueOf(10.1));
check("numberPlusPlus", Double.valueOf(10.1));
check("numberPlus", Double.valueOf(11.1));
check("numberMinusOrig", Double.valueOf(10.1));
check("numberMinusMinus", Double.valueOf(10.1));
check("numberMinus", Double.valueOf(9.1));
// decimal
check("decimalPlusOrig", new BigDecimal("10.1"));
check("decimalPlusPlus", new BigDecimal("10.1"));
check("decimalPlus", new BigDecimal("11.1"));
check("decimalMinusOrig", new BigDecimal("10.1"));
check("decimalMinusMinus", new BigDecimal("10.1"));
check("decimalMinus", new BigDecimal("9.1"));
// prefix operators
// integer
check("plusIntOrig", Integer.valueOf(10));
check("plusPlusInt", Integer.valueOf(11));
check("plusInt", Integer.valueOf(11));
check("minusIntOrig", Integer.valueOf(10));
check("minusMinusInt", Integer.valueOf(9));
check("minusInt", Integer.valueOf(9));
check("unaryInt", Integer.valueOf(-10));
// long
check("plusLongOrig", Long.valueOf(10));
check("plusPlusLong", Long.valueOf(11));
check("plusLong", Long.valueOf(11));
check("minusLongOrig", Long.valueOf(10));
check("minusMinusLong", Long.valueOf(9));
check("minusLong", Long.valueOf(9));
check("unaryLong", Long.valueOf(-10));
// double
check("plusNumberOrig", Double.valueOf(10.1));
check("plusPlusNumber", Double.valueOf(11.1));
check("plusNumber", Double.valueOf(11.1));
check("minusNumberOrig", Double.valueOf(10.1));
check("minusMinusNumber", Double.valueOf(9.1));
check("minusNumber", Double.valueOf(9.1));
check("unaryNumber", Double.valueOf(-10.1));
// decimal
check("plusDecimalOrig", new BigDecimal("10.1"));
check("plusPlusDecimal", new BigDecimal("11.1"));
check("plusDecimal", new BigDecimal("11.1"));
check("minusDecimalOrig", new BigDecimal("10.1"));
check("minusMinusDecimal", new BigDecimal("9.1"));
check("minusDecimal", new BigDecimal("9.1"));
check("unaryDecimal", new BigDecimal("-10.1"));
// record values
assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue());
//record as parameter
assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue());
// logical not
check("booleanValue", true);
check("negation", false);
check("doubleNegation", true);
}
public void test_operators_unary_record() {
doCompileExpectErrors("test_operators_unary_record", Arrays.asList(
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_operator_equal() {
doCompile("test_operator_equal");
check("eq0", true);
check("eq1", true);
check("eq1a", true);
check("eq1b", true);
check("eq1c", false);
check("eq2", true);
check("eq3", true);
check("eq4", true);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", false);
check("eq9", true);
check("eq10", false);
check("eq11", true);
check("eq12", false);
check("eq13", true);
check("eq14", false);
check("eq15", false);
check("eq16", true);
check("eq17", false);
check("eq18", false);
check("eq19", false);
// byte
check("eq20", true);
check("eq21", true);
check("eq22", false);
check("eq23", false);
check("eq24", true);
check("eq25", false);
check("eq20c", true);
check("eq21c", true);
check("eq22c", false);
check("eq23c", false);
check("eq24c", true);
check("eq25c", false);
check("eq26", true);
check("eq27", true);
}
public void test_operator_non_equal(){
doCompile("test_operator_non_equal");
check("inei", false);
check("inej", true);
check("jnei", true);
check("jnej", false);
check("lnei", false);
check("inel", false);
check("lnej", true);
check("jnel", true);
check("lnel", false);
check("dnei", false);
check("ined", false);
check("dnej", true);
check("jned", true);
check("dnel", false);
check("lned", false);
check("dned", false);
check("dned_different_scale", false);
}
public void test_operator_in() {
doCompile("test_operator_in");
check("a", Integer.valueOf(1));
check("haystack", Collections.EMPTY_LIST);
check("needle", Integer.valueOf(2));
check("b1", true);
check("b2", false);
check("h2", Arrays.asList(2.1D, 2.0D, 2.2D));
check("b3", true);
check("h3", Arrays.asList("memento", "mori", "memento mori"));
check("n3", "memento mori");
check("b4", true);
}
public void test_operator_greater_less() {
doCompile("test_operator_greater_less");
check("eq1", true);
check("eq2", true);
check("eq3", true);
check("eq4", false);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", true);
check("eq9", true);
}
public void test_operator_ternary(){
doCompile("test_operator_ternary");
// simple use
check("trueValue", true);
check("falseValue", false);
check("res1", Integer.valueOf(1));
check("res2", Integer.valueOf(2));
// nesting in positive branch
check("res3", Integer.valueOf(1));
check("res4", Integer.valueOf(2));
check("res5", Integer.valueOf(3));
// nesting in negative branch
check("res6", Integer.valueOf(2));
check("res7", Integer.valueOf(3));
// nesting in both branches
check("res8", Integer.valueOf(1));
check("res9", Integer.valueOf(1));
check("res10", Integer.valueOf(2));
check("res11", Integer.valueOf(3));
check("res12", Integer.valueOf(2));
check("res13", Integer.valueOf(4));
check("res14", Integer.valueOf(3));
check("res15", Integer.valueOf(4));
}
public void test_operators_logical(){
doCompile("test_operators_logical");
//TODO: please double check this.
check("res1", false);
check("res2", false);
check("res3", true);
check("res4", true);
check("res5", false);
check("res6", false);
check("res7", true);
check("res8", false);
}
public void test_regex(){
doCompile("test_regex");
check("eq0", false);
check("eq1", true);
check("eq2", false);
check("eq3", true);
check("eq4", false);
check("eq5", true);
}
public void test_if() {
doCompile("test_if");
// if with single statement
check("cond1", true);
check("res1", true);
// if with mutliple statements (block)
check("cond2", true);
check("res21", true);
check("res22", true);
// else with single statement
check("cond3", false);
check("res31", false);
check("res32", true);
// else with multiple statements (block)
check("cond4", false);
check("res41", false);
check("res42", true);
check("res43", true);
// if with block, else with block
check("cond5", false);
check("res51", false);
check("res52", false);
check("res53", true);
check("res54", true);
// else-if with single statement
check("cond61", false);
check("cond62", true);
check("res61", false);
check("res62", true);
// else-if with multiple statements
check("cond71", false);
check("cond72", true);
check("res71", false);
check("res72", true);
check("res73", true);
// if-elseif-else test
check("cond81", false);
check("cond82", false);
check("res81", false);
check("res82", false);
check("res83", true);
// if with single statement + inactive else
check("cond9", true);
check("res91", true);
check("res92", false);
// if with multiple statements + inactive else with block
check("cond10", true);
check("res101", true);
check("res102", true);
check("res103", false);
check("res104", false);
// if with condition
check("i", 0);
check("j", 1);
check("res11", true);
}
public void test_switch() {
doCompile("test_switch");
// simple switch
check("cond1", 1);
check("res11", false);
check("res12", true);
check("res13", false);
// switch, no break
check("cond2", 1);
check("res21", false);
check("res22", true);
check("res23", true);
// default branch
check("cond3", 3);
check("res31", false);
check("res32", false);
check("res33", true);
// no default branch => no match
check("cond4", 3);
check("res41", false);
check("res42", false);
check("res43", false);
// multiple statements in a single case-branch
check("cond5", 1);
check("res51", false);
check("res52", true);
check("res53", true);
check("res54", false);
// single statement shared by several case labels
check("cond6", 1);
check("res61", false);
check("res62", true);
check("res63", true);
check("res64", false);
}
public void test_int_switch(){
doCompile("test_int_switch");
// simple switch
check("cond1", 1);
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", 1);
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", 12);
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", 11);
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", 11);
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", 16);
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_non_int_switch(){
doCompile("test_non_int_switch");
// simple switch
check("cond1", "1");
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", "1");
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", "12");
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", "11");
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", "11");
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", "16");
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_while() {
doCompile("test_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_do_while() {
doCompile("test_do_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, null, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_for() {
doCompile("test_for");
// simple loop
check("res1", Arrays.asList(0,1,2));
// continue
check("res2", Arrays.asList(0,null,2));
// break
check("res3", Arrays.asList(0));
// empty init
check("res4", Arrays.asList(0,1,2));
// empty update
check("res5", Arrays.asList(0,1,2));
// empty final condition
check("res6", Arrays.asList(0,1,2));
// all conditions empty
check("res7", Arrays.asList(0,1,2));
}
public void test_for1() {
//5125: CTL2: "for" cycle is EXTREMELY memory consuming
doCompile("test_for1");
checkEquals("counter", "COUNT");
}
@SuppressWarnings("unchecked")
public void test_foreach() {
doCompile("test_foreach");
check("intRes", Arrays.asList(VALUE_VALUE));
check("longRes", Arrays.asList(BORN_MILLISEC_VALUE));
check("doubleRes", Arrays.asList(AGE_VALUE));
check("decimalRes", Arrays.asList(CURRENCY_VALUE));
check("booleanRes", Arrays.asList(FLAG_VALUE));
check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE));
check("dateRes", Arrays.asList(BORN_VALUE));
List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes");
List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size());
for (Object o: integerStringMapResTmp) {
integerStringMapRes.add(String.valueOf(o));
}
List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes");
List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes");
Collections.sort(integerStringMapRes);
Collections.sort(stringIntegerMapRes);
assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes);
assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes);
final int N = 5;
assertEquals(N, stringRecordMapRes.size());
int equalRecords = 0;
for (int i = 0; i < N; i++) {
for (DataRecord r: stringRecordMapRes) {
if (Integer.valueOf(i).equals(r.getField("Value").getValue())
&& "A string".equals(String.valueOf(r.getField("Name").getValue()))) {
equalRecords++;
break;
}
}
}
assertEquals(N, equalRecords);
}
public void test_return(){
doCompile("test_return");
check("lhs", Integer.valueOf(1));
check("rhs", Integer.valueOf(2));
check("res", Integer.valueOf(3));
}
public void test_return_incorrect() {
doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'");
}
public void test_return_void() {
doCompile("test_return_void");
}
public void test_overloading() {
doCompile("test_overloading");
check("res1", Integer.valueOf(3));
check("res2", "Memento mori");
}
public void test_overloading_incorrect() {
doCompileExpectErrors("test_overloading_incorrect", Arrays.asList(
"Duplicate function 'integer sum(integer, integer)'",
"Duplicate function 'integer sum(integer, integer)'"));
}
//Test case for 4038
public void test_function_parameter_without_type() {
doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'");
}
public void test_duplicate_import() {
URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl");
String expStr = "import '" + importLoc + "';\n";
expStr += "import '" + importLoc + "';\n";
doCompile(expStr, "test_duplicate_import");
}
/*TODO:
* public void test_invalid_import() {
URL importLoc = getClass().getResource("test_duplicate_import.ctl");
String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n";
expStr += expStr;
doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error"));
//doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error"));
} */
public void test_built_in_functions(){
doCompile("test_built_in_functions");
check("notNullValue", Integer.valueOf(1));
checkNull("nullValue");
check("isNullRes1", false);
check("isNullRes2", true);
assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1"));
check("nvlRes2", Integer.valueOf(2));
assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1"));
check("nvl2Res2", Integer.valueOf(2));
check("iifRes1", Integer.valueOf(2));
check("iifRes2", Integer.valueOf(1));
}
public void test_mapping(){
doCompile("test_mapping");
// simple mappings
assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString());
assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString());
assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue());
// * mapping
assertTrue(recordEquals(inputRecords[1], outputRecords[1]));
check("len", 2);
}
public void test_mapping_null_values() {
doCompile("test_mapping_null_values");
assertTrue(recordEquals(inputRecords[2], outputRecords[0]));
}
public void test_copyByName() {
doCompile("test_copyByName");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment() {
doCompile("test_copyByName_assignment");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment1() {
doCompile("test_copyByName_assignment1");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", null, outputRecords[3].getField("Age").getValue());
assertEquals("City", null, outputRecords[3].getField("City").getValue());
}
public void test_sequence(){
doCompile("test_sequence");
check("intRes", Arrays.asList(0,1,2));
check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2)));
check("stringRes", Arrays.asList("0","1","2"));
check("intCurrent", Integer.valueOf(2));
check("longCurrent", Long.valueOf(2));
check("stringCurrent", "2");
}
//TODO: If this test fails please double check whether the test is correct?
public void test_lookup(){
doCompile("test_lookup");
check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella"));
check("bravoResult", Arrays.asList("Bruxelles","Bruxelles"));
check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov"));
check("countResult", Arrays.asList(3,3));
check("charlieUpdatedCount", 5);
check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim"));
check("putResult", true);
}
public void test_containerlib_append() {
doCompile("test_containerlib_append");
check("appendElem", Integer.valueOf(10));
check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10));
}
@SuppressWarnings("unchecked")
public void test_containerlib_clear() {
doCompile("test_containerlib_clear");
assertTrue(((List<Integer>) getVariable("clearList")).isEmpty());
}
public void test_containerlib_copy() {
doCompile("test_containerlib_copy");
check("copyList", Arrays.asList(1, 2, 3, 4, 5));
check("returnedList", Arrays.asList(1, 2, 3, 4, 5));
Map<String, String> expectedMap = new HashMap<String, String>();
expectedMap.put("a", "a");
expectedMap.put("b", "b");
expectedMap.put("c", "c");
expectedMap.put("d", "d");
check("copyMap", expectedMap);
check("returnedMap", expectedMap);
}
public void test_containerlib_insert() {
doCompile("test_containerlib_insert");
check("insertElem", Integer.valueOf(7));
check("insertIndex", Integer.valueOf(3));
check("insertList", Arrays.asList(1, 2, 3, 7, 4, 5));
check("insertList1", Arrays.asList(7, 8, 11, 10, 11));
check("insertList2", Arrays.asList(7, 8, 10, 9, 11));
}
public void test_containerlib_isEmpty() {
doCompile("test_containerlib_isEmpty");
check("emptyMap", true);
check("fullMap", false);
check("emptyList", true);
check("fullList", false);
}
public void test_containerlib_poll() {
doCompile("test_containerlib_poll");
check("pollElem", Integer.valueOf(1));
check("pollList", Arrays.asList(2, 3, 4, 5));
}
public void test_containerlib_pop() {
doCompile("test_containerlib_pop");
check("popElem", Integer.valueOf(5));
check("popList", Arrays.asList(1, 2, 3, 4));
}
@SuppressWarnings("unchecked")
public void test_containerlib_push() {
doCompile("test_containerlib_push");
check("pushElem", Integer.valueOf(6));
check("pushList", Arrays.asList(1, 2, 3, 4, 5, 6));
// there is hardly any way to get an instance of DataRecord
// hence we just check if the list has correct size
// and if its elements have correct metadata
List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList");
List<DataRecordMetadata> mdList = Arrays.asList(
graph.getDataRecordMetadata(OUTPUT_1),
graph.getDataRecordMetadata(INPUT_2),
graph.getDataRecordMetadata(INPUT_1)
);
assertEquals(mdList.size(), recordList.size());
for (int i = 0; i < mdList.size(); i++) {
assertEquals(mdList.get(i), recordList.get(i).getMetadata());
}
}
public void test_containerlib_remove() {
doCompile("test_containerlib_remove");
check("removeElem", Integer.valueOf(3));
check("removeIndex", Integer.valueOf(2));
check("removeList", Arrays.asList(1, 2, 4, 5));
}
public void test_containerlib_reverse() {
doCompile("test_containerlib_reverse");
check("reverseList", Arrays.asList(5, 4, 3, 2, 1));
}
public void test_containerlib_sort() {
doCompile("test_containerlib_sort");
check("sortList", Arrays.asList(1, 1, 2, 3, 5));
}
public void test_containerlib_containsAll() {
doCompile("test_containerlib_containsAll");
check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false));
}
public void test_containerlib_containsKey() {
doCompile("test_containerlib_containsKey");
check("results", Arrays.asList(false, true, false, true, false, true));
}
public void test_containerlib_containsValue() {
doCompile("test_containerlib_containsValue");
check("results", Arrays.asList(true, false, false, true, false, false, true, false));
}
public void test_containerlib_getKeys() {
doCompile("test_containerlib_getKeys");
Map<?, ?> stringIntegerMap = (Map<?, ?>) inputRecords[3].getField("integerMapField").getValue();
Map<?, ?> integerStringMap = (Map<?, ?>) getVariable("integerStringMap");
List<?> stringList = (List<?>) getVariable("stringList");
List<?> integerList = (List<?>) getVariable("integerList");
assertEquals(stringIntegerMap.keySet().size(), stringList.size());
assertEquals(integerStringMap.keySet().size(), integerList.size());
assertEquals(stringIntegerMap.keySet(), new HashSet<Object>(stringList));
assertEquals(integerStringMap.keySet(), new HashSet<Object>(integerList));
}
public void test_stringlib_cache() {
doCompile("test_stringlib_cache");
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "The cat says meow. All cats say meow.");
check("rep3", "The cat says meow. All cats say meow.");
check("find1", Arrays.asList("to", "to", "to", "tro", "to"));
check("find2", Arrays.asList("to", "to", "to", "tro", "to"));
check("find3", Arrays.asList("to", "to", "to", "tro", "to"));
check("split1", Arrays.asList("one", "two", "three", "four", "five"));
check("split2", Arrays.asList("one", "two", "three", "four", "five"));
check("split3", Arrays.asList("one", "two", "three", "four", "five"));
check("chop01", "ting soming choping function");
check("chop02", "ting soming choping function");
check("chop03", "ting soming choping function");
check("chop11", "testing end of lines cutting");
check("chop12", "testing end of lines cutting");
}
public void test_stringlib_charAt() {
doCompile("test_stringlib_charAt");
String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG ";
String[] expected = new String[input.length()];
for (int i = 0; i < expected.length; i++) {
expected[i] = String.valueOf(input.charAt(i));
}
check("chars", Arrays.asList(expected));
}
public void test_stringlib_charAt_error(){
//test: attempt to access char at position, which is out of bounds -> upper bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: attempt to access char at position, which is out of bounds -> lower bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: argument for position is null
try {
doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_concat() {
doCompile("test_stringlib_concat");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("concat", "");
check("concat1", "ello hi ELLO 2,today is " + format.format(new Date()));
check("concat2", "");
check("concat3", "clover");
check("test_null1", "null");
check("test_null2", "null");
check("test_null3","skynullisnullblue");
}
public void test_stringlib_countChar() {
doCompile("test_stringlib_countChar");
check("charCount", 3);
check("count2", 0);
}
public void test_stringlib_countChar_emptychar() {
// test: attempt to count empty chars in string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
// test: attempt to count empty chars in empty string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 1
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 2
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 3
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cut() {
doCompile("test_stringlib_cut");
check("cutInput", Arrays.asList("a", "1edf", "h3ijk"));
}
public void test_string_cut_expect_error() {
// test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and
// user attempt to cut out after position 8.
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from
// position
// 4 substring 4 characters long
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut a substring with negative length
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring from negative position. E.g cut([-3,3]).
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_editDistance() {
doCompile("test_stringlib_editDistance");
check("dist", 1);
check("dist1", 1);
check("dist2", 0);
check("dist5", 1);
check("dist3", 1);
check("dist4", 0);
check("dist6", 4);
check("dist7", 5);
check("dist8", 0);
check("dist9", 0);
}
public void test_stringlib_editDistance_expect_error(){
//test: input - empty string - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input- empty string - second arg
try {
doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - second argument
try {
doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both empty
try {
doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both null
try {
doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
}
public void test_stringlib_find() {
doCompile("test_stringlib_find");
check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g"));
check("findList2", Arrays.asList("mark.twain"));
check("findList3", Arrays.asList());
check("findList4", Arrays.asList("", "", "", "", ""));
check("findList5", Arrays.asList("twain"));
check("findList6", Arrays.asList(""));
}
public void test_stringlib_find_expect_error() {
//test: regexp group number higher then count of regexp groups
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: negative regexp group number
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test1
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test2
try {
doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 and arg2 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_join() {
doCompile("test_stringlib_join");
//check("joinedString", "Bagr,3,3.5641,-87L,CTL2");
check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1");
check("joinedString2", "5.054.6567.0231.0");
//check("joinedString3", "554656723180=5455.987-5=5455.9873=0.1CTL242");
check("test_empty1", "abc");
check("test_empty2", "");
check("test_empty3"," ");
check("test_empty4","anullb");
check("test_empty5","80=5455.987-5=5455.9873=0.1");
check("test_empty6","80=5455.987 -5=5455.987 3=0.1");
check("test_null1","abc");
check("test_null2","");
check("test_null3","anullb");
check("test_null4","80=5455.987-5=5455.9873=0.1");
//CLO-1210
// check("test_empty7","a=xb=nullc=z");
// check("test_empty8","a=x b=null c=z");
// check("test_empty9","null=xeco=storm");
// check("test_empty10","null=x eco=storm");
// check("test_null5","a=xb=nullc=z");
// check("test_null6","null=xeco=storm");
}
public void test_stringlib_join_expect_error(){
try {
doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_left() {
//CLO - 1193
// doCompile("test_stringlib_left");
// check("test1", "aa");
// check("test2", "aaa");
// check("test3", "");
// check("test4", null);
// check("test5", "abc");
// check("test6", "ab ");
// check("test7", " ");
// check("test8", " ");
// check("test9", "abc");
// check("test10", "abc");
// check("test11", "");
// check("test12", null);
}
public void test_stringlib_length() {
doCompile("test_stringlib_length");
check("lenght1", new BigDecimal(50));
check("lenghtByte", 18);
check("stringLength", 8);
check("listLength", 8);
check("mapLength", 3);
check("recordLength", 9);
check("length_empty", 0);
check("length_null1", 0);
check("length_null2", 0);
check("length_null3", 0);
check("length_null4", 0);
check("length_null5", 0);
}
public void test_stringlib_lowerCase() {
doCompile("test_stringlib_lowerCase");
check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr ");
check("lower_empty", "");
check("lower_null", null);
}
public void test_stringlib_matches() {
doCompile("test_stringlib_matches");
check("matches1", true);
check("matches2", true);
check("matches3", false);
check("matches4", true);
check("matches5", false);
check("matches6", false);
check("matches7", false);
check("matches8", false);
check("matches9", true);
check("matches10", true);
}
public void test_stringlib_matches_expect_error(){
//test: regexp param null - test 1
try {
doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 2
try {
doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 3
try {
doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups() {
doCompile("test_stringlib_matchGroups");
check("result1", null);
check("result2", Arrays.asList(
//"(([^:]*)([:])([\\(]))(.*)(\\))(((
"zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt",
"zip:(",
"zip",
":",
"(",
"zip:(/path/name?.zip)#innerfolder/file.zip",
")",
"#innermostfolder?/filename*.txt",
"#innermostfolder?/filename*.txt",
"
"innermostfolder?/filename*.txt",
null
)
);
check("result3", null);
check("test_empty1", null);
check("test_empty2", Arrays.asList(""));
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_matchGroups_expect_error(){
//test: regexp is null - test 1
try {
doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 2
try {
doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 3
try {
doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups_unmodifiable() {
try {
doCompile("test_stringlib_matchGroups_unmodifiable");
fail();
} catch (RuntimeException re) {
};
}
public void test_stringlib_metaphone() {
doCompile("test_stringlib_metaphone");
check("metaphone1", "XRS");
check("metaphone2", "KWNTLN");
check("metaphone3", "KWNT");
check("metaphone4", "");
check("metaphone5", "");
check("test_empty1", "");
check("test_empty2", "");
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_nysiis() {
doCompile("test_stringlib_nysiis");
check("nysiis1", "CAP");
check("nysiis2", "CAP");
check("nysiis3", "1234");
check("nysiis4", "C2 PRADACTAN");
check("nysiis_empty", "");
check("nysiis_null", null);
}
public void test_stringlib_replace() {
doCompile("test_stringlib_replace");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("rep", format.format(new Date()).replaceAll("[lL]", "t"));
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "intruders must die");
check("test_empty1", "a");
check("test_empty2", "");
check("test_null", null);
check("test_null2","");
check("test_null3","bbb");
check("test_null4",null);
}
public void test_stringlib_replace_expect_error(){
//test: regexp null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //test: arg3 null - test2
// try {
// doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
// //test: arg3 null - test3
// try {
// doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_right() {
doCompile("test_stringlib_right");
check("righ", "y dog");
check("rightNotPadded", "y dog");
check("rightPadded", "y dog");
check("padded", " y dog");
check("notPadded", "y dog");
check("short", "Dog");
check("shortNotPadded", "Dog");
check("shortPadded", " Dog");
check("simple", "milk");
check("test_null1", null);
check("test_null2", null);
check("test_null3", " ");
check("test_empty1", "");
check("test_empty2", "");
check("test_empty3"," ");
}
public void test_stringlib_soundex() {
doCompile("test_stringlib_soundex");
check("soundex1", "W630");
check("soundex2", "W643");
check("test_null", null);
check("test_empty", "");
}
public void test_stringlib_split() {
doCompile("test_stringlib_split");
check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g"));
check("test_empty", Arrays.asList(""));
check("test_empty2", Arrays.asList("","a","a"));
List<String> tmp = new ArrayList<String>();
tmp.add(null);
check("test_null", tmp);
}
public void test_stringlib_split_expect_error(){
//test: regexp null - test1
try {
doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_substring() {
doCompile("test_stringlib_substring");
check("subs", "UICk ");
check("test1", "");
check("test_empty", "");
}
public void test_stringlib_substring_expect_error(){
try {
doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_trim() {
doCompile("test_stringlib_trim");
check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG");
check("trim_empty", "");
check("trim_null", null);
}
public void test_stringlib_upperCase() {
doCompile("test_stringlib_upperCase");
check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_isFormat() {
doCompile("test_stringlib_isFormat");
check("test", "test");
check("isBlank", Boolean.FALSE);
check("blank", "");
checkNull("nullValue");
check("isBlank1", true);
check("isBlank2", true);
check("isAscii1", true);
check("isAscii2", false);
check("isAscii3", true);
check("isAscii4", true);
check("isNumber", false);
check("isNumber1", false);
check("isNumber2", true);
check("isNumber3", true);
check("isNumber4", false);
check("isNumber5", true);
check("isNumber6", true);
check("isNumber7", false);
check("isNumber8", false);
check("isInteger", false);
check("isInteger1", false);
check("isInteger2", false);
check("isInteger3", true);
check("isInteger4", false);
check("isInteger5", false);
check("isLong", true);
check("isLong1", false);
check("isLong2", false);
check("isLong3", false);
check("isLong4", false);
check("isDate", true);
check("isDate1", false);
// "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23)
check("isDate2", true);
check("isDate3", true);
check("isDate4", false);
check("isDate5", true);
check("isDate6", true);
check("isDate7", false);
check("isDate9", false);
check("isDate10", false);
check("isDate11", false);
check("isDate12", true);
check("isDate13", false);
check("isDate14", false);
// empty string: invalid
check("isDate15", false);
check("isDate16", false);
check("isDate17", true);
check("isDate18", true);
check("isDate19", false);
check("isDate20", false);
check("isDate21", false);
/* CLO-1190
check("isDate22", false);
check("isDate23", false);
check("isDate24", true);
check("isDate25", false);
*/
}
public void test_stringlib_empty_strings() {
String[] expressions = new String[] {
"isInteger(?)",
"isNumber(?)",
"isLong(?)",
"isAscii(?)",
"isBlank(?)",
"isDate(?, \"yyyy\")",
"isUrl(?)",
"string x = ?; length(x)",
"lowerCase(?)",
"matches(?, \"\")",
"NYSIIS(?)",
"removeBlankSpace(?)",
"removeDiacritic(?)",
"removeNonAscii(?)",
"removeNonPrintable(?)",
"replace(?, \"a\", \"a\")",
"translate(?, \"ab\", \"cd\")",
"trim(?)",
"upperCase(?)",
"chop(?)",
"concat(?)",
"getAlphanumericChars(?)",
};
StringBuilder sb = new StringBuilder();
for (String expr : expressions) {
String emptyString = expr.replace("?", "\"\"");
boolean crashesEmpty = test_expression_crashes(emptyString);
assertFalse("Function " + emptyString + " crashed", crashesEmpty);
String nullString = expr.replace("?", "null");
boolean crashesNull = test_expression_crashes(nullString);
sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok"));
}
System.out.println(sb.toString());
}
private boolean test_expression_crashes(String expr) {
String expStr = "function integer transform() { " + expr + "; return 0; }";
try {
doCompile(expStr, "test_stringlib_empty_null_strings");
return false;
} catch (RuntimeException e) {
return true;
}
}
public void test_stringlib_removeBlankSpace() {
String expStr =
"string r1;\n" +
"string str_empty;\n" +
"string str_null;\n" +
"function integer transform() {\n" +
"r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" +
"printErr(r1);\n" +
"str_empty = removeBlankSpace('');\n" +
"str_null = removeBlankSpace(null);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_removeBlankSpace");
check("r1", "abcdef");
check("str_empty", "");
check("str_null", null);
}
public void test_stringlib_removeNonPrintable() {
doCompile("test_stringlib_removeNonPrintable");
check("nonPrintableRemoved", "AHOJ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_getAlphanumericChars() {
String expStr =
"string an1;\n" +
"string an2;\n" +
"string an3;\n" +
"string an4;\n" +
"string an5;\n" +
"string an6;\n" +
"string an7;\n" +
"string an8;\n" +
"string an9;\n" +
"string an10;\n" +
"string an11;\n" +
"string an12;\n" +
"string an13;\n" +
"string an14;\n" +
"string an15;\n" +
"function integer transform() {\n" +
"an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" +
"an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" +
"an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" +
"an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" +
"an5=getAlphanumericChars(\"\");\n" +
"an6=getAlphanumericChars(\"\",true,true);\n"+
"an7=getAlphanumericChars(\"\",true,false);\n"+
"an8=getAlphanumericChars(\"\",false,true);\n"+
"an9=getAlphanumericChars(null);\n" +
"an10=getAlphanumericChars(null,false,false);\n" +
"an11=getAlphanumericChars(null,true,false);\n" +
"an12=getAlphanumericChars(null,false,true);\n" +
"an13=getAlphanumericChars(' 0 ľeškó11');\n" +
"an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" +
//CLO-1174
"string tmp = \""+StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\";\n"+
"printErr('BEFORE DO COMPILE: '+tmp); \n"+
"an15=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,false);\n" +
"printErr('AFTER GET_ALPHA_NUMERIC_CHARS: '+ an15);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_getAlphanumericChars");
check("an1", "a1bcde2f");
check("an2", "a1bcde2f");
check("an3", "abcdef");
check("an4", "12");
check("an5", "");
check("an6", "");
check("an7", "");
check("an8", "");
check("an9", null);
check("an10", null);
check("an11", null);
check("an12", null);
check("an13", "0ľeškó11");
check("an14"," 0 ľeškó11");
//CLO-1174
String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n");
System.out.println("FROM JAVA - AFTER DO COMPILE: "+ tmp);
//check("an15", tmp);
}
public void test_stringlib_indexOf(){
doCompile("test_stringlib_indexOf");
check("index",2);
check("index1",9);
check("index2",0);
check("index3",-1);
check("index4",6);
check("index5",-1);
check("index6",0);
check("index7",4);
check("index8",4);
check("index9", -1);
check("index10", 2);
check("index_empty1", -1);
check("index_empty2", 0);
check("index_empty3", 0);
check("index_empty4", -1);
}
public void test_stringlib_indexOf_expect_error(){
//test: second arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: both args are null
try {
doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeDiacritic(){
doCompile("test_stringlib_removeDiacritic");
check("test","tescik");
check("test1","zabicka");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_translate(){
doCompile("test_stringlib_translate");
check("trans","hippi");
check("trans1","hipp");
check("trans2","hippi");
check("trans3","");
check("trans4","y lanuaX nXXd thX lXttXr X");
check("trans5", "hello");
check("test_empty1", "");
check("test_empty2", "");
check("test_null", null);
}
public void test_stringlib_translate_expect_error(){
try {
doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeNonAscii(){
doCompile("test_stringlib_removeNonAscii");
check("test1", "Sun is shining");
check("test2", "");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_chop() {
doCompile("test_stringlib_chop");
check("s1", "hello");
check("s6", "hello");
check("s5", "hello");
check("s2", "hello");
check("s7", "helloworld");
check("s3", "hello ");
check("s4", "hello");
check("s8", "hello");
check("s9", "world");
check("s10", "hello");
check("s11", "world");
check("s12", "mark.twain");
check("s13", "two words");
check("s14", "");
check("s15", "");
check("s16", "");
check("s17", "");
check("s18", "");
check("s19", "word");
check("s20", "");
check("s21", "");
check("s22", "mark.twain");
}
public void test_stringlib_chop_expect_error() {
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null
try {
doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null - test 2
try {
doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test2
try {
doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test3
try {
doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitIsSet(){
doCompile("test_bitwise_bitIsSet");
check("test1", true);
check("test2", false);
check("test3", false);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", false);
}
public void test_bitwise_bitIsSet_expect_error(){
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_or() {
doCompile("test_bitwise_or");
check("resultInt1", 1);
check("resultInt2", 1);
check("resultInt3", 3);
check("resultInt4", 3);
check("resultLong1", 1l);
check("resultLong2", 1l);
check("resultLong3", 3l);
check("resultLong4", 3l);
}
public void test_bitwise_and() {
doCompile("test_bitwise_and");
check("resultInt1", 0);
check("resultInt2", 1);
check("resultInt3", 0);
check("resultInt4", 1);
check("resultLong1", 0l);
check("resultLong2", 1l);
check("resultLong3", 0l);
check("resultLong4", 1l);
//CLO-1385
// check("test_mixed1", 12l);
// check("test_mixed2", 12l);
}
public void test_bitwise_and_expect_error(){
try {
doCompile("function integer transform(){\n"
+ "integer a = null; integer b = 16;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "integer a = 16; integer b = null;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = 16l; long b = null;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = null; long b = 10l;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_xor() {
doCompile("test_bitwise_xor");
check("resultInt1", 1);
check("resultInt2", 0);
check("resultInt3", 3);
check("resultInt4", 2);
check("resultLong1", 1l);
check("resultLong2", 0l);
check("resultLong3", 3l);
check("resultLong4", 2l);
}
public void test_bitwise_lshift() {
doCompile("test_bitwise_lshift");
check("resultInt1", 2);
check("resultInt2", 4);
check("resultInt3", 10);
check("resultInt4", 20);
check("resultInt5", -2147483648);
check("resultLong1", 2l);
check("resultLong2", 4l);
check("resultLong3", 10l);
check("resultLong4", 20l);
check("resultLong5",-9223372036854775808l);
}
public void test_bitwise_lshift_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_rshift() {
doCompile("test_bitwise_rshift");
check("resultInt1", 2);
check("resultInt2", 0);
check("resultInt3", 4);
check("resultInt4", 2);
check("resultLong1", 2l);
check("resultLong2", 0l);
check("resultLong3", 4l);
check("resultLong4", 2l);
}
public void test_bitwise_negate() {
doCompile("test_bitwise_negate");
check("resultInt", -59081717);
check("resultLong", -3321654987654105969L);
check("test_zero_int", -1);
check("test_zero_long", -1l);
}
public void test_bitwise_negate_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_set_bit() {
doCompile("test_set_bit");
check("resultInt1", 0x2FF);
check("resultInt2", 0xFB);
check("resultLong1", 0x4000000000000l);
check("resultLong2", 0xFFDFFFFFFFFFFFFl);
check("resultBool1", true);
check("resultBool2", false);
check("resultBool3", true);
check("resultBool4", false);
}
public void test_mathlib_abs() {
doCompile("test_mathlib_abs");
check("absIntegerPlus", new Integer(10));
check("absIntegerMinus", new Integer(1));
check("absLongPlus", new Long(10));
check("absLongMinus", new Long(1));
check("absDoublePlus", new Double(10.0));
check("absDoubleMinus", new Double(1.0));
check("absDecimalPlus", new BigDecimal(5.0));
check("absDecimalMinus", new BigDecimal(5.0));
}
public void test_mathlib_abs_expect_error(){
try {
doCompile("function integer transform(){ \n "
+ "integer tmp;\n "
+ "tmp = null; \n"
+ " integer i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "long tmp;\n "
+ "tmp = null; \n"
+ "long i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "double tmp;\n "
+ "tmp = null; \n"
+ "double i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "decimal tmp;\n "
+ "tmp = null; \n"
+ "decimal i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_ceil() {
doCompile("test_mathlib_ceil");
check("ceil1", -3.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(3.0, -3.0));
check("decimalResult", Arrays.asList(3.0, -3.0));
}
public void test_mathlib_e() {
doCompile("test_mathlib_e");
check("varE", Math.E);
}
public void test_mathlib_exp() {
doCompile("test_mathlib_exp");
check("ex", Math.exp(1.123));
}
public void test_mathlib_floor() {
doCompile("test_mathlib_floor");
check("floor1", -4.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(2.0, -4.0));
check("decimalResult", Arrays.asList(2.0, -4.0));
}
public void test_mathlib_log() {
doCompile("test_mathlib_log");
check("ln", Math.log(3));
}
public void test_mathlib_log10() {
doCompile("test_mathlib_log10");
check("varLog10", Math.log10(3));
}
public void test_mathlib_pi() {
doCompile("test_mathlib_pi");
check("varPi", Math.PI);
}
public void test_mathlib_pow() {
doCompile("test_mathlib_pow");
check("power1", Math.pow(3,1.2));
check("power2", Double.NaN);
check("intResult", Arrays.asList(8d, 8d, 8d, 8d));
check("longResult", Arrays.asList(8d, 8d, 8d, 8d));
check("doubleResult", Arrays.asList(8d, 8d, 8d, 8d));
check("decimalResult", Arrays.asList(8d, 8d, 8d, 8d));
}
public void test_mathlib_round() {
doCompile("test_mathlib_round");
check("round1", -4l);
check("intResult", Arrays.asList(2l, 3l));
check("longResult", Arrays.asList(2l, 3l));
check("doubleResult", Arrays.asList(2l, 4l));
check("decimalResult", Arrays.asList(2l, 4l));
}
public void test_mathlib_sqrt() {
doCompile("test_mathlib_sqrt");
check("sqrtPi", Math.sqrt(Math.PI));
check("sqrt9", Math.sqrt(9));
}
public void test_datelib_cache() {
doCompile("test_datelib_cache");
check("b11", true);
check("b12", true);
check("b21", true);
check("b22", true);
check("b31", true);
check("b32", true);
check("b41", true);
check("b42", true);
checkEquals("date3", "date3d");
checkEquals("date4", "date4d");
checkEquals("date7", "date7d");
checkEquals("date8", "date8d");
}
public void test_datelib_trunc() {
doCompile("test_datelib_trunc");
check("truncDate", new GregorianCalendar(2004, 00, 02).getTime());
}
public void test_datelib_truncDate() {
doCompile("test_datelib_truncDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("truncBornDate", cal.getTime());
}
public void test_datelib_today() {
doCompile("test_datelib_today");
Date expectedDate = new Date();
//the returned date does not need to be exactly the same date which is in expectedData variable
//let say 1000ms is tolerance for equality
assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000);
}
public void test_datelib_zeroDate() {
doCompile("test_datelib_zeroDate");
check("zeroDate", new Date(0));
}
public void test_datelib_dateDiff() {
doCompile("test_datelib_dateDiff");
long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears();
check("ddiff", diffYears);
long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L};
String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"};
for (int i = 0; i < results.length; i++) {
check(vars[i], results[i]);
}
}
public void test_datelib_dateDiff_epect_error(){
try {
doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_dateAdd() {
doCompile("test_datelib_dateAdd");
check("datum", new Date(BORN_MILLISEC_VALUE + 100));
}
public void test_datelib_dateAdd_expect_error(){
try {
doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractTime() {
doCompile("test_datelib_extractTime");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("bornExtractTime", cal.getTime());
check("originalDate", BORN_VALUE);
}
public void test_datelib_extractTime_expect_error(){
try {
doCompile("function integer transform(){date d = extractTime(null); return 0;}","test_datelib_extractTime_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractDate() {
doCompile("test_datelib_extractDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)};
cal.clear();
cal.set(Calendar.DAY_OF_MONTH, portion[0]);
cal.set(Calendar.MONTH, portion[1]);
cal.set(Calendar.YEAR, portion[2]);
check("bornExtractDate", cal.getTime());
check("originalDate", BORN_VALUE);
}
public void test_datelib_extractDate_expect_error(){
try {
doCompile("function integer transform(){date d = extractDate(null); return 0;}","test_datelib_extractDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_createDate() {
doCompile("test_datelib_createDate");
Calendar cal = Calendar.getInstance();
// no time zone
cal.clear();
cal.set(2013, 5, 11);
check("date1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis1", cal.getTime());
// literal
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
cal.clear();
cal.set(2013, 5, 11);
check("date2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis2", cal.getTime());
// variable
cal.clear();
cal.set(2013, 5, 11);
check("date3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis3", cal.getTime());
}
public void test_datelib_getPart() {
doCompile("test_datelib_getPart");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+1"));
cal.set(2013, 5, 11, 14, 46, 34);
cal.set(Calendar.MILLISECOND, 123);
Date date = cal.getTime();
cal = Calendar.getInstance();
cal.setTime(date);
// no time zone
check("year1", cal.get(Calendar.YEAR));
check("month1", cal.get(Calendar.MONTH) + 1);
check("day1", cal.get(Calendar.DAY_OF_MONTH));
check("hour1", cal.get(Calendar.HOUR_OF_DAY));
check("minute1", cal.get(Calendar.MINUTE));
check("second1", cal.get(Calendar.SECOND));
check("millisecond1", cal.get(Calendar.MILLISECOND));
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
// literal
check("year2", cal.get(Calendar.YEAR));
check("month2", cal.get(Calendar.MONTH) + 1);
check("day2", cal.get(Calendar.DAY_OF_MONTH));
check("hour2", cal.get(Calendar.HOUR_OF_DAY));
check("minute2", cal.get(Calendar.MINUTE));
check("second2", cal.get(Calendar.SECOND));
check("millisecond2", cal.get(Calendar.MILLISECOND));
// variable
check("year3", cal.get(Calendar.YEAR));
check("month3", cal.get(Calendar.MONTH) + 1);
check("day3", cal.get(Calendar.DAY_OF_MONTH));
check("hour3", cal.get(Calendar.HOUR_OF_DAY));
check("minute3", cal.get(Calendar.MINUTE));
check("second3", cal.get(Calendar.SECOND));
check("millisecond3", cal.get(Calendar.MILLISECOND));
check("year_null", 2013);
check("month_null", 6);
check("day_null", 11);
check("hour_null", 15);
check("minute_null", cal.get(Calendar.MINUTE));
check("second_null", cal.get(Calendar.SECOND));
check("milli_null", cal.get(Calendar.MILLISECOND));
}
public void test_datelib_getPart_expect_error(){
try {
doCompile("function integer transform(){integer i = getYear(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMonth(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getDay(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getHour(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMinute(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getSecond(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMillisecond(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_randomDate() {
doCompile("test_datelib_randomDate");
final long HOUR = 60L * 60L * 1000L;
Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L);
check("noTimeZone1", BORN_VALUE);
check("noTimeZone2", BORN_VALUE_NO_MILLIS);
check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3
check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5
assertNotNull(getVariable("patt_null"));
}
public void test_datelib_randomDate_expect_error(){
try {
doCompile("function integer transform(){date a = null; date b = today(); "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = today(); date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = null; date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = 843484317231l; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = 12115641158l; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//wrong format
try {
doCompile("function integer transform(){"
+ "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//start date bigger then end date
try {
doCompile("function integer transform(){"
+ "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_cache() {
// set default locale to en.US so the date is formatted uniformly on all systems
Locale.setDefault(Locale.US);
doCompile("test_convertlib_cache");
Calendar cal = Calendar.getInstance();
cal.set(2000, 6, 20, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("sdate1", format.format(new Date()));
check("sdate2", format.format(new Date()));
check("date01", checkDate);
check("date02", checkDate);
check("date03", checkDate);
check("date04", checkDate);
check("date11", checkDate);
check("date12", checkDate);
check("date13", checkDate);
}
public void test_convertlib_base64byte() {
doCompile("test_convertlib_base64byte");
assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog")));
}
public void test_convertlib_base64byte_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = base64byte(null); return 0;}","test_convertlib_base64byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bits2str() {
doCompile("test_convertlib_bits2str");
check("bitsAsString1", "00000000");
check("bitsAsString2", "11111111");
check("bitsAsString3", "010100000100110110100000");
}
public void test_convertlib_bits2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = bits2str(null); return 0;}","test_convertlib_bits2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bool2num() {
doCompile("test_convertlib_bool2num");
check("resultTrue", 1);
check("resultFalse", 0);
}
public void test_convertlib_bool2num_expect_error(){
// CLO-1255
// //this test should be expected to success in future
// try {
// doCompile("function integer transform(){integer s = bool2num(null);return 0;}","test_convertlib_bool2num_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_byte2base64() {
doCompile("test_convertlib_byte2base64");
check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes()));
}
public void test_convertlib_byte2base64_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = byte2base64(null);return 0;}","test_convertlib_byte2base64_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2hex() {
doCompile("test_convertlib_byte2hex");
check("hexResult", "41626563656461207a65646c612064656461");
check("test_null", null);
}
public void test_convertlib_date2long() {
doCompile("test_convertlib_date2long");
check("bornDate", BORN_MILLISEC_VALUE);
check("zeroDate", 0l);
}
public void test_convertlib_date2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long l = date2long(null);return 0;}","test_convertlib_date2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_date2num() {
doCompile("test_convertlib_date2num");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
check("yearDate", 1987);
check("monthDate", 5);
check("secondDate", 0);
check("yearBorn", cal.get(Calendar.YEAR));
check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1;
check("secondBorn", cal.get(Calendar.SECOND));
check("yearMin", 1970);
check("monthMin", 1);
check("weekMin", 1);
check("weekMinCs", 1);
check("dayMin", 1);
check("hourMin", 1); //TODO: check!
check("minuteMin", 0);
check("secondMin", 0);
check("millisecMin", 0);
}
public void test_convertlib_date2num_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(null,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(null,year); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_date2str() {
doCompile("test_convertlib_date2str");
check("inputDate", "1987:05:12");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd");
check("bornDate", sdf.format(BORN_VALUE));
SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ"));
check("czechBornDate", sdfCZ.format(BORN_VALUE));
SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en"));
check("englishBornDate", sdfEN.format(BORN_VALUE));
{
String[] locales = {"en", "pl", null, "cs.CZ", null};
List<String> expectedDates = new ArrayList<String>();
for (String locale: locales) {
expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE));
}
check("loopTest", expectedDates);
}
SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en"));
sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("timeZone", sdfGMT8.format(BORN_VALUE));
}
public void test_convertlib_date2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = date2str(null,'yyyy:MMMM:dd', 'cs.CZ', 'GMT+8');return 0;}","test_convertlib_date2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = date2str(1985-11-12,null, 'cs.CZ', 'GMT+8');return 0;}","test_convertlib_date2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2double() {
doCompile("test_convertlib_decimal2double");
check("toDouble", 0.007d);
}
public void test_convertlib_decimal2double_except_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){double d = decimal2double(null); return 0;}","test_convertlib_decimal2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2integer() {
doCompile("test_convertlib_decimal2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
}
public void test_convertlib_decimal2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = decimal2integer(null); return 0;}","test_convertlib_decimal2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2long() {
doCompile("test_convertlib_decimal2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
}
public void test_convertlib_decimal2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long i = decimal2long(null); return 0;}","test_convertlib_decimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_double2integer() {
doCompile("test_convertlib_double2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
}
public void test_convertlib_double2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = double2integer(null); return 0;}","test_convertlib_doublel2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_double2long() {
doCompile("test_convertlib_double2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
}
public void test_convertlib_double2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long l = double2long(null); return 0;}","test_convertlib_doublel2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_getFieldName() {
doCompile("test_convertlib_getFieldName");
check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
}
public void test_convertlib_getFieldType() {
doCompile("test_convertlib_getFieldType");
check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(),
DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(),
DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName()));
}
public void test_convertlib_hex2byte() {
doCompile("test_convertlib_hex2byte");
assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE));
check("test_null", null);
}
public void test_convertlib_long2date() {
doCompile("test_convertlib_long2date");
check("fromLong1", new Date(0));
check("fromLong2", new Date(50000000000L));
check("fromLong3", new Date(-5000L));
}
public void test_convertlib_long2date_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){date d = long2date(null); return 0;}","test_convertlib_long2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2integer() {
doCompile("test_convertlib_long2integer");
check("fromLong1", 10);
check("fromLong2", -10);
}
public void test_convertlib_long2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = long2integer(null); return 0;}","test_convertlib_long2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2packDecimal() {
doCompile("test_convertlib_long2packDecimal");
assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12}));
}
public void test_convertlib_long2packDecimal_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = long2packDecimal(null); return 0;}","test_convertlib_long2packDecimal_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_md5() {
doCompile("test_convertlib_md5");
assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, "")));
}
public void test_convertlib_md5_expect_error(){
//CLO-1254
// //this test should be expected to success in future
// try {
// doCompile("function integer transform(){byte b = md5(null); return 0;}","test_convertlib_md5_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_num2bool() {
doCompile("test_convertlib_num2bool");
check("integerTrue", true);
check("integerFalse", false);
check("longTrue", true);
check("longFalse", false);
check("doubleTrue", true);
check("doubleFalse", false);
check("decimalTrue", true);
check("decimalFalse", false);
}
public void test_convertlib_num2bool_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: decimal
try {
doCompile("decimal input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_num2str() {
System.out.println("num2str() test:");
doCompile("test_convertlib_num2str");
check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs"));
check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs"));
check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs"));
check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs"));
check("test_null_dec", "NaN");
}
public void test_converlib_num2str_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //this test should be expected to success in future
// //test: decimal
// try {
// doCompile("decimal input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_packdecimal2long() {
doCompile("test_convertlib_packDecimal2long");
check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE));
}
public void test_convertlib_packdecimal2long_expect_error(){
try {
doCompile("function integer transform(){long l =packDecimal2long(null); return 0;}","test_convertlib_packdecimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_sha() {
doCompile("test_convertlib_sha");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, "")));
}
public void test_convertlib_sha_expect_error(){
// CLO-1258
// try {
// doCompile("function integer transform(){byte b = sha(null); return 0;}","test_convertlib_sha_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_sha256() {
doCompile("test_convertlib_sha256");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, "")));
}
public void test_convertlib_sha256_expect_error(){
// CLO-1258
// try {
// doCompile("function integer transform(){byte b = sha256(null); return 0;}","test_convertlib_sha256_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_str2bits() {
doCompile("test_convertlib_str2bits");
//TODO: uncomment -> test will pass, but is that correct?
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {}));
}
public void test_convertlib_str2bits_expect_error(){
try {
doCompile("function integer transform(){byte b = str2bits(null); return 0;}","test_convertlib_str2bits_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2bool() {
doCompile("test_convertlib_str2bool");
check("fromTrueString", true);
check("fromFalseString", false);
}
public void test_convertlib_str2bool_expect_error(){
try {
doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(null); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_str2date() {
doCompile("test_convertlib_str2date");
Calendar cal = Calendar.getInstance();
cal.set(2050, 4, 19, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
check("date1", checkDate);
check("date2", checkDate);
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone1", cal.getTime());
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone2", cal.getTime());
assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2")));
}
public void test_convertlib_str2date_expect_error(){
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date(null, 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date(null, null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2decimal() {
doCompile("test_convertlib_str2decimal");
check("parsedDecimal1", new BigDecimal("100.13"));
check("parsedDecimal2", new BigDecimal("123123123.123"));
check("parsedDecimal3", new BigDecimal("-350000.01"));
check("parsedDecimal4", new BigDecimal("1000000"));
check("parsedDecimal5", new BigDecimal("1000000.99"));
check("parsedDecimal6", new BigDecimal("123123123.123"));
check("parsedDecimal7", new BigDecimal("5.01"));
}
public void test_convertlib_str2decimal_expect_result(){
try {
doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal(null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal(null,'#.# US'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2double() {
doCompile("test_convertlib_str2double");
check("parsedDouble1", 100.13);
check("parsedDouble2", 123123123.123);
check("parsedDouble3", -350000.01);
}
public void test_convertlib_str2double_expect_error(){
try {
doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double(null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2integer() {
doCompile("test_convertlib_str2integer");
check("parsedInteger1", 123456789);
check("parsedInteger2", 123123);
check("parsedInteger3", -350000);
check("parsedInteger4", 419);
}
public void test_convertlib_str2integer_expect_error(){
try {
doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(null); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2long() {
doCompile("test_convertlib_str2long");
check("parsedLong1", 1234567890123L);
check("parsedLong2", 123123123456789L);
check("parsedLong3", -350000L);
check("parsedLong4", 133L);
}
public void test_convertlib_str2long_expect_error(){
try {
doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(null); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_toString() {
doCompile("test_convertlib_toString");
check("integerString", "10");
check("longString", "110654321874");
check("doubleString", "1.547874E-14");
check("decimalString", "-6847521431.1545874");
check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]");
check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}");
String byteMapString = getVariable("byteMapString").toString();
assertTrue(byteMapString.contains("1=value1"));
assertTrue(byteMapString.contains("2=value2"));
String fieldByteMapString = getVariable("fieldByteMapString").toString();
assertTrue(fieldByteMapString.contains("key1=value1"));
assertTrue(fieldByteMapString.contains("key2=value2"));
check("byteListString", "[firstElement, secondElement]");
check("fieldByteListString", "[firstElement, secondElement]");
// CLO-1262
// check("test_null_l", "null");
// check("test_null_dec", "null");
// check("test_null_d", "null");
// check("test_null_i", "null");
}
public void test_convertlib_str2byte() {
doCompile("test_convertlib_str2byte");
checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 });
checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 });
checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 });
checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 });
checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 });
checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 });
checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
}
public void test_convertlib_str2byte_expect_error(){
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-8'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-16'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'MacCentralEurope'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'ascii'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'iso-8859-2'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'windows-1250'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2str() {
doCompile("test_convertlib_byte2str");
String hello = "Hello World!";
String horse = "Příliš žluťoučký kůň pěl ďáblské ódy";
String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω";
check("utf8Hello", hello);
check("utf8Horse", horse);
check("utf8Math", math);
check("utf16Hello", hello);
check("utf16Horse", horse);
check("utf16Math", math);
check("macHello", hello);
check("macHorse", horse);
check("asciiHello", hello);
check("isoHello", hello);
check("isoHorse", horse);
check("cpHello", hello);
check("cpHorse", horse);
}
public void test_convertlib_byte2str_expect_error(){
try {
doCompile("function integer transform(){string s = byte2str(null,'utf-8'); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_conditional_fail() {
doCompile("test_conditional_fail");
check("result", 3);
}
public void test_expression_statement(){
// test case for issue 4174
doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected"));
}
public void test_dictionary_read() {
doCompile("test_dictionary_read");
check("s", "Verdon");
check("i", Integer.valueOf(211));
check("l", Long.valueOf(226));
check("d", BigDecimal.valueOf(239483061));
check("n", Double.valueOf(934.2));
check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
check("b", true);
byte[] y = (byte[]) getVariable("y");
assertEquals(10, y.length);
assertEquals(89, y[9]);
check("sNull", null);
check("iNull", null);
check("lNull", null);
check("dNull", null);
check("nNull", null);
check("aNull", null);
check("bNull", null);
check("yNull", null);
check("stringList", Arrays.asList("aa", "bb", null, "cc"));
check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) getVariable("byteList");
assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
}
public void test_dictionary_write() {
doCompile("test_dictionary_write");
assertEquals(832, graph.getDictionary().getValue("i") );
assertEquals("Guil", graph.getDictionary().getValue("s"));
assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l"));
assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d"));
assertEquals(934.2, graph.getDictionary().getValue("n"));
assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a"));
assertEquals(true, graph.getDictionary().getValue("b"));
byte[] y = (byte[]) graph.getDictionary().getValue("y");
assertEquals(2, y.length);
assertEquals(18, y[0]);
assertEquals(-94, y[1]);
assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList"));
assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList"));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF}));
check("assignmentReturnValue", "Guil");
}
public void test_dictionary_write_null() {
doCompile("test_dictionary_write_null");
assertEquals(null, graph.getDictionary().getValue("s"));
assertEquals(null, graph.getDictionary().getValue("sVerdon"));
assertEquals(null, graph.getDictionary().getValue("i") );
assertEquals(null, graph.getDictionary().getValue("i211") );
assertEquals(null, graph.getDictionary().getValue("l"));
assertEquals(null, graph.getDictionary().getValue("l452"));
assertEquals(null, graph.getDictionary().getValue("d"));
assertEquals(null, graph.getDictionary().getValue("d621"));
assertEquals(null, graph.getDictionary().getValue("n"));
assertEquals(null, graph.getDictionary().getValue("n9342"));
assertEquals(null, graph.getDictionary().getValue("a"));
assertEquals(null, graph.getDictionary().getValue("a1992"));
assertEquals(null, graph.getDictionary().getValue("b"));
assertEquals(null, graph.getDictionary().getValue("bTrue"));
assertEquals(null, graph.getDictionary().getValue("y"));
assertEquals(null, graph.getDictionary().getValue("yFib"));
}
public void test_dictionary_invalid_key(){
doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist"));
}
public void test_dictionary_string_to_int(){
doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'"));
}
public void test_utillib_sleep() {
long time = System.currentTimeMillis();
doCompile("test_utillib_sleep");
long tmp = System.currentTimeMillis() - time;
assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000);
}
public void test_utillib_random_uuid() {
doCompile("test_utillib_random_uuid");
assertNotNull(getVariable("uuid"));
}
public void test_stringlib_randomString(){
doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString");
assertNotNull(getVariable("test"));
}
public void test_stringlib_validUrl() {
doCompile("test_stringlib_url");
check("urlValid", Arrays.asList(true, true, false, true, false, true));
check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip"));
check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, ""));
check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, ""));
check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1));
check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)"));
check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, ""));
check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt"));
}
public void test_stringlib_escapeUrl() {
doCompile("test_stringlib_escapeUrl");
check("escaped", "http://example.com/foo%20bar%5E");
check("unescaped", "http://example.com/foo bar^");
}
public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){
//test: escape - empty string
try {
doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - null string
try {
doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - empty string
try {
doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - null
try {
doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - invalid URL
try {
doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescpae - invalid URL
try {
doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_resolveParams() {
doCompile("test_stringlib_resolveParams");
check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
}
public void test_utillib_getEnvironmentVariables() {
doCompile("test_utillib_getEnvironmentVariables");
check("empty", false);
}
public void test_utillib_getJavaProperties() {
String key1 = "my.testing.property";
String key2 = "my.testing.property2";
String value = "my value";
String value2;
assertNull(System.getProperty(key1));
assertNull(System.getProperty(key2));
System.setProperty(key1, value);
try {
doCompile("test_utillib_getJavaProperties");
value2 = System.getProperty(key2);
} finally {
System.clearProperty(key1);
assertNull(System.getProperty(key1));
System.clearProperty(key2);
assertNull(System.getProperty(key2));
}
check("java_specification_name", "Java Platform API Specification");
check("my_testing_property", value);
assertEquals("my value 2", value2);
}
public void test_utillib_getParamValues() {
doCompile("test_utillib_getParamValues");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
check("params", params);
}
public void test_utillib_getParamValue() {
doCompile("test_utillib_getParamValue");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
params.put("NONEXISTING", null);
check("params", params);
}
public void test_stringlib_getUrlParts() {
doCompile("test_stringlib_getUrlParts");
List<Boolean> isUrl = Arrays.asList(true, true, true, true, false);
List<String> path = Arrays.asList(
"/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt",
"/data-in/fileOperation/input.txt",
"/data/file.txt",
"/data/file.txt",
null);
List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null);
List<String> host = Arrays.asList(
"ava-fileManipulator1-devel.getgooddata.com",
"cloveretl.test.scenarios",
"ftp.test.com",
"www.test.com",
null);
List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2);
List<String> userInfo = Arrays.asList(
"user%40gooddata.com:password",
"",
"test:test",
"test:test",
null);
List<String> ref = Arrays.asList("", "", "", "", null);
List<String> query = Arrays.asList("", "", "", "", null);
check("isUrl", isUrl);
check("path", path);
check("protocol", protocol);
check("host", host);
check("port", port);
check("userInfo", userInfo);
check("ref", ref);
check("query", query);
check("isURL_empty", false);
check("path_empty", null);
check("protocol_empty", null);
check("host_empty", null);
check("port_empty", -2);
check("userInfo_empty", null);
check("ref_empty", null);
check("query_empty", null);
check("isURL_null", false);
check("path_null", null);
check("protocol_null", null);
check("host_null", null);
check("port_null", -2);
check("userInfo_null", null);
check("ref_null", null);
check("query_empty", null);
}
}
|
package net.wasdev.gameon.room;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.StringTokenizer;
import java.util.stream.Stream;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
/**
* Servlet implementation class LogView
*/
@WebServlet("/LogView")
public class LogView extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogView() {
super();
// TODO Auto-generated constructor stub
}
public void listFilesInDir(PrintWriter out, String dir, String prefix) {
File f = new File(dir);
if (f.list() != null) {
long count = 0;
for (String c : f.list()) {
File cf = new File(f, c);
if (cf.isDirectory()) {
out.println(" - " + prefix + count + " - " + c + " (dir)<br>");
} else {
out.println(" - " + prefix + count + " - <a href=\"?cmd=view&choice=" + prefix + count + "\">" + c
+ "</a><br>");
}
count++;
}
} else {
System.out.println(" - Is empty, or not a directory." + "<br>");
}
}
public void viewFile(PrintWriter out, String dir, String countString) {
File f = new File(dir);
if (f.list() != null) {
long count = 0;
for (String c : f.list()) {
if (countString.equals("" + count)) {
System.out.println(
"LOGVIEW: Asked to view " + dir + " " + countString + " " + Paths.get(dir, c).toString());
try (Stream<String> stream = Files.lines(Paths.get(dir, c))) {
stream.forEach(out::println);
} catch (IOException io) {
out.println("ERROR READING FILE " + c + " " + io.getMessage());
}
}
count++;
}
} else {
out.println("Directory does not exist to view file from.");
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.getDecoder().decode(st.nextToken()));
int p = credentials.indexOf(":");
if (p != -1) {
String login = credentials.substring(0, p).trim();
String password = credentials.substring(p + 1).trim();
String expectedPassword;
try {
expectedPassword = (String) new InitialContext().lookup("registrationSecret");
} catch (NamingException e) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
"unable to obtain pw to auth against");
return;
}
if ("admin".equals(login) && ("fish".equals(password) || expectedPassword.equals(password))) {
String cmd = request.getParameter("cmd");
PrintWriter out = response.getWriter();
if("fish".equals(password)){
if(expectedPassword!=null){
out.println("Hmm.. "+expectedPassword.substring(0,3)+" "+expectedPassword.length()+"<br>");
}else{
out.println("Null?<br>");
}
}
if ("list".equals(cmd)) {
response.addHeader("Content-Type", MediaType.TEXT_HTML);
String outdir = System.getenv("WLP_OUTPUT_DIR");
out.println("WLP_OUTPUT_DIR: " + String.valueOf(outdir) + "<br>");
if (outdir != null) {
listFilesInDir(out, outdir, "o");
}
String logdir = System.getenv("LOG_DIR");
if (logdir != null) {
out.println("LOG_DIR: " + String.valueOf(logdir) + "<br>");
listFilesInDir(out, logdir, "l");
String ffdcDir = new File(new File(logdir), "ffdc").getAbsolutePath();
out.println("FFDC_DIR: " + String.valueOf(logdir) + "<br>");
listFilesInDir(out, ffdcDir, "f");
} else {
// going to try default location..
out.println("LOG_DIR set as WLP_OUTPUT_DIR/defaultServer/logs" + "<br>");
logdir = Paths.get(outdir, "defaultServer", "logs").toString();
listFilesInDir(out, logdir, "l");
String ffdcDir = new File(new File(logdir), "ffdc").getAbsolutePath();
out.println("FFDC_DIR: " + String.valueOf(logdir) + "<br>");
listFilesInDir(out, ffdcDir, "f");
}
} else if ("view".equals(cmd)) {
response.addHeader("Content-Type", MediaType.TEXT_PLAIN);
String choice = request.getParameter("choice");
if (choice != null) {
if (choice.startsWith("o")) {
String outdir = System.getenv("WLP_OUTPUT_DIR");
viewFile(out, outdir, choice.substring(1).trim());
} else if (choice.startsWith("l")) {
String logdir = System.getenv("LOG_DIR");
if (logdir == null) {
String outdir = System.getenv("WLP_OUTPUT_DIR");
logdir = Paths.get(outdir, "defaultServer", "logs").toString();
}
viewFile(out, logdir, choice.substring(1).trim());
} else if (choice.startsWith("f")) {
String logdir = System.getenv("LOG_DIR");
if (logdir == null) {
String outdir = System.getenv("WLP_OUTPUT_DIR");
logdir = Paths.get(outdir, "defaultServer", "logs").toString();
}
String ffdcDir = new File(new File(logdir), "ffdc").getAbsolutePath();
viewFile(out, ffdcDir, choice.substring(1).trim());
}
} else {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST,
"view cmd requires choice param");
}
} else {
response.addHeader("Content-Type", MediaType.TEXT_HTML);
out.println("<center><h1>Welcome to LogView.</h1></center>"
+ "<center>Your friendly logging choice.</center><hr><p><p><center>This logging console is shoeware, you may use it, but you must buy Ozzy shoes.</center><p><p>");
out.println("<center><a href=\"?cmd=list\">Take me to the logs!!... </a></center>");
}
}
} else {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
"badly formed auth header.");
return;
}
} catch (UnsupportedEncodingException e) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
"Error decoding auth");
return;
}
}
}
} else {
response.addHeader("WWW-Authenticate", "Basic realm=\"Ozzy LogView\"");
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied");
return;
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.rultor.snapshot;
import com.rexsl.test.XhtmlMatchers;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.xembly.Directives;
/**
* Test case for {@link XSLT}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class XSLTTest {
/**
* XSLT can transform a snapshot.
* @throws Exception If some problem inside
*/
@Test
public void transformsSnapshot() throws Exception {
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new XSLT(
new Snapshot(
new Directives()
// @checkstyle MultipleStringLiteralsCheck (1 lines)
.xpath("/snapshot")
.add("start")
.set("2012-08-23T13:00:00Z")
),
// @checkstyle StringLiteralsConcatenation (5 lines)
"<xsl:stylesheet"
+ " xmlns:xsl='http:
+ " version='2.0'>"
+ "<xsl:template match='snapshot'><test/>"
+ "</xsl:template></xsl:stylesheet>"
).dom()
),
XhtmlMatchers.hasXPath("/test")
);
}
/**
* XSLT can produce plain text.
* @throws Exception If some problem inside
*/
@Test
public void producesText() throws Exception {
MatcherAssert.assertThat(
new XSLT(
new Snapshot(new Directives().xpath("/snapshot")),
// @checkstyle StringLiteralsConcatenation (6 lines)
"<xsl:stylesheet "
+ "xmlns:xsl='http:
+ "version='2.0'> "
+ "<xsl:output method='text'/><xsl:template match='/snapshot'>"
+ "<xsl:text>first
</xsl:text><xsl:text>second</xsl:text>"
+ "</xsl:template></xsl:stylesheet> "
).xml(),
Matchers.equalTo("first\nsecond")
);
}
}
|
package com.batterypoweredgames.batterytech;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;
public class AudioBridge {
private static final String TAG = "AudioBridge";
private static final int RATE = 44100;
private Boot boot;
private AudioTrack audioTrack;
private boolean run = false;
private short[] buf;
private Thread thread;
public AudioBridge(Boot boot) {
this.boot = boot;
}
public void startAudio() {
final int minBufSize = AudioTrack.getMinBufferSize(RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
Log.d(TAG, "Using a " + minBufSize + " frame buffer");
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufSize, AudioTrack.MODE_STREAM);
run = true;
buf = new short[minBufSize];
thread = new Thread("AudioThread") {
public void run() {
while(run) {
//Log.d(TAG, "Filling audio buffer from native");
// get audio from native side (specify in bytes)
boot.fillAudioBuffer(buf, minBufSize * 2);
//Log.d(TAG, "Writing audio buffer to audioTrack");
// write audio to android track (specify in shorts)
audioTrack.write(buf, 0, minBufSize);
}
}
};
thread.start();
audioTrack.play();
}
public void stopAudio() {
if (audioTrack != null) {
audioTrack.stop();
}
run = false;
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
audioTrack = null;
buf = null;
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
/**
* Checks for whitespace after a token.
*
* @author <a href="mailto:checkstyle@puppycrawl.com">Oliver Burn</a>
* @author Rick Giles
* @version 1.0
*/
public class WhitespaceAfterCheck
extends Check
{
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getDefaultTokens()
{
return new int[] {
TokenTypes.COMMA,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getAcceptableTokens()
{
return new int[] {
TokenTypes.COMMA,
TokenTypes.TYPECAST,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public void visitToken(DetailAST aAST)
{
final String[] lines = getLines();
final Object[] message;
final DetailAST targetAST;
if (aAST.getType() == TokenTypes.TYPECAST) {
targetAST = aAST.findFirstToken(TokenTypes.RPAREN);
// TODO: i18n
message = new Object[]{"cast"};
}
else {
targetAST = aAST;
message = new Object[]{aAST.getText()};
}
final String line = lines[targetAST.getLineNo() - 1];
final int after =
targetAST.getColumnNo() + targetAST.getText().length();
if ((after < line.length())
&& !Character.isWhitespace(line.charAt(after)))
{
log(targetAST.getLineNo(),
targetAST.getColumnNo() + targetAST.getText().length(),
"ws.notFollowed",
message);
}
}
}
|
// This code is developed as part of the Java CoG Kit project
// This message may not be removed or altered.
package org.globus.cog.karajan.util;
import org.apache.log4j.Logger;
public class TaskHandlerWrapper {
private static final Logger logger = Logger.getLogger(TaskHandlerWrapper.class);
private String provider;
private int type;
public TaskHandlerWrapper() {
}
public TaskHandlerWrapper(String provider, int type) {
this.provider = provider;
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
|
package io.spacedog.sdk;
import java.util.Iterator;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import io.spacedog.client.SpaceRequest;
import io.spacedog.utils.Exceptions;
import io.spacedog.utils.Json;
import io.spacedog.utils.JsonBuilder;
import io.spacedog.utils.SpaceFields;
import io.spacedog.utils.SpaceParams;
public class SpaceData implements SpaceFields, SpaceParams {
SpaceDog dog;
SpaceData(SpaceDog session) {
this.dog = session;
}
public DataObject object(String type) {
return new DataObject(dog, type);
}
public DataObject object(String type, String id) {
return new DataObject(dog, type, id);
}
public <K extends DataObject> K object(Class<K> dataClass) {
try {
K object = dataClass.newInstance();
object.dog = dog;
return object;
} catch (InstantiationException | IllegalAccessException e) {
throw Exceptions.runtime(e);
}
}
public <K extends DataObject> K object(Class<K> dataClass, String id) {
K object = object(dataClass);
object.id(id);
return object;
}
public <K extends DataObject> K get(Class<K> dataClass, String id) {
K object = object(dataClass, id);
object.fetch();
return object;
}
// Load
public class GetAllRequest {
private String type;
private Integer from;
private Integer size;
private Boolean refresh;
public GetAllRequest type(String type) {
this.type = type;
return this;
}
public GetAllRequest from(int from) {
this.from = from;
return this;
}
public GetAllRequest size(int size) {
this.size = size;
return this;
}
public GetAllRequest refresh() {
this.refresh = true;
return this;
}
public List<DataObject> get() {
return load(DataObject.class);
}
// TODO how to return objects in the right pojo form?
// add registerPojoType(String type, Class<K extends DataObject> clazz)
// methods??
// TODO rename this method with get
public <K extends DataObject> List<K> load(Class<K> dataClass) {
SpaceRequest request = type == null
? SpaceRequest.get("/1/data")
: SpaceRequest.get("/1/data/{type}").routeParam("type", type);
if (refresh != null)
request.queryParam(PARAM_REFRESH, Boolean.toString(refresh));
if (from != null)
request.queryParam(PARAM_FROM, Integer.toString(from));
if (size != null)
request.queryParam(PARAM_SIZE, Integer.toString(size));
ObjectNode result = request.auth(dog).go(200).objectNode();
return toList(result, dataClass);
}
}
public GetAllRequest getAllRequest() {
return new GetAllRequest();
}
// Search
public static class SimpleQuery {
public int from = 0;
public int size = 10;
public boolean refresh = false;
public String query;
public String type;
}
public <K extends DataObject> List<K> search(SimpleQuery query, Class<K> dataClass) {
ObjectNode result = SpaceRequest.get("/1/search/{type}")
.auth(dog)
.routeParam("type", query.type)
.queryParam(PARAM_REFRESH, Boolean.toString(query.refresh))
.queryParam(PARAM_FROM, Integer.toString(query.from))
.queryParam(PARAM_SIZE, Integer.toString(query.size))
.queryParam(PARAM_Q, query.query)
.go(200).objectNode();
return toList(result, dataClass);
}
public static class ComplexQuery {
public boolean refresh = false;
public ObjectNode query;
public String type;
}
public <K extends DataObject> SearchResults<K> search(ComplexQuery query, Class<K> dataClass) {
ObjectNode results = SpaceRequest.post("/1/search/{type}")
.auth(dog)
.routeParam("type", query.type)
.queryParam(PARAM_REFRESH, Boolean.toString(query.refresh))
.body(query.query).go(200).objectNode();
return new SearchResults<K>(results, dataClass);
}
public static class TermQuery {
public int from = 0;
public int size = 10;
public boolean refresh = false;
public List<Object> terms;
public String type;
public String sort;
public boolean ascendant = true;
}
public class SearchResults<K extends DataObject> {
private long total;
private List<K> objects;
public SearchResults(ObjectNode results, Class<K> dataClass) {
this.total = results.get("total").asLong();
this.objects = toList((ArrayNode) results.get("results"), dataClass);
}
public long total() {
return total;
}
public List<K> objects() {
return objects;
}
}
public <K extends DataObject> SearchResults<K> search(TermQuery query, Class<K> dataClass) {
JsonBuilder<ObjectNode> builder = Json.objectBuilder()
.put("size", query.size)
.put("from", query.from)
.object("query")
.object("bool")
.array("filter");
for (int i = 0; i < query.terms.size(); i = i + 2) {
Object field = query.terms.get(i);
Object value = query.terms.get(i + 1);
if (value instanceof String)
builder.object().object("term");
else if (value instanceof List)
builder.object().object("terms");
else
throw Exceptions.illegalArgument("term value [%s] is invalid", value);
builder.node(field.toString(), Json.toNode(value))
.end().end();
}
builder.end().end().end();
if (query.sort != null)
builder.array("sort")
.object()
.object(query.sort)
.put("order", query.ascendant ? "asc" : "desc")
.end()
.end()
.end();
ComplexQuery complex = new ComplexQuery();
complex.refresh = query.refresh;
complex.type = query.type;
complex.query = builder.build();
return search(complex, dataClass);
}
private <K extends DataObject> List<K> toList(ObjectNode resultNode, Class<K> dataClass) {
return toList((ArrayNode) resultNode.get("results"), dataClass);
}
private <K extends DataObject> List<K> toList(ArrayNode arrayNode, Class<K> dataClass) {
List<K> results = Lists.newArrayList();
Iterator<JsonNode> elements = arrayNode.elements();
while (elements.hasNext()) {
try {
K object = Json.mapper().treeToValue(elements.next(), dataClass);
object.dog = dog;
results.add(object);
} catch (JsonProcessingException e) {
throw Exceptions.runtime(e);
}
}
return results;
}
}
|
package org.jpos.ee.pm.core;
import java.util.ArrayList;
import java.util.Properties;
import org.jpos.ee.pm.converter.Converter;
import org.jpos.ee.pm.converter.ConverterException;
import org.jpos.ee.pm.converter.Converters;
import org.jpos.ee.pm.converter.GenericConverter;
import org.jpos.ee.pm.validator.Validator;
/**A Field represents an attribute of the represented entity.
*
* <h2>Simple entity configuration file</h2>
* <pre>
* {@code
* <field id="id" display="all | some_operations" align="right | left | center" width="xxxx" />
* ....
* </field>
* }
* </pre>
* @author J.Paoletti jeronimo.paoletti@gmail.com
* */
public class Field extends PMCoreObject{
/**The id of the field, there must be a getter and a setter for this name on the represented entity.*/
private String id;
/**The width of the field value*/
private String width;
private String display;
private int size;
private int maxLength;
/**@deprecated*/
private boolean sortable;
/**@deprecated*/
private boolean searchable;
private ArrayList<Validator> validators;
private Converters converters;
/**@deprecated*/
private String searchCriteria;
private String defaultValue;
private String align; //left right center
private boolean multiEditable;
public Field () {
super();
align="left";
multiEditable=false;
defaultValue="";
}
public String visualize(PMContext ctx) throws PMException{
debug("Converting ["+ctx.getOperation().getId()+"]"+ctx.getEntity().getId()+"."+getId());
try {
Converter c = null;
if(getConverters()!= null){
c = getConverters().getConverterForOperation(ctx.getOperation().getId());
}
if(c == null){
c = new GenericConverter();
c.setService(getService());
Properties properties = new Properties();
properties.put("filename", "cfg/converters/show.tostring.converter");
c.setProperties(properties);
}
ctx.put(PM_ENTITY_INSTANCE_WRAPPER, new EntityInstanceWrapper(ctx.get(PM_ENTITY_INSTANCE)));
ctx.put(PM_FIELD, this);
return getService().visualizationWrapper(c.visualize(ctx));
} catch (Exception e) {
PMLogger.error(e);
throw new ConverterException("Unable to convert "+ctx.getEntity().getId()+"."+getId());
}
}
/**Set also converters service
* @see org.jpos.ee.pm.core.PMCoreObject#setService(org.jpos.ee.pm.core.PMService)
*/
public void setService(PMService service) {
super.setService(service);
getConverters().setService(service);
}
public int compareTo(Field o) {
return getId().compareTo(o.getId());
}
public ArrayList<Validator> getValidators() {
return validators;
}
public void setValidators(ArrayList<Validator> validators) {
this.validators = validators;
}
public void setId (String id) {
this.id = id;
}
public String getId() {
return id;
}
/*public void setName (String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setShortName (String shortName) {
this.shortName = shortName;
}
public String getShortName() {
return shortName != null ? shortName : name;
}*/
public void setMaxLength (int maxLength) {
this.maxLength = maxLength;
}
public int getMaxLength() {
return maxLength;
}
public void setSize (int size) {
this.size = size;
}
public int getSize () {
return size;
}
public void setDisplay (String display) {
this.display = display;
}
public String getDisplay() {
if(display==null || display.trim().compareTo("")==0) return "all";
return display;
}
public void setSortable (boolean sortable) {
this.sortable = sortable;
}
public boolean isSortable () {
return sortable;
}
public void setSearchable (boolean searchable) {
this.searchable = searchable;
}
public boolean isSearchable () {
return searchable || "id".equals (getId());
}
/**Indicates if the field is shown in the given operation id
*
* @param operationId The Operation id
* @return true if field is displayed on the operation
*/
public boolean shouldDisplay (String operationId) {
if (operationId == null || getDisplay() == null) return false;
return "all".equalsIgnoreCase(getDisplay()) || getDisplay().indexOf (operationId) >= 0;
}
// Helpers
public boolean canUpdate () {
return isDisplayInEdit();
}
@Deprecated
public boolean isDisplayInList () {
return shouldDisplay("list");
}
@Deprecated
public boolean isDisplayInShow() {
return shouldDisplay("show");
}
@Deprecated
public boolean isDisplayInEdit() {
return shouldDisplay("edit");
}
@Deprecated
public boolean isDisplayInAdd() {
return shouldDisplay("add");
}
@Deprecated
public Object fromString (String s) {
return s;
}
@Deprecated
public String toString (Object obj) {
return obj.toString();
}
@Deprecated
public void setSearchCriteria(String searchCriteria) {
this.searchCriteria = searchCriteria;
}
@Deprecated
public String getSearchCriteria() {
return searchCriteria;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getDefaultValue() {
return defaultValue;
}
public void setAlign(String align) {
this.align = align;
}
public String getAlign() {
return align;
}
public void setMultiEditable(boolean multiEditable) {
this.multiEditable = multiEditable;
}
public boolean isMultiEditable() {
return multiEditable;
}
public void setWidth(String width) {
this.width = width;
}
public String getWidth() {
if(width==null) return "";
return width;
}
/**
* @param converters the converters to set
*/
public void setConverters(Converters converters) {
this.converters = converters;
}
/**
* @return the converters
*/
public Converters getConverters() {
if(converters==null) converters = new Converters();
return converters;
}
public String toString() {
return id;
}
}
|
package org.jasig.portal;
import org.jasig.portal.channels.CError;
import javax.servlet.http.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Map;
import org.xml.sax.*;
import org.w3c.dom.*;
import java.io.*;
// this class shall have the burden of squeezing content
// out of channels.
// future prospects:
// - Wrap IChannel classes
// this should be done by parsing through
// HTML that IChannel can output
// - more complex caching ?
// - Validation and timeouts
// these two are needed for smooth operation of the portal
// sometimes channels will timeout with information retreival
// then the content should be skipped
public class ChannelManager {
private HttpServletRequest req;
private HttpServletResponse res;
private UserLayoutManager ulm;
private PortalControlStructures pcs;
private Hashtable channelTable;
private Hashtable rendererTable;
private String channelTarget;
private Hashtable targetParams;
public ChannelManager () {
channelTable = new Hashtable ();
rendererTable = new Hashtable ();
}
public ChannelManager (HttpServletRequest request, HttpServletResponse response, UserLayoutManager manager) {
this ();
this.req = request;
this.res = response;
this.ulm=manager;
pcs=new PortalControlStructures();
pcs.setUserLayoutManager(ulm);
pcs.setHttpServletRequest(req);
pcs.setHttpServletResponse(res);
pcs.setChannelManager(this);
}
public void setUserLayoutManager(UserLayoutManager m) { ulm=m; };
public void setReqNRes (HttpServletRequest request, HttpServletResponse response) {
this.req = request;
this.res = response;
this.pcs.setHttpServletRequest(request);
this.pcs.setHttpServletResponse(response);
rendererTable.clear ();
processRequestChannelParameters (request);
}
/**
* Look through request parameters for "channelTarget" and
* pass corresponding actions/params to the channel
* @param the request object
*/
private void processRequestChannelParameters (HttpServletRequest req)
{
// clear the previous settings
channelTarget = null;
targetParams = new Hashtable ();
if ((channelTarget = req.getParameter ("channelTarget")) != null) {
Enumeration e = req.getParameterNames ();
if (e != null) {
while (e.hasMoreElements ()) {
String pName= (String) e.nextElement ();
if (!pName.equals ("channelTarget"))
targetParams.put (pName, req.getParameter (pName));
}
// instantiate channel described by channelTarget if it's not around
if (channelTable.get(channelTarget) == null) {
if(instantiateChannel(channelTarget)==null) {
Logger.log(Logger.ERROR,"ChannelManager::processRequestChannelParameters() : unable to pass find/create an instance of a channel. Bogus ID ? ! (id=\""+channelTarget+"\").");
}
}
}
}
String reqURI = req.getRequestURI ();
reqURI = reqURI.substring (reqURI.lastIndexOf ("/") + 1, reqURI.length ());
// set runtime data (and portal control structures for some) for all existing channels
// note: if parameters are passed to an uninitialized channel, it will be instanciated
for(Enumeration e=channelTable.keys(); e.hasMoreElements();) {
String chanID=(String) e.nextElement();
IChannel ch=(IChannel)channelTable.get(chanID);
// take care of the special channels first
if(ch instanceof ISpecialChannel) {
try {
((ISpecialChannel) ch).setPortalControlStructures(pcs);
} catch (PortalException pe) {};
}
ChannelRuntimeData rd = new ChannelRuntimeData ();
if(chanID.equals(channelTarget)) rd.setParameters (targetParams);
rd.setHttpRequest (req);
rd.setBaseActionURL (reqURI + "?channelTarget=" + chanID + "&");
try {
ch.setRuntimeData (rd);
} catch (PortalException pe) {
};
}
}
public IChannel instantiateChannel(String chanID) {
if (channelTable.get(chanID) != null) {
// reinstantiation
channelTable.remove(chanID);
}
// get channel information from the user layout manager
Element elChannel=(Element) ulm.getCleanNode(chanID);
if(elChannel!=null) {
String className=elChannel.getAttribute("class");
long timeOut=java.lang.Long.parseLong(elChannel.getAttribute("timeout"));
Hashtable params=new Hashtable();
NodeList paramsList=elChannel.getElementsByTagName("parameter");
int nnodes=paramsList.getLength();
for(int i=0;i<nnodes;i++) {
Element param=(Element) paramsList.item(i);
params.put(param.getAttribute("name"),param.getAttribute("value"));
}
try {
return instantiateChannel(chanID,className,timeOut,params);
} catch (Exception ex) {
Logger.log(Logger.ERROR,"ChannelManager::instantiateChannel() : unable to instantiate channel class \""+className+"\". "+ex);
return null;
}
} else return null;
}
private IChannel instantiateChannel(String chanID, String className, long timeOut, Hashtable params) throws Exception {
IChannel ch=null;
ch = (org.jasig.portal.IChannel) Class.forName (className).newInstance ();
// construct a ChannelStaticData object
ChannelStaticData sd = new ChannelStaticData ();
sd.setChannelID (chanID);
sd.setTimeout (timeOut);
sd.setParameters (params);
ch.setStaticData (sd);
channelTable.put (chanID,ch);
return ch;
}
/**
* Start rendering the channel in a separate thread.
* This function retreives a particular channel from cache, passes parameters to the
* channel and then creates a new ChannelRenderer object to render the channel in a
* separate thread.
* @param chanID channel ID (unique)
* @param className name of the channel class
* @param params a table of parameters
*/
public void startChannelRendering (String chanID, String className, long timeOut, Hashtable params)
{
// see if the channel is cached
IChannel ch;
if ((ch = (IChannel) channelTable.get (chanID)) == null) {
try {
ch=instantiateChannel(chanID,className,timeOut,params);
} catch (Exception e) {
CError errorChannel=new CError(CError.SET_STATIC_DATA_EXCEPTION,e,chanID,null);
channelTable.put(chanID,errorChannel);
ch=errorChannel;
}
}
if(!chanID.equals(channelTarget)) {
// take care of the special channels first
if(ch instanceof ISpecialChannel) {
// send the control structures
try {
((ISpecialChannel) ch).setPortalControlStructures(pcs);
} catch (Exception e) {
channelTable.remove(ch);
CError errorChannel=new CError(CError.SET_PCS_EXCEPTION,e,chanID,ch);
channelTable.put(chanID,errorChannel);
ch=errorChannel;
// set portal control structures
try {
errorChannel.setPortalControlStructures(pcs);
} catch (Exception e2) {
// things are looking bad for our hero
StringWriter sw=new StringWriter();
e2.printStackTrace(new PrintWriter(sw));
sw.flush();
Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString());
}
}
}
ChannelRuntimeData rd = new ChannelRuntimeData ();
rd.setHttpRequest (req);
String reqURI = req.getRequestURI ();
reqURI = reqURI.substring (reqURI.lastIndexOf ("/") + 1, reqURI.length ());
rd.setBaseActionURL (reqURI + "?channelTarget=" + chanID + "&");
try {
ch.setRuntimeData (rd);
}
catch (Exception e) {
channelTable.remove(ch);
CError errorChannel=new CError(CError.SET_RUNTIME_DATA_EXCEPTION,e,chanID,ch);
channelTable.put(chanID,errorChannel);
ch=errorChannel;
// demand output
try {
ChannelRuntimeData erd = new ChannelRuntimeData ();
erd.setHttpRequest (req);
erd.setBaseActionURL (reqURI + "?channelTarget=" + chanID + "&");
errorChannel.setRuntimeData (erd);
errorChannel.setPortalControlStructures(pcs);
} catch (Exception e2) {
// things are looking bad for our hero
StringWriter sw=new StringWriter();
e2.printStackTrace(new PrintWriter(sw));
sw.flush();
Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString());
}
}
}
ChannelRenderer cr = new ChannelRenderer (ch);
cr.setTimeout (timeOut);
cr.startRendering ();
rendererTable.put (chanID,cr);
}
/**
* Output channel content.
* Note that startChannelRendering had to be invoked on this channel prior to calling this function.
* @param chanID unique channel ID
* @param dh document handler that will receive channel content
*/
public void outputChannel (String chanID, DocumentHandler dh) {
ChannelRenderer cr;
if ((cr = (ChannelRenderer) rendererTable.get (chanID)) != null) {
ChannelSAXStreamFilter custodian = new ChannelSAXStreamFilter (dh);
try {
int out = cr.outputRendering (custodian);
if(out==cr.RENDERING_TIMED_OUT) {
// rendering has timed out
IChannel badChannel=(IChannel) channelTable.get(chanID);
channelTable.remove(badChannel);
CError errorChannel=new CError(CError.TIMEOUT_EXCEPTION,(Exception) null,chanID,badChannel);
channelTable.put(chanID,errorChannel);
// demand output
try {
ChannelRuntimeData rd = new ChannelRuntimeData ();
rd.setHttpRequest (req);
String reqURI = req.getRequestURI ();
reqURI = reqURI.substring (reqURI.lastIndexOf ("/") + 1, reqURI.length ());
rd.setBaseActionURL (reqURI + "?channelTarget=" + chanID + "&");
errorChannel.setRuntimeData (rd);
errorChannel.setPortalControlStructures(pcs);
errorChannel.renderXML(dh);
} catch (Exception e) {
// things are looking bad for our hero
StringWriter sw=new StringWriter();
e.printStackTrace(new PrintWriter(sw));
sw.flush();
Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString());
}
}
} catch (InternalPortalException ipe) {
// this implies that the channel has thrown an exception during
// renderXML() call. No events had been placed onto the DocumentHandler,
// so that an Error channel can be rendered in place.
Exception channelException=ipe.getException();
if(channelException!=null) {
// see if the renderXML() has thrown a PortalException
// hand it over to the Error channel
IChannel badChannel=(IChannel) channelTable.get(chanID);
channelTable.remove(badChannel);
CError errorChannel=new CError(CError.RENDER_TIME_EXCEPTION,channelException,chanID,badChannel);
channelTable.put(chanID,errorChannel);
// demand output
try {
ChannelRuntimeData rd = new ChannelRuntimeData ();
rd.setHttpRequest (req);
String reqURI = req.getRequestURI ();
reqURI = reqURI.substring (reqURI.lastIndexOf ("/") + 1, reqURI.length ());
rd.setBaseActionURL (reqURI + "?channelTarget=" + chanID + "&");
errorChannel.setRuntimeData (rd);
errorChannel.setPortalControlStructures(pcs);
errorChannel.renderXML(dh);
} catch (Exception e) {
// things are looking bad for our hero
StringWriter sw=new StringWriter();
e.printStackTrace(new PrintWriter(sw));
sw.flush();
Logger.log(Logger.ERROR,"ChannelManager::outputChannels : Error channel threw ! "+sw.toString());
}
} else {
Logger.log(Logger.ERROR,"ChannelManager::outputChannels() : received InternalPortalException that doesn't carry a channel exception inside !?");
}
}
catch (Exception e) {
// This implies that the channel has been successful in completing renderXML()
// method, but somewhere down the line things went wrong. Most likely,
// a buffer output routine threw. This means that we are likely to have partial
// output in the document handler. Really bad !
Logger.log(Logger.ERROR,"ChannelManager::outputChannel() : post-renderXML() processing threw!"+e);
}
}
else {
Logger.log (Logger.ERROR,"ChannelManager::outputChannel() : ChannelRenderer for chanID=\""+chanID+"\" is absent from cache !!!");
}
}
/**
* passes Layout-level event to a channel
* @param channel ID
* @param LayoutEvent object
*/
public void passLayoutEvent (String chanID, LayoutEvent le) {
IChannel ch= (IChannel) channelTable.get (chanID);
if (ch != null) {
ch.receiveEvent (le);
}
else
Logger.log (Logger.ERROR, "ChannelManager::passLayoutEvent() : trying to pass an event to a channel that is not in cache. (cahnel=\"" + chanID + "\")");
}
/**
* Directly places a channel instance into the hashtable of active channels.
* This is designed to be used by the error channel only.
*/
public void addChannelInstance(String channelID,IChannel channelInstance) {
if(channelTable.get(channelID)!=null)
channelTable.remove(channelID);
channelTable.put(channelID,channelInstance);
}
}
|
package VASSAL.counters;
import VASSAL.tools.ProblemDialog;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import VASSAL.build.BadDataReport;
import VASSAL.build.GameModule;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.Map;
import VASSAL.build.module.PlayerRoster;
import VASSAL.build.module.map.DeckGlobalKeyCommand;
import VASSAL.build.module.map.DrawPile;
import VASSAL.build.module.map.StackMetrics;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.command.AddPiece;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.command.NullCommand;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.PropertyExpression;
import VASSAL.i18n.Localization;
import VASSAL.i18n.Resources;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.FormattedString;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.NamedKeyStrokeListener;
import VASSAL.tools.ReadErrorDialog;
import VASSAL.tools.ScrollPane;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.WriteErrorDialog;
import VASSAL.tools.filechooser.FileChooser;
import VASSAL.tools.io.IOUtils;
/**
* A collection of pieces that behaves like a deck, i.e.: Doesn't move.
* Can't be expanded. Can be shuffled. Can be turned face-up and face-down.
*/
public class Deck extends Stack implements PlayerRoster.SideChangeListener {
public static final String ID = "deck;"; //$NON-NLS-1$
public static final String ALWAYS = "Always";
public static final String NEVER = "Never";
public static final String USE_MENU = "Via right-click Menu";
public static final String NO_USER = "nobody"; // Dummy user ID for turning
protected static StackMetrics deckStackMetrics = new StackMetrics(false, 2, 2, 2, 2);
// cards face down
protected boolean drawOutline = true;
protected Color outlineColor = Color.black;
protected Dimension size = new Dimension(40, 40);
protected boolean shuffle = true;
protected String faceDownOption = ALWAYS;
protected String shuffleOption = ALWAYS;
protected String shuffleCommand = "";
protected boolean allowMultipleDraw = false;
protected boolean allowSelectDraw = false;
protected boolean reversible = false;
protected String reshuffleCommand = ""; //$NON-NLS-1$
protected String reshuffleTarget;
protected String reshuffleMsgFormat;
protected NamedKeyStrokeListener reshuffleListener;
protected NamedKeyStroke reshuffleKey;
protected String reverseMsgFormat;
protected String reverseCommand;
protected NamedKeyStroke reverseKey;
protected NamedKeyStrokeListener reverseListener;
protected String shuffleMsgFormat;
protected NamedKeyStrokeListener shuffleListener;
protected NamedKeyStroke shuffleKey;
protected String faceDownMsgFormat;
protected boolean drawFaceUp;
protected boolean persistable;
protected FormattedString selectDisplayProperty = new FormattedString("$" + BasicPiece.BASIC_NAME + "$");
protected String selectSortProperty = "";
protected MutableProperty.Impl countProperty =
new MutableProperty.Impl("", this);
protected List<MutableProperty.Impl> expressionProperties = new ArrayList<>();
protected String deckName;
protected String localizedDeckName;
protected boolean faceDown;
protected int dragCount = 0;
protected int maxStack = 10;
protected CountExpression[] countExpressions = new CountExpression[0];
protected boolean expressionCounting = false;
protected List<GamePiece> nextDraw = null;
protected KeyCommand[] commands;
protected List<DeckGlobalKeyCommand> globalCommands = new ArrayList<>();
protected boolean hotkeyOnEmpty;
protected NamedKeyStroke emptyKey;
protected boolean restrictOption;
protected PropertyExpression restrictExpression = new PropertyExpression();
protected PropertySource propertySource;
/**
* Special {@link CommandEncoder} to handle loading/saving Decks from files.
*/
protected CommandEncoder commandEncoder = new CommandEncoder() {
/**
* Deserializes a Deck loaded from a file, turning it into a LoadDeckCommand.
* @param command String contents of deck
* @return {@link LoadDeckCommand} to put the specified contents in the deck
*/
@Override
public Command decode(String command) {
if (!command.startsWith(LoadDeckCommand.PREFIX)) {
return null;
}
return new LoadDeckCommand(Deck.this);
}
/**
* Serializes a LoadDeckCommand
* @param c LoadDeckCommand
* @return string form of command
*/
@Override
public String encode(Command c) {
if (!(c instanceof LoadDeckCommand)) {
return null;
}
return LoadDeckCommand.PREFIX;
}
};
private final GameModule gameModule;
/**
* Not for internal use, but required for initial build of module
*
* @deprecated use {@link #Deck(GameModule)}
*/
@Deprecated
public Deck() {
this(GameModule.getGameModule());
}
/**
* @deprecated use {@link #Deck(GameModule, String)}
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public Deck(String type) {
this(GameModule.getGameModule(), type);
ProblemDialog.showDeprecated("2020-08-06");
}
/**
* @deprecated use {@link #Deck(GameModule, String, PropertySource)}
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public Deck(String type, PropertySource source) {
this(GameModule.getGameModule(), type, source);
ProblemDialog.showDeprecated("2020-08-06");
}
/**
* Create an empty deck
* @param gameModule The game module
*/
public Deck(GameModule gameModule) {
this(gameModule, ID);
}
/**
* Creates an empty deck using specified type information
* @param gameModule The game module
* @param type Type information for the deck (the configuration information that does not change during the game)
*/
public Deck(GameModule gameModule, String type) {
this.gameModule = gameModule;
mySetType(type);
gameModule.addSideChangeListenerToPlayerRoster(this);
}
/**
* Creates an empty deck using specified type information
* @param gameModule The game module
* @param type Type information for the deck (the configuration information that does not change during the game)
* @param source PropertySource
*/
public Deck(GameModule gameModule, String type, PropertySource source) {
this(gameModule, type);
propertySource = source;
}
/**
* Sets the Deck's property source
* @param source PropertySource
*/
public void setPropertySource(PropertySource source) {
propertySource = source;
if (globalCommands != null) {
for (DeckGlobalKeyCommand globalCommand : globalCommands) {
globalCommand.setPropertySource(propertySource);
}
}
}
/**
* Listener for when the local player changes side. Updates all of our counts of expressions of pieces configured to be counted.
* @param oldSide local player's old side
* @param newSide local player's new side
*/
@Override
public void sideChanged(String oldSide, String newSide) {
updateCountsAll();
}
/**
* Adds a Deck Global Key Command (DGKC).
* @param globalCommand The command to add
*/
public void addGlobalKeyCommand(DeckGlobalKeyCommand globalCommand) {
globalCommands.add(globalCommand);
}
/**
* Removes a Deck Global Key Command (DGKC).
* @param globalCommand The command to remove
*/
public void removeGlobalKeyCommand(DeckGlobalKeyCommand globalCommand) {
globalCommands.remove(globalCommand);
}
/**
* @return A list of Deck Global Key Commands for this deck, serialized by their encoder.
*/
protected String[] getGlobalCommands() {
String[] commands = new String[globalCommands.size()];
for (int i = 0; i < globalCommands.size(); i++) {
commands[i] = globalCommands.get(i).encode();
}
return commands;
}
/**
* Sets the list of Deck Global Key Commands for this deck
* @param commands The list of commands to set (in serialized string form)
*/
protected void setGlobalCommands(String[] commands) {
globalCommands = new ArrayList<>(commands.length);
for (String command : commands) {
globalCommands.add(new DeckGlobalKeyCommand(command, propertySource));
}
}
/**
* Update map-level count properties for all "expressions" of pieces that are configured
* to be counted. These are held in the String[] countExpressions.
*/
private void updateCountsAll() {
if (!doesExpressionCounting() || getMap() == null) {
return;
}
//Clear out all of the registered count expressions
for (int index = 0; index < countExpressions.length; index++) {
expressionProperties.get(index).setPropertyValue("0"); //$NON-NLS-1$
}
//Increase all of the pieces with expressions specified in this deck
asList().stream()
.filter(Objects::nonNull)
.forEach(p -> updateCounts(p, true));
}
/**
* Update map-level count property for a piece located at index
* @param index Index (within the Deck, counting from the top) of the piece whose count to update
*/
private void updateCounts(int index) {
if (!doesExpressionCounting()) {
return;
}
if (index >= 0 && index < getPieceCount()) {
GamePiece p = getPieceAt(index);
if (p == null) {
//can't figure out the piece, do a full update
updateCountsAll();
}
else {
updateCounts(p, false);
}
}
else {
//can't figure out the piece, do a full update
updateCountsAll();
}
}
/**
* Update map-level count property for a piece
* @param p Game piece to update counts for
* @param increase if true, increase the count; if false, decrease.
*/
private void updateCounts(GamePiece p, boolean increase) {
if (!doesExpressionCounting() || getMap() == null) {
return;
}
//test all the expressions for this deck
for (int index = 0; index < countExpressions.length; index++) {
MutableProperty.Impl prop = expressionProperties.get(index);
FormattedString formatted =
new FormattedString(countExpressions[index].getExpression());
PieceFilter f = PropertiesPieceFilter.parse(formatted.getText());
if (f.accept(p)) {
String mapProperty = prop.getPropertyValue();
if (mapProperty != null) {
int newValue = Integer.decode(mapProperty);
if (increase) {
newValue++;
}
else {
newValue
}
prop.setPropertyValue(String.valueOf(newValue));
}
}
}
}
/**
* Set the <deckName>_numPieces property in the containing Map
*/
protected void fireNumCardsProperty() {
countProperty.setPropertyValue(String.valueOf(pieceCount));
}
/**
* Inserts a piece into a specific position into the Deck (counting down from the top)
* @param p Piece to insert
* @param index "How many cards down into the Deck" to put it.
*/
@Override
protected void insertPieceAt(GamePiece p, int index) {
super.insertPieceAt(p, index);
updateCounts(p, true);
fireNumCardsProperty();
}
/**
* Removes a piece from a specific location in the deck
* @param index Piece to remove, counting down from the top
*/
@Override
protected void removePieceAt(int index) {
int startCount = pieceCount;
updateCounts(index);
super.removePieceAt(index);
fireNumCardsProperty();
if (hotkeyOnEmpty && emptyKey != null && startCount > 0 && pieceCount == 0) {
gameModule.fireKeyStroke(emptyKey);
}
}
/**
* Removes all pieces from the Deck.
*/
@Override
public void removeAll() {
super.removeAll();
updateCountsAll();
fireNumCardsProperty();
}
/**
* Sets the Map this Deck appears on
* @param map Map to assign Deck to
*/
@Override
public void setMap(Map map) {
if (map != getMap()) {
countProperty.removeFromContainer();
if (map != null) countProperty.addTo(map);
for (MutableProperty.Impl prop : expressionProperties) {
prop.removeFromContainer();
if (map != null) prop.addTo(map);
}
}
super.setMap(map);
updateCountsAll();
fireNumCardsProperty();
}
/** Sets the information for this Deck. See {@link Decorator#myGetType}
* @param type a serialized configuration string to
* set the "type information" of this Deck, which is
* information that doesn't change during the course of
* a single game (e.g. Image Files, Context Menu strings,
* etc, rules about when deck is shuffled, whether it is
* face-up or face down, etc).
*/
protected void mySetType(String type) {
SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
drawOutline = st.nextBoolean(true);
outlineColor = ColorConfigurer.stringToColor(st.nextToken("0,0,0")); //$NON-NLS-1$
size.setSize(st.nextInt(40), st.nextInt(40));
faceDownOption = st.nextToken("Always"); //$NON-NLS-1$
shuffleOption = st.nextToken("Always"); //$NON-NLS-1$
allowMultipleDraw = st.nextBoolean(true);
allowSelectDraw = st.nextBoolean(true);
reversible = st.nextBoolean(true);
reshuffleCommand = st.nextToken(""); //$NON-NLS-1$
reshuffleTarget = st.nextToken(""); //$NON-NLS-1$
reshuffleMsgFormat = st.nextToken(""); //$NON-NLS-1$
setDeckName(st.nextToken("Deck"));
shuffleMsgFormat = st.nextToken(""); //$NON-NLS-1$
reverseMsgFormat = st.nextToken(""); //$NON-NLS-1$
faceDownMsgFormat = st.nextToken(""); //$NON-NLS-1$
drawFaceUp = st.nextBoolean(false);
persistable = st.nextBoolean(false);
shuffleKey = st.nextNamedKeyStroke(null);
reshuffleKey = st.nextNamedKeyStroke(null);
maxStack = st.nextInt(10);
setCountExpressions(st.nextStringArray(0));
expressionCounting = st.nextBoolean(false);
setGlobalCommands(st.nextStringArray(0));
hotkeyOnEmpty = st.nextBoolean(false);
emptyKey = st.nextNamedKeyStroke(null);
selectDisplayProperty.setFormat(st.nextToken("$" + BasicPiece.BASIC_NAME + "$"));
selectSortProperty = st.nextToken("");
restrictOption = st.nextBoolean(false);
restrictExpression.setExpression(st.nextToken(""));
shuffleCommand = st.nextToken(Resources.getString("Deck.shuffle"));
reverseCommand = st.nextToken(Resources.getString("Deck.reverse"));
reverseKey = st.nextNamedKeyStroke(null);
if (shuffleListener == null) {
shuffleListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(shuffle());
repaintMap();
});
gameModule.addKeyStrokeListener(shuffleListener);
}
shuffleListener.setKeyStroke(getShuffleKey());
if (reshuffleListener == null) {
reshuffleListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(sendToDeck());
repaintMap();
});
gameModule.addKeyStrokeListener(reshuffleListener);
}
reshuffleListener.setKeyStroke(getReshuffleKey());
if (reverseListener == null) {
reverseListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(reverse());
repaintMap();
});
gameModule.addKeyStrokeListener(reverseListener);
}
reverseListener.setKeyStroke(getReverseKey());
final DrawPile myPile = DrawPile.findDrawPile(getDeckName());
if (myPile != null && myPile.getDeck() == null) {
myPile.setDeck(this);
}
}
public String getFaceDownOption() {
return faceDownOption;
}
/**
* @return true if cards are turned face up when drawn from this deck
*/
public boolean isDrawFaceUp() {
return drawFaceUp;
}
public void setDrawFaceUp(boolean drawFaceUp) {
this.drawFaceUp = drawFaceUp;
}
public void setFaceDownOption(String faceDownOption) {
this.faceDownOption = faceDownOption;
faceDown = !faceDownOption.equals(NEVER);
}
public Dimension getSize() {
return size;
}
public void setSize(Dimension size) {
this.size.setSize(size);
}
public String getShuffleOption() {
return shuffleOption;
}
public void setShuffleOption(String shuffleOption) {
this.shuffleOption = shuffleOption;
}
public boolean isShuffle() {
return shuffle;
}
public int getMaxStack() {
return maxStack;
}
@Override
public int getMaximumVisiblePieceCount() {
return Math.min(pieceCount, maxStack);
}
public String[] getCountExpressions() {
String[] fullstrings = new String[countExpressions.length];
for (int index = 0; index < countExpressions.length; index++) {
fullstrings[index] = countExpressions[index].getFullString();
}
return fullstrings;
}
public boolean doesExpressionCounting() {
return expressionCounting;
}
public String getFaceDownMsgFormat() {
return faceDownMsgFormat;
}
public void setFaceDownMsgFormat(String faceDownMsgFormat) {
this.faceDownMsgFormat = faceDownMsgFormat;
}
public String getReverseMsgFormat() {
return reverseMsgFormat;
}
public void setReverseMsgFormat(String reverseMsgFormat) {
this.reverseMsgFormat = reverseMsgFormat;
}
public String getReverseCommand() {
return reverseCommand;
}
public void setReverseCommand(String s) {
reverseCommand = s;
}
public NamedKeyStroke getReverseKey() {
return reverseKey;
}
public void setReverseKey(NamedKeyStroke reverseKey) {
this.reverseKey = reverseKey;
}
public String getShuffleMsgFormat() {
return shuffleMsgFormat;
}
public void setShuffleMsgFormat(String shuffleMsgFormat) {
this.shuffleMsgFormat = shuffleMsgFormat;
}
public NamedKeyStroke getShuffleKey() {
return shuffleKey;
}
public void setShuffleKey(NamedKeyStroke shuffleKey) {
this.shuffleKey = shuffleKey;
}
public String getShuffleCommand() {
return shuffleCommand;
}
public void setShuffleCommand(String s) {
shuffleCommand = s;
}
public void setShuffle(boolean shuffle) {
this.shuffle = shuffle;
}
public boolean isAllowMultipleDraw() {
return allowMultipleDraw;
}
public void setAllowMultipleDraw(boolean allowMultipleDraw) {
this.allowMultipleDraw = allowMultipleDraw;
}
public boolean isAllowSelectDraw() {
return allowSelectDraw;
}
public void setMaxStack(int maxStack) {
this.maxStack = maxStack;
}
public void setCountExpressions(String[] countExpressionsString) {
CountExpression[] c = new CountExpression[countExpressionsString.length];
int goodExpressionCount = 0;
for (int index = 0; index < countExpressionsString.length; index++) {
CountExpression n = new CountExpression(countExpressionsString[index]);
if (n.getName() != null) {
c[index] = n;
goodExpressionCount++;
}
}
this.countExpressions = Arrays.copyOf(c, goodExpressionCount);
while (countExpressions.length > expressionProperties.size()) {
expressionProperties.add(new MutableProperty.Impl("", this));
}
for (int i = 0; i < countExpressions.length; i++) {
expressionProperties.get(i).setPropertyName(
deckName + "_" + countExpressions[i].getName());
}
}
public void setExpressionCounting(boolean expressionCounting) {
this.expressionCounting = expressionCounting;
}
public void setAllowSelectDraw(boolean allowSelectDraw) {
this.allowSelectDraw = allowSelectDraw;
}
public boolean isReversible() {
return reversible;
}
public void setReversible(boolean reversible) {
this.reversible = reversible;
}
public void setDeckName(String n) {
if (Localization.getInstance().isTranslationInProgress()) {
localizedDeckName = n;
}
else {
deckName = n;
}
countProperty.setPropertyName(deckName + "_numPieces");
for (int i = 0; i < countExpressions.length; ++i) {
expressionProperties.get(i).setPropertyName(
deckName + "_" + countExpressions[i].getName());
}
}
public String getDeckName() {
return deckName;
}
public String getLocalizedDeckName() {
return localizedDeckName == null ? deckName : localizedDeckName;
}
/**
* @return The popup menu text for the command that sends the entire deck to another deck
*/
public String getReshuffleCommand() {
return reshuffleCommand;
}
public void setReshuffleCommand(String reshuffleCommand) {
this.reshuffleCommand = reshuffleCommand;
}
public NamedKeyStroke getReshuffleKey() {
return reshuffleKey;
}
public void setReshuffleKey(NamedKeyStroke reshuffleKey) {
this.reshuffleKey = reshuffleKey;
}
/**
* The name of the {@link VASSAL.build.module.map.DrawPile} to which the
* contents of this deck will be sent when the reshuffle command is selected
*/
public String getReshuffleTarget() {
return reshuffleTarget;
}
public void setReshuffleTarget(String reshuffleTarget) {
this.reshuffleTarget = reshuffleTarget;
}
/**
* @return The message to send to the chat window when the deck is reshuffled to another deck
*/
public String getReshuffleMsgFormat() {
return reshuffleMsgFormat;
}
public void setReshuffleMsgFormat(String reshuffleMsgFormat) {
this.reshuffleMsgFormat = reshuffleMsgFormat;
}
public boolean isHotkeyOnEmpty() {
return hotkeyOnEmpty;
}
public void setHotkeyOnEmpty(boolean b) {
hotkeyOnEmpty = b;
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public KeyStroke getEmptyKey() {
ProblemDialog.showDeprecated("2020-08-06");
return emptyKey.getKeyStroke();
}
public NamedKeyStroke getNamedEmptyKey() {
return emptyKey;
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public void setEmptyKey(KeyStroke k) {
ProblemDialog.showDeprecated("2020-08-06");
emptyKey = new NamedKeyStroke(k);
}
public void setEmptyKey(NamedKeyStroke k) {
emptyKey = k;
}
public void setRestrictOption(boolean restrictOption) {
this.restrictOption = restrictOption;
}
public boolean isRestrictOption() {
return restrictOption;
}
public void setRestrictExpression(PropertyExpression restrictExpression) {
this.restrictExpression = restrictExpression;
}
public PropertyExpression getRestrictExpression() {
return restrictExpression;
}
/**
* Does the specified GamePiece meet the rules to be contained
* in this Deck.
*/
public boolean mayContain(GamePiece piece) {
if (! restrictOption || restrictExpression.isNull()) {
return true;
}
else {
return restrictExpression.accept(piece);
}
}
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(drawOutline)
.append(ColorConfigurer.colorToString(outlineColor))
.append(String.valueOf(size.width))
.append(String.valueOf(size.height))
.append(faceDownOption)
.append(shuffleOption)
.append(String.valueOf(allowMultipleDraw))
.append(String.valueOf(allowSelectDraw))
.append(String.valueOf(reversible))
.append(reshuffleCommand)
.append(reshuffleTarget)
.append(reshuffleMsgFormat)
.append(deckName)
.append(shuffleMsgFormat)
.append(reverseMsgFormat)
.append(faceDownMsgFormat)
.append(drawFaceUp)
.append(persistable)
.append(shuffleKey)
.append(reshuffleKey)
.append(String.valueOf(maxStack))
.append(getCountExpressions())
.append(expressionCounting)
.append(getGlobalCommands())
.append(hotkeyOnEmpty)
.append(emptyKey)
.append(selectDisplayProperty.getFormat())
.append(selectSortProperty)
.append(restrictOption)
.append(restrictExpression)
.append(shuffleCommand)
.append(reverseCommand)
.append(reverseKey);
return ID + se.getValue();
}
/** Shuffle the contents of the Deck */
public Command shuffle() {
final GamePiece[] a = new GamePiece[pieceCount];
System.arraycopy(contents, 0, a, 0, pieceCount);
final List<GamePiece> l = Arrays.asList(a);
DragBuffer.getBuffer().clear();
Collections.shuffle(l, gameModule.getRNG());
return setContents(l).append(reportCommand(shuffleMsgFormat, Resources.getString("Deck.shuffle"))); //$NON-NLS-1$
}
/**
* Return an iterator of pieces to be drawn from the Deck. Normally, a random
* piece will be drawn, but if the Deck supports it, the user may have
* specified a particular set of pieces or a fixed number of pieces to select
* with the next draw.
*/
public PieceIterator drawCards() {
Iterator<GamePiece> it;
if (nextDraw != null) {
it = nextDraw.iterator();
}
else if (getPieceCount() == 0) {
it = Collections.emptyIterator();
}
else {
int count = Math.max(dragCount, Math.min(1, getPieceCount()));
final ArrayList<GamePiece> pieces = new ArrayList<>();
if (ALWAYS.equals(shuffleOption)) {
// Instead of shuffling the entire deck, just pick <b>count</b> random elements
final ArrayList<Integer> indices = new ArrayList<>();
for (int i = 0; i < getPieceCount(); ++i) {
indices.add(i);
}
final Random rng = gameModule.getRNG();
while (count-- > 0 && indices.size() > 0) {
final int i = rng.nextInt(indices.size());
final int index = indices.get(i);
indices.remove(i);
final GamePiece p = getPieceAt(index);
pieces.add(p);
}
}
else {
final Iterator<GamePiece> i = getPiecesReverseIterator();
while (count-- > 0 && i.hasNext()) pieces.add(i.next());
}
it = pieces.iterator();
}
dragCount = 0;
nextDraw = null;
return new PieceIterator(it) {
@Override
public GamePiece nextPiece() {
GamePiece p = super.nextPiece();
/*
* Bug 12951 results in Cards going back into a Deck via Undo in an inconsistent state.
* This statement is the culprit. As far as I can tell, it is not needed as Deck.pieceRemoved()
* sets OBSCURED_BY if drawing a facedown card from a face down Deck which is the only case
* where this would be needed.
* This will need thorough testing in Deck heavy modules.
*/
// if (faceDown) {
// p.setProperty(Properties.OBSCURED_BY, NO_USER);
return p;
}
};
}
/** Set the contents of this Deck to a Collection of GamePieces */
protected Command setContents(Collection<GamePiece> c) {
ChangeTracker track = new ChangeTracker(this);
removeAll();
for (GamePiece child : c) {
insertChild(child, pieceCount);
}
return track.getChangeCommand();
}
/**
* Set the contents of this Deck to an Iterator of GamePieces
* @deprecated Use {@link #setContents(Collection)} instead.
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
protected Command setContents(Iterator<GamePiece> it) {
ProblemDialog.showDeprecated("2020-08-06");
ChangeTracker track = new ChangeTracker(this);
removeAll();
while (it.hasNext()) {
GamePiece child = it.next();
insertChild(child, pieceCount);
}
return track.getChangeCommand();
}
@Override
public String getState() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(getMap() == null ? "null" : getMap().getIdentifier()).append(getPosition().x).append(getPosition().y); //$NON-NLS-1$
se.append(faceDown);
final SequenceEncoder se2 = new SequenceEncoder(',');
asList().forEach(gamePiece -> se2.append(gamePiece.getId()));
if (se2.getValue() != null) {
se.append(se2.getValue());
}
return se.getValue();
}
@Override
public void setState(String state) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(state, ';');
final String mapId = st.nextToken();
setPosition(new Point(st.nextInt(0), st.nextInt(0)));
Map m = null;
if (!"null".equals(mapId)) { //$NON-NLS-1$
m = Map.getMapById(mapId);
if (m == null) {
ErrorDialog.dataWarning(new BadDataReport("No such map", mapId, null));
}
}
if (m != getMap()) {
if (m != null) {
m.addPiece(this);
}
else {
setMap(null);
}
}
faceDown = "true".equals(st.nextToken()); //$NON-NLS-1$
final ArrayList<GamePiece> l = new ArrayList<>();
if (st.hasMoreTokens()) {
final SequenceEncoder.Decoder st2 =
new SequenceEncoder.Decoder(st.nextToken(), ',');
while (st2.hasMoreTokens()) {
final GamePiece p = gameModule.getGameState()
.getPieceForId(st2.nextToken());
if (p != null) {
l.add(p);
}
}
}
setContents(l);
commands = null; // Force rebuild of popup menu
}
public Command setContentsFaceDown(boolean value) {
ChangeTracker t = new ChangeTracker(this);
Command c = new NullCommand();
faceDown = value;
return t.getChangeCommand().append(c).append(reportCommand(faceDownMsgFormat, value ? Resources.getString("Deck.face_down") : Resources.getString("Deck.face_up"))); //$NON-NLS-1$ //$NON-NLS-2$
}
/** Reverse the order of the contents of the Deck */
public Command reverse() {
final ArrayList<GamePiece> list = new ArrayList<>();
for (Iterator<GamePiece> i = getPiecesReverseIterator(); i.hasNext(); ) {
list.add(i.next());
}
return setContents(list).append(reportCommand(
reverseMsgFormat, Resources.getString("Deck.reverse"))); //$NON-NLS-1$
}
public boolean isDrawOutline() {
return drawOutline;
}
public void setOutlineColor(Color outlineColor) {
this.outlineColor = outlineColor;
}
public void setDrawOutline(boolean drawOutline) {
this.drawOutline = drawOutline;
}
public Color getOutlineColor() {
return outlineColor;
}
public boolean isFaceDown() {
return faceDown;
}
@Override
public Command pieceAdded(GamePiece p) {
return null;
}
@Override
public Command pieceRemoved(GamePiece p) {
ChangeTracker tracker = new ChangeTracker(p);
p.setProperty(Properties.OBSCURED_TO_OTHERS, isFaceDown() && !isDrawFaceUp());
return tracker.getChangeCommand();
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
@Override
public void draw(java.awt.Graphics g, int x, int y, Component obs, double zoom) {
int count = Math.min(getPieceCount(), maxStack);
GamePiece top = (nextDraw != null && nextDraw.size() > 0) ?
nextDraw.get(0) : topPiece();
if (top != null) {
Object owner = top.getProperty(Properties.OBSCURED_BY);
top.setProperty(Properties.OBSCURED_BY, faceDown ? NO_USER : null);
Color blankColor = getBlankColor();
Rectangle r = top.getShape().getBounds();
r.setLocation(x + (int) (zoom * (r.x)), y + (int) (zoom * (r.y)));
r.setSize((int) (zoom * r.width), (int) (zoom * r.height));
for (int i = 0; i < count - 1; ++i) {
if (blankColor != null) {
g.setColor(blankColor);
g.fillRect(r.x + (int) (zoom * 2 * i), r.y - (int) (zoom * 2 * i), r.width, r.height);
g.setColor(Color.black);
g.drawRect(r.x + (int) (zoom * 2 * i), r.y - (int) (zoom * 2 * i), r.width, r.height);
}
else if (faceDown) {
top.draw(g, x + (int) (zoom * 2 * i), y - (int) (zoom * 2 * i), obs, zoom);
}
else {
getPieceAt(count - i - 1).draw(g, x + (int) (zoom * 2 * i), y - (int) (zoom * 2 * i), obs, zoom);
}
}
top.draw(g, x + (int) (zoom * 2 * (count - 1)), y - (int) (zoom * 2 * (count - 1)), obs, zoom);
top.setProperty(Properties.OBSCURED_BY, owner);
}
else {
if (drawOutline) {
Rectangle r = boundingBox();
r.setLocation(x + (int) (zoom * r.x), y + (int) (zoom * r.y));
r.setSize((int) (zoom * r.width), (int) (zoom * r.height));
g.setColor(outlineColor);
g.drawRect(r.x, r.y, r.width, r.height);
}
}
}
/**
* The color used to draw boxes representing cards underneath the top one. If
* null, then draw each card normally for face-up decks, and duplicate the top
* card for face-down decks
*/
protected Color getBlankColor() {
Color c = Color.white;
if (getMap() != null) {
c = getMap().getStackMetrics().getBlankColor();
}
return c;
}
@Override
public StackMetrics getStackMetrics() {
return deckStackMetrics;
}
@Override
public Rectangle boundingBox() {
GamePiece top = topPiece();
Dimension d = top == null ? size : top.getShape().getBounds().getSize();
Rectangle r = new Rectangle(new Point(), d);
r.translate(-r.width / 2, -r.height / 2);
for (int i = 0, n = getMaximumVisiblePieceCount(); i < n; ++i) {
r.y -= 2;
r.height += 2;
r.width += 2;
}
return r;
}
@Override
public Shape getShape() {
return boundingBox();
}
@Override
public Object getProperty(Object key) {
Object value = null;
if (Properties.NO_STACK.equals(key)) {
value = Boolean.TRUE;
}
else if (Properties.KEY_COMMANDS.equals(key)) {
value = getKeyCommands();
}
return value;
}
protected KeyCommand[] getKeyCommands() {
if (commands == null) {
ArrayList<KeyCommand> l = new ArrayList<>();
KeyCommand c;
if (USE_MENU.equals(shuffleOption)) {
c = new KeyCommand(shuffleCommand, getShuffleKey(), this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(shuffle());
repaintMap();
}
};
l.add(c);
}
if (reshuffleCommand.length() > 0) {
c = new KeyCommand(reshuffleCommand, getReshuffleKey(), this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
gameModule.sendAndLog(sendToDeck());
repaintMap();
}
};
l.add(c);
}
if (USE_MENU.equals(faceDownOption)) {
KeyCommand faceDownAction = new KeyCommand(faceDown ? Resources.getString("Deck.face_up") : Resources.getString("Deck.face_down"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$ //$NON-NLS-2$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final Command c = setContentsFaceDown(!faceDown);
gameModule.sendAndLog(c);
repaintMap();
}
};
l.add(faceDownAction);
}
if (reversible) {
c = new KeyCommand(reverseCommand, NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final Command c = reverse();
gameModule.sendAndLog(c);
repaintMap();
}
};
l.add(c);
}
if (allowMultipleDraw) {
c = new KeyCommand(Resources.getString("Deck.draw_multiple"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
promptForDragCount();
}
};
l.add(c);
}
if (allowSelectDraw) {
c = new KeyCommand(Resources.getString("Deck.draw_specific"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
promptForNextDraw();
repaintMap();
}
};
l.add(c);
}
if (persistable) {
c = new KeyCommand(Resources.getString(Resources.SAVE), NamedKeyStroke.NULL_KEYSTROKE, this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(saveDeck());
repaintMap();
}
};
l.add(c);
c = new KeyCommand(Resources.getString(Resources.LOAD), NamedKeyStroke.NULL_KEYSTROKE, this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(loadDeck());
repaintMap();
}
};
l.add(c);
}
for (DeckGlobalKeyCommand cmd : globalCommands) {
l.add(cmd.getKeyCommand(this));
}
commands = l.toArray(new KeyCommand[0]);
}
for (KeyCommand command : commands) {
if (Resources.getString("Deck.face_up").equals(command.getValue(Action.NAME)) && !faceDown) { //$NON-NLS-1$
command.putValue(Action.NAME, Resources.getString("Deck.face_down")); //$NON-NLS-1$
}
else if (Resources.getString("Deck.face_down").equals(command.getValue(Action.NAME)) && faceDown) { //$NON-NLS-1$
command.putValue(Action.NAME, Resources.getString("Deck.face_up")); //$NON-NLS-1$
}
}
return commands;
}
/*
* Format command report as per module designers setup.
*/
protected Command reportCommand(String format, String commandName) {
Command c = null;
FormattedString reportFormat = new FormattedString(format);
reportFormat.setProperty(DrawPile.DECK_NAME, getLocalizedDeckName());
reportFormat.setProperty(DrawPile.COMMAND_NAME, commandName);
String rep = reportFormat.getLocalizedText();
if (rep.length() > 0) {
c = new Chatter.DisplayText(gameModule.getChatter(), "* " + rep); //$NON-NLS-1$
c.execute();
}
return c;
}
public void promptForDragCount() {
while (true) {
final String s = JOptionPane.showInputDialog(
Resources.getString("Deck.enter_the_number")); //$NON-NLS-1$
if (s != null) {
try {
dragCount = Integer.parseInt(s);
dragCount = Math.min(dragCount, getPieceCount());
if (dragCount >= 0) break;
}
catch (NumberFormatException ex) {
// Ignore if user doesn't enter a number
}
}
else {
break;
}
}
}
protected void promptForNextDraw() {
final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, map.getView()), true);
d.setTitle(Resources.getString("Deck.draw")); //$NON-NLS-1$
d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS));
class AvailablePiece implements Comparable<AvailablePiece> {
private final GamePiece piece;
public AvailablePiece(GamePiece piece) {
this.piece = piece;
}
@Override
public int compareTo(AvailablePiece other) {
if (other == null) return 1;
final String otherProperty =
(String) other.piece.getProperty(selectSortProperty);
if (otherProperty == null) return 1;
final String myProperty =
(String) piece.getProperty(selectSortProperty);
if (myProperty == null) return -1;
return -otherProperty.compareTo(myProperty);
}
public String toString() {
return selectDisplayProperty.getText(piece);
}
public boolean equals(Object o) {
if (! (o instanceof AvailablePiece)) return false;
return ((AvailablePiece)o).piece.equals(piece);
}
}
final AvailablePiece[] pieces = new AvailablePiece[getPieceCount()];
for (int i = 0; i < pieces.length; ++i) {
pieces[pieces.length - i - 1] = new AvailablePiece(getPieceAt(i));
}
if (selectSortProperty != null && selectSortProperty.length() > 0) {
Arrays.sort(pieces);
}
final JList<AvailablePiece> list = new JList<>(pieces);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
d.add(new ScrollPane(list));
d.add(new JLabel(Resources.getString("Deck.select_cards"))); //$NON-NLS-1$
d.add(new JLabel(Resources.getString("Deck.then_click"))); //$NON-NLS-1$
Box box = Box.createHorizontalBox();
JButton b = new JButton(Resources.getString(Resources.OK));
b.addActionListener(e -> {
int[] selection = list.getSelectedIndices();
if (selection.length > 0) {
nextDraw = new ArrayList<>();
for (int value : selection) {
nextDraw.add(pieces[value].piece);
}
}
else {
nextDraw = null;
}
d.dispose();
});
box.add(b);
b = new JButton(Resources.getString(Resources.CANCEL));
b.addActionListener(e -> d.dispose());
box.add(b);
d.add(box);
d.pack();
d.setLocationRelativeTo(d.getOwner());
d.setVisible(true);
}
/**
* Combine the contents of this Deck with the contents of the deck specified
* by {@link #reshuffleTarget}
*/
public Command sendToDeck() {
Command c = null;
nextDraw = null;
DrawPile target = DrawPile.findDrawPile(reshuffleTarget);
if (target != null) {
if (reshuffleMsgFormat.length() > 0) {
c = reportCommand(reshuffleMsgFormat, reshuffleCommand);
if (c == null) {
c = new NullCommand();
}
}
else {
c = new NullCommand();
}
// move cards to deck
int cnt = getPieceCount() - 1;
for (int i = cnt; i >= 0; i
c.append(target.addToContents(getPieceAt(i)));
}
}
return c;
}
@Override
public boolean isExpanded() {
return false;
}
/** Return true if this deck can be saved to and loaded from a file on disk */
public boolean isPersistable() {
return persistable;
}
public void setPersistable(boolean persistable) {
this.persistable = persistable;
}
private File getSaveFileName() {
FileChooser fc = gameModule.getFileChooser();
File sf = fc.getSelectedFile();
if (sf != null) {
String name = sf.getPath();
int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(0, index) + ".sav"; //$NON-NLS-1$
fc.setSelectedFile(new File(name));
}
}
if (fc.showSaveDialog(map.getView()) != FileChooser.APPROVE_OPTION)
return null;
File outputFile = fc.getSelectedFile();
if (outputFile != null &&
outputFile.exists() &&
shouldConfirmOverwrite() &&
JOptionPane.NO_OPTION ==
JOptionPane.showConfirmDialog(gameModule.getPlayerWindow(),
Resources.getString("Deck.overwrite", outputFile.getName()), Resources.getString("Deck.file_exists"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JOptionPane.YES_NO_OPTION)) {
outputFile = null;
}
return outputFile;
}
private boolean shouldConfirmOverwrite() {
return System.getProperty("os.name").trim().equalsIgnoreCase("linux"); //$NON-NLS-1$ //$NON-NLS-2$
}
private Command saveDeck() {
final Command c = new NullCommand();
gameModule.warn(Resources.getString("Deck.saving_deck")); //$NON-NLS-1$
final File saveFile = getSaveFileName();
try {
if (saveFile != null) {
saveDeck(saveFile);
gameModule.warn(Resources.getString("Deck.deck_saved")); //$NON-NLS-1$
}
else {
gameModule.warn(Resources.getString("Deck.save_canceled")); //$NON-NLS-1$
}
}
catch (IOException e) {
WriteErrorDialog.error(e, saveFile);
}
return c;
}
public void saveDeck(File f) throws IOException {
Command comm = new LoadDeckCommand(null);
for (GamePiece p : asList()) {
p.setMap(null);
comm = comm.append(new AddPiece(p));
}
try (Writer fw = new FileWriter(f, StandardCharsets.UTF_8);
BufferedWriter out = new BufferedWriter(fw)) {
gameModule.addCommandEncoder(commandEncoder);
out.write(gameModule.encode(comm));
gameModule.removeCommandEncoder(commandEncoder);
}
}
private File getLoadFileName() {
FileChooser fc = gameModule.getFileChooser();
fc.selectDotSavFile();
if (fc.showOpenDialog(map.getView()) != FileChooser.APPROVE_OPTION)
return null;
return fc.getSelectedFile();
}
private Command loadDeck() {
Command c = new NullCommand();
gameModule.warn(Resources.getString("Deck.loading_deck")); //$NON-NLS-1$
final File loadFile = getLoadFileName();
try {
if (loadFile != null) {
c = loadDeck(loadFile);
gameModule.warn(Resources.getString("Deck.deck_loaded")); //$NON-NLS-1$
}
else {
gameModule.warn(Resources.getString("Deck.load_canceled")); //$NON-NLS-1$
}
}
catch (IOException e) {
ReadErrorDialog.error(e, loadFile);
}
return c;
}
public Command loadDeck(File f) throws IOException {
String ds;
try (Reader fr = new FileReader(f, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(fr)) {
ds = IOUtils.toString(in);
}
gameModule.addCommandEncoder(commandEncoder);
Command c = gameModule.decode(ds);
gameModule.removeCommandEncoder(commandEncoder);
if (c instanceof LoadDeckCommand) {
/*
* A LoadDeckCommand doesn't specify the deck to be changed (since the
* saved deck can be loaded into any deck) so the Command we send to other
* players is a ChangePiece command for this deck, which we need to place
* after the AddPiece commands for the contents
*/
final ChangeTracker t = new ChangeTracker(this);
c.execute();
final Command[] sub = c.getSubCommands();
c = new NullCommand();
for (Command command : sub) {
c.append(command);
}
c.append(t.getChangeCommand());
updateCountsAll();
}
else {
gameModule.warn(Resources.getString("Deck.not_a_saved_deck", f.getName())); //$NON-NLS-1$
c = null;
}
return c;
}
/**
* Command to set the contents of this deck from a saved file. The contents
* are saved with whatever id's the pieces have in the game when the deck was
* saved, but new copies are created when the deck is re-loaded.
*
* @author rkinney
*
*/
protected static class LoadDeckCommand extends Command {
public static final String PREFIX = "DECK\t"; //$NON-NLS-1$
private final Deck target;
public LoadDeckCommand(Deck target) {
this.target = target;
}
@Override
protected void executeCommand() {
target.removeAll();
Command[] sub = getSubCommands();
for (Command command : sub) {
if (command instanceof AddPiece) {
GamePiece p = ((AddPiece) command).getTarget();
// We set the id to null so that the piece will get a new id
// when the AddPiece command executes
p.setId(null);
target.add(p);
}
}
}
public String getTargetId() {
return target == null ? "" : target.getId(); //$NON-NLS-1$
}
@Override
protected Command myUndoCommand() {
return null;
}
}
/**
* An object that parses expression strings from the config window
*/
public static class CountExpression {
private String fullstring;
private String name;
private String expression;
public CountExpression(String expressionString) {
String[] split = expressionString.split("\\s*:\\s*", 2); //$NON-NLS-1$
if (split.length == 2) {
name = split[0];
expression = split[1];
fullstring = expressionString;
}
}
public String getName() {
return name;
}
public String getExpression() {
return expression;
}
public String getFullString() {
return fullstring;
}
}
/**
* Return the number of cards to be returned by next call to
* {@link #drawCards()}.
*/
public int getDragCount() {
return dragCount;
}
/**
* Set the number of cards to be returned by next call to
* {@link #drawCards()}.
*
* @param dragCount number of cards to be returned
*/
public void setDragCount(int dragCount) {
this.dragCount = dragCount;
}
public void setSelectDisplayProperty(String promptDisplayProperty) {
this.selectDisplayProperty.setFormat(promptDisplayProperty);
}
public void setSelectSortProperty(String promptSortProperty) {
this.selectSortProperty = promptSortProperty;
}
public String getSelectDisplayProperty() {
return selectDisplayProperty.getFormat();
}
public String getSelectSortProperty() {
return selectSortProperty;
}
protected void repaintMap() {
if (map != null) {
map.repaint();
}
}
}
|
package imj2.tools;
import static java.lang.Math.abs;
import static java.lang.Math.pow;
import static java.lang.Math.round;
import static java.lang.Math.sqrt;
import static net.sourceforge.aprog.swing.SwingTools.horizontalBox;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.tools.Tools.array;
import static net.sourceforge.aprog.tools.Tools.debug;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import imj.IntList;
import imj2.tools.Image2DComponent.Painter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.MathTools.Statistics;
import net.sourceforge.aprog.tools.TicToc;
import net.sourceforge.aprog.tools.Tools;
import org.junit.Test;
/**
* @author codistmonk (creation 2014-04-09)
*/
@SuppressWarnings("unchecked")
public final class BitwiseQuantizationTest {
// @Test
public final void test1() {
final TreeMap<double[], String> lines = new TreeMap<double[], String>(DoubleArrayComparator.INSTANCE);
for (int qR0 = 0; qR0 <= 7; ++qR0) {
final int qR = qR0;
for (int qG0 = 0; qG0 <= 7; ++qG0) {
final int qG = qG0;
for (int qB0 = 0; qB0 <= 7; ++qB0) {
final int qB = qB0;
MultiThreadTools.getExecutor().submit(new Runnable() {
@Override
public final void run() {
final int[] rgb = new int[3];
final int[] qRGB = rgb.clone();
final float[] xyz = new float[3];
final float[] cielab = new float[3];
final float[] qCIELAB = cielab.clone();
final Statistics error = new Statistics();
for (int color = 0; color <= 0x00FFFFFF; ++color) {
rgbToRGB(color, rgb);
rgbToXYZ(rgb, xyz);
xyzToCIELAB(xyz, cielab);
quantize(rgb, qR, qG, qB, qRGB);
rgbToXYZ(qRGB, xyz);
xyzToCIELAB(xyz, qCIELAB);
error.addValue(distance2(cielab, qCIELAB));
}
final double[] key = { qR + qG + qB, error.getMean() };
final String line = "qRGB: " + qR + " " + qG + " " + qB + " " + ((qR + qG + qB)) +
" error: " + error.getMinimum() + " <= " + error.getMean() +
" ( " + sqrt(error.getVariance()) + " ) <= " + error.getMaximum();
synchronized (lines) {
lines.put(key, line);
System.out.println(line);
}
}
});
}
}
}
for (int qH0 = 0; qH0 <= 7; ++qH0) {
final int qH = qH0;
for (int qS0 = 0; qS0 <= 7; ++qS0) {
final int qS = qS0;
for (int qV0 = 0; qV0 <= 7; ++qV0) {
final int qV = qV0;
MultiThreadTools.getExecutor().submit(new Runnable() {
@Override
public final void run() {
final int[] rgb = new int[3];
final int[] qRGB = rgb.clone();
final float[] xyz = new float[3];
final float[] cielab = new float[3];
final float[] qCIELAB = cielab.clone();
final int[] hsv = new int[3];
final int[] qHSV = hsv.clone();
final Statistics error = new Statistics();
for (int color = 0; color <= 0x00FFFFFF; ++color) {
rgbToRGB(color, rgb);
rgbToXYZ(rgb, xyz);
xyzToCIELAB(xyz, cielab);
rgbToHSV(rgb, hsv);
quantize(hsv, qH, qS, qV, qHSV);
hsvToRGB(qHSV, qRGB);
rgbToXYZ(qRGB, xyz);
xyzToCIELAB(xyz, qCIELAB);
error.addValue(distance2(cielab, qCIELAB));
}
final double[] key = { qH + qS + qV, error.getMean() };
final String line = "qHSV: " + qH + " " + qS + " " + qV + " " + ((qH + qS + qV)) +
" error: " + error.getMinimum() + " <= " + error.getMean() +
" ( " + sqrt(error.getVariance()) + " ) <= " + error.getMaximum();
synchronized (lines) {
lines.put(key, line);
System.out.println(line);
}
}
});
}
}
}
shutdownAndWait(MultiThreadTools.getExecutor(), Long.MAX_VALUE);
System.out.println();
for (final String line : lines.values()) {
System.out.println(line);
}
}
@Test
public final void test2() {
final Color contourColor = Color.GREEN;
final int minimumComponentSize = 80;
debugPrint(quantizers);
final SimpleImageView imageView = new SimpleImageView();
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(12, 0, quantizers.size() - 1, 1));
imageView.getPainters().add(new Painter<SimpleImageView>() {
private Canvas labels = new Canvas();
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
final TicToc timer = new TicToc();
timer.tic();
final ColorQuantizer quantizer = quantizers.get(((Number) spinner.getValue()).intValue());
final BufferedImage image = imageView.getImage();
final BufferedImage buffer = imageView.getBufferImage();
final int w = buffer.getWidth();
final int h = buffer.getHeight();
this.labels.setFormat(w, h, BufferedImage.TYPE_3BYTE_BGR);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
this.labels.getImage().setRGB(x, y, quantizer.pack(image.getRGB(x, y)));
}
}
debugPrint(timer.toc());
final SchedulingData schedulingData = new SchedulingData();
int totalPixelCount = 0;
final IntList small = new IntList();
for (int y = 0, pixel = 0, labelId = 0xFF000000; y < h; ++y) {
for (int x = 0; x < w; ++x, ++pixel) {
if (!schedulingData.getDone().get(pixel)) {
schedulingData.getTodo().add(pixel);
final int rgb = this.labels.getImage().getRGB(x, y);
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
this.labels.getImage().setRGB(p % w, p / w, labelId);
this.process(w, h, schedulingData, p % w, p / w, p, rgb);
}
final int componentPixelCount = schedulingData.getTodo().size();
++labelId;
totalPixelCount += componentPixelCount;
if (componentPixelCount < minimumComponentSize) {
small.add(pixel);
}
schedulingData.getTodo().clear();
}
}
}
schedulingData.getDone().clear();
debugPrint(timer.toc());
while (!small.isEmpty()) {
if (5000L <= timer.toc()) {
debugPrint(small.size());
timer.tic();
}
final int pixel = small.remove(0);
final int x = pixel % w;
final int y = pixel / w;
final int labelId = this.labels.getImage().getRGB(x, y);
if (!schedulingData.getDone().get(pixel)) {
schedulingData.getTodo().add(pixel);
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
this.process(w, h, schedulingData, p % w, p / w, p, labelId);
}
if (schedulingData.getTodo().size() < minimumComponentSize) {
final IntList neighborLabels = new IntList();
final IntList neighborRGBs = new IntList();
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
final int xx = p % w;
final int yy = p / w;
if (0 < yy) {
final int neighborLabel = this.labels.getImage().getRGB(xx, yy - 1);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
neighborRGBs.add(image.getRGB(xx, yy - 1));
}
}
if (0 < xx) {
final int neighborLabel = this.labels.getImage().getRGB(xx - 1, yy);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
neighborRGBs.add(image.getRGB(xx - 1, yy));
}
}
if (xx + 1 < w) {
final int neighborLabel = this.labels.getImage().getRGB(xx + 1, yy);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
neighborRGBs.add(image.getRGB(xx + 1, yy));
}
}
if (yy + 1 < h) {
final int neighborLabel = this.labels.getImage().getRGB(xx, yy + 1);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
neighborRGBs.add(image.getRGB(xx, yy + 1));
}
}
}
int neighborLabel = -1;
int closestNeighborColorDistance = Integer.MAX_VALUE;
final int[] rgb = rgbToRGB(image.getRGB(x, y), new int[3]);
final int[] neighborRGB = new int[3];
for (int i = 0; i < neighborLabels.size(); ++i) {
rgbToRGB(neighborRGBs.get(i), neighborRGB);
final int d = distance1(rgb, neighborRGB);
if (d < closestNeighborColorDistance) {
closestNeighborColorDistance = d;
neighborLabel = neighborLabels.get(i);
}
}
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
final int xx = p % w;
final int yy = p / w;
this.labels.getImage().setRGB(xx, yy, neighborLabel);
}
}
schedulingData.getDone().clear();
schedulingData.getTodo().clear();
}
}
debugPrint(timer.getTotalTime());
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
int north = 0;
int west = 0;
int east = 0;
int south = 0;
if (0 < y) {
north = this.labels.getImage().getRGB(x, y - 1);
}
if (0 < x) {
west = this.labels.getImage().getRGB(x - 1, y);
}
if (x + 1 < w) {
east = this.labels.getImage().getRGB(x + 1, y);
}
if (y + 1 < h) {
south = this.labels.getImage().getRGB(x, y + 1);
}
final int center = this.labels.getImage().getRGB(x, y);
// buffer.setRGB(x, y, center << 2);
if (min(north, west, east, south) < center) {
buffer.setRGB(x, y, contourColor.getRGB());
}
}
}
if (w * h != totalPixelCount) {
System.err.println(debug(Tools.DEBUG_STACK_OFFSET, "Error:", "expected:", w * h, "actual:", totalPixelCount));
}
debugPrint(timer.getTotalTime());
}
private final void process(final int w, final int h,
final SchedulingData schedulingData, final int x, final int y,
final int pixel, final int labelRGB) {
schedulingData.getDone().set(pixel);
if (0 < y && this.labels.getImage().getRGB(x, y - 1) == labelRGB) {
final int neighbor = pixel - w;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
if (0 < x && this.labels.getImage().getRGB(x - 1, y) == labelRGB) {
final int neighbor = pixel - 1;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
if (x + 1 < w && this.labels.getImage().getRGB(x + 1, y) == labelRGB) {
final int neighbor = pixel + 1;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
if (y + 1 < h && this.labels.getImage().getRGB(x, y + 1) == labelRGB) {
final int neighbor = pixel + w;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = 8306989611117085093L;
});
final JPanel panel = new JPanel(new BorderLayout());
SwingTools.setCheckAWT(false);
spinner.addChangeListener(new ChangeListener() {
@Override
public final void stateChanged(final ChangeEvent event) {
imageView.refreshBuffer();
}
});
panel.add(horizontalBox(spinner), BorderLayout.NORTH);
panel.add(imageView, BorderLayout.CENTER);
show(panel, this.getClass().getSimpleName(), true);
}
private static final List<Object[]> table = new ArrayList<Object[]>();
static final List<ColorQuantizer> quantizers = new ArrayList<ColorQuantizer>();
static {
table.add(array("qRGB", 0, 0, 0, 0.0));
table.add(array("qHSV", 0, 0, 0, 0.6955260904279362));
table.add(array("qRGB", 1, 0, 0, 0.32641454294213));
table.add(array("qRGB", 0, 0, 1, 0.6240309742241252));
table.add(array("qRGB", 0, 1, 0, 0.7514458393503941));
table.add(array("qHSV", 0, 0, 1, 0.8751917410004951));
table.add(array("qHSV", 0, 1, 0, 1.126961289651885));
table.add(array("qHSV", 1, 0, 0, 1.7813204349626734));
table.add(array("qRGB", 1, 0, 1, 0.8583117538819247));
table.add(array("qRGB", 1, 1, 0, 0.8692188281204635));
table.add(array("qRGB", 2, 0, 0, 0.9808307435374101));
table.add(array("qRGB", 0, 1, 1, 1.0380778379038296));
table.add(array("qHSV", 0, 0, 2, 1.1659382941554577));
table.add(array("qHSV", 0, 1, 1, 1.2559919477363735));
table.add(array("qHSV", 1, 0, 1, 1.8951245566432926));
table.add(array("qRGB", 0, 0, 2, 1.8980446031157745));
table.add(array("qHSV", 1, 1, 0, 2.092400382244634));
table.add(array("qHSV", 0, 2, 0, 2.115374741291907));
table.add(array("qRGB", 0, 2, 0, 2.265005588909907));
table.add(array("qHSV", 2, 0, 0, 4.528551120210534));
table.add(array("qRGB", 1, 1, 1, 1.1180287803753424));
table.add(array("qRGB", 2, 1, 0, 1.2748883526552783));
table.add(array("qRGB", 2, 0, 1, 1.4067111100652796));
table.add(array("qHSV", 0, 1, 2, 1.5203314800623147));
table.add(array("qHSV", 0, 0, 3, 1.809747264609731));
table.add(array("qRGB", 0, 1, 2, 1.9618195348396559));
table.add(array("qRGB", 1, 0, 2, 2.064893103362241));
table.add(array("qHSV", 1, 0, 2, 2.1016815466827374));
table.add(array("qHSV", 1, 1, 1, 2.177229033053775));
table.add(array("qHSV", 0, 2, 1, 2.2173938408647693));
table.add(array("qRGB", 1, 2, 0, 2.2504013406529717));
table.add(array("qRGB", 0, 2, 1, 2.2932977370369603));
table.add(array("qRGB", 3, 0, 0, 2.2959598157696686));
table.add(array("qHSV", 1, 2, 0, 2.8907950047008057));
table.add(array("qHSV", 0, 3, 0, 4.270360710208371));
table.add(array("qRGB", 0, 0, 3, 4.52553090293637));
table.add(array("qHSV", 2, 0, 1, 4.592369919131593));
table.add(array("qHSV", 2, 1, 0, 4.722213766837409));
table.add(array("qRGB", 0, 3, 0, 5.333067162914784));
table.add(array("qHSV", 3, 0, 0, 10.133061431545565));
table.add(array("qRGB", 2, 1, 1, 1.4880175209433724));
table.add(array("qRGB", 1, 1, 2, 2.0282165668025764));
table.add(array("qHSV", 0, 1, 3, 2.152929318600153));
table.add(array("qRGB", 1, 2, 1, 2.2559129235446513));
table.add(array("qRGB", 3, 1, 0, 2.370351273948446));
table.add(array("qHSV", 1, 1, 2, 2.3731733681910288));
table.add(array("qRGB", 2, 2, 0, 2.389170595189107));
table.add(array("qHSV", 0, 2, 2, 2.450676449335271));
table.add(array("qRGB", 2, 0, 2, 2.4962070471616475));
table.add(array("qHSV", 1, 0, 3, 2.614980863199656));
table.add(array("qRGB", 3, 0, 1, 2.61968019557456));
table.add(array("qRGB", 0, 2, 2, 2.775659263227969));
table.add(array("qHSV", 1, 2, 1, 2.9645149300940132));
table.add(array("qHSV", 0, 0, 4, 3.308055191838597));
table.add(array("qRGB", 0, 1, 3, 4.3145002832409265));
table.add(array("qHSV", 0, 3, 1, 4.356094355535418));
table.add(array("qRGB", 1, 0, 3, 4.6480678384750584));
table.add(array("qHSV", 2, 0, 2, 4.720369162242616));
table.add(array("qHSV", 2, 1, 1, 4.771642243384687));
table.add(array("qHSV", 1, 3, 0, 4.820816066888919));
table.add(array("qRGB", 4, 0, 0, 4.951001286754124));
table.add(array("qRGB", 0, 3, 1, 5.179776824191323));
table.add(array("qRGB", 1, 3, 0, 5.245476477957572));
table.add(array("qHSV", 2, 2, 0, 5.275040700873244));
table.add(array("qHSV", 0, 4, 0, 8.608606861303441));
table.add(array("qRGB", 0, 0, 4, 10.005984804008115));
table.add(array("qHSV", 3, 0, 1, 10.16591826453798));
table.add(array("qHSV", 3, 1, 0, 10.246741129698233));
table.add(array("qRGB", 0, 4, 0, 11.621132862924227));
table.add(array("qHSV", 4, 0, 0, 21.441441059860917));
table.add(array("qRGB", 2, 1, 2, 2.345664153459157));
table.add(array("qRGB", 2, 2, 1, 2.3803760800798126));
table.add(array("qRGB", 3, 1, 1, 2.548324173801728));
table.add(array("qRGB", 1, 2, 2, 2.7386225128738215));
table.add(array("qHSV", 1, 1, 3, 2.890959844279944));
table.add(array("qHSV", 0, 2, 3, 3.039789316612684));
table.add(array("qRGB", 3, 2, 0, 3.0876627555063707));
table.add(array("qHSV", 1, 2, 2, 3.149855857626206));
table.add(array("qRGB", 3, 0, 2, 3.5456082043397177));
table.add(array("qHSV", 0, 1, 4, 3.6408406868479344));
table.add(array("qHSV", 1, 0, 4, 3.9301965018206424));
table.add(array("qRGB", 1, 1, 3, 4.377510140614242));
table.add(array("qRGB", 0, 2, 3, 4.55417176057843));
table.add(array("qHSV", 0, 3, 2, 4.558363544642229));
table.add(array("qRGB", 4, 1, 0, 4.866263779024119));
table.add(array("qHSV", 1, 3, 1, 4.890021661874276));
table.add(array("qHSV", 2, 1, 2, 4.896690972204208));
table.add(array("qRGB", 2, 0, 3, 4.975510162691538));
table.add(array("qHSV", 2, 0, 3, 5.073700328823798));
table.add(array("qRGB", 1, 3, 1, 5.076416388035941));
table.add(array("qRGB", 2, 3, 0, 5.186407432321236));
table.add(array("qRGB", 4, 0, 1, 5.18922966136709));
table.add(array("qRGB", 0, 3, 2, 5.253668905846729));
table.add(array("qHSV", 2, 2, 1, 5.321301853278064));
table.add(array("qHSV", 2, 3, 0, 6.78099035432321));
table.add(array("qHSV", 0, 0, 5, 6.8001379002246205));
table.add(array("qHSV", 0, 4, 1, 8.6804212735382));
table.add(array("qHSV", 1, 4, 0, 8.96150522653321));
table.add(array("qRGB", 0, 1, 4, 9.621269654573805));
table.add(array("qRGB", 1, 0, 4, 10.10082618502018));
table.add(array("qHSV", 3, 0, 2, 10.239604490826345));
table.add(array("qHSV", 3, 1, 1, 10.273738901017087));
table.add(array("qRGB", 5, 0, 0, 10.357214019008278));
table.add(array("qHSV", 3, 2, 0, 10.595095232353103));
table.add(array("qRGB", 0, 4, 1, 11.345079146799256));
table.add(array("qRGB", 1, 4, 0, 11.499694035514397));
table.add(array("qHSV", 0, 5, 0, 16.979860091230222));
table.add(array("qHSV", 4, 0, 1, 21.447935998355156));
table.add(array("qHSV", 4, 1, 0, 21.462964882808116));
table.add(array("qRGB", 0, 0, 5, 21.56144319342579));
table.add(array("qRGB", 0, 5, 0, 24.732918303318232));
table.add(array("qHSV", 5, 0, 0, 43.77691374160295));
table.add(array("qRGB", 2, 2, 2, 2.852922516764376));
table.add(array("qRGB", 3, 2, 1, 3.0828291421052723));
table.add(array("qRGB", 3, 1, 2, 3.3041165241821764));
table.add(array("qHSV", 1, 2, 3, 3.6541400074569506));
table.add(array("qHSV", 1, 1, 4, 4.215862457035969));
table.add(array("qHSV", 0, 2, 4, 4.460470627495945));
table.add(array("qRGB", 1, 2, 3, 4.539080994752359));
table.add(array("qRGB", 2, 1, 3, 4.6363242231465));
table.add(array("qRGB", 2, 3, 1, 5.004329263328033));
table.add(array("qRGB", 4, 1, 1, 5.011027074098335));
table.add(array("qHSV", 0, 3, 3, 5.062496531035296));
table.add(array("qHSV", 1, 3, 2, 5.063458476675465));
table.add(array("qRGB", 1, 3, 2, 5.147515511354933));
table.add(array("qRGB", 4, 2, 0, 5.167587135912787));
table.add(array("qHSV", 2, 1, 3, 5.260392593892533));
table.add(array("qRGB", 3, 3, 0, 5.432007270000069));
table.add(array("qHSV", 2, 2, 2, 5.446669044137193));
table.add(array("qRGB", 3, 0, 3, 5.825331577595821));
table.add(array("qRGB", 4, 0, 2, 5.931000598479003));
table.add(array("qHSV", 2, 0, 4, 6.082311495314012));
table.add(array("qRGB", 0, 3, 3, 6.254886430030773));
table.add(array("qHSV", 2, 3, 1, 6.830073389040216));
table.add(array("qHSV", 0, 1, 5, 7.122838491638112));
table.add(array("qHSV", 1, 0, 5, 7.218793962972602));
table.add(array("qHSV", 0, 4, 2, 8.848843990753025));
table.add(array("qHSV", 1, 4, 1, 9.024514418743152));
table.add(array("qRGB", 0, 2, 4, 9.322599398655775));
table.add(array("qRGB", 1, 1, 4, 9.682368743150985));
table.add(array("qRGB", 5, 1, 0, 10.172020644792356));
table.add(array("qHSV", 3, 1, 2, 10.346634555923645));
table.add(array("qRGB", 2, 0, 4, 10.349131860405612));
table.add(array("qHSV", 2, 4, 0, 10.378143392591879));
table.add(array("qHSV", 3, 0, 3, 10.46174533248007));
table.add(array("qRGB", 5, 0, 1, 10.533497144893856));
table.add(array("qHSV", 3, 2, 1, 10.62143108459401));
table.add(array("qRGB", 0, 4, 2, 11.08684873356561));
table.add(array("qRGB", 1, 4, 1, 11.212816854561149));
table.add(array("qRGB", 2, 4, 0, 11.32752806549405));
table.add(array("qHSV", 3, 3, 0, 11.635117350399002));
table.add(array("qHSV", 0, 0, 6, 15.668032586962413));
table.add(array("qHSV", 0, 5, 1, 17.04482075137555));
table.add(array("qHSV", 1, 5, 0, 17.187108424535914));
table.add(array("qRGB", 0, 1, 5, 21.08512918203094));
table.add(array("qHSV", 4, 1, 1, 21.469367174690095));
table.add(array("qHSV", 4, 0, 2, 21.473931969823585));
table.add(array("qRGB", 6, 0, 0, 21.532049376223195));
table.add(array("qHSV", 4, 2, 0, 21.59445165396762));
table.add(array("qRGB", 1, 0, 5, 21.638632549717023));
table.add(array("qRGB", 0, 5, 1, 24.37721172994415));
table.add(array("qRGB", 1, 5, 0, 24.60734851909329));
table.add(array("qHSV", 0, 6, 0, 32.73574351446413));
table.add(array("qHSV", 5, 1, 0, 43.751204156283656));
table.add(array("qHSV", 5, 0, 1, 43.76416717883281));
table.add(array("qRGB", 0, 0, 6, 46.13239365025457));
table.add(array("qRGB", 0, 6, 0, 52.70802175522528));
table.add(array("qHSV", 6, 0, 0, 83.81508873246744));
table.add(array("qRGB", 3, 2, 2, 3.527362691503131));
table.add(array("qRGB", 2, 2, 3, 4.653057616366176));
table.add(array("qHSV", 1, 2, 4, 4.950383818907108));
table.add(array("qRGB", 2, 3, 2, 5.068365988414407));
table.add(array("qRGB", 4, 2, 1, 5.178832026758057));
table.add(array("qRGB", 3, 3, 1, 5.253549057030269));
table.add(array("qRGB", 3, 1, 3, 5.433232494141032));
table.add(array("qHSV", 1, 3, 3, 5.516563492291423));
table.add(array("qRGB", 4, 1, 2, 5.635111396603524));
table.add(array("qHSV", 2, 2, 3, 5.816758192084616));
table.add(array("qRGB", 1, 3, 3, 6.166399561123543));
table.add(array("qHSV", 2, 1, 4, 6.289879138851597));
table.add(array("qHSV", 0, 3, 4, 6.345495263856095));
table.add(array("qRGB", 4, 3, 0, 6.783776610747946));
table.add(array("qHSV", 2, 3, 2, 6.958393497024418));
table.add(array("qHSV", 1, 1, 5, 7.514279390344463));
table.add(array("qHSV", 0, 2, 5, 7.850523125363171));
table.add(array("qRGB", 4, 0, 3, 7.909364447767676));
table.add(array("qHSV", 2, 0, 5, 8.893228803404542));
table.add(array("qHSV", 1, 4, 2, 9.177754256712644));
table.add(array("qHSV", 0, 4, 3, 9.270509807166043));
table.add(array("qRGB", 1, 2, 4, 9.33366729062409));
table.add(array("qRGB", 2, 1, 4, 9.890118915323102));
table.add(array("qRGB", 0, 3, 4, 9.929929778266683));
table.add(array("qRGB", 5, 2, 0, 10.138080062468157));
table.add(array("qRGB", 5, 1, 1, 10.29114858366));
table.add(array("qHSV", 2, 4, 1, 10.428669001108311));
table.add(array("qHSV", 3, 1, 3, 10.577000076352872));
table.add(array("qHSV", 3, 2, 2, 10.69795588995799));
table.add(array("qRGB", 1, 4, 2, 10.949224161393213));
table.add(array("qRGB", 3, 0, 4, 11.00602110019438));
table.add(array("qRGB", 2, 4, 1, 11.02877492642026));
table.add(array("qRGB", 5, 0, 2, 11.102983007881091));
table.add(array("qHSV", 3, 0, 4, 11.158505372879214));
table.add(array("qRGB", 3, 4, 0, 11.227760965671465));
table.add(array("qRGB", 0, 4, 3, 11.309405765689151));
table.add(array("qHSV", 3, 3, 1, 11.664870489106614));
table.add(array("qHSV", 3, 4, 0, 14.395372498170593));
table.add(array("qHSV", 1, 0, 6, 15.901936420764862));
table.add(array("qHSV", 0, 1, 6, 15.991471787000199));
table.add(array("qHSV", 0, 5, 2, 17.176936549609696));
table.add(array("qHSV", 1, 5, 1, 17.247695065696494));
table.add(array("qHSV", 2, 5, 0, 18.082575505826718));
table.add(array("qRGB", 0, 2, 5, 20.405035493287702));
table.add(array("qRGB", 1, 1, 5, 21.14347635507767));
table.add(array("qRGB", 6, 1, 0, 21.293096999751032));
table.add(array("qHSV", 4, 1, 2, 21.496241062179358));
table.add(array("qHSV", 4, 0, 3, 21.580207287110984));
table.add(array("qHSV", 4, 2, 1, 21.602329841806487));
table.add(array("qRGB", 6, 0, 1, 21.67462497600947));
table.add(array("qRGB", 2, 0, 5, 21.830723642418008));
table.add(array("qHSV", 4, 3, 0, 22.133768474410587));
table.add(array("qRGB", 0, 5, 2, 23.86359478382961));
table.add(array("qRGB", 1, 5, 1, 24.244431205525952));
table.add(array("qRGB", 2, 5, 0, 24.39691267076655));
table.add(array("qHSV", 0, 6, 1, 32.80316538441022));
table.add(array("qHSV", 1, 6, 0, 32.842233350233535));
table.add(array("qHSV", 5, 2, 0, 43.74076975658067));
table.add(array("qHSV", 5, 1, 1, 43.742010947423));
table.add(array("qHSV", 5, 0, 2, 43.7562916943628));
table.add(array("qHSV", 0, 0, 7, 44.92160259247629));
table.add(array("qRGB", 7, 0, 0, 45.176087377745176));
table.add(array("qRGB", 0, 1, 6, 45.62356017773505));
table.add(array("qRGB", 1, 0, 6, 46.196411417482125));
table.add(array("qRGB", 0, 6, 1, 52.301160399275815));
table.add(array("qRGB", 1, 6, 0, 52.61193218654751));
table.add(array("qHSV", 0, 7, 0, 61.80730533010471));
table.add(array("qHSV", 6, 1, 0, 83.63587197808127));
table.add(array("qHSV", 6, 0, 1, 83.76551042010584));
table.add(array("qRGB", 0, 0, 7, 98.58169362835481));
table.add(array("qRGB", 0, 7, 0, 113.80279045303948));
table.add(array("qHSV", 7, 0, 0, 156.02265105719644));
table.add(array("qRGB", 3, 2, 3, 5.253916642742753));
table.add(array("qRGB", 3, 3, 2, 5.313590650823462));
table.add(array("qRGB", 4, 2, 2, 5.575899042570833));
table.add(array("qRGB", 2, 3, 3, 6.102583333976196));
table.add(array("qRGB", 4, 3, 1, 6.637861657250586));
table.add(array("qHSV", 1, 3, 4, 6.720167065205978));
table.add(array("qHSV", 2, 2, 4, 6.853957182198859));
table.add(array("qHSV", 2, 3, 3, 7.313034588867101));
table.add(array("qRGB", 4, 1, 3, 7.4952032204868));
table.add(array("qHSV", 1, 2, 5, 8.19464651896803));
table.add(array("qHSV", 2, 1, 5, 9.128864210622176));
table.add(array("qRGB", 2, 2, 4, 9.45054024064088));
table.add(array("qHSV", 0, 3, 5, 9.50272830656282));
table.add(array("qHSV", 1, 4, 3, 9.57225682172096));
table.add(array("qRGB", 1, 3, 4, 9.878300576656232));
table.add(array("qRGB", 5, 2, 1, 10.168317697289462));
table.add(array("qHSV", 0, 4, 4, 10.325282646966802));
table.add(array("qRGB", 3, 1, 4, 10.513446996566712));
table.add(array("qHSV", 2, 4, 2, 10.553962637282169));
table.add(array("qRGB", 2, 4, 2, 10.754583231629907));
table.add(array("qRGB", 5, 1, 2, 10.78334660852396));
table.add(array("qRGB", 3, 4, 1, 10.923400572688765));
table.add(array("qHSV", 3, 2, 3, 10.940245342238159));
table.add(array("qRGB", 5, 3, 0, 10.948747935514554));
table.add(array("qRGB", 1, 4, 3, 11.177647318386894));
table.add(array("qHSV", 3, 1, 4, 11.292017176980279));
table.add(array("qHSV", 3, 3, 2, 11.749442609095881));
table.add(array("qRGB", 4, 4, 0, 11.754305664224468));
table.add(array("qRGB", 4, 0, 4, 12.707821916090875));
table.add(array("qRGB", 5, 0, 3, 12.721094610289231));
table.add(array("qHSV", 3, 0, 5, 13.321914762530062));
table.add(array("qRGB", 0, 4, 4, 13.462907410406403));
table.add(array("qHSV", 3, 4, 1, 14.428941545444602));
table.add(array("qHSV", 1, 1, 6, 16.213530849741776));
table.add(array("qHSV", 0, 2, 6, 16.595732776692728));
table.add(array("qHSV", 2, 0, 6, 16.990247872051476));
table.add(array("qHSV", 1, 5, 2, 17.37262548192689));
table.add(array("qHSV", 0, 5, 3, 17.50097970500494));
table.add(array("qHSV", 2, 5, 1, 18.135576856216254));
table.add(array("qRGB", 0, 3, 5, 19.920991125299423));
table.add(array("qRGB", 1, 2, 5, 20.43422559355158));
table.add(array("qHSV", 3, 5, 0, 20.953539337715004));
table.add(array("qRGB", 6, 2, 0, 21.039614618747564));
table.add(array("qRGB", 2, 1, 5, 21.311634080572432));
table.add(array("qRGB", 6, 1, 1, 21.402040306383505));
table.add(array("qHSV", 4, 1, 3, 21.607639767259705));
table.add(array("qHSV", 4, 2, 2, 21.635546199656854));
table.add(array("qHSV", 4, 0, 4, 21.980255130529887));
table.add(array("qRGB", 6, 0, 2, 22.113679071750695));
table.add(array("qHSV", 4, 3, 1, 22.144316336683882));
table.add(array("qRGB", 3, 0, 5, 22.328417765460777));
table.add(array("qRGB", 0, 5, 3, 23.401054294240303));
table.add(array("qRGB", 1, 5, 2, 23.725014384855967));
table.add(array("qHSV", 4, 4, 0, 23.862897375364486));
table.add(array("qRGB", 2, 5, 1, 24.024643580435026));
table.add(array("qRGB", 3, 5, 0, 24.123412933265822));
table.add(array("qHSV", 0, 6, 2, 32.89667758007501));
table.add(array("qHSV", 1, 6, 1, 32.90781890164448));
table.add(array("qHSV", 2, 6, 0, 33.32236993216267));
table.add(array("qHSV", 5, 2, 1, 43.73216585611982));
table.add(array("qHSV", 5, 1, 2, 43.73285247357186));
table.add(array("qHSV", 5, 0, 3, 43.773924275773595));
table.add(array("qHSV", 5, 3, 0, 43.87212842657174));
table.add(array("qRGB", 0, 2, 6, 44.73957191563254));
table.add(array("qRGB", 7, 1, 0, 44.91994210785489));
table.add(array("qHSV", 1, 0, 7, 45.012075852208746));
table.add(array("qRGB", 7, 0, 1, 45.321510970753366));
table.add(array("qHSV", 0, 1, 7, 45.3975990469012));
table.add(array("qRGB", 1, 1, 6, 45.67720247527094));
table.add(array("qRGB", 2, 0, 6, 46.3468570278201));
table.add(array("qRGB", 0, 6, 2, 51.60143636551707));
table.add(array("qRGB", 1, 6, 1, 52.200354051560105));
table.add(array("qRGB", 2, 6, 0, 52.442942082617805));
table.add(array("qHSV", 1, 7, 0, 61.84624110147413));
table.add(array("qHSV", 0, 7, 1, 61.98559575821476));
table.add(array("qHSV", 6, 2, 0, 83.31021735981916));
table.add(array("qHSV", 6, 1, 1, 83.59644325622138));
table.add(array("qHSV", 6, 0, 2, 83.70003079189063));
table.add(array("qRGB", 0, 1, 7, 98.09175375687065));
table.add(array("qRGB", 1, 0, 7, 98.63222463427425));
table.add(array("qRGB", 0, 7, 1, 113.35848060108387));
table.add(array("qRGB", 1, 7, 0, 113.79100745068551));
table.add(array("qHSV", 7, 1, 0, 155.76875083166007));
table.add(array("qHSV", 7, 0, 1, 155.9388815899415));
table.add(array("qRGB", 3, 3, 3, 6.340866483189372));
table.add(array("qRGB", 4, 3, 2, 6.709653006265603));
table.add(array("qRGB", 4, 2, 3, 7.129963963236756));
table.add(array("qHSV", 2, 3, 4, 8.320823808478119));
table.add(array("qHSV", 2, 2, 5, 9.692344955617365));
table.add(array("qHSV", 1, 3, 5, 9.779610923631795));
table.add(array("qRGB", 2, 3, 4, 9.857522392338288));
table.add(array("qRGB", 3, 2, 4, 9.950763892439424));
table.add(array("qRGB", 5, 2, 2, 10.507557830242826));
table.add(array("qHSV", 1, 4, 4, 10.584318858953525));
table.add(array("qRGB", 3, 4, 2, 10.638399022749269));
table.add(array("qRGB", 5, 3, 1, 10.85649017076917));
table.add(array("qHSV", 2, 4, 3, 10.886674213271974));
table.add(array("qRGB", 2, 4, 3, 10.986209294528791));
table.add(array("qRGB", 4, 4, 1, 11.46652530930045));
table.add(array("qHSV", 3, 2, 4, 11.673906598335554));
table.add(array("qHSV", 3, 3, 3, 11.994609999866599));
table.add(array("qRGB", 4, 1, 4, 12.20218340832902));
table.add(array("qRGB", 5, 1, 3, 12.312975745853725));
table.add(array("qHSV", 0, 4, 5, 13.149357181796196));
table.add(array("qRGB", 1, 4, 4, 13.35518595291978));
table.add(array("qHSV", 3, 1, 5, 13.487052808959266));
table.add(array("qHSV", 3, 4, 2, 14.518904965426142));
table.add(array("qRGB", 5, 4, 0, 14.556491367623703));
table.add(array("qHSV", 1, 2, 6, 16.799177364455836));
table.add(array("qRGB", 5, 0, 4, 16.923951577513773));
table.add(array("qHSV", 2, 1, 6, 17.266229614644402));
table.add(array("qHSV", 1, 5, 3, 17.683854172496947));
table.add(array("qHSV", 0, 3, 6, 18.027459361336454));
table.add(array("qHSV", 2, 5, 2, 18.246274714415243));
table.add(array("qHSV", 0, 5, 4, 18.349046936514938));
table.add(array("qRGB", 1, 3, 5, 19.907650136450783));
table.add(array("qHSV", 3, 0, 6, 20.31449096221656));
table.add(array("qRGB", 2, 2, 5, 20.549489748044554));
table.add(array("qHSV", 3, 5, 1, 20.994690069622262));
table.add(array("qRGB", 6, 2, 1, 21.093244874228947));
table.add(array("qRGB", 6, 3, 0, 21.19254912139334));
table.add(array("qRGB", 0, 4, 5, 21.246600560116846));
table.add(array("qHSV", 4, 2, 3, 21.75875632193585));
table.add(array("qRGB", 3, 1, 5, 21.78644893297665));
table.add(array("qRGB", 6, 1, 2, 21.79250600681563));
table.add(array("qHSV", 4, 1, 4, 22.02443261543551));
table.add(array("qHSV", 4, 3, 2, 22.186876867524546));
table.add(array("qRGB", 1, 5, 3, 23.260883706223176));
table.add(array("qRGB", 6, 0, 3, 23.386703338692957));
table.add(array("qHSV", 4, 0, 5, 23.427093643965375));
table.add(array("qRGB", 2, 5, 2, 23.493924375351092));
table.add(array("qRGB", 4, 0, 5, 23.642266327011406));
table.add(array("qRGB", 3, 5, 1, 23.741972884777905));
table.add(array("qHSV", 4, 4, 1, 23.879017394229695));
table.add(array("qRGB", 0, 5, 4, 23.943637893089022));
table.add(array("qRGB", 4, 5, 0, 24.063262335361493));
table.add(array("qHSV", 4, 5, 0, 28.615899360492723));
table.add(array("qHSV", 1, 6, 2, 32.99827811369083));
table.add(array("qHSV", 0, 6, 3, 33.1286253581266));
table.add(array("qHSV", 2, 6, 1, 33.3839421900219));
table.add(array("qHSV", 3, 6, 0, 35.009802069537756));
table.add(array("qRGB", 0, 3, 6, 43.460896182311956));
table.add(array("qHSV", 5, 2, 2, 43.73202855891318));
table.add(array("qHSV", 5, 1, 3, 43.7535637956447));
table.add(array("qHSV", 5, 3, 1, 43.86640260615535));
table.add(array("qHSV", 5, 0, 4, 43.92909101484812));
table.add(array("qHSV", 5, 4, 0, 44.55571124845371));
table.add(array("qRGB", 7, 2, 0, 44.55833251204558));
table.add(array("qRGB", 1, 2, 6, 44.776897391602574));
table.add(array("qRGB", 7, 1, 1, 45.04637978612198));
table.add(array("qHSV", 1, 1, 7, 45.482246920674726));
table.add(array("qHSV", 2, 0, 7, 45.51365112224777));
table.add(array("qRGB", 7, 0, 2, 45.70512868979869));
table.add(array("qRGB", 2, 1, 6, 45.813611637632384));
table.add(array("qHSV", 0, 2, 7, 45.89436224260916));
table.add(array("qRGB", 3, 0, 6, 46.720243380629405));
table.add(array("qRGB", 0, 6, 3, 50.56913459912434));
table.add(array("qRGB", 1, 6, 2, 51.495507349823036));
table.add(array("qRGB", 2, 6, 1, 52.024598427168634));
table.add(array("qRGB", 3, 6, 0, 52.19106917882459));
table.add(array("qHSV", 0, 7, 2, 62.01143653140464));
table.add(array("qHSV", 1, 7, 1, 62.023247577307245));
table.add(array("qHSV", 2, 7, 0, 62.02579926667945));
table.add(array("qHSV", 6, 3, 0, 82.76435853485751));
table.add(array("qHSV", 6, 2, 1, 83.27401911307462));
table.add(array("qHSV", 6, 1, 2, 83.53199900326042));
table.add(array("qHSV", 6, 0, 3, 83.58759338540732));
table.add(array("qRGB", 0, 2, 7, 97.16239083873536));
table.add(array("qRGB", 1, 1, 7, 98.13677798324206));
table.add(array("qRGB", 2, 0, 7, 98.74559245319055));
table.add(array("qRGB", 0, 7, 2, 112.52326535326874));
table.add(array("qRGB", 1, 7, 1, 113.34355286396212));
table.add(array("qRGB", 2, 7, 0, 113.78207678079858));
table.add(array("qHSV", 7, 2, 0, 155.26271089738088));
table.add(array("qHSV", 7, 1, 1, 155.69921989766797));
table.add(array("qHSV", 7, 0, 2, 155.81640234578813));
table.add(array("qRGB", 4, 3, 3, 7.688442546008208));
table.add(array("qRGB", 3, 3, 4, 10.095141022638085));
table.add(array("qRGB", 3, 4, 3, 10.864897114402869));
table.add(array("qRGB", 5, 3, 2, 10.951615663240458));
table.add(array("qHSV", 2, 3, 5, 11.070154272260991));
table.add(array("qRGB", 4, 4, 2, 11.191632862199885));
table.add(array("qRGB", 4, 2, 4, 11.52598396241005));
table.add(array("qHSV", 2, 4, 4, 11.782463229695244));
table.add(array("qRGB", 5, 2, 3, 11.819634155213707));
table.add(array("qHSV", 3, 3, 4, 12.734447695338403));
table.add(array("qRGB", 2, 4, 4, 13.198005564072307));
table.add(array("qHSV", 1, 4, 5, 13.349700851194054));
table.add(array("qHSV", 3, 2, 5, 13.89682265182176));
table.add(array("qRGB", 5, 4, 1, 14.322611845014073));
table.add(array("qHSV", 3, 4, 3, 14.765915006914788));
table.add(array("qRGB", 5, 1, 4, 16.431998213672987));
table.add(array("qHSV", 2, 2, 6, 17.794743002263));
table.add(array("qHSV", 1, 3, 6, 18.19966125131184));
table.add(array("qHSV", 1, 5, 4, 18.509866614595577));
table.add(array("qHSV", 2, 5, 3, 18.52725317113241));
table.add(array("qRGB", 2, 3, 5, 19.933533714232336));
table.add(array("qHSV", 3, 1, 6, 20.533316034673383));
table.add(array("qHSV", 0, 5, 5, 20.662238654155118));
table.add(array("qRGB", 3, 2, 5, 20.95052655636009));
table.add(array("qHSV", 3, 5, 2, 21.083018105884644));
table.add(array("qHSV", 0, 4, 6, 21.110219649964062));
table.add(array("qRGB", 6, 3, 1, 21.161371921806357));
table.add(array("qRGB", 1, 4, 5, 21.18027776782719));
table.add(array("qRGB", 6, 2, 2, 21.38663005776269));
table.add(array("qHSV", 4, 2, 4, 22.196381149547953));
table.add(array("qHSV", 4, 3, 3, 22.32389197746879));
table.add(array("qRGB", 6, 1, 3, 23.0029729164763));
table.add(array("qRGB", 2, 5, 3, 23.022684799085344));
table.add(array("qRGB", 4, 1, 5, 23.086305798726343));
table.add(array("qRGB", 3, 5, 2, 23.194828446980296));
table.add(array("qRGB", 6, 4, 0, 23.288580709898017));
table.add(array("qHSV", 4, 1, 5, 23.501867553611202));
table.add(array("qRGB", 4, 5, 1, 23.68088624329254));
table.add(array("qRGB", 1, 5, 4, 23.811048702797404));
table.add(array("qHSV", 4, 4, 2, 23.930560280338014));
table.add(array("qRGB", 5, 5, 0, 25.402895483675284));
table.add(array("qRGB", 6, 0, 4, 26.864638036544115));
table.add(array("qRGB", 5, 0, 5, 27.081377578441117));
table.add(array("qRGB", 0, 5, 5, 28.54063915420294));
table.add(array("qHSV", 4, 5, 1, 28.641730651838913));
table.add(array("qHSV", 4, 0, 6, 28.854331775352687));
table.add(array("qHSV", 1, 6, 3, 33.22460294147693));
table.add(array("qHSV", 2, 6, 2, 33.46921764781381));
table.add(array("qHSV", 0, 6, 4, 33.702579763034635));
table.add(array("qHSV", 3, 6, 1, 35.06389034413055));
table.add(array("qHSV", 4, 6, 0, 40.137731481784115));
table.add(array("qRGB", 0, 4, 6, 42.525753512691516));
table.add(array("qRGB", 1, 3, 6, 43.47286860289719));
table.add(array("qHSV", 5, 2, 3, 43.75703255179147));
table.add(array("qHSV", 5, 3, 2, 43.86973635535911));
table.add(array("qHSV", 5, 1, 4, 43.9193503618413));
table.add(array("qRGB", 7, 3, 0, 44.309567106007385));
table.add(array("qHSV", 5, 4, 1, 44.55595283640167));
table.add(array("qRGB", 7, 2, 1, 44.652283598962846));
table.add(array("qHSV", 5, 0, 5, 44.70057087412785));
table.add(array("qRGB", 2, 2, 6, 44.88342483911719));
table.add(array("qRGB", 7, 1, 2, 45.40073048149536));
table.add(array("qHSV", 2, 1, 7, 45.957826377522295));
table.add(array("qHSV", 1, 2, 7, 45.97438884520198));
table.add(array("qRGB", 3, 1, 6, 46.171046220192245));
table.add(array("qRGB", 7, 0, 3, 46.74410786531797));
table.add(array("qHSV", 0, 3, 7, 46.94047509487422));
table.add(array("qHSV", 5, 5, 0, 46.98065616162865));
table.add(array("qHSV", 3, 0, 7, 47.31084724651443));
table.add(array("qRGB", 4, 0, 6, 47.69348627992129));
table.add(array("qRGB", 0, 6, 4, 49.58886169746684));
table.add(array("qRGB", 1, 6, 3, 50.45815908106512));
table.add(array("qRGB", 2, 6, 2, 51.30975863355777));
table.add(array("qRGB", 3, 6, 1, 51.76398032287591));
table.add(array("qRGB", 4, 6, 0, 51.98456631116456));
table.add(array("qHSV", 1, 7, 2, 62.0476400938254));
table.add(array("qHSV", 0, 7, 3, 62.08910702114573));
table.add(array("qHSV", 2, 7, 1, 62.19923587229031));
table.add(array("qHSV", 3, 7, 0, 62.71396179748241));
table.add(array("qHSV", 6, 4, 0, 82.01003193662558));
table.add(array("qHSV", 6, 3, 1, 82.73396479269887));
table.add(array("qHSV", 6, 2, 2, 83.2140183000991));
table.add(array("qHSV", 6, 1, 3, 83.4241302922701));
table.add(array("qHSV", 6, 0, 4, 83.43394427208376));
table.add(array("qRGB", 0, 3, 7, 95.5024295094967));
table.add(array("qRGB", 1, 2, 7, 97.19867684302076));
table.add(array("qRGB", 2, 1, 7, 98.2421679833705));
table.add(array("qRGB", 3, 0, 7, 99.01508349160125));
table.add(array("qRGB", 0, 7, 3, 111.04199670996694));
table.add(array("qRGB", 1, 7, 2, 112.50410102149714));
table.add(array("qRGB", 2, 7, 1, 113.32974893931791));
table.add(array("qRGB", 3, 7, 0, 113.8193934779908));
table.add(array("qHSV", 7, 3, 0, 154.25179097350306));
table.add(array("qHSV", 7, 2, 1, 155.19759088118153));
table.add(array("qHSV", 7, 0, 3, 155.5731316317515));
table.add(array("qHSV", 7, 1, 2, 155.57639462650135));
table.add(array("qRGB", 4, 3, 4, 11.300385291883343));
table.add(array("qRGB", 4, 4, 3, 11.413287765007333));
table.add(array("qRGB", 5, 3, 3, 11.835590580277925));
table.add(array("qRGB", 3, 4, 4, 13.105170302239044));
table.add(array("qRGB", 5, 4, 2, 14.102725593278263));
table.add(array("qHSV", 2, 4, 5, 14.342172542032769));
table.add(array("qHSV", 3, 3, 5, 14.946261925820883));
table.add(array("qHSV", 3, 4, 4, 15.46518525367638));
table.add(array("qRGB", 5, 2, 4, 15.6937208294619));
table.add(array("qHSV", 2, 3, 6, 19.079145485722293));
table.add(array("qHSV", 2, 5, 4, 19.290435137212366));
table.add(array("qRGB", 3, 3, 5, 20.16864052990391));
table.add(array("qHSV", 1, 5, 5, 20.791984112466153));
table.add(array("qHSV", 3, 2, 6, 20.96089276744169));
table.add(array("qRGB", 2, 4, 5, 21.08938909810169));
table.add(array("qHSV", 1, 4, 6, 21.243770468351563));
table.add(array("qRGB", 6, 3, 2, 21.288110810768334));
table.add(array("qHSV", 3, 5, 3, 21.312307819388156));
table.add(array("qRGB", 4, 2, 5, 22.178404640544578));
table.add(array("qRGB", 6, 2, 3, 22.45089367092038));
table.add(array("qRGB", 3, 5, 3, 22.70561761512323));
table.add(array("qHSV", 4, 3, 4, 22.783387113717136));
table.add(array("qRGB", 4, 5, 2, 23.12311052644533));
table.add(array("qRGB", 6, 4, 1, 23.13965229796283));
table.add(array("qRGB", 2, 5, 4, 23.581710343484367));
table.add(array("qHSV", 4, 2, 5, 23.712242409809047));
table.add(array("qHSV", 4, 4, 3, 24.08132103092352));
table.add(array("qRGB", 5, 5, 1, 25.045878832584336));
table.add(array("qRGB", 6, 1, 4, 26.409192843237044));
table.add(array("qRGB", 5, 1, 5, 26.529047924439634));
table.add(array("qHSV", 0, 5, 6, 27.63065202910769));
table.add(array("qRGB", 1, 5, 5, 28.431190265339374));
table.add(array("qHSV", 4, 5, 2, 28.6992567436543));
table.add(array("qHSV", 4, 1, 6, 28.982662338530055));
table.add(array("qRGB", 6, 5, 0, 31.698950614604737));
table.add(array("qHSV", 2, 6, 3, 33.68213058054486));
table.add(array("qHSV", 1, 6, 4, 33.78916238071692));
table.add(array("qHSV", 3, 6, 2, 35.137672403014726));
table.add(array("qHSV", 0, 6, 5, 35.38285901058025));
table.add(array("qRGB", 6, 0, 5, 35.798088797723715));
table.add(array("qHSV", 4, 6, 1, 40.17942007592115));
table.add(array("qRGB", 1, 4, 6, 42.499987755993985));
table.add(array("qRGB", 2, 3, 6, 43.52716203099239));
table.add(array("qHSV", 5, 3, 3, 43.906895816832254));
table.add(array("qHSV", 5, 2, 4, 43.935627297756106));
table.add(array("qRGB", 7, 3, 1, 44.349719267806194));
table.add(array("qHSV", 5, 4, 2, 44.56590570376091));
table.add(array("qHSV", 5, 1, 5, 44.70977685547477));
table.add(array("qRGB", 7, 2, 2, 44.94814474219706));
table.add(array("qRGB", 0, 5, 6, 45.098262849514896));
table.add(array("qRGB", 3, 2, 6, 45.19680023082748));
table.add(array("qRGB", 7, 4, 0, 45.24050897140638));
table.add(array("qRGB", 7, 1, 3, 46.397617749593216));
table.add(array("qHSV", 2, 2, 7, 46.42892542288154));
table.add(array("qHSV", 5, 5, 1, 46.98756966975928));
table.add(array("qHSV", 1, 3, 7, 47.01472807679523));
table.add(array("qRGB", 4, 1, 6, 47.12882395174464));
table.add(array("qHSV", 3, 1, 7, 47.69825145609503));
table.add(array("qHSV", 5, 0, 6, 48.30892314902963));
table.add(array("qHSV", 0, 4, 7, 49.13722160795946));
table.add(array("qRGB", 1, 6, 4, 49.47449215886267));
table.add(array("qRGB", 7, 0, 4, 49.56445112803157));
table.add(array("qRGB", 2, 6, 3, 50.26044398911863));
table.add(array("qRGB", 5, 0, 6, 50.31137045369451));
table.add(array("qRGB", 0, 6, 5, 50.568076039984064));
table.add(array("qRGB", 3, 6, 2, 51.032435381608266));
table.add(array("qRGB", 4, 6, 1, 51.548862763853826));
table.add(array("qRGB", 5, 6, 0, 52.552285583869214));
table.add(array("qHSV", 4, 0, 7, 52.8129511776001));
table.add(array("qHSV", 5, 6, 0, 54.13995592279949));
table.add(array("qHSV", 1, 7, 3, 62.123968137878016));
table.add(array("qHSV", 2, 7, 2, 62.221939996879684));
table.add(array("qHSV", 0, 7, 4, 62.31871516714029));
table.add(array("qHSV", 3, 7, 1, 62.87714478304283));
table.add(array("qHSV", 4, 7, 0, 65.07473789181662));
table.add(array("qHSV", 6, 5, 0, 81.4408397301875));
table.add(array("qHSV", 6, 4, 1, 81.98400997685754));
table.add(array("qHSV", 6, 3, 2, 82.67858543292775));
table.add(array("qHSV", 6, 2, 3, 83.11171679692882));
table.add(array("qHSV", 6, 1, 4, 83.27724778864844));
table.add(array("qHSV", 6, 0, 5, 83.41585847422323));
table.add(array("qRGB", 0, 4, 7, 92.95641588673492));
table.add(array("qRGB", 1, 3, 7, 95.52435465074312));
table.add(array("qRGB", 2, 2, 7, 97.28774943440655));
table.add(array("qRGB", 3, 1, 7, 98.50079273033025));
table.add(array("qRGB", 4, 0, 7, 99.70123907935444));
table.add(array("qRGB", 0, 7, 4, 108.70942567609441));
table.add(array("qRGB", 1, 7, 3, 111.01652069235655));
table.add(array("qRGB", 2, 7, 2, 112.48198468055303));
table.add(array("qRGB", 3, 7, 1, 113.35964114383401));
table.add(array("qRGB", 4, 7, 0, 114.08455335800612));
table.add(array("qHSV", 7, 4, 0, 152.26767295140053));
table.add(array("qHSV", 7, 3, 1, 154.18872685701697));
table.add(array("qHSV", 7, 2, 2, 155.07487080911943));
table.add(array("qHSV", 7, 0, 4, 155.09750765195514));
table.add(array("qHSV", 7, 1, 3, 155.33090566219985));
table.add(array("qRGB", 4, 4, 4, 13.635492369684071));
table.add(array("qRGB", 5, 4, 3, 14.339651153267729));
table.add(array("qRGB", 5, 3, 4, 15.105009711688462));
table.add(array("qHSV", 3, 4, 5, 17.613021066244166));
table.add(array("qRGB", 3, 4, 5, 21.06899986017425));
table.add(array("qRGB", 4, 3, 5, 21.163357953208294));
table.add(array("qHSV", 2, 5, 5, 21.459022937564324));
table.add(array("qHSV", 3, 5, 4, 21.953548327784002));
table.add(array("qHSV", 2, 4, 6, 21.953794391617667));
table.add(array("qHSV", 3, 3, 6, 22.015191420102827));
table.add(array("qRGB", 6, 3, 3, 22.057818941088346));
table.add(array("qRGB", 4, 5, 3, 22.611345132538872));
table.add(array("qRGB", 6, 4, 2, 23.01722632330868));
table.add(array("qRGB", 3, 5, 4, 23.26583544312819));
table.add(array("qHSV", 4, 3, 5, 24.334741391416884));
table.add(array("qRGB", 5, 5, 2, 24.513149100441726));
table.add(array("qHSV", 4, 4, 4, 24.54206993455648));
table.add(array("qRGB", 5, 2, 5, 25.583221839197073));
table.add(array("qRGB", 6, 2, 4, 25.672319962794653));
table.add(array("qHSV", 1, 5, 6, 27.723584486538304));
table.add(array("qRGB", 2, 5, 5, 28.24066686271142));
table.add(array("qHSV", 4, 5, 3, 28.858335408264463));
table.add(array("qHSV", 4, 2, 6, 29.245750524384043));
table.add(array("qRGB", 6, 5, 1, 31.41318872510949));
table.add(array("qHSV", 2, 6, 4, 34.22040714241764));
table.add(array("qRGB", 6, 1, 5, 35.27323810665261));
table.add(array("qHSV", 3, 6, 3, 35.32334270831286));
table.add(array("qHSV", 1, 6, 5, 35.45535791369207));
table.add(array("qHSV", 4, 6, 2, 40.23476684721952));
table.add(array("qHSV", 0, 6, 6, 40.75582097662498));
table.add(array("qRGB", 2, 4, 6, 42.47457324801316));
table.add(array("qRGB", 3, 3, 6, 43.743810942045144));
table.add(array("qHSV", 5, 3, 4, 44.10013792348927));
table.add(array("qRGB", 7, 3, 2, 44.5399115043061));
table.add(array("qHSV", 5, 4, 3, 44.61240036097907));
table.add(array("qHSV", 5, 2, 5, 44.75074825138069));
table.add(array("qRGB", 1, 5, 6, 45.02628653090765));
table.add(array("qRGB", 7, 4, 1, 45.19548827530423));
table.add(array("qRGB", 7, 2, 3, 45.85128412568048));
table.add(array("qRGB", 4, 2, 6, 46.104706678281275));
table.add(array("qHSV", 5, 5, 2, 47.00216719845255));
table.add(array("qHSV", 2, 3, 7, 47.434430403929944));
table.add(array("qHSV", 3, 2, 7, 48.113864245075504));
table.add(array("qHSV", 5, 1, 6, 48.35414705431072));
table.add(array("qRGB", 7, 1, 4, 49.16085177151545));
table.add(array("qHSV", 1, 4, 7, 49.200744348108195));
table.add(array("qRGB", 2, 6, 4, 49.26688031984588));
table.add(array("qRGB", 5, 1, 6, 49.736293373767865));
table.add(array("qRGB", 3, 6, 3, 49.95796953990217));
table.add(array("qRGB", 1, 6, 5, 50.455210971385455));
table.add(array("qRGB", 4, 6, 2, 50.79571129684579));
table.add(array("qRGB", 7, 5, 0, 51.06486999908676));
table.add(array("qRGB", 5, 6, 1, 52.116365829212135));
table.add(array("qHSV", 4, 1, 7, 53.10463249735915));
table.add(array("qHSV", 0, 5, 7, 53.78015545839082));
table.add(array("qHSV", 5, 6, 1, 54.159747593732384));
table.add(array("qRGB", 6, 6, 0, 56.65347676334426));
table.add(array("qRGB", 7, 0, 5, 57.05088417395533));
table.add(array("qRGB", 6, 0, 6, 57.387399296171345));
table.add(array("qRGB", 0, 6, 6, 59.83107919981765));
table.add(array("qHSV", 2, 7, 3, 62.295216190063));
table.add(array("qHSV", 1, 7, 4, 62.35076210418596));
table.add(array("qHSV", 3, 7, 2, 62.89298902640965));
table.add(array("qHSV", 0, 7, 5, 63.112997894458175));
table.add(array("qHSV", 4, 7, 1, 65.22501380465377));
table.add(array("qHSV", 5, 0, 7, 67.35803299473069));
table.add(array("qHSV", 5, 7, 0, 72.5529842358517));
table.add(array("qHSV", 6, 5, 1, 81.41961158006531));
table.add(array("qHSV", 6, 4, 2, 81.93752641201267));
table.add(array("qHSV", 6, 3, 3, 82.59066390393983));
table.add(array("qHSV", 6, 6, 0, 82.68591896276428));
table.add(array("qHSV", 6, 2, 4, 82.97878839973524));
table.add(array("qHSV", 6, 1, 5, 83.27251053606977));
table.add(array("qHSV", 6, 0, 6, 84.8281185595414));
table.add(array("qRGB", 0, 5, 7, 90.63206534182964));
table.add(array("qRGB", 1, 4, 7, 92.95451501587132));
table.add(array("qRGB", 2, 3, 7, 95.58421617689663));
table.add(array("qRGB", 3, 2, 7, 97.52004006544156));
table.add(array("qRGB", 4, 1, 7, 99.1720497524499));
table.add(array("qRGB", 5, 0, 7, 101.56712234851004));
table.add(array("qRGB", 0, 7, 5, 105.99908554244503));
table.add(array("qRGB", 1, 7, 4, 108.67401118003978));
table.add(array("qRGB", 2, 7, 3, 110.9808282044467));
table.add(array("qRGB", 3, 7, 2, 112.49699129233186));
table.add(array("qRGB", 4, 7, 1, 113.61400042659453));
table.add(array("qRGB", 5, 7, 0, 115.24588503540951));
table.add(array("qHSV", 7, 5, 0, 148.4866525222472));
table.add(array("qHSV", 7, 4, 1, 152.20702004897882));
table.add(array("qHSV", 7, 3, 2, 154.06650658928004));
table.add(array("qHSV", 7, 0, 5, 154.22820386668872));
table.add(array("qHSV", 7, 2, 3, 154.8302458267778));
table.add(array("qHSV", 7, 1, 4, 154.85496721006646));
table.add(array("qRGB", 5, 4, 4, 16.452327018216238));
table.add(array("qRGB", 4, 4, 5, 21.576691496711987));
table.add(array("qRGB", 4, 5, 4, 23.151504858179628));
table.add(array("qRGB", 6, 4, 3, 23.29238320073896));
table.add(array("qHSV", 3, 5, 5, 23.855937179825872));
table.add(array("qRGB", 5, 5, 3, 24.010895759787857));
table.add(array("qRGB", 5, 3, 5, 24.345372151173603));
table.add(array("qHSV", 3, 4, 6, 24.483664759259558));
table.add(array("qRGB", 6, 3, 4, 24.84121606806918));
table.add(array("qHSV", 4, 4, 5, 26.121861030618177));
table.add(array("qRGB", 3, 5, 5, 27.975681776202745));
table.add(array("qHSV", 2, 5, 6, 28.22285519819319));
table.add(array("qHSV", 4, 5, 4, 29.326939071136668));
table.add(array("qHSV", 4, 3, 6, 29.941881324210264));
table.add(array("qRGB", 6, 5, 2, 30.97884589500067));
table.add(array("qRGB", 6, 2, 5, 34.346490652277055));
table.add(array("qHSV", 3, 6, 4, 35.80586465661823));
table.add(array("qHSV", 2, 6, 5, 35.831301740769405));
table.add(array("qHSV", 4, 6, 3, 40.37922211577201));
table.add(array("qHSV", 1, 6, 6, 40.81321272585543));
table.add(array("qRGB", 3, 4, 6, 42.525019656531576));
table.add(array("qRGB", 4, 3, 6, 44.51060848937224));
table.add(array("qHSV", 5, 4, 4, 44.81908847853915));
table.add(array("qRGB", 2, 5, 6, 44.902350932273606));
table.add(array("qHSV", 5, 3, 5, 44.954338178029914));
table.add(array("qRGB", 7, 4, 2, 45.209654110379404));
table.add(array("qRGB", 7, 3, 3, 45.25226318990082));
table.add(array("qHSV", 5, 5, 3, 47.067622456344374));
table.add(array("qHSV", 5, 2, 6, 48.43284417039696));
table.add(array("qRGB", 7, 2, 4, 48.48082801682692));
table.add(array("qRGB", 5, 2, 6, 48.67260126855884));
table.add(array("qRGB", 3, 6, 4, 48.93754909302421));
table.add(array("qHSV", 3, 3, 7, 49.02681684469041));
table.add(array("qHSV", 2, 4, 7, 49.56029119812139));
table.add(array("qRGB", 4, 6, 3, 49.67978878365301));
table.add(array("qRGB", 2, 6, 5, 50.2467901034742));
table.add(array("qRGB", 7, 5, 1, 50.89632581346104));
table.add(array("qRGB", 5, 6, 2, 51.349978241781436));
table.add(array("qHSV", 4, 2, 7, 53.40986543747504));
table.add(array("qHSV", 1, 5, 7, 53.832715409307504));
table.add(array("qHSV", 5, 6, 2, 54.17452931216259));
table.add(array("qRGB", 6, 6, 1, 56.24604742164139));
table.add(array("qRGB", 7, 1, 5, 56.576264479355444));
table.add(array("qRGB", 6, 1, 6, 56.814909591996674));
table.add(array("qRGB", 1, 6, 6, 59.72839648703533));
table.add(array("qHSV", 2, 7, 4, 62.51176621430742));
table.add(array("qHSV", 3, 7, 3, 62.96174689694058));
table.add(array("qHSV", 1, 7, 5, 63.14358049455555));
table.add(array("qHSV", 0, 6, 7, 63.465936946588535));
table.add(array("qHSV", 4, 7, 2, 65.23155454626794));
table.add(array("qHSV", 0, 7, 6, 66.36369767041624));
table.add(array("qHSV", 5, 1, 7, 67.49295507997199));
table.add(array("qRGB", 7, 6, 0, 72.32032989402973));
table.add(array("qHSV", 5, 7, 1, 72.6504972897907));
table.add(array("qRGB", 7, 0, 6, 76.11764832983383));
table.add(array("qHSV", 6, 5, 2, 81.38302809602966));
table.add(array("qHSV", 6, 4, 3, 81.86192037913459));
table.add(array("qHSV", 6, 3, 4, 82.47611149206824));
table.add(array("qHSV", 6, 6, 1, 82.67225695734406));
table.add(array("qHSV", 6, 2, 5, 83.00311321520888));
table.add(array("qHSV", 6, 1, 6, 84.70426204696611));
table.add(array("qHSV", 6, 7, 0, 90.32392117480995));
table.add(array("qRGB", 1, 5, 7, 90.59284659085877));
table.add(array("qRGB", 2, 4, 7, 92.96533250892645));
table.add(array("qRGB", 0, 6, 7, 94.23816148736213));
table.add(array("qRGB", 3, 3, 7, 95.76126172444539));
table.add(array("qHSV", 6, 0, 7, 96.77929387101405));
table.add(array("qRGB", 4, 2, 7, 98.15417423649613));
table.add(array("qRGB", 5, 1, 7, 101.01783865813661));
table.add(array("qRGB", 1, 7, 5, 105.9478151508339));
table.add(array("qRGB", 0, 7, 6, 106.2108223866618));
table.add(array("qRGB", 6, 0, 7, 106.88184436821574));
table.add(array("qRGB", 2, 7, 4, 108.61661495825513));
table.add(array("qRGB", 3, 7, 3, 110.9684674837774));
table.add(array("qRGB", 4, 7, 2, 112.72714747788302));
table.add(array("qRGB", 5, 7, 1, 114.76166638761399));
table.add(array("qRGB", 6, 7, 0, 119.55559324301412));
table.add(array("qHSV", 7, 6, 0, 141.64444052630054));
table.add(array("qHSV", 7, 5, 1, 148.4251492515059));
table.add(array("qHSV", 7, 4, 2, 152.0899192589707));
table.add(array("qHSV", 7, 0, 6, 153.00264635518943));
table.add(array("qHSV", 7, 3, 3, 153.83156011108096));
table.add(array("qHSV", 7, 1, 5, 153.98670951089673));
table.add(array("qHSV", 7, 2, 4, 154.36075363667933));
table.add(array("qRGB", 5, 4, 5, 24.071811935682792));
table.add(array("qRGB", 5, 5, 4, 24.519064488681344));
table.add(array("qRGB", 6, 4, 4, 25.197573119249448));
table.add(array("qRGB", 4, 5, 5, 27.88679667800512));
table.add(array("qHSV", 3, 5, 6, 30.125155623703037));
table.add(array("qRGB", 6, 5, 3, 30.57235916304928));
table.add(array("qHSV", 4, 5, 5, 30.80517648683717));
table.add(array("qHSV", 4, 4, 6, 31.699842078117207));
table.add(array("qRGB", 6, 3, 5, 32.99240577170763));
table.add(array("qHSV", 3, 6, 5, 37.271137072988665));
table.add(array("qHSV", 4, 6, 4, 40.75410626562716));
table.add(array("qHSV", 2, 6, 6, 41.107826122575894));
table.add(array("qRGB", 4, 4, 6, 42.983901487038864));
table.add(array("qRGB", 3, 5, 6, 44.73696740093618));
table.add(array("qRGB", 7, 4, 3, 45.575935181665926));
table.add(array("qHSV", 5, 4, 5, 45.73706665815075));
table.add(array("qRGB", 5, 3, 6, 46.93140066470426));
table.add(array("qHSV", 5, 5, 4, 47.31457765402981));
table.add(array("qRGB", 7, 3, 4, 47.57904720235397));
table.add(array("qRGB", 4, 6, 4, 48.59959709126427));
table.add(array("qHSV", 5, 3, 6, 48.70967709693754));
table.add(array("qRGB", 3, 6, 5, 49.90415093680079));
table.add(array("qRGB", 5, 6, 3, 50.19162493994238));
table.add(array("qRGB", 7, 5, 2, 50.64474510643907));
table.add(array("qHSV", 3, 4, 7, 50.97542315094293));
table.add(array("qHSV", 2, 5, 7, 54.10765028158217));
table.add(array("qHSV", 4, 3, 7, 54.119314448377594));
table.add(array("qHSV", 5, 6, 3, 54.240483810016585));
table.add(array("qRGB", 6, 6, 2, 55.51362394958891));
table.add(array("qRGB", 7, 2, 5, 55.72738548239443));
table.add(array("qRGB", 6, 2, 6, 55.74309141050442));
table.add(array("qRGB", 2, 6, 6, 59.53589671516055));
table.add(array("qHSV", 3, 7, 4, 63.157139098842364));
table.add(array("qHSV", 2, 7, 5, 63.28833907338459));
table.add(array("qHSV", 1, 6, 7, 63.50457128922028));
table.add(array("qHSV", 4, 7, 3, 65.29115018166584));
table.add(array("qHSV", 1, 7, 6, 66.39194736243954));
table.add(array("qHSV", 5, 2, 7, 67.61437384583752));
table.add(array("qRGB", 7, 6, 1, 71.99761869066867));
table.add(array("qHSV", 5, 7, 2, 72.62668860926118));
table.add(array("qRGB", 7, 1, 6, 75.56911192801118));
table.add(array("qHSV", 6, 5, 3, 81.33113264372975));
table.add(array("qHSV", 6, 4, 4, 81.78259962534494));
table.add(array("qHSV", 6, 3, 5, 82.54804950625551));
table.add(array("qHSV", 6, 6, 2, 82.64653580433713));
table.add(array("qHSV", 0, 7, 7, 82.98009795855553));
table.add(array("qHSV", 6, 2, 6, 84.49086288438515));
table.add(array("qHSV", 6, 7, 1, 90.3539481096517));
table.add(array("qRGB", 2, 5, 7, 90.52673250324939));
table.add(array("qRGB", 3, 4, 7, 93.04225296123272));
table.add(array("qRGB", 1, 6, 7, 94.15118331333835));
table.add(array("qRGB", 4, 3, 7, 96.30652031331188));
table.add(array("qHSV", 6, 1, 7, 96.66311028783815));
table.add(array("qRGB", 5, 2, 7, 99.9525311596843));
table.add(array("qRGB", 2, 7, 5, 105.85586615081006));
table.add(array("qRGB", 1, 7, 6, 106.13379451983877));
table.add(array("qRGB", 6, 1, 7, 106.30844111204077));
table.add(array("qRGB", 3, 7, 4, 108.55788479941238));
table.add(array("qRGB", 4, 7, 3, 111.1485560507927));
table.add(array("qRGB", 5, 7, 2, 113.84057827200076));
table.add(array("qRGB", 6, 7, 1, 119.0611377850553));
table.add(array("qRGB", 0, 7, 7, 121.61122326525965));
table.add(array("qRGB", 7, 0, 7, 122.22938888033444));
table.add(array("qHSV", 7, 7, 0, 130.39792724870412));
table.add(array("qRGB", 7, 7, 0, 133.93140854155877));
table.add(array("qHSV", 7, 6, 1, 141.57678709847553));
table.add(array("qHSV", 7, 5, 2, 148.3157517124646));
table.add(array("qHSV", 7, 4, 3, 151.85812919582494));
table.add(array("qHSV", 7, 1, 6, 152.75698339389902));
table.add(array("qHSV", 7, 3, 4, 153.36844533228413));
table.add(array("qHSV", 7, 2, 5, 153.50798443432024));
table.add(array("qHSV", 7, 0, 7, 154.42826003900322));
table.add(array("qRGB", 5, 5, 5, 29.16035761415699));
table.add(array("qRGB", 6, 5, 4, 31.076711561370868));
table.add(array("qRGB", 6, 4, 5, 32.067109009705945));
table.add(array("qHSV", 4, 5, 6, 36.083595936249296));
table.add(array("qHSV", 4, 6, 5, 41.964190211364595));
table.add(array("qHSV", 3, 6, 6, 42.29930100726572));
table.add(array("qRGB", 4, 5, 6, 44.727040748103285));
table.add(array("qRGB", 5, 4, 6, 44.968623478214795));
table.add(array("qRGB", 7, 4, 4, 47.278835169696876));
table.add(array("qHSV", 5, 5, 5, 48.217951512529));
table.add(array("qRGB", 5, 6, 4, 49.01993078520322));
table.add(array("qRGB", 4, 6, 5, 49.51021618599725));
table.add(array("qHSV", 5, 4, 6, 49.547304173959944));
table.add(array("qRGB", 7, 5, 3, 50.45381424547857));
table.add(array("qRGB", 6, 3, 6, 53.916454183431405));
table.add(array("qRGB", 6, 6, 3, 54.37236041600201));
table.add(array("qRGB", 7, 3, 5, 54.41183262515647));
table.add(array("qHSV", 5, 6, 4, 54.45350302726497));
table.add(array("qHSV", 3, 5, 7, 55.244904587366044));
table.add(array("qHSV", 4, 4, 7, 55.64610512093585));
table.add(array("qRGB", 3, 6, 6, 59.209737174708884));
table.add(array("qHSV", 2, 6, 7, 63.6751728390727));
table.add(array("qHSV", 3, 7, 5, 63.88987040305082));
table.add(array("qHSV", 4, 7, 4, 65.43916877735103));
table.add(array("qHSV", 2, 7, 6, 66.50671872962488));
table.add(array("qHSV", 5, 3, 7, 67.9918424704696));
table.add(array("qRGB", 7, 6, 2, 71.40548869524387));
table.add(array("qHSV", 5, 7, 3, 72.65552942805532));
table.add(array("qRGB", 7, 2, 6, 74.539198911411));
table.add(array("qHSV", 6, 5, 4, 81.28294078298102));
table.add(array("qHSV", 6, 4, 5, 81.90954861718659));
table.add(array("qHSV", 6, 6, 3, 82.60810662817708));
table.add(array("qHSV", 1, 7, 7, 83.01474461331952));
table.add(array("qHSV", 6, 3, 6, 84.12128748832396));
table.add(array("qHSV", 6, 7, 2, 90.30191795302524));
table.add(array("qRGB", 3, 5, 7, 90.44343880501384));
table.add(array("qRGB", 4, 4, 7, 93.39992710387831));
table.add(array("qRGB", 2, 6, 7, 93.98542612049617));
table.add(array("qHSV", 6, 2, 7, 96.531808332587));
table.add(array("qRGB", 5, 3, 7, 97.98623863661277));
table.add(array("qRGB", 6, 2, 7, 105.18986761294468));
table.add(array("qRGB", 3, 7, 5, 105.72241391531153));
table.add(array("qRGB", 2, 7, 6, 105.9861999725296));
table.add(array("qRGB", 4, 7, 4, 108.64397196690527));
table.add(array("qRGB", 5, 7, 3, 112.1823057298339));
table.add(array("qRGB", 6, 7, 2, 118.1068250687499));
table.add(array("qRGB", 1, 7, 7, 121.49344484417644));
table.add(array("qRGB", 7, 1, 7, 121.63454416537526));
table.add(array("qHSV", 7, 7, 1, 130.27815752171145));
table.add(array("qRGB", 7, 7, 1, 133.45192537538827));
table.add(array("qHSV", 7, 6, 2, 141.4759110619432));
table.add(array("qHSV", 7, 5, 3, 148.09813296839445));
table.add(array("qHSV", 7, 4, 4, 151.41705304769513));
table.add(array("qHSV", 7, 2, 6, 152.30122027302545));
table.add(array("qHSV", 7, 3, 5, 152.53646872834864));
table.add(array("qHSV", 7, 1, 7, 154.0768707620358));
table.add(array("qRGB", 6, 5, 5, 35.400137435029016));
table.add(array("qRGB", 5, 5, 6, 45.8233771590495));
table.add(array("qHSV", 4, 6, 6, 46.40245579086771));
table.add(array("qRGB", 5, 6, 5, 49.782515993143186));
table.add(array("qRGB", 7, 5, 4, 51.041409413692236));
table.add(array("qRGB", 6, 4, 6, 51.54216148099061));
table.add(array("qHSV", 5, 5, 6, 51.940531483076605));
table.add(array("qRGB", 7, 4, 5, 53.137756535881834));
table.add(array("qRGB", 6, 6, 4, 53.14396294559098));
table.add(array("qHSV", 5, 6, 5, 55.228715876666485));
table.add(array("qRGB", 4, 6, 6, 58.79585620026274));
table.add(array("qHSV", 4, 5, 7, 59.203972102699964));
table.add(array("qHSV", 3, 6, 7, 64.44018880057266));
table.add(array("qHSV", 4, 7, 5, 66.07804953551427));
table.add(array("qHSV", 3, 7, 6, 67.02198891573136));
table.add(array("qHSV", 5, 4, 7, 68.82377873985625));
table.add(array("qRGB", 7, 6, 3, 70.45097650807729));
table.add(array("qHSV", 5, 7, 4, 72.72379724972508));
table.add(array("qRGB", 7, 3, 6, 72.7496334594355));
table.add(array("qHSV", 6, 5, 5, 81.45839848659669));
table.add(array("qHSV", 6, 6, 4, 82.57432023168315));
table.add(array("qHSV", 2, 7, 7, 83.09689252187526));
table.add(array("qHSV", 6, 4, 6, 83.60367097668954));
table.add(array("qHSV", 6, 7, 3, 90.24254703335666));
table.add(array("qRGB", 4, 5, 7, 90.47157622213018));
table.add(array("qRGB", 3, 6, 7, 93.69327279840577));
table.add(array("qRGB", 5, 4, 7, 94.78848826316275));
table.add(array("qHSV", 6, 3, 7, 96.34074236006498));
table.add(array("qRGB", 6, 3, 7, 103.09409877318586));
table.add(array("qRGB", 4, 7, 5, 105.64751778991774));
table.add(array("qRGB", 3, 7, 6, 105.73289902046317));
table.add(array("qRGB", 5, 7, 4, 109.50856313511423));
table.add(array("qRGB", 6, 7, 3, 116.35263661572063));
table.add(array("qRGB", 7, 2, 7, 120.47091510995996));
table.add(array("qRGB", 2, 7, 7, 121.25909325650642));
table.add(array("qHSV", 7, 7, 2, 130.189412070187));
table.add(array("qRGB", 7, 7, 2, 132.51054904265393));
table.add(array("qHSV", 7, 6, 3, 141.2750518038755));
table.add(array("qHSV", 7, 5, 4, 147.68593530869273));
table.add(array("qHSV", 7, 4, 5, 150.63169725118138));
table.add(array("qHSV", 7, 3, 6, 151.39341368885468));
table.add(array("qHSV", 7, 2, 7, 153.7261405181208));
table.add(array("qRGB", 6, 5, 6, 51.16588678216485));
table.add(array("qRGB", 6, 6, 5, 53.65792546587413));
table.add(array("qRGB", 7, 5, 5, 54.86314628308258));
table.add(array("qHSV", 5, 6, 6, 58.5541643813996));
table.add(array("qRGB", 5, 6, 6, 58.88231069937044));
table.add(array("qHSV", 4, 6, 7, 67.29232843725568));
table.add(array("qHSV", 4, 7, 6, 68.98398547192));
table.add(array("qRGB", 7, 6, 4, 69.35909510351173));
table.add(array("qRGB", 7, 4, 6, 70.20612999951547));
table.add(array("qHSV", 5, 5, 7, 70.9522982391356));
table.add(array("qHSV", 5, 7, 5, 73.15155535858463));
table.add(array("qHSV", 6, 6, 5, 82.78120697495775));
table.add(array("qHSV", 6, 5, 6, 83.28443665149418));
table.add(array("qHSV", 3, 7, 7, 83.45320638949539));
table.add(array("qHSV", 6, 7, 4, 90.172638730084));
table.add(array("qRGB", 5, 5, 7, 91.24646560431594));
table.add(array("qRGB", 4, 6, 7, 93.2732797260707));
table.add(array("qHSV", 6, 4, 7, 96.09723782084295));
table.add(array("qRGB", 6, 4, 7, 99.54726990857749));
table.add(array("qRGB", 4, 7, 6, 105.39366045848752));
table.add(array("qRGB", 5, 7, 5, 106.18657681840735));
table.add(array("qRGB", 6, 7, 4, 113.434492479518));
table.add(array("qRGB", 7, 3, 7, 118.27215956840143));
table.add(array("qRGB", 3, 7, 7, 120.8193361510788));
table.add(array("qHSV", 7, 7, 3, 130.01513071046674));
table.add(array("qRGB", 7, 7, 3, 130.72885419357505));
table.add(array("qHSV", 7, 6, 4, 140.9012578035098));
table.add(array("qHSV", 7, 5, 5, 146.95565866567614));
table.add(array("qHSV", 7, 4, 6, 149.59413316853056));
table.add(array("qHSV", 7, 3, 7, 153.00106824868672));
table.add(array("qRGB", 6, 6, 6, 62.13342555613777));
table.add(array("qRGB", 7, 5, 6, 68.76461465385874));
table.add(array("qRGB", 7, 6, 5, 69.64939924785347));
table.add(array("qHSV", 5, 7, 6, 75.49661507284307));
table.add(array("qHSV", 5, 6, 7, 76.37570829713836));
table.add(array("qHSV", 6, 6, 6, 84.60279131029957));
table.add(array("qHSV", 4, 7, 7, 84.87036525141197));
table.add(array("qHSV", 6, 7, 5, 90.25307437485817));
table.add(array("qRGB", 5, 6, 7, 93.09297348388682));
table.add(array("qRGB", 6, 5, 7, 95.09765215140195));
table.add(array("qHSV", 6, 5, 7, 96.05791272541956));
table.add(array("qRGB", 5, 7, 6, 105.35293816829977));
table.add(array("qRGB", 6, 7, 5, 109.55213823708338));
table.add(array("qRGB", 7, 4, 7, 114.43406884005788));
table.add(array("qRGB", 4, 7, 7, 120.06463886098378));
table.add(array("qRGB", 7, 7, 4, 127.61800680953633));
table.add(array("qHSV", 7, 7, 4, 129.69888897137199));
table.add(array("qHSV", 7, 6, 5, 140.26914343765014));
table.add(array("qHSV", 7, 5, 6, 146.10742102345884));
table.add(array("qHSV", 7, 4, 7, 151.5596422793711));
table.add(array("qRGB", 7, 6, 6, 76.82768387008761));
table.add(array("qHSV", 5, 7, 7, 89.91254983728324));
table.add(array("qHSV", 6, 7, 6, 91.6934546217888));
table.add(array("qRGB", 6, 6, 7, 95.13524389792414));
table.add(array("qHSV", 6, 6, 7, 97.3143392560389));
table.add(array("qRGB", 6, 7, 6, 107.54519533200947));
table.add(array("qRGB", 7, 5, 7, 109.04192747205848));
table.add(array("qRGB", 5, 7, 7, 119.07036843710114));
table.add(array("qRGB", 7, 7, 5, 123.04945636715787));
table.add(array("qHSV", 7, 7, 5, 129.19031913082105));
table.add(array("qHSV", 7, 6, 6, 139.72383239068853));
table.add(array("qHSV", 7, 5, 7, 148.72214401655344));
table.add(array("qHSV", 6, 7, 7, 103.02970911320593));
table.add(array("qRGB", 7, 6, 7, 106.51658523554815));
table.add(array("qRGB", 6, 7, 7, 119.09765442358427));
table.add(array("qRGB", 7, 7, 6, 119.10670119292193));
table.add(array("qHSV", 7, 7, 6, 129.00909805599323));
table.add(array("qHSV", 7, 6, 7, 143.4394848729931));
table.add(array("qRGB", 7, 7, 7, 126.23189633081189));
table.add(array("qHSV", 7, 7, 7, 134.22861938161395));
for (final Object[] row : table) {
final String type = (String) row[0];
/*if ("qHSV".equals(type))*/ {
final int qA = ((Number) row[1]).intValue();
final int qB = ((Number) row[2]).intValue();
final int qC = ((Number) row[3]).intValue();
final int q = qA + qB + qC;
if (quantizers.size() <= q) {
quantizers.add(ColorQuantizer.newQuantizer(type, qA, qB, qC));
}
}
}
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static abstract class ColorQuantizer implements Serializable {
private final int qA;
private final int qB;
private final int qC;
protected ColorQuantizer(final int qA, final int qB, final int qC) {
this.qA = qA;
this.qB = qB;
this.qC = qC;
}
public final int quantize(final int rgb) {
final int[] abc = new int[3];
this.rgbToABC(rgb, abc);
abc[0] = ((abc[0] & 0xFF) >> this.qA) << this.qA;
abc[1] = ((abc[1] & 0xFF) >> this.qB) << this.qB;
abc[2] = ((abc[2] & 0xFF) >> this.qC) << this.qC;
this.abcToRGB(abc, abc);
return (abc[0] << 16) | (abc[1] << 8) | (abc[2] << 0);
}
public final int pack(final int rgb) {
final int[] abc = new int[3];
this.rgbToABC(rgb, abc);
final int a = (abc[0] & 0xFF) >> this.qA;
final int b = (abc[1] & 0xFF) >> this.qB;
final int c = (abc[2] & 0xFF) >> this.qC;
return (a << (16 - this.qB - this.qC)) | (b << (8 - this.qC)) | (c << 0);
}
public final String getType() {
if (this instanceof RGBQuantizer) {
return "qRGB";
}
if (this instanceof HSVQuantizer) {
return "qHSV";
}
return this.getClass().getSimpleName();
}
@Override
public final String toString() {
return this.getType() + this.qA + "" + this.qB + "" + this.qC;
}
protected abstract void rgbToABC(final int rgb, final int[] abc);
protected abstract void abcToRGB(final int[] abc, final int[] rgb);
/**
* {@value}.
*/
private static final long serialVersionUID = -5601399591176973099L;
public static final ColorQuantizer newQuantizer(final String type, final int qA, final int qB, final int qC) {
if ("qRGB".equals(type)) {
return new RGBQuantizer(qA, qC, qB);
}
if ("qHSV".equals(type)) {
return new HSVQuantizer(qA, qC, qB);
}
throw new IllegalArgumentException();
}
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static final class RGBQuantizer extends ColorQuantizer {
public RGBQuantizer(final int qR, final int qG, final int qB) {
super(qR, qG, qB);
}
@Override
protected final void rgbToABC(final int rgb, final int[] abc) {
rgbToRGB(rgb, abc);
}
@Override
protected final void abcToRGB(final int[] abc, final int[] rgb) {
System.arraycopy(abc, 0, rgb, 0, abc.length);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -739890245396913487L;
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static final class HSVQuantizer extends ColorQuantizer {
public HSVQuantizer(final int qH, final int qS, final int qV) {
super(qH, qS, qV);
}
@Override
protected final void rgbToABC(final int rgb, final int[] abc) {
rgbToRGB(rgb, abc);
rgbToHSV(abc, abc);
}
@Override
protected final void abcToRGB(final int[] abc, final int[] rgb) {
hsvToRGB(abc, rgb);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -739890245396913487L;
}
public static final void shutdownAndWait(final ExecutorService executor, final long milliseconds) {
executor.shutdown();
try {
executor.awaitTermination(milliseconds, TimeUnit.MILLISECONDS);
} catch (final InterruptedException exception) {
exception.printStackTrace();
}
}
public static final int[] rgbToRGB(final int rgb, final int[] result) {
result[0] = (rgb >> 16) & 0xFF;
result[1] = (rgb >> 8) & 0xFF;
result[2] = (rgb >> 0) & 0xFF;
return result;
}
public static final int[] rgbToHSV(final int[] rgb, final int[] result) {
final float[] hsv = new float[3];
Color.RGBtoHSB(rgb[0], rgb[1], rgb[2], hsv);
result[0] = round(hsv[0] * 255F);
result[1] = round(hsv[1] * 255F);
result[2] = round(hsv[2] * 255F);
return result;
}
public static final int[] hsvToRGB(final int[] hsv, final int[] result) {
return rgbToRGB(Color.HSBtoRGB(hsv[0] / 255F, hsv[1] / 255F, hsv[2] / 255F), result);
}
public static final float[] rgbToXYZ(final int[] rgb, final float[] result) {
final float r = rgb[0] / 255F;
final float g = rgb[1] / 255F;
final float b = rgb[2] / 255F;
final float b21 = 0.17697F;
result[0] = (0.49F * r + 0.31F * g + 0.20F * b) / b21;
result[1] = (b21 * r + 0.81240F * g + 0.01063F * b) / b21;
result[2] = (0.00F * r + 0.01F * g + 0.99F * b) / b21;
return result;
}
public static final int[] xyzToRGB(final float[] xyz, final int[] result) {
final float x = xyz[0];
final float y = xyz[1];
final float z = xyz[2];
result[0] = round(255F * (0.41847F * x - 0.15866F * y - 0.082835F * z));
result[1] = round(255F * (-0.091169F * x + 0.25243F * y + 0.015708F * z));
result[2] = round(255F * (0.00092090F * x - 0.0025498F * y + 0.17860F * z));
return result;
}
public static final float[] xyzToCIELAB(final float[] xyz, final float[] result) {
final float d65X = 0.95047F;
final float d65Y = 1.0000F;
final float d65Z = 1.08883F;
final float fX = f(xyz[0] / d65X);
final float fY = f(xyz[1] / d65Y);
final float fZ = f(xyz[2] / d65Z);
result[0] = 116F * fY - 16F;
result[1] = 500F * (fX - fY);
result[2] = 200F * (fY - fZ);
return result;
}
public static final float[] cielabToXYZ(final float[] cielab, final float[] result) {
final float d65X = 0.95047F;
final float d65Y = 1.0000F;
final float d65Z = 1.08883F;
final float lStar = cielab[0];
final float aStar = cielab[1];
final float bStar = cielab[2];
final float c = (lStar + 16F) / 116F;
result[0] = d65X * fInv(c + aStar / 500F);
result[1] = d65Y * fInv(c);
result[2] = d65Z * fInv(c - bStar / 200F);
return result;
}
public static final float f(final float t) {
return cube(6F / 29F) < t ? (float) pow(t, 1.0 / 3.0) : square(29F / 6F) * t / 3F + 4F / 29F;
}
public static final float fInv(final float t) {
return 6F / 29F < t ? cube(t) : 3F * square(6F / 29F) * (t - 4F / 29F);
}
public static final float square(final float value) {
return value * value;
}
public static final float cube(final float value) {
return value * value * value;
}
public static final int[] quantize(final int[] abc, final int q, final int[] result) {
return quantize(abc, q, q, q, result);
}
public static final int[] quantize(final int[] abc, final int qA, final int qB, final int qC, final int[] result) {
result[0] = abc[0] & ((~0) << qA);
result[1] = abc[1] & ((~0) << qB);
result[2] = abc[2] & ((~0) << qC);
return result;
}
public static final int distance1(final int[] abc1, final int[] abc2) {
final int n = abc1.length;
int result = 0;
for (int i = 0; i < n; ++i) {
result += abs(abc1[i] - abc2[i]);
}
return result;
}
public static final double distance2(final float[] abc1, final float[] abc2) {
final int n = abc1.length;
double sum = 0.0;
for (int i = 0; i < n; ++i) {
sum += square(abc1[i] - abc2[i]);
}
return sqrt(sum);
}
public static final int min(final int... values) {
int result = Integer.MAX_VALUE;
for (final int value : values) {
if (value < result) {
result = value;
}
}
return result;
}
public static final int max(final int... values) {
int result = Integer.MIN_VALUE;
for (final int value : values) {
if (result < value) {
result = value;
}
}
return result;
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static final class DoubleArrayComparator implements Serializable, Comparator<double[]> {
@Override
public final int compare(final double[] array1, final double[] array2) {
final int n1 = array1.length;
final int n2 = array2.length;
final int n = Math.min(n1, n2);
for (int i = 0; i < n; ++i) {
final int comparison = Double.compare(array1[i], array2[i]);
if (comparison != 0) {
return comparison;
}
}
return n1 - n2;
}
/**
* {@value}.
*/
private static final long serialVersionUID = -88586465954519984L;
public static final DoubleArrayComparator INSTANCE = new DoubleArrayComparator();
}
}
|
package iplagiarism;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.SwingWorker;
import org.apache.commons.io.FileUtils;
/**
*
* @author Jatan
*/
public class checkPlagiarism extends SwingWorker<Void, String> {
String filePath0;
String filePath1;
String randomNum;
ArrayList<String> lineList;
checkPlagiarism(String filePath0, String filePath1) {
this.filePath0 = filePath0;
this.filePath1 = filePath1;
}
@Override
protected Void doInBackground() throws Exception {
String f1 = readFile(filePath0);
String f2 = readFile(filePath1);
ArrayList<String> file1 = splitLines(f1);
int length = file1.size();
System.out.println("size "+ length);
for(String s : file1){
System.out.println(s);
}
ArrayList<String> file2 = splitLines(f2);
return null;
}
private String readFile(String path) throws IOException {
String contents = null;
File file = new File(path);
contents = FileUtils.readFileToString(file, "UTF-8");
return contents;
}
private ArrayList<String> splitLines(String contents) {
contents = replaceRegex(contents);
String[] lines = contents.split(randomNum);
lineList = new ArrayList<String>(Arrays.asList(lines));
return lineList;
}
private String replaceRegex(String contents) {
String result = null;
int rand = 3000 + (int)(Math.random() * 6000);
this.randomNum = " "+String.valueOf(rand)+" ";
result = contents.replaceAll("\\.", randomNum);
return result;
}
}
|
package samples;
import java.net.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.io.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
public class QiClient {
Gson mGson = null;
private String baseUrl = null;
private String tenantName = null;
static String _resource = "PLACEHOLDER_REPLACE_WITH_RESOURCE";
static String _authority = "PLACEHOLDER_REPLACE_WITH_AUTHORITY";
static String _appId = "PLACEHOLDER_REPLACE_WITH_USER_ID";
static String _appKey = "PLACEHOLDER_REPLACE_WITH_USER_SECRET";
// REST API url strings
private String tenantsBase = "/Qi/Tenants";
private String typesBase = "/Qi/Types";
private String streamsBase = "/Qi/Streams";
private String behaviorsBase = "/Qi/Behaviors";
private String insertSingle = "/Data/InsertValue";
private String insertMultiple = "/Data/InsertValues";
private String getTemplate = "/Data/GetWindowValues?";
private String updateSingle = "/Data/UpdateValue";
private String updateMultiple = "/Data/UpdateValues";
private String removeSingleTemplate = "/{0}/Data/RemoveValue?index={1}";
private String removeMultipleTemplate = "/{0}/Data/RemoveWindowValues?startIndex={1}&endIndex={2}";
private static AuthenticationContext _authContext = null;
private static ExecutorService service = null;
private static AuthenticationResult result = null;
// void error formats fixme
//private String _createError = "Failed to create {0} with Id = {1}";
public static java.net.HttpURLConnection getConnection(URL url, String method){
java.net.HttpURLConnection urlConnection = null;
AuthenticationResult token = AcquireAuthToken();
try{
urlConnection = (java.net.HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty( "Authorization", token.getAccessTokenType()+ " "+ token.getAccessToken());
if (method == "POST" || method == "PUT" || method == "DELETE"){
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
}else if(method == "GET"){
}
}catch(SocketTimeoutException e){
e.getMessage();
}
catch (ProtocolException e){
e.getMessage();
} catch (IllegalStateException e) {
e.getMessage();
}catch(Exception e) {
e.printStackTrace();
}
return urlConnection;
}
public QiClient(String baseUrl)
{
mGson = new GsonBuilder().registerTypeAdapter(GregorianCalendar.class, new UTCDateTypeAdapter()).setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").create();
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
this.baseUrl = baseUrl;
try
{
url = new URL(this.baseUrl);
urlConnection = getConnection(url, "POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}catch (ProtocolException e){
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void UpdateStream(String streamId, QiStream streamDef){
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" +streamId );
urlConnection = getConnection(url,"PUT");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try{
String body = mGson.toJson(streamDef);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(body);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("Update Stream request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Stream update failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public String CreateBehavior(QiStreamBehavior behavior){
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
String inputLine;
StringBuffer response = new StringBuffer();
try
{
url = new URL(baseUrl + behaviorsBase );
urlConnection = getConnection(url,"POST");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try{
String body = mGson.toJson(behavior);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(body);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("behavior creation request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "behavior creation failed");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch (Exception e){
e.printStackTrace();
}
return response.toString();
}
public void DeleteBehavior(String behaviorId){
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + behaviorsBase + "/" + behaviorId);
urlConnection = getConnection(url,"DELETE");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("behavior creation request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "delete behavior request failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public String getRangeValues(String streamId, String startIndex, int skip, int count, boolean reverse, QiBoundaryType boundaryType)
{
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
String inputLine;
StringBuffer response = new StringBuffer();
try
{
url = new URL(baseUrl +streamsBase+ "/" +streamId + "/Data/GetRangeValues?startIndex="+startIndex+"&skip="+skip+"&count="+count+"&reversed="+reverse+"&boundaryType="+boundaryType );
urlConnection = getConnection(url,"GET");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("get range values request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "get range values request failed");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch (Exception e){
e.printStackTrace();
}
return response.toString();
}
public String CreateType(QiType typeDef)
{
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
String inputLine;
StringBuffer response = new StringBuffer();
try
{
url = new URL(baseUrl + typesBase );
urlConnection = getConnection(url,"POST");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try{
String body = mGson.toJson(typeDef);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(body);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("type creation request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Type creation failed");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch (Exception e){
e.printStackTrace();
}
return response.toString();
}
public String CreateStream(QiStream streamDef)
{
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
String inputLine;
StringBuffer response = new StringBuffer();
try
{
url = new URL(baseUrl + streamsBase );
urlConnection = getConnection(url,"POST");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}catch (Exception e) {
e.printStackTrace();
}
try
{
String body = mGson.toJson(streamDef);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(body);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("stream creation request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Stream creation failed");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}catch (Exception e){
e.printStackTrace();
}
return response.toString();
}
public void CreateEvent(String streamId, String evt)
{
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + insertSingle);
urlConnection = getConnection(url,"POST");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(evt);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("Event creation request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Event creation failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public void CreateEvents(String streamId, String json) throws QiError {
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
int HttpResult = 0;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + insertMultiple);
urlConnection = getConnection(url,"POST");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(json);
writer.close();
HttpResult = urlConnection.getResponseCode();
}catch (Exception e){
e.printStackTrace();
}
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("Events creation request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Events creation failed");
}
}
public String GetWindowValues (String streamId, String startIndex, String endIndex)throws QiError
{
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
String inputLine;
StringBuffer jsonResults = new StringBuffer();
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + getTemplate + "startIndex=" + startIndex + "&" + "endIndex=" + endIndex);
urlConnection = getConnection(url,"GET");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("GetWindowValues request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "GetWindowValues request failed");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
jsonResults.append(inputLine);
}
in.close();
}catch (Exception e){
e.printStackTrace();
}
return jsonResults.toString();
}
public void updateValue(String streamId, String json)throws QiError {
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + updateSingle);
urlConnection = getConnection(url,"PUT");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(json);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("UpdateValue request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "GetWindowValues request failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public void updateValues(String streamId, String json) {
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + updateMultiple);
urlConnection = getConnection(url,"PUT");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(json);
writer.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("Update Values request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Update Values request failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public void removeValue(String streamId, String index) throws QiError{
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + "/" + "/Data/RemoveValue?index=" + index);
urlConnection = getConnection(url,"DELETE");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("remove Value request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Remove value request failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public void removeWindowValues(String streamId, String startIndex, String endIndex) {
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId + "/Data/RemoveWindowValues?startIndex=" + startIndex + "&" + "endIndex=" + endIndex );
urlConnection = getConnection(url,"DELETE");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("removeWindowValues request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Remove windows value request failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public void deleteStream(String streamId) {
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + streamsBase + "/" + streamId );
urlConnection = getConnection(url,"DELETE");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("deleteStream request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Delete Stream failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
public void deleteType(String typeId) {
java.net.URL url = null;
java.net.HttpURLConnection urlConnection = null;
try
{
url = new URL(baseUrl + typesBase + "/" + typeId );
urlConnection = getConnection(url,"DELETE");
}
catch (MalformedURLException mal)
{
System.out.println("MalformedURLException");
}catch (IllegalStateException e) {
e.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
try
{
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
System.out.println("deleteType request succeded");
}
if (HttpResult != HttpURLConnection.HTTP_OK && HttpResult != HttpURLConnection.HTTP_CREATED)
{
throw new QiError(urlConnection, "Delete type failed");
}
}catch (Exception e){
e.printStackTrace();
}
}
static protected AuthenticationResult AcquireAuthToken()
{
service = Executors.newFixedThreadPool(1);
try
{
if (_authContext == null)
{
_authContext = new AuthenticationContext(_authority, true , service);
}
// tokens expire after a certain period of time
// You can check this with the ExpiresOn property of AuthenticationResult, but it is not necessary.
// ADAL maintains an in-memory cache of tokens and transparently refreshes them as needed
ClientCredential userCred = new ClientCredential(_appId, _appKey);
Future<AuthenticationResult> authResult = _authContext.acquireToken(_resource, userCred, null);
//AcquireToken(_resource, userCred);
result = authResult.get();
}
catch (Exception e)
{
}finally {
service.shutdown();
}
return result;
}
}
|
/*
* $Log: Misc.java,v $
* Revision 1.33 2011-08-09 10:14:43 L190409
* renamed arrayListToString to listToString
*
* Revision 1.32 2011/07/07 12:13:51 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added method arrayListToString
*
* Revision 1.31 2010/11/12 15:11:14 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added isForceFixedForwardingByDefault
*
* Revision 1.30 2010/10/18 13:04:57 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* modified UUID generation (2)
*
* Revision 1.29 2010/10/18 09:22:04 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* modified UUID generation
*
* Revision 1.28 2010/03/25 12:58:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made close optional in readerToWriter
*
* Revision 1.27 2009/12/28 12:53:07 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* cosmetic changes
*
* Revision 1.26 2009/12/24 08:27:55 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added methods getResponseBodySizeWarnByDefault and getResponseBodySizeErrorByDefault
*
* Revision 1.25 2009/11/12 12:36:04 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* Pipeline: added attributes messageSizeWarn and messageSizeError
*
* Revision 1.24 2009/11/10 10:27:40 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* method getEnvironmentVariables splitted for J2SE 1.4 and J2SE 5.0
*
* Revision 1.23 2009/01/29 07:02:29 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* removed "j2c.properties resource path" from getEnvironmentVariables()
*
* Revision 1.22 2009/01/28 11:21:29 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added "j2c.properties resource path" to getEnvironmentVariables()
*
* Revision 1.21 2008/12/15 12:21:06 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added getApplicationDeploymentDescriptor
*
* Revision 1.20 2008/12/15 09:39:45 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* getDeployedApplicationBindings: replaced property WAS_HOMES by user.install.root
*
* Revision 1.19 2008/12/08 13:06:58 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added createNumericUUID
*
* Revision 1.18 2008/11/25 10:17:10 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added getDeployedApplicationName and getDeployedApplicationBindings
*
* Revision 1.17 2008/09/08 15:00:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* avoid NPE in getEnvironmentVariables
*
* Revision 1.16 2008/08/27 16:24:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made closeInput optional in streamToStream
*
* Revision 1.15 2007/09/05 13:05:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added function to copy context
*
* Revision 1.14 2007/06/12 11:24:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added getHostname()
*
* Revision 1.13 2005/10/27 08:43:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* moved getEnvironmentVariables to Misc
*
* Revision 1.12 2005/10/17 11:26:58 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* addded concatString and compression-functions
*
* Revision 1.11 2005/09/22 15:54:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added replace function
*
* Revision 1.10 2005/07/19 11:37:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added stream copying functions
*
* Revision 1.9 2004/10/26 15:36:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* set UTF-8 as default inputstream encoding
*
*/
package nl.nn.adapterframework.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.rmi.server.UID;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Miscellanous conversion functions.
* @version Id
*/
public class Misc {
static Logger log = LogUtil.getLogger(Misc.class);
public static final int BUFFERSIZE=20000;
public static final String DEFAULT_INPUT_STREAM_ENCODING="UTF-8";
public static final String MESSAGE_SIZE_WARN_BY_DEFAULT_KEY = "message.size.warn.default";
public static final String MESSAGE_SIZE_ERROR_BY_DEFAULT_KEY = "message.size.error.default";
public static final String RESPONSE_BODY_SIZE_WARN_BY_DEFAULT_KEY = "response.body.size.warn.default";
public static final String RESPONSE_BODY_SIZE_ERROR_BY_DEFAULT_KEY = "response.body.size.error.default";
public static final String FORCE_FIXED_FORWARDING_BY_DEFAULT_KEY = "force.fixed.forwarding.default";
private static Long messageSizeWarnByDefault = null;
private static Long messageSizeErrorByDefault = null;
private static Long responseBodySizeWarnByDefault = null;
private static Long responseBodySizeErrorByDefault = null;
private static Boolean forceFixedForwardingByDefault = null;
/**
* Creates a Universally Unique Identifier, via the java.rmi.server.UID class.
*/
public static String createSimpleUUID() {
UID uid = new UID();
String uidString=asHex(getIPAddress())+"-"+uid.toString();
// Replace semi colons by underscores, so IBIS will support it
uidString = uidString.replace(':', '_');
return uidString;
}
static public String createUUID() {
return createSimpleUUID();
}
private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
public static String asHex(byte[] buf)
{
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
static private byte[] getIPAddress() {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
return inetAddress.getAddress();
}
catch (UnknownHostException uhe) {
return new byte[] {127,0,0,1};
}
}
static public String createNumericUUID() {
byte[] ipAddress = getIPAddress();
DecimalFormat df = new DecimalFormat("000");
String ia1 = df.format(unsignedByteToInt(ipAddress[0]));
String ia2 = df.format(unsignedByteToInt(ipAddress[1]));
String ia3 = df.format(unsignedByteToInt(ipAddress[2]));
String ia4 = df.format(unsignedByteToInt(ipAddress[3]));
String ia = ia1 + ia2 + ia3 + ia4;
long hashL = Math.round(Math.random() * 1000000);
df = new DecimalFormat("000000");
String hash = df.format(hashL);
//Unique string is <ipaddress with length 4*3><currentTime with length 13><hashcode with length 6>
StringBuffer s = new StringBuffer();
s.append(ia).append(getCurrentTimeMillis()).append(hash);
return s.toString();
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
public static synchronized long getCurrentTimeMillis(){
return System.currentTimeMillis();
}
public static void fileToWriter(String filename, Writer writer) throws IOException {
readerToWriter(new FileReader(filename), writer);
}
public static void fileToStream(String filename, OutputStream output) throws IOException {
streamToStream(new FileInputStream(filename), output);
}
public static void streamToStream(InputStream input, OutputStream output) throws IOException {
streamToStream(input,output,true);
}
public static void streamToStream(InputStream input, OutputStream output, boolean closeInput) throws IOException {
if (input!=null) {
byte buffer[]=new byte[BUFFERSIZE];
int bytesRead;
while ((bytesRead=input.read(buffer,0,BUFFERSIZE))>0) {
output.write(buffer,0,bytesRead);
}
if (closeInput) {
input.close();
}
}
}
public static void readerToWriter(Reader reader, Writer writer) throws IOException {
readerToWriter(reader,writer,true);
}
public static void readerToWriter(Reader reader, Writer writer, boolean closeInput) throws IOException {
if (reader!=null) {
char buffer[]=new char[BUFFERSIZE];
int charsRead;
while ((charsRead=reader.read(buffer,0,BUFFERSIZE))>0) {
writer.write(buffer,0,charsRead);
}
if (closeInput) {
reader.close();
}
}
}
/**
* Please consider using resourceToString() instead of relying on files.
*/
public static String fileToString(String fileName) throws IOException {
return fileToString(fileName, null, false);
}
/**
* Please consider using resourceToString() instead of relying on files.
*/
public static String fileToString(String fileName, String endOfLineString) throws IOException {
return fileToString(fileName, endOfLineString, false);
}
/**
* Please consider using resourceToString() instead of relying on files.
*/
public static String fileToString(String fileName, String endOfLineString, boolean xmlEncode) throws IOException {
FileReader reader = new FileReader(fileName);
try {
return readerToString(reader, endOfLineString, xmlEncode);
}
finally {
reader.close();
}
}
public static String readerToString(Reader reader, String endOfLineString, boolean xmlEncode) throws IOException {
StringBuffer sb = new StringBuffer();
int curChar = -1;
int prevChar = -1;
while ((curChar = reader.read()) != -1 || prevChar == '\r') {
if (prevChar == '\r' || curChar == '\n') {
if (endOfLineString == null) {
if (prevChar == '\r')
sb.append((char) prevChar);
if (curChar == '\n')
sb.append((char) curChar);
}
else {
sb.append(endOfLineString);
}
}
if (curChar != '\r' && curChar != '\n' && curChar != -1) {
String appendStr =""+(char) curChar;
sb.append(xmlEncode ? (XmlUtils.encodeChars(appendStr)):(appendStr));
}
prevChar = curChar;
}
return sb.toString();
}
public static String streamToString(InputStream stream, String endOfLineString, String streamEncoding, boolean xmlEncode)
throws IOException {
return readerToString(new InputStreamReader(stream,streamEncoding), endOfLineString, xmlEncode);
}
public static String streamToString(InputStream stream, String endOfLineString, boolean xmlEncode)
throws IOException {
return streamToString(stream,endOfLineString, DEFAULT_INPUT_STREAM_ENCODING, xmlEncode);
}
public static String resourceToString(URL resource, String endOfLineString, boolean xmlEncode) throws IOException {
InputStream stream = resource.openStream();
try {
return streamToString(stream, endOfLineString, xmlEncode);
}
finally {
stream.close();
}
}
public static String resourceToString(URL resource) throws IOException {
return resourceToString(resource, null, false);
}
public static String resourceToString(URL resource, String endOfLineString) throws IOException {
return resourceToString(resource, endOfLineString, false);
}
public static void stringToFile(String string, String fileName) throws IOException {
FileWriter fw = new FileWriter(fileName);
try {
fw.write(string);
}
finally {
fw.close();
}
}
/**
* String replacer.
*
* @param target is the original string
* @param from is the string to be replaced
* @param to is the string which will used to replace
* @return
*/
public static String replace (String source, String from, String to) {
int start = source.indexOf(from);
if (start==-1) {
return source;
}
int fromLength = from.length();
char [] sourceArray = source.toCharArray();
StringBuffer buffer = new StringBuffer();
int srcPos=0;
while (start != -1) {
buffer.append (sourceArray, srcPos, start-srcPos);
buffer.append (to);
srcPos=start+fromLength;
start = source.indexOf (from, srcPos);
}
buffer.append (sourceArray, srcPos, sourceArray.length-srcPos);
return buffer.toString();
}
public static String concatStrings(String part1, String separator, String part2) {
if (StringUtils.isEmpty(part1)) {
return part2;
}
if (StringUtils.isEmpty(part2)) {
return part1;
}
return part1+separator+part2;
}
public static String byteArrayToString(byte[] input, String endOfLineString, boolean xmlEncode) throws IOException{
ByteArrayInputStream bis = new ByteArrayInputStream(input);
return streamToString(bis, endOfLineString, xmlEncode);
}
public static byte[] gzip(String input) throws IOException {
return gzip(input.getBytes(DEFAULT_INPUT_STREAM_ENCODING));
}
public static byte[] gzip(byte[] input) throws IOException {
// Create an expandable byte array to hold the compressed data.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
GZIPOutputStream gz = new GZIPOutputStream(bos);
gz.write(input);
gz.close();
bos.close();
// Get the compressed data
return bos.toByteArray();
}
public static String gunzipToString(byte[] input) throws DataFormatException, IOException {
return byteArrayToString(gunzip(input),"\n",false);
}
public static byte[] gunzip(byte[] input) throws DataFormatException, IOException {
// Create an expandable byte array to hold the decompressed data
ByteArrayInputStream bis = new ByteArrayInputStream(input);
GZIPInputStream gz = new GZIPInputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Decompress the data
byte[] buf = new byte[1024];
while (gz.available()>0) {
int count = gz.read(buf,0,1024);
if (count>0) {
bos.write(buf, 0, count);
}
}
bos.close();
// Get the decompressed data
return bos.toByteArray();
}
public static byte[] compress(String input) throws IOException {
return compress(input.getBytes(DEFAULT_INPUT_STREAM_ENCODING));
}
public static byte[] compress(byte[] input) throws IOException {
// Create the compressor with highest level of compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
// Give the compressor the data to compress
compressor.setInput(input);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Compress the data
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
// Get the compressed data
return bos.toByteArray();
}
public static String decompressToString(byte[] input) throws DataFormatException, IOException {
return byteArrayToString(decompress(input),"\n",false);
}
public static byte[] decompress(byte[] input) throws DataFormatException, IOException {
// Create the decompressor and give it the data to compress
Inflater decompressor = new Inflater();
decompressor.setInput(input);
// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
bos.close();
// Get the decompressed data
return bos.toByteArray();
}
public static Properties getEnvironmentVariables() throws IOException {
Properties props = new Properties();
try {
Method getenvs = System.class.getMethod( "getenv", (java.lang.Class[]) null );
Map env = (Map) getenvs.invoke( null, (java.lang.Object[]) null );
for (Iterator it = env.keySet().iterator(); it.hasNext();) {
String key = (String)it.next();
String value = (String)env.get(key);
props.setProperty(key,value);
}
} catch ( NoSuchMethodException e ) {
log.debug("Caught NoSuchMethodException, just not on JDK 1.5: "+e.getMessage());
} catch ( IllegalAccessException e ) {
log.debug("Caught IllegalAccessException, using JDK 1.4 method",e);
} catch ( InvocationTargetException e ) {
log.debug("Caught InvocationTargetException, using JDK 1.4 method",e);
}
if (props.size() == 0) {
BufferedReader br = null;
Process p = null;
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
if (OS.indexOf("windows 9") > -1) {
p = r.exec("command.com /c set");
} else if (
(OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 20") > -1)
|| (OS.indexOf("windows xp") > -1)) {
p = r.exec("cmd.exe /c set");
} else {
//assume Unix
p = r.exec("env");
}
// props.load(p.getInputStream()); // this does not work, due to potential malformed escape sequences
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
int idx = line.indexOf('=');
if (idx>=0) {
String key = line.substring(0, idx);
String value = line.substring(idx + 1);
props.setProperty(key,value);
}
}
}
return props;
}
public static String getHostname() {
String localHost=null;
// String localIP="";
try {
InetAddress localMachine = InetAddress.getLocalHost();
//localIP = localMachine.getHostAddress();
localHost = localMachine.getHostName();
} catch(UnknownHostException uhe) {
if (localHost==null) {
localHost="unknown ("+uhe.getMessage()+")";
}
}
return localHost;
}
public static void copyContext(String keys, Map from, Map to) {
if (StringUtils.isNotEmpty(keys) && from!=null && to!=null) {
StringTokenizer st = new StringTokenizer(keys,",;");
while (st.hasMoreTokens()) {
String key=st.nextToken();
Object value=from.get(key);
to.put(key,value);
}
}
}
public static String getDeployedApplicationName() {
URL url= ClassUtils.getResourceURL(Misc.class, "");
String path = url.getPath();
log.debug("classloader resource [" + path + "]");
StringTokenizer st = new StringTokenizer(path, File.separator);
String appName = null;
while (st.hasMoreTokens() && appName == null) {
String token = st.nextToken();
if (StringUtils.upperCase(token).endsWith(".EAR")) {
appName = token.substring(0,token.length()-4);
}
}
log.debug("deployedApplicationName [" + appName + "]");
return appName;
}
public static String getDeployedApplicationBindings(String appName) throws IOException {
String appBndFile =
getApplicationDeploymentDescriptorPath(appName)
+ File.separator
+ "ibm-application-bnd.xmi";
log.debug("deployedApplicationBindingsFile [" + appBndFile + "]");
return fileToString(appBndFile);
}
public static String getApplicationDeploymentDescriptorPath(String appName) throws IOException {
String appPath =
// "${WAS_HOME}"
"${user.install.root}"
+ File.separator
+ "config"
+ File.separator
+ "cells"
+ File.separator
+ "${WAS_CELL}"
+ File.separator
+ "applications"
+ File.separator
+ appName
+ ".ear"
+ File.separator
+ "deployments"
+ File.separator
+ appName
+ File.separator
+ "META-INF";
Properties props = Misc.getEnvironmentVariables();
props.putAll(System.getProperties());
String resolvedAppPath = StringResolver.substVars(appPath, props);
return resolvedAppPath;
}
public static String getApplicationDeploymentDescriptor (String appName) throws IOException {
String appFile =
getApplicationDeploymentDescriptorPath(appName)
+ File.separator
+ "application.xml";
log.debug("applicationDeploymentDescriptor [" + appFile + "]");
return fileToString(appFile);
}
public static long toFileSize(String value, long defaultValue) {
if(value == null)
return defaultValue;
String s = value.trim().toUpperCase();
long multiplier = 1;
int index;
if((index = s.indexOf("KB")) != -1) {
multiplier = 1024;
s = s.substring(0, index);
}
else if((index = s.indexOf("MB")) != -1) {
multiplier = 1024*1024;
s = s.substring(0, index);
}
else if((index = s.indexOf("GB")) != -1) {
multiplier = 1024*1024*1024;
s = s.substring(0, index);
}
if(s != null) {
try {
return Long.valueOf(s).longValue() * multiplier;
}
catch (NumberFormatException e) {
log.error("[" + value + "] not in expected format", e);
}
}
return defaultValue;
}
public static String toFileSize(long value) {
long divider = 1024*1024*1024;
String suffix = null;
if (value>=divider) {
suffix = "GB";
} else {
divider = 1024*1024;
if (value>=divider) {
suffix = "MB";
} else {
divider = 1024;
if (value>=divider) {
suffix = "KB";
}
}
}
if (suffix==null) {
return Long.toString(value);
} else {
float f = (float)value / divider;
return Math.round(f) + suffix;
}
}
public static synchronized long getMessageSizeWarnByDefault() {
if (messageSizeWarnByDefault==null) {
String definitionString=AppConstants.getInstance().getString(MESSAGE_SIZE_WARN_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
messageSizeWarnByDefault = new Long(definition);
}
return messageSizeWarnByDefault.longValue();
}
public static synchronized long getMessageSizeErrorByDefault() {
if (messageSizeErrorByDefault==null) {
String definitionString=AppConstants.getInstance().getString(MESSAGE_SIZE_ERROR_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
messageSizeErrorByDefault = new Long(definition);
}
return messageSizeErrorByDefault.longValue();
}
public static synchronized long getResponseBodySizeWarnByDefault() {
if (responseBodySizeWarnByDefault==null) {
String definitionString=AppConstants.getInstance().getString(RESPONSE_BODY_SIZE_WARN_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
responseBodySizeWarnByDefault = new Long(definition);
}
return responseBodySizeWarnByDefault.longValue();
}
public static synchronized long getResponseBodySizeErrorByDefault() {
if (responseBodySizeErrorByDefault==null) {
String definitionString=AppConstants.getInstance().getString(RESPONSE_BODY_SIZE_ERROR_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
responseBodySizeErrorByDefault = new Long(definition);
}
return responseBodySizeErrorByDefault.longValue();
}
public static synchronized boolean isForceFixedForwardingByDefault() {
if (forceFixedForwardingByDefault==null) {
boolean force=AppConstants.getInstance().getBoolean(FORCE_FIXED_FORWARDING_BY_DEFAULT_KEY, false);
forceFixedForwardingByDefault = new Boolean(force);
}
return forceFixedForwardingByDefault.booleanValue();
}
public static String listToString(List list) {
StringBuffer sb = new StringBuffer();
for (Iterator it=list.iterator(); it.hasNext();) {
sb.append((String) it.next());
}
return sb.toString();
}
}
|
package nc.popup;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.proxy.MenuItemProxy;
import org.appcelerator.titanium.proxy.TiViewProxy;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnDismissListener;
import android.widget.PopupMenu.OnMenuItemClickListener;
@Kroll.proxy(creatableInModule=NcPopupModule.class)
public class PopupMenuProxy extends KrollProxy implements OnMenuItemClickListener, OnDismissListener{
private static final String TAG = "NcPopupModule";
private static final int MSG_FIRST_ID = KrollProxy.MSG_LAST_ID + 1;
private static final int MSG_SHOW = MSG_FIRST_ID + 100;
protected static final int MSG_LAST_ID = MSG_FIRST_ID + 999;
private static final String PROPERTY_OPTIONS = "options";
private static final String PROPERTY_VIEW = "view";
private static final String EVENT_CLICK = "click";
private static final String EVENT_DISMISS = "dismiss";
private PopupMenu mPopupMenu;
public PopupMenuProxy() {
super();
}
public PopupMenuProxy(TiContext tiContext) {
this();
}
@Override
public void handleCreationDict(KrollDict dict) {
super.handleCreationDict(dict);
String[] options = null;
View view = null;
if (dict.containsKey(PROPERTY_OPTIONS)) {
options = dict.getStringArray(PROPERTY_OPTIONS);
}
if (options == null) {
throw new IllegalArgumentException("'options' is required");
}
if (dict.containsKey(PROPERTY_VIEW)) {
Object v = dict.get(PROPERTY_VIEW);
if (v instanceof TiViewProxy) {
TiViewProxy vp = (TiViewProxy) v;
view = vp.getOrCreateView().getOuterView();
}
if (v instanceof MenuItemProxy) {
view = getActivity().findViewById(((MenuItemProxy) v).getItemId());
}
}
if (view == null) {
throw new IllegalArgumentException("'view' is required");
}
mPopupMenu = new PopupMenu(getActivity(), view);
mPopupMenu.setOnMenuItemClickListener(this);
mPopupMenu.setOnDismissListener(this);
int i = 0;
for (String option : options) {
mPopupMenu.getMenu().add(Menu.NONE, Menu.NONE, i++, option);
}
}
@Kroll.method
public void show() {
if (TiApplication.isUIThread()) {
handleShow();
} else {
getMainHandler().obtainMessage(MSG_SHOW).sendToTarget();
}
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_SHOW:
handleShow();
return true;
}
return super.handleMessage(msg);
}
private void handleShow() {
mPopupMenu.show();
}
@Override
public void onDismiss(PopupMenu menu) {
if (hasListeners(EVENT_DISMISS)) {
fireEvent(EVENT_DISMISS, null);
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (hasListeners(EVENT_CLICK)) {
KrollDict data = new KrollDict();
data.put("index", item.getOrder());
fireEvent(EVENT_CLICK, data);
}
return true;
}
}
|
package cx2x.xcodeml.xelement;
import org.w3c.dom.Element;
import cx2x.xcodeml.helper.*;
/**
* The Xbound represents the lowerBound and upperBound (8.12, 8.13) element in
* XcodeML intermediate representation.
*
* Elements:
* - exprModel
*
* @author clementval
*/
public class Xbound extends XbaseElement {
private String _value = null;
private boolean _constant = false;
private boolean _isVar = false;
private Xvar _var = null;
private XexprModel _exprModel = null;
/**
* Xelement standard ctor. Pass the base element to the base class and read
* inner information (elements and attributes).
* @param baseElement The root element of the Xelement
*/
public Xbound(Element baseElement){
super(baseElement);
_exprModel = XelementHelper.findExprModel(this, false);
}
/**
* Get the inner element
* @return Inner element as exprModel
*/
public XexprModel getExprModel(){
return _exprModel;
}
public String getValue(){
if(_exprModel.isVar()){
return _exprModel.getVar().getValue();
}
if(_exprModel.isConstant()){
return _exprModel.getConstant().getValue();
}
return null;
}
@Override
public boolean equals(Object ob) {
if (ob == null) return false;
if (ob.getClass() != getClass()) return false;
Xbound other = (Xbound)ob;
if(getValue() != null && other.getValue() != null
&& getValue().toLowerCase().equals(other.getValue().toLowerCase()))
{
return true;
}
return false;
}
@Override
public int hashCode() {
return _value.hashCode();
}
}
|
package kg.apc.jmeter.jmxmon;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXServiceURL;
import kg.apc.emulators.TestJMeterUtils;
import kg.apc.jmeter.JMeterPluginsUtils;
import kg.apc.jmeter.vizualizers.JMXMonGui;
import org.apache.jmeter.gui.util.PowerTableModel;
import org.apache.jmeter.samplers.SampleEvent;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author cyberw
*/
public class JMXMonTest {
public static final String URL = "service:jmx:rmi:///jndi/rmi://localhost:6969/jmxrmi";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String OBJ_NAME1 = "Something:name=objectName1";
public static final String OBJ_NAME2 = "Something:name=objectName1";
public static final String ATTRIBUTE1 = "attribute1";
public static final String ATTRIBUTE2 = "attribute2";
public static final String PROBE1 = "probe1";
public static final String PROBE2 = "probe2";
private PowerTableModel dataModel;
private boolean threadStoped = false;
private Map<String, Double> latestSamples = new HashMap<String, Double>();
private Map<String, Double> queryResults = new HashMap<String, Double>();
@Before
public void setUp() {
TestJMeterUtils.createJmeterEnv();
dataModel = new PowerTableModel(JMXMonGui.columnIdentifiers, JMXMonGui.columnClasses);
dataModel.addRow(new Object[]{ PROBE1, URL, USERNAME, PASSWORD, OBJ_NAME1, ATTRIBUTE1, false });
dataModel.addRow(new Object[]{ PROBE2, URL, USERNAME, PASSWORD, OBJ_NAME1, ATTRIBUTE2, true });
}
@Test
public void testRun() throws InterruptedException {
// FIXME: this test is broken, need to enable assertions back and fix it in "Test All" mode
JMXMonCollector instance = new TestJMXMonCollector();
instance.setData(JMeterPluginsUtils.tableModelRowsToCollectionProperty(dataModel, JMXMonCollector.DATA_PROPERTY));
instance.testStarted();
setQueryResult(ATTRIBUTE1, 1);
setQueryResult(ATTRIBUTE2, 1);
instance.processConnectors();
//assertLastSample(PROBE1, 1);
//assertNull(latestSamples.get(PROBE2)); // Deleta can not produce values at first loop
setQueryResult(ATTRIBUTE1, -2);
setQueryResult(ATTRIBUTE2, 2);
instance.processConnectors();
//assertLastSample(PROBE1, -2);
//assertLastSample(PROBE2, 1);
setQueryResult(ATTRIBUTE1, 13);
setQueryResult(ATTRIBUTE2, 1);
instance.processConnectors();
//assertLastSample(PROBE1, 13);
//assertLastSample(PROBE2, -1);
instance.testEnded();
//assertSampleGeneratorThreadIsStoped();
}
public void setQueryResult(String attribute, double value) {
queryResults.put(attribute, value);
}
// @Override
// public ResultSet getQueryResult(String probeName) {
// return TestConnection.resultSet(queryResults.get(probeName));
private void assertSampleGeneratorThreadIsStoped() throws InterruptedException {
synchronized (this) {
if (!threadStoped) {
wait(1000);
assertTrue(threadStoped);
}
}
}
private void assertLastSample(String probeName, double expected) {
final Double actual = latestSamples.get(probeName);
assertEquals(expected, actual, 0.0001);
}
/*
private class TestDataSource implements DataSourceComponent {
@Override
public Connection getConnection() throws SQLException {
return new TestConnection(JMXMonTest.this);
}
@Override
public void configure(Configuration c) throws ConfigurationException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
*/
private class TestJMXMonCollector extends JMXMonCollector {
@Override
public void run() {
try {
// Override run to controll the entire flow from the test
Thread.sleep(24*60*60*1000);
} catch (InterruptedException ex) {
synchronized (JMXMonTest.this) {
threadStoped = true;
JMXMonTest.this.notifyAll();
}
}
}
@Override
protected void initiateConnector(JMXServiceURL u, Hashtable attributes, String name, boolean delta, String objectName, String attribute) throws MalformedURLException, IOException {
MBeanServerConnection conn = new MBeanServerConnectionEmul(queryResults);
jmxMonSamplers.add(new JMXMonSampler(conn, name, objectName, attribute, delta));
}
@Override
public void jmxMonSampleOccurred(SampleEvent event) {
super.sampleOccurred(event);
double value = JMXMonSampleResult.getValue(event.getResult());
latestSamples.put(event.getResult().getSampleLabel(), value);
}
@Override
public void testEnded() {
super.testEnded(); //To change body of generated methods, choose Tools | Templates.
}
}
}
|
import static org.junit.Assert.*;
import java.util.*;
import org.junit.Test;
public class MultiMapTest {
@Test
public void testInitialSizeValue(){
MultiMap<String, List<Integer>> mp = new MultiMap<String, List<Integer>>();
assertEquals(0, mp.size());
}
@Test
public void testWhatIPutIsWhatIGet(){
MultiMap<Integer, List<String>> mp = new MultiMap<Integer, List<String>>();
mp.put(1, new ArrayList<String>());
assertEquals(new Integer(1), mp.get().get(0));
}
@Test
public void testSizeForNotEmptyMap(){
MultiMap<Integer, List<Integer>> mp = new MultiMap<Integer, List<Integer>>();
for(int i = 0; i < 5; i++){
mp.put(i, new ArrayList<Integer>());
}
assertEquals(5, mp.size());
}
@Test
public void testThatEmptyMapIsEmpty(){
MultiMap<Integer, List<Integer>> mp = new MultiMap<Integer, List<Integer>>();
assertTrue(mp.isEmpty());
}
@Test
public void testThatNotEmptyMapIsNotEmpty(){
MultiMap<Integer, List<Integer>> mp = new MultiMap<Integer, List<Integer>>();
mp.put(1, new LinkedList<Integer>());
assertFalse(mp.isEmpty());
}
@Test(expected = NullPointerException.class)
public void testNullKeyCausesException(){
MultiMap<Integer, List<Integer>> mp = new MultiMap<Integer, List<Integer>>();
mp.put(null, new LinkedList<Integer>());
}
@Test(expected = NullPointerException.class)
public void testNullValueCausesException(){
MultiMap<Integer, List<Integer>> mp = new MultiMap<Integer, List<Integer>>();
mp.put(1,null);
}
@Test
public void testWhatIPutIsWhatIGetForBigNumbers(){
Set<Integer> s1 = new HashSet<Integer>();
MultiMap<Integer, List<Integer>> mp = new MultiMap<Integer, List<Integer>>();
for(int i = 0; i < 1000; i++){
mp.put(i, new ArrayList<Integer>());
s1.add(i);
}
Set<Integer> s2 = new HashSet<Integer>();
s2.addAll(mp.get());
assertTrue(s1.equals(s2));
}
}
|
package edu.psu.compbio.seqcode.projects.akshay.bayesments.analysis;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.bayesnet.BIC;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.bayesnet.EMtrain;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.bayesnet.MAPassignment;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.experiments.ExperimentManager;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.features.GenomicLocations;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.framework.Config;
import edu.psu.compbio.seqcode.projects.akshay.bayesments.utils.BayesmentsSandbox;
/**
* The main driver class for the Bayesments project
* @author akshaykakumanu
*
*/
public class Bayesments {
public static void main(String[] args){
// Build the Config class the comman line arguments
Config c = new Config(args);
if(c.helpWanter()){
System.err.println("Bayesments:");
System.err.println(c.getArgsList());
}else{
// Make the output directories using the provided root name
c.makeGPSOutputDirs(c.doEMplot());
ExperimentManager manager = null;
GenomicLocations trainingData = null;
//Loading/reading tags
if(!c.doSimulation()){
// Store the reads by building the ExperimentManager
System.out.println("Loading Reads\n");
manager = new ExperimentManager(c,c.loadReads());
// Read and store the training data in a GenomicLocations object
System.out.println("Filling Training Data\n");
trainingData = new GenomicLocations(manager,c);
// Plot the cumulative plots of the training data
System.out.println("Plotting the traning data");
trainingData.plotData(c, manager);
}
EMrunner trainer = null;
double[][] bic_vals = new double[c.getMaxChromStates()-c.getMinChromStates()+1][c.getMaxFacStates()-c.getMinFacStates()+1];
int nRows = c.getMaxChromStates()-c.getMinChromStates()+1;
int nCols = c.getMaxFacStates()-c.getMinFacStates()+1;
for(int i=0; i<nRows; i++){
for(int j=0; j<nCols; j++){
if(!c.doSimulation()){
trainer = new EMrunner(c, trainingData, manager, i+c.getMinChromStates(), j+c.getMinFacStates(), false);
}else{
trainer = new EMrunner(c, i+c.getMinChromStates(), j+c.getMinFacStates(), false);
}
trainer.trainModel();
BIC temp_bic = new BIC(c, trainer.getModel(), i+c.getMinChromStates(), j+c.getMinFacStates());
bic_vals[i][j] = temp_bic.calculateBicScore();
}
}
int nChromStates = BayesmentsSandbox.getMinIndex(bic_vals).car()+c.getMinChromStates();
int nFacStates = BayesmentsSandbox.getMinIndex(bic_vals).cdr()+c.getMinFacStates();
trainer = null;
if(!c.doSimulation()){
trainer = new EMrunner(c, trainingData, manager, nChromStates, nFacStates,c.doRegularization());
}else{
trainer = new EMrunner(c, nChromStates, nFacStates,c.doRegularization());
}
//Initialize EMrunner and train the model
trainer.trainModel();
//Do MAP assignament
if(!c.doSimulation()){
MAPassignment map = new MAPassignment(trainer.getModel(), c, trainingData.getLocations(), c.getNumChrmStates(), c.getNumFacStates());
map.execute(true);
}else{
MAPassignment map = new MAPassignment(trainer.getModel(), c, null, c.getNumChrmStates(), c.getNumFacStates());
map.execute(false);
}
// Print all the learned parameters
//System.out.println("PI-C values\n");
//BayesmentsSandbox.printArray(trainer.getPIj(), "chrom_state");
System.out.println("MU-C values\n");
BayesmentsSandbox.printArray(trainer.getMUc(),"MUc" , "MUc", trainer.getModel().getConditionNames());
System.out.println("MU-F values\n");
BayesmentsSandbox.printArray(trainer.getMUf(),"MUf" , "MUf", trainer.getModel().getConditionNames());
if(!c.runOnlyChrom()){
System.out.println("MU-S values\n");
BayesmentsSandbox.printArray(trainer.getMUs(),"MUS" , "MUS", trainer.getModel().getConditionNames());
}
System.out.println("SIGMA-C values\n");
BayesmentsSandbox.printArray(trainer.getSIGMAc(),"SIGMAc" , "SIGMAc", trainer.getModel().getConditionNames());
System.out.println("SIGMA-F values\n");
BayesmentsSandbox.printArray(trainer.getSIGMAf(),"SIGMAf" , "SIGMAf", trainer.getModel().getConditionNames());
if(!c.runOnlyChrom()){
System.out.println("SIGMA-S values\n");
BayesmentsSandbox.printArray(trainer.getSIGMAs(),"SIGMAs" , "SIGMAs", trainer.getModel().getConditionNames());
}
System.out.println("Bjk values\n");
BayesmentsSandbox.printArray(trainer.getBjk(),"chromatin_State" , "factor_state", trainer.getModel().getConditionNames());
if(c.doRegularization()){
System.out.println("Chromatin Weight values\n");
BayesmentsSandbox.printArray(trainer.getChromWeights(), "Chromatin Feature");
if(!c.runOnlyChrom()){
System.out.println("Sequence Weight values\n");
BayesmentsSandbox.printArray(trainer.getSeqWeights(), "Sequence Feature");
}
}
}
}
}
|
package org.orbeon.oxf.xforms.state;
import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.orbeon.oxf.cache.CacheLinkedList;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.pipeline.StaticExternalContext;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.Datasource;
import org.orbeon.oxf.processor.xmldb.XMLDBProcessor;
import org.orbeon.oxf.xforms.XFormsModelSubmission;
import org.orbeon.oxf.xforms.XFormsProperties;
import org.orbeon.oxf.xforms.XFormsSubmissionUtils;
import org.orbeon.oxf.xforms.XFormsUtils;
import org.orbeon.oxf.xforms.processor.XFormsServer;
import org.orbeon.oxf.xml.TransformerUtils;
import org.orbeon.oxf.xml.dom4j.LocationDocumentResult;
import org.orbeon.saxon.om.FastStringBuffer;
import org.xml.sax.ContentHandler;
import javax.xml.transform.sax.TransformerHandler;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This store keeps XFormsState instances into an application store and persists data going over a given size.
*
* This store leverages the underlying memory store.
*
* o When an entry from the memory store is expiring, it is migrated to the persistent store.
* o When an entry is not found in the memory store, it is searched for in the persistent store.
* o A session id is added when available.
* o When a session expires, both memory and persistent entries are expired.
* o Upon first use, all persistent entries with session information are expired.
*/
public class XFormsPersistentApplicationStateStore extends XFormsStateStore {
private static final boolean TEMP_PERF_TEST = false;
private static final int TEMP_PERF_ITERATIONS = 100;
private static final boolean TEMP_USE_XMLDB = true;
// Ideally we wouldn't want to force session creation, but it's hard to implement the more elaborate expiration
private static final boolean FORCE_SESSION_CREATION = true;
private static final String PERSISTENT_STATE_STORE_APPLICATION_KEY = "oxf.xforms.state.store.persistent-application-key";
private static final String XFORMS_STATE_STORE_LISTENER_STATE_KEY = "oxf.xforms.state.store.has-session-listeners-key";
// For now the driver is not configurable, but everything else (URI, username, password, collection) is configurable in properties
private static final String EXIST_XMLDB_DRIVER = "org.exist.xmldb.DatabaseImpl";
// Map session ids -> Map of keys
private final Map sessionToKeysMap = new HashMap();
public synchronized static XFormsStateStore instance(ExternalContext externalContext) {
{
final XFormsStateStore existingStateStore
= (XFormsStateStore) externalContext.getAttributesMap().get(PERSISTENT_STATE_STORE_APPLICATION_KEY);
if (existingStateStore != null)
return existingStateStore;
}
{
// Create new store
final XFormsPersistentApplicationStateStore newStateStore = new XFormsPersistentApplicationStateStore();
// Expire remaining persistent entries with session information
newStateStore.expireAllPersistentWithSession();
// newStateStore.expireAllPersistent();
// Keep new store in application scope
externalContext.getAttributesMap().put(PERSISTENT_STATE_STORE_APPLICATION_KEY, newStateStore);
return newStateStore;
}
}
protected int getMaxSize() {
return XFormsProperties.getApplicationStateStoreSize();
}
protected String getStoreDebugName() {
return "global application";
}
// NOTE: The super() method doesn't do anything
protected void persistEntry(StoreEntry storeEntry) {
if (XFormsServer.logger.isDebugEnabled()) {
debug("persisting entry for key: " + storeEntry.key + " (" + (storeEntry.value.length() * 2) + " bytes).");
}
final PipelineContext pipelineContext = getPipelineContext();
final ExternalContext externalContext = getExternalContext();
if (TEMP_PERF_TEST) {
// Do the operation TEMP_PERF_ITERATIONS times to test performance
final long startTime = System.currentTimeMillis();
for (int i = 0; i < TEMP_PERF_ITERATIONS; i ++) {
if (TEMP_USE_XMLDB) {
persistEntryExistXMLDB(pipelineContext, externalContext, storeEntry);
} else {
persistEntryExistHTTP(pipelineContext, externalContext, storeEntry);
}
}
debug("average write persistence time: " + ((System.currentTimeMillis() - startTime) / TEMP_PERF_ITERATIONS) + " ms." );
} else {
if (TEMP_USE_XMLDB) {
persistEntryExistXMLDB(pipelineContext, externalContext, storeEntry);
} else {
persistEntryExistHTTP(pipelineContext, externalContext, storeEntry);
}
}
}
// NOTE: This calls super() and handles session information
protected void addOne(String key, String value, boolean isInitialEntry) {
// Actually add
super.addOne(key, value, isInitialEntry);
final ExternalContext.Session session = getExternalContext().getSession(FORCE_SESSION_CREATION);
if (session != null) {
// Remember that this key is associated with a session
final String sessionId = session.getId();
Map sessionMap = (Map) sessionToKeysMap.get(sessionId);
if (sessionMap == null) {
sessionMap = new HashMap();
sessionToKeysMap.put(sessionId, sessionMap);
}
sessionMap.put(key, "");
}
}
// This calls super() (without the session id) and handles session information
// NOTE: This version is used when called from the session listener
private void removeStoreEntry(String sessionId, CacheLinkedList.ListEntry existingListEntry) {
// Actually remove
super.removeStoreEntry(existingListEntry);
// Remove the mapping of the session to this key, if any
final Map sessionMap = (Map) sessionToKeysMap.get(sessionId);
if (sessionMap != null) {
sessionMap.remove(((StoreEntry) existingListEntry.element).key);
}
}
// This calls super() and handles session information
protected void removeStoreEntry(CacheLinkedList.ListEntry existingListEntry) {
// Actually remove
super.removeStoreEntry(existingListEntry);
final ExternalContext.Session session = getExternalContext().getSession(false);
if (session != null) {
// Remove the mapping of the session to this key, if any
final String sessionId = session.getId();
final Map sessionMap = (Map) sessionToKeysMap.get(sessionId);
if (sessionMap != null) {
sessionMap.remove(((StoreEntry) existingListEntry.element).key);
}
}
}
// This calls super() and if that fails, tries the persistent store
protected String findOne(String key) {
final String memoryValue = super.findOne(key);
if (memoryValue != null) {
// Try memory first
return memoryValue;
} else {
// Try the persistent cache
final StoreEntry persistedStoreEntry = findPersistedEntry(key);
if (persistedStoreEntry != null) {
// Add the key to the list in memory
addOne(persistedStoreEntry.key, persistedStoreEntry.value, persistedStoreEntry.isInitialEntry);
debug("migrated persisted entry for key: " + key);
return persistedStoreEntry.value;
} else {
// Not found
debug("did not find entry in persistent cache for key: " + key);
return null;
}
}
}
private void persistEntryExistXMLDB(PipelineContext pipelineContext, ExternalContext externalContext, StoreEntry storeEntry) {
final String messageBody = encodeMessageBody(pipelineContext, externalContext, storeEntry);
try {
new XMLDBAccessor().storeResource(pipelineContext, new Datasource(EXIST_XMLDB_DRIVER,
XFormsProperties.getStoreURI(), XFormsProperties.getStoreUsername(), XFormsProperties.getStorePassword()), XFormsProperties.getStoreCollection(),
true, storeEntry.key, messageBody);
} catch (Exception e) {
throw new OXFException("Unable to store entry in persistent state store for key: " + storeEntry.key, e);
}
}
private void persistEntryExistHTTP(PipelineContext pipelineContext, ExternalContext externalContext, StoreEntry storeEntry) {
final String url = "/exist/rest" + XFormsProperties.getStoreCollection() + storeEntry.key;
final String resolvedURL = externalContext.getResponse().rewriteResourceURL(url, true);
final byte[] messageBody;
try {
messageBody = encodeMessageBody(pipelineContext, externalContext, storeEntry).getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
throw new OXFException(e);// won't happen
}
// Put document into external storage
XFormsModelSubmission.ConnectionResult result = XFormsSubmissionUtils.doRegular(externalContext, "put", resolvedURL, null, null, "application/xml", messageBody, null);
if (result.resultCode < 200 || result.resultCode >= 300)
throw new OXFException("Got non-successful return code from store persistence layer: " + result.resultCode);
}
/**
* Remove all memory entries which have the given session id.
*
* @param sessionId Servlet session id
*/
private void expireMemoryBySession(String sessionId) {
final Map sessionMap = (Map) sessionToKeysMap.get(sessionId);
if (sessionMap != null) {
final int storeSizeBeforeExpire = getCurrentStoreSize();
int expiredCount = 0;
for (Iterator i = sessionMap.keySet().iterator(); i.hasNext();) {
final String currentKey = (String) i.next();
final CacheLinkedList.ListEntry currenEntry = findEntry(currentKey);
removeStoreEntry(sessionId, currenEntry);
expiredCount++;
}
sessionToKeysMap.remove(sessionId);
if (expiredCount > 0 && XFormsServer.logger.isDebugEnabled())
debug("expired " + expiredCount + " entries for session " + sessionId + " (" + (storeSizeBeforeExpire - getCurrentStoreSize()) + " bytes).");
}
}
/**
* Remove all persisted entries which have the given session id.
*
* @param sessionId Servlet session id
*/
private void expirePersistentBySession(String sessionId) {
final String query = "xquery version \"1.0\";" +
" declare namespace xmldb=\"http://exist-db.org/xquery/xmldb\";" +
" declare namespace util=\"http://exist-db.org/xquery/util\";" +
" <result>" +
" {" +
" count(for $entry in /entry[session-id = '" + sessionId + "']" +
" return (xmldb:remove(util:collection-name($entry), util:document-name($entry)), ''))" +
" }" +
" </result>";
final Document result = executeQuery(query);
final int count = Integer.parseInt(result.getDocument().getRootElement().getStringValue());
debug("expired " + count + " persistent entries for session (" + sessionId + ").");
}
private void expireAllPersistentWithSession() {
final String query = "xquery version \"1.0\";" +
" declare namespace xmldb=\"http://exist-db.org/xquery/xmldb\";" +
" declare namespace util=\"http://exist-db.org/xquery/util\";" +
" <result>" +
" {" +
" count(for $entry in /entry[session-id]" +
" return (xmldb:remove(util:collection-name($entry), util:document-name($entry)), ''))" +
" }" +
" </result>";
final Document result = executeQuery(query);
final int count = Integer.parseInt(result.getRootElement().getStringValue());
debug("expired " + count + " persistent entries with session information.");
}
public void expireAllPersistent() {
final String query = "xquery version \"1.0\";" +
" declare namespace xmldb=\"http://exist-db.org/xquery/xmldb\";" +
" declare namespace util=\"http://exist-db.org/xquery/util\";" +
" <result>" +
" {" +
" count(for $entry in /entry" +
" return (xmldb:remove(util:collection-name($entry), util:document-name($entry)), ''))" +
" }" +
" </result>";
final Document result = executeQuery(query);
final int count = Integer.parseInt(result.getRootElement().getStringValue());
debug("expired " + count + " persistent entries.");
}
private Document executeQuery(String query) {
final DocumentResult result = new DocumentResult();
final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler();
identity.setResult(result);
new XMLDBAccessor().query(getPipelineContext(), new Datasource(EXIST_XMLDB_DRIVER,
XFormsProperties.getStoreURI(), XFormsProperties.getStoreUsername(), XFormsProperties.getStorePassword()), XFormsProperties.getStoreCollection(),
true, null, query, null, identity);
return result.getDocument();
}
private PipelineContext getPipelineContext() {
// NOTE: We may not have a StaticContext when we are called from a session listener, but that should be ok
// (PipelineContext is used further down the line to ensure that the db drive is registered, but it should
final StaticExternalContext.StaticContext staticContext = StaticExternalContext.getStaticContext();
return (staticContext != null) ? staticContext.getPipelineContext() : null;
}
private ExternalContext getExternalContext() {
final StaticExternalContext.StaticContext staticContext = StaticExternalContext.getStaticContext();
return (staticContext != null) ? staticContext.getExternalContext() : null;
}
private String encodeMessageBody(PipelineContext pipelineContext, ExternalContext externalContext, StoreEntry storeEntry) {
final FastStringBuffer sb = new FastStringBuffer("<entry><key>");
sb.append(storeEntry.key);
sb.append("</key><value>");
// Store the value and make sure it is encrypted as it will be externalized
final String encryptedValue;
if (storeEntry.value.startsWith("X3") || storeEntry.value.startsWith("X4")) {
// Data is currently not encrypted, so encrypt it
final byte[] decodedValue = XFormsUtils.decodeBytes(pipelineContext, storeEntry.value, XFormsProperties.getXFormsPassword());
encryptedValue = XFormsUtils.encodeBytes(pipelineContext, decodedValue, XFormsProperties.getXFormsPassword());
} else {
// Data is already encrypted
encryptedValue = storeEntry.value;
}
sb.append(encryptedValue);
sb.append("</value>");
// Store the session id if any
final ExternalContext.Session session = externalContext.getSession(FORCE_SESSION_CREATION);
if (session != null) {
sb.append("<session-id>");
sb.append(session.getId());
sb.append("</session-id>");
// Add session listener if needed (we want to register only one expiration listener per session)
final Map sessionAttributes = session.getAttributesMap(ExternalContext.Session.APPLICATION_SCOPE);
if (sessionAttributes.get(XFORMS_STATE_STORE_LISTENER_STATE_KEY) == null) {
session.addListener(new ExternalContext.Session.SessionListener() {
public void sessionDestroyed() {
// Expire both memory and persistent entries
expireMemoryBySession(session.getId());
expirePersistentBySession(session.getId());
}
});
sessionAttributes.put(XFORMS_STATE_STORE_LISTENER_STATE_KEY, "");
}
}
// Store the initial entry flag
sb.append("<is-initial-entry>");
sb.append(Boolean.toString(storeEntry.isInitialEntry));
sb.append("</is-initial-entry></entry>");
return sb.toString();
}
private StoreEntry findPersistedEntry(String key) {
if (XFormsServer.logger.isDebugEnabled()) {
debug("finding persisting entry for key: " + key + ".");
}
StoreEntry result = null;
if (TEMP_PERF_TEST) {
// Do the operation TEMP_PERF_ITERATIONS times to test performance
final long startTime = System.currentTimeMillis();
for (int i = 0; i < TEMP_PERF_ITERATIONS; i ++) {
if (TEMP_USE_XMLDB) {
result = findPersistedEntryExistXMLDB(key);
} else {
result = findPersistedEntryExistHTTP(key);
}
if (result == null)
return null;
}
debug("average read persistence time: " + ((System.currentTimeMillis() - startTime) / TEMP_PERF_ITERATIONS) + " ms." );
} else {
if (TEMP_USE_XMLDB) {
result = findPersistedEntryExistXMLDB(key);
} else {
result = findPersistedEntryExistHTTP(key);
}
}
return result;
}
private StoreEntry findPersistedEntryExistXMLDB(String key) {
final PipelineContext pipelineContext = getPipelineContext();
final LocationDocumentResult documentResult = new LocationDocumentResult();
final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler();
identity.setResult(documentResult);
try {
new XMLDBAccessor().getResource(pipelineContext, new Datasource(EXIST_XMLDB_DRIVER,
XFormsProperties.getStoreURI(), XFormsProperties.getStoreUsername(), XFormsProperties.getStorePassword()),
XFormsProperties.getStoreCollection(), true, key, identity);
} catch (Exception e) {
throw new OXFException("Unable to find entry in persistent state store for key: " + key, e);
}
final Document document = documentResult.getDocument();
return getStoreEntryFromDocument(key, document);
}
private StoreEntry findPersistedEntryExistHTTP(String key) {
final ExternalContext externalContext = getExternalContext();
final String url = "/exist/rest" + XFormsProperties.getStoreCollection() + key;
final String resolvedURL = externalContext.getResponse().rewriteResourceURL(url, true);
XFormsModelSubmission.ConnectionResult result = XFormsSubmissionUtils.doRegular(externalContext, "get", resolvedURL, null, null, null, null, null);
if (result.resultCode == 404)
return null;
if (result.resultCode < 200 || result.resultCode >= 300)
throw new OXFException("Got non-successful return code from store persistence layer: " + result.resultCode);
final Document document = TransformerUtils.readDom4j(result.getResultInputStream(), result.resourceURI);
return getStoreEntryFromDocument(key, document);
}
private StoreEntry getStoreEntryFromDocument(String key, Document document) {
final String value = document.getRootElement().element("value").getStringValue();
final boolean isInitialEntry = new Boolean(document.getRootElement().element("is-initial-entry").getStringValue()).booleanValue();
return new StoreEntry(key, value, isInitialEntry);
}
private static class XMLDBAccessor extends XMLDBProcessor {
// public void update(PipelineContext pipelineContext, Datasource datasource, String collectionName, boolean createCollection, String resourceId, String query) {
// super.update(pipelineContext, datasource, collectionName, createCollection, resourceId, query);
public void query(PipelineContext pipelineContext, Datasource datasource, String collectionName, boolean createCollection, String resourceId, String query, Map namespaceContext, ContentHandler contentHandler) {
super.query(pipelineContext, datasource, collectionName, createCollection, resourceId, query, namespaceContext, contentHandler);
}
protected void getResource(PipelineContext pipelineContext, Datasource datasource, String collectionName, boolean createCollection, String resourceName, ContentHandler contentHandler) {
super.getResource(pipelineContext, datasource, collectionName, createCollection, resourceName, contentHandler);
}
protected void storeResource(PipelineContext pipelineContext, Datasource datasource, String collectionName, boolean createCollection, String resourceName, String document) {
super.storeResource(pipelineContext, datasource, collectionName, createCollection, resourceName, document);
}
}
}
|
package org.mockito.release.notes.improvements;
import org.json.simple.DeserializationException;
import org.json.simple.JsonObject;
import org.mockito.release.notes.model.Improvement;
import org.mockito.release.notes.util.GitHubFetcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
class GitHubTicketFetcher {
private static final Logger LOG = LoggerFactory.getLogger(GitHubTicketFetcher.class);
Collection<Improvement> fetchTickets(String repository, String authToken, Collection<String> ticketIds, Collection<String> labels,
boolean onlyPullRequests) {
List<Improvement> out = new LinkedList<Improvement>();
if (ticketIds.isEmpty()) {
return out;
}
LOG.info("Querying GitHub API for {} tickets", ticketIds.size());
Queue<Long> tickets = queuedTicketNumbers(ticketIds);
try {
GitHubIssues issues = GitHubIssues.forRepo(repository, authToken)
.state("closed")
.labels(CommaSeparated.commaSeparated(labels))
.filter("all")
.direction("desc")
.browse();
while (!tickets.isEmpty() && issues.hasNextPage()) {
List<JsonObject> page = issues.nextPage();
out.addAll(extractImprovements(
dropTicketsAboveMaxInPage(tickets, page),
page, onlyPullRequests));
}
} catch (Exception e) {
throw new RuntimeException("Problems fetching " + ticketIds.size() + " tickets from GitHub", e);
}
return out;
}
private Queue<Long> dropTicketsAboveMaxInPage(Queue<Long> tickets, List<JsonObject> page) {
if (page.isEmpty()) {
return tickets;
}
BigDecimal highestId = (BigDecimal) page.get(0).get("number");
while (!tickets.isEmpty() && tickets.peek() > highestId.longValue()) {
tickets.poll();
}
return tickets;
}
private Queue<Long> queuedTicketNumbers(Collection<String> ticketIds) {
List<Long> tickets = new ArrayList<Long>();
for (String id : ticketIds) {
tickets.add(Long.parseLong(id));
}
Collections.sort(tickets);
PriorityQueue<Long> longs = new PriorityQueue<Long>(tickets.size(), Collections.reverseOrder());
longs.addAll(tickets);
return longs;
}
private static List<Improvement> extractImprovements(Collection<Long> tickets, List<JsonObject> issues,
boolean onlyPullRequests) {
if(tickets.isEmpty()) {
return Collections.emptyList();
}
ArrayList<Improvement> pagedImprovements = new ArrayList<Improvement>();
for (JsonObject issue : issues) {
Improvement i = GitHubImprovementsJSON.toImprovement(issue);
if (tickets.remove(i.getId())) {
if (!onlyPullRequests || i.isPullRequest()) {
pagedImprovements.add(i);
}
if (tickets.isEmpty()) {
return pagedImprovements;
}
}
}
return pagedImprovements;
}
private static class GitHubIssues {
private final GitHubFetcher fetcher;
private GitHubIssues(String nextPageUrl) {
fetcher = new GitHubFetcher(nextPageUrl);
}
boolean hasNextPage() {
return fetcher.hasNextPage();
}
List<JsonObject> nextPage() throws IOException, DeserializationException {
return fetcher.nextPage();
}
static GitHubIssuesBuilder forRepo(String repository, String authToken) {
return new GitHubIssuesBuilder(repository, authToken);
}
private static class GitHubIssuesBuilder {
private final String authToken;
private final String repository;
private String state;
private String filter;
private String direction;
private String labels;
GitHubIssuesBuilder(String repository, String authToken) {
this.repository = repository;
this.authToken = authToken;
}
GitHubIssuesBuilder state(String state) {
this.state = state;
return this;
}
GitHubIssuesBuilder filter(String filter) {
this.filter = filter;
return this;
}
GitHubIssuesBuilder direction(String direction) {
this.direction = direction;
return this;
}
/**
* Only list issues with given labels, comma separated list.
* Empty string is ok and means that we are interested in all issues, regardless of the label.
*/
public GitHubIssuesBuilder labels(String labels) {
this.labels = labels;
return this;
}
GitHubIssues browse() {
String nextPageUrl = String.format("%s%s%s%s%s%s%s",
"https://api.github.com/repos/" + repository + "/issues",
"?access_token=" + authToken,
state == null ? "" : "&state=" + state,
filter == null ? "" : "&filter=" + filter,
"&labels=" + labels,
direction == null ? "" : "&direction=" + direction,
"&page=1"
);
return new GitHubIssues(nextPageUrl);
}
}
}
}
|
package cn.kunter.common.generator.make.database;
import cn.kunter.common.generator.config.PropertyHolder;
import cn.kunter.common.generator.entity.Column;
import cn.kunter.common.generator.entity.Table;
import cn.kunter.common.generator.make.GetTableConfig;
import cn.kunter.common.generator.util.StringUtility;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
/**
* DBExcel
*
* @author
* @version 1.0 2015611
*/
public class MakeDatabaseOfExcel {
public static void main(String[] args) throws Exception {
List<Table> tables = GetTableConfig.getTableConfig();
MakeDatabaseOfExcel.makerSheet(tables);
}
/**
* Sheet
*
* @param tables
* @throws Exception
* @author
*/
public static void makerSheet(List<Table> tables) throws Exception {
// Excel
Workbook workbook = new XSSFWorkbook();
// Sheet
makerHisSheet(workbook);
makerListSheet(workbook, tables);
for (Table table : tables) {
makerTableSheet(workbook, table);
}
FileOutputStream fileOut = new FileOutputStream(PropertyHolder.getConfigProperty("target") + ".xlsx");
// Excel
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
workbook.close();
}
/**
* TableSheet
*
* @param workbook
* @param table
* @throws Exception
* @author
*/
public static void makerTableSheet(Workbook workbook, Table table) throws Exception {
// Sheet TableNameSheet
String tableName = table.getTableName();
// Excelsheet31sheetName
if (tableName.length() > 31) {
// TODO
tableName = StringUtility.convertTableNameToAlias(tableName, "_");
}
Sheet sheet = null;
try {
sheet = workbook.createSheet(tableName);
} catch (IllegalArgumentException ex) {
sheet = workbook.createSheet(tableName + "1");
}
sheet.setDefaultRowHeight((short) 350);
sheet.setDefaultColumnWidth(2);
CellStyle cellStyle = getCellStyle(workbook);
for (int i = 0; i < table.getCols().size() + 5; i++) {
Row row = sheet.createRow(i);
for (int j = 0; j < 44; j++) {
Cell cell = row.createCell(j, CellType.STRING);
cell.setCellStyle(cellStyle);
}
}
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 6);
sheet.addMergedRegion(region);
Row row = sheet.getRow(0);
Cell cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(0, 0, 7, 21);
sheet.addMergedRegion(region);
cell = row.createCell(7, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell.setCellValue(table.getRemarks());
region = new CellRangeAddress(0, 0, 22, 26);
sheet.addMergedRegion(region);
cell = row.createCell(22, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(0, 0, 27, 32);
sheet.addMergedRegion(region);
cell = row.createCell(27, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell.setCellValue("");
region = new CellRangeAddress(0, 0, 33, 37);
sheet.addMergedRegion(region);
cell = row.createCell(33, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(0, 0, 38, 43);
sheet.addMergedRegion(region);
cell = row.createCell(38, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
CellStyle cellStyleDate = getCellStyle(workbook);
DataFormat format = workbook.createDataFormat();
cellStyleDate.setDataFormat(format.getFormat("yyyy-mm-dd"));
row = sheet.getRow(1);
region = new CellRangeAddress(1, 1, 0, 6);
sheet.addMergedRegion(region);
cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(1, 1, 7, 21);
sheet.addMergedRegion(region);
cell = row.createCell(7, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell.setCellValue(table.getTableName());
region = new CellRangeAddress(1, 1, 22, 26);
sheet.addMergedRegion(region);
cell = row.createCell(22, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(1, 1, 27, 32);
sheet.addMergedRegion(region);
cell = row.createCell(27, CellType.STRING);
cell.setCellStyle(cellStyleDate);
cell.setCellValue(new Date());
region = new CellRangeAddress(1, 1, 33, 37);
sheet.addMergedRegion(region);
cell = row.createCell(33, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(1, 1, 38, 43);
sheet.addMergedRegion(region);
cell = row.createCell(38, CellType.STRING);
cell.setCellStyle(cellStyleDate);
CreationHelper createHelper = workbook.getCreationHelper();
row = sheet.getRow(2);
region = new CellRangeAddress(2, 2, 0, 6);
sheet.addMergedRegion(region);
cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(getCellStyleBlue(workbook));
cell.setCellValue("");
region = new CellRangeAddress(2, 2, 7, 37);
sheet.addMergedRegion(region);
cell = row.createCell(7, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell.setCellValue(table.getRemarks());
region = new CellRangeAddress(2, 2, 38, 43);
sheet.addMergedRegion(region);
Hyperlink link = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
link.setAddress("#!A1");
cell = row.createCell(38, CellType.STRING);
cell.setCellStyle(getLinkStyle(workbook));
cell.setHyperlink(link);
cell.setCellValue("");
row = sheet.getRow(3);
region = new CellRangeAddress(3, 3, 0, 43);
sheet.addMergedRegion(region);
CellStyle sellStyleTitle = getCellStyleBlue(workbook);
sellStyleTitle.setAlignment(HorizontalAlignment.CENTER);
row = sheet.getRow(4);
region = new CellRangeAddress(4, 4, 0, 1);
sheet.addMergedRegion(region);
cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 2, 7);
sheet.addMergedRegion(region);
cell = row.createCell(2, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 8, 12);
sheet.addMergedRegion(region);
cell = row.createCell(8, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 13, 17);
sheet.addMergedRegion(region);
cell = row.createCell(13, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 18, 20);
sheet.addMergedRegion(region);
cell = row.createCell(18, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 21, 22);
sheet.addMergedRegion(region);
cell = row.createCell(21, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 23, 24);
sheet.addMergedRegion(region);
cell = row.createCell(23, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 25, 27);
sheet.addMergedRegion(region);
cell = row.createCell(25, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 28, 29);
sheet.addMergedRegion(region);
cell = row.createCell(28, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
region = new CellRangeAddress(4, 4, 30, 43);
sheet.addMergedRegion(region);
cell = row.createCell(30, CellType.STRING);
cell.setCellStyle(sellStyleTitle);
cell.setCellValue("");
CellStyle cellStyleCenter = getCellStyle(workbook);
cellStyleCenter.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < table.getCols().size(); i++) {
Column column = table.getCols().get(i);
int rowNum = i + 5;
row = sheet.getRow(rowNum);
region = new CellRangeAddress(rowNum, rowNum, 0, 1);
sheet.addMergedRegion(region);
cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(cellStyleCenter);
cell.setCellValue(column.getSerial());
region = new CellRangeAddress(rowNum, rowNum, 2, 7);
sheet.addMergedRegion(region);
cell = row.createCell(2, CellType.STRING);
cell.setCellStyle(cellStyle);
cell.setCellValue(column.getRemarks());
region = new CellRangeAddress(rowNum, rowNum, 8, 12);
sheet.addMergedRegion(region);
cell = row.createCell(8, CellType.STRING);
cell.setCellStyle(cellStyle);
cell.setCellValue(column.getColumnName());
region = new CellRangeAddress(rowNum, rowNum, 13, 17);
sheet.addMergedRegion(region);
cell = row.createCell(13, CellType.STRING);
cell.setCellStyle(cellStyleCenter);
cell.setCellValue(column.getSqlType().toLowerCase());
region = new CellRangeAddress(rowNum, rowNum, 18, 20);
sheet.addMergedRegion(region);
cell = row.createCell(18, CellType.STRING);
cell.setCellStyle(cellStyle);
cell.setCellValue(column.getLength());
region = new CellRangeAddress(rowNum, rowNum, 21, 22);
sheet.addMergedRegion(region);
cell = row.createCell(21, CellType.STRING);
cell.setCellStyle(cellStyleCenter);
cell.setCellValue("NO".equals(column.getIsNotNull()) ? "" : null);
region = new CellRangeAddress(rowNum, rowNum, 23, 24);
sheet.addMergedRegion(region);
cell = row.createCell(23, CellType.STRING);
cell.setCellStyle(cellStyleCenter);
for (Column columnKey : table.getPrimaryKey()) {
if (columnKey.getColumnName().equals(column.getColumnName())) {
cell.setCellValue("");
break;
}
}
region = new CellRangeAddress(rowNum, rowNum, 25, 27);
sheet.addMergedRegion(region);
cell = row.createCell(25, CellType.STRING);
cell.setCellStyle(cellStyleCenter);
for (Column columnKey : table.getPrimaryKey()) {
if (columnKey.getColumnName().equals(column.getColumnName())) {
cell.setCellValue(columnKey.getPrimaryKeyOrder());
break;
}
}
region = new CellRangeAddress(rowNum, rowNum, 28, 29);
sheet.addMergedRegion(region);
cell = row.createCell(28, CellType.STRING);
cell.setCellStyle(cellStyleCenter);
for (Column columnExp : table.getExportedKey()) {
if (columnExp.getColumnName().equals(column.getColumnName())) {
cell.setCellValue("");
break;
}
}
region = new CellRangeAddress(rowNum, rowNum, 30, 43);
sheet.addMergedRegion(region);
cell = row.createCell(30, CellType.STRING);
cell.setCellStyle(cellStyle);
cell.setCellValue(column.getRemarks());
}
}
/**
* Sheet
*
* @param workbook
* @param tables
* @throws Exception
* @author
*/
public static void makerListSheet(Workbook workbook, List<Table> tables) throws Exception {
// Sheet
Sheet sheet = workbook.createSheet("");
CellStyle cellStyleDate = getCellStyle(workbook);
DataFormat format = workbook.createDataFormat();
cellStyleDate.setDataFormat(format.getFormat("yyyy-mm-dd"));
cellStyleDate.setAlignment(HorizontalAlignment.CENTER);
CreationHelper createHelper = workbook.getCreationHelper();
for (int i = 0; i < tables.size(); i++) {
Table table = tables.get(i);
Row row = sheet.createRow(i + 2);
row.setHeightInPoints(15);
Cell cell = row.createCell(0, CellType.STRING);
cell.setCellValue(i + 1);
cell.setCellStyle(getCellStyle(workbook));
cell = row.createCell(1, CellType.STRING);
cell.setCellStyle(getLinkStyle(workbook));
cell.setCellValue(table.getRemarks());
Hyperlink link = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
link.setAddress("#" + table.getTableName() + "!A1");
cell.setHyperlink(link);
cell = row.createCell(2, CellType.STRING);
cell.setCellStyle(getLinkStyle(workbook));
cell.setCellValue(table.getTableName());
link = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
link.setAddress("#" + table.getTableName() + "!A1");
cell.setHyperlink(link);
cell = row.createCell(3, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell.setCellValue(table.getRemarks());
cell = row.createCell(4, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell.setCellValue("");
cell = row.createCell(5, CellType.STRING);
cell.setCellStyle(cellStyleDate);
cell.setCellValue(new Date());
cell = row.createCell(6, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
cell = row.createCell(7, CellType.STRING);
cell.setCellStyle(cellStyleDate);
}
Row row = sheet.createRow(0);
row.setHeightInPoints(25);
Font font = getFont(workbook, 12);
font.setBold(true);
CellStyle cellStyle = getCellStyle(workbook);
cellStyle.setFont(font);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
Cell cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(cellStyle);
cell.setCellValue("");
CellStyle cellStyleBlue = getCellStyleBlue(workbook);
cellStyleBlue.setAlignment(HorizontalAlignment.CENTER);
row = sheet.createRow(1);
row.setHeightInPoints(30);
cell = row.createCell(0);
cell.setCellType(CellType.STRING);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("No.");
cell = row.createCell(1);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(2);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(3);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(4);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(5);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(6);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(7);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 7);
sheet.addMergedRegion(region);
sheet.createFreezePane(8, 2);
sheet.setColumnWidth(0, 1000);
sheet.setColumnWidth(1, 6500);
sheet.setColumnWidth(2, 6500);
sheet.setColumnWidth(3, 10000);
sheet.setColumnWidth(4, 2500);
sheet.setColumnWidth(5, 2500);
sheet.setColumnWidth(6, 2500);
sheet.setColumnWidth(7, 2500);
}
/**
* Sheet
*
* @param workbook
* @throws Exception
* @author
*/
public static void makerHisSheet(Workbook workbook) throws Exception {
// Sheet
Sheet sheet = workbook.createSheet("");
CellStyle cellStyleDate = getCellStyle(workbook);
DataFormat format = workbook.createDataFormat();
cellStyleDate.setDataFormat(format.getFormat("yyyy-mm-dd"));
cellStyleDate.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < 33; i++) {
Row row = sheet.createRow(i);
row.setHeightInPoints(15);
for (int j = 0; j < 6; j++) {
Cell cell = row.createCell(j, CellType.STRING);
cell.setCellStyle(getCellStyle(workbook));
if (j == 0) {
cell.setCellStyle(cellStyleDate);
}
}
}
Row row = sheet.createRow(0);
row.setHeightInPoints(25);
Font font = getFont(workbook, 12);
font.setBold(true);
CellStyle cellStyleBold = getCellStyle(workbook);
cellStyleBold.setFont(font);
cellStyleBold.setAlignment(HorizontalAlignment.CENTER);
Cell cell = row.createCell(0, CellType.STRING);
cell.setCellStyle(cellStyleBold);
cell.setCellValue("");
CellStyle cellStyleBlue = getCellStyleBlue(workbook);
cellStyleBlue.setAlignment(HorizontalAlignment.CENTER);
row = sheet.createRow(1);
row.setHeightInPoints(30);
cell = row.createCell(0);
cell.setCellType(CellType.STRING);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(1);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(2);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(3);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(4);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
cell = row.createCell(5);
cell.setCellStyle(cellStyleBlue);
cell.setCellValue("");
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 5);
sheet.addMergedRegion(region);
sheet.createFreezePane(6, 2);
sheet.setColumnWidth(0, 3500);
sheet.setColumnWidth(1, 5500);
sheet.setColumnWidth(2, 5500);
sheet.setColumnWidth(3, 10000);
sheet.setColumnWidth(4, 7000);
sheet.setColumnWidth(5, 2000);
}
/**
*
*
* @param workbook
* @return
* @author
*/
private static CellStyle getCellStyle(Workbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(getFont(workbook, null));
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return cellStyle;
}
/**
*
*
* @param workbook
* @return
* @author
*/
private static CellStyle getCellStyleBlue(Workbook workbook) {
CellStyle cellStyle = getCellStyle(workbook);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
return cellStyle;
}
private static CellStyle getLinkStyle(Workbook workbook) {
Font font = getFont(workbook, null);
font.setColor(IndexedColors.BLUE.getIndex());
CellStyle cellStyle = getCellStyle(workbook);
cellStyle.setFont(font);
return cellStyle;
}
/**
*
*
* @param workbook
* @param fontSize
* @return
* @author
*/
private static Font getFont(Workbook workbook, Integer fontSize) {
if (fontSize == null) {
fontSize = 10;
}
Font font = workbook.createFont();
font.setFontName("");
font.setFontHeightInPoints(fontSize.shortValue());
return font;
}
}
|
package com.akiban.server.store.statistics;
import static com.akiban.server.store.statistics.IndexStatistics.*;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.Table;
import com.akiban.ais.model.TableName;
import com.akiban.server.PersistitKeyValueSource;
import com.akiban.server.PersistitKeyValueTarget;
import com.akiban.server.types.FromObjectValueSource;
import com.akiban.server.types.ToObjectValueTarget;
import com.akiban.server.types.conversion.Converters;
import com.persistit.Key;
import com.persistit.Persistit;
import com.akiban.server.error.AkibanInternalException;
import com.akiban.server.error.NoSuchIndexException;
import com.akiban.server.error.NoSuchTableException;
import org.yaml.snakeyaml.Yaml;
import java.util.*;
import java.io.*;
/** Load / dump index stats from / to Yaml files.
*/
public class IndexStatisticsYamlLoader
{
private AkibanInformationSchema ais;
private String defaultSchema;
private final Key key = new Key((Persistit)null);
private final PersistitKeyValueSource keySource = new PersistitKeyValueSource();
private final PersistitKeyValueTarget keyTarget = new PersistitKeyValueTarget();
public IndexStatisticsYamlLoader(AkibanInformationSchema ais, String defaultSchema) {
this.ais = ais;
this.defaultSchema = defaultSchema;
}
public Map<Index,IndexStatistics> load(File file) throws IOException {
Map<Index,IndexStatistics> result = new HashMap<Index,IndexStatistics>();
Yaml yaml = new Yaml();
FileInputStream istr = new FileInputStream(file);
try {
for (Object doc : yaml.loadAll(istr)) {
IndexStatistics indexStatistics = parseStatistics(doc);
result.put(indexStatistics.getIndex(), indexStatistics);
}
}
finally {
istr.close();
}
return result;
}
protected IndexStatistics parseStatistics(Object obj) {
if (!(obj instanceof Map))
throw new AkibanInternalException("Document not in expected format");
Map<?,?> map = (Map<?,?>)obj;
TableName tableName = TableName.create(defaultSchema, (String)map.get("Table"));
Table table = ais.getTable(tableName);
if (table == null)
throw new NoSuchTableException(tableName);
String indexName = (String)map.get("Index");
Index index = table.getIndex(indexName);
if (index == null) {
index = table.getGroup().getIndex(indexName);
if (index == null)
throw new NoSuchIndexException(indexName);
}
IndexStatistics result = new IndexStatistics(index);
for (Object e : (Iterable)map.get("Statistics")) {
Map<?,?> em = (Map<?,?>)e;
int columnCount = (Integer)em.get("Columns");
Histogram h = parseHistogram(em.get("Histogram"), index, columnCount);
result.addHistogram(h);
}
return result;
}
protected Histogram parseHistogram(Object obj, Index index, int columnCount) {
if (!(obj instanceof Iterable))
throw new AkibanInternalException("Histogram not in expected format");
List<HistogramEntry> entries = new ArrayList<HistogramEntry>();
for (Object eobj : (Iterable)obj) {
if (!(eobj instanceof Map))
throw new AkibanInternalException("Entry not in expected format");
Map<?,?> emap = (Map<?,?>)eobj;
Key key = encodeKey(index, columnCount, (List<?>)emap.get("key"));
String keyString = key.toString();
byte[] keyBytes = new byte[key.getEncodedSize()];
System.arraycopy(key.getEncodedBytes(), 0, keyBytes, 0, keyBytes.length);
int eqCount = (Integer)emap.get("eq");
int ltCount = (Integer)emap.get("lt");
int distinctCount = (Integer)emap.get("distinct");
entries.add(new HistogramEntry(keyString, keyBytes,
eqCount, ltCount, distinctCount));
}
return new Histogram(index, columnCount, entries);
}
protected Key encodeKey(Index index, int columnCount, List<?> values) {
if (values.size() != columnCount)
throw new AkibanInternalException("Key values do not match column count");
FromObjectValueSource valueSource = new FromObjectValueSource();
key.clear();
keyTarget.attach(key);
for (int i = 0; i < columnCount; i++) {
keyTarget.expectingType(index.getColumns().get(i).getColumn().getType().akType());
valueSource.setReflectively(values.get(i));
Converters.convert(valueSource, keyTarget);
}
return key;
}
public void dump(Collection<IndexStatistics> stats, File file) throws IOException {
List<Object> docs = new ArrayList<Object>(stats.size());
for (IndexStatistics stat : stats) {
docs.add(buildStatistics(stat));
}
Yaml yaml = new Yaml();
FileWriter ostr = new FileWriter(file);
try {
yaml.dumpAll(docs.iterator(), ostr);
}
finally {
ostr.close();
}
}
protected Object buildStatistics(IndexStatistics indexStatistics) {
Map map = new TreeMap();
Index index = indexStatistics.getIndex();
map.put("Index", index.getIndexName().getName());
map.put("Table", index.getIndexName().getTableName());
List<Object> stats = new ArrayList<Object>();
for (int i = 0; i < index.getColumns().size(); i++) {
Histogram histogram = indexStatistics.getHistogram(i + 1);
if (histogram == null) continue;
stats.add(buildHistogram(histogram));
}
map.put("Statistics", stats);
return map;
}
protected Object buildHistogram(Histogram histogram) {
Map map = new TreeMap();
Index index = histogram.getIndex();
int columnCount = histogram.getColumnCount();
map.put("Columns", columnCount);
List<Object> entries = new ArrayList<Object>();
for (HistogramEntry entry : histogram.getEntries()) {
Map emap = new TreeMap();
emap.put("eq", entry.getEqualCount());
emap.put("lt", entry.getLessCount());
emap.put("distinct", entry.getDistinctCount());
emap.put("key", decodeKey(index, columnCount, entry.getKeyBytes()));
entries.add(emap);
}
map.put("Histogram", entries);
return map;
}
protected List<Object> decodeKey(Index index, int columnCount, byte[] bytes) {
key.setEncodedSize(bytes.length);
System.arraycopy(bytes, 0, key.getEncodedBytes(), 0, bytes.length);
ToObjectValueTarget valueTarget = new ToObjectValueTarget();
List<Object> result = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
keySource.attach(key, index.getColumns().get(i));
// TODO: Special handling for date/time types to make them
// more legible than internal long representation?
result.add(valueTarget.convertFromSource(keySource));
}
return result;
}
}
|
package com.alwaysallthetime.messagebeast.manager;
import android.content.Intent;
import android.util.Log;
import com.alwaysallthetime.adnlib.AppDotNetClient;
import com.alwaysallthetime.adnlib.data.Channel;
import com.alwaysallthetime.messagebeast.ADNApplication;
import com.alwaysallthetime.messagebeast.PrivateChannelUtility;
import com.alwaysallthetime.messagebeast.filter.MessageFilter;
import com.alwaysallthetime.messagebeast.model.ChannelRefreshResult;
import com.alwaysallthetime.messagebeast.model.ChannelRefreshResultSet;
import com.alwaysallthetime.messagebeast.model.ChannelSpec;
import com.alwaysallthetime.messagebeast.model.ChannelSpecSet;
import com.alwaysallthetime.messagebeast.model.FullSyncState;
import com.alwaysallthetime.messagebeast.model.MessagePlus;
import com.alwaysallthetime.messagebeast.model.TargetWithActionChannelsSpecSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChannelSyncManager {
public static final String INTENT_ACTION_CHANNELS_INITIALIZED = "com.alwaysallthetime.messagebeast.manager.ChannelSyncManager.intent.channelsInitialized";
private static final String TAG = "ADNLibUtils_ChannelSyncManager";
private MessageManager mMessageManager;
private ActionMessageManager mActionMessageManager;
//the constructor you use will determine which of the following fields are used:
//either these
private TargetWithActionChannelsSpecSet mTargetWithActionChannelsSpecSet;
private Channel mTargetChannel;
private Map<String, Channel> mActionChannels; //indexed by action type
//these
private ChannelSpecSet mChannelSpecSet;
private Map<String, Channel> mChannels; //indexed by channel id
private interface ChannelInitializedHandler {
public void onChannelInitialized(Channel channel);
public void onException();
}
public interface ChannelsInitializedHandler {
public void onChannelsInitialized();
public void onException();
}
public static abstract class ChannelSyncStatusHandler {
public abstract void onSyncComplete();
public abstract void onSyncStarted();
public abstract void onSyncException(Exception exception);
//override this in the case where you pass false value for
//automaticallyResumeSyncIfPreviouslyStarted to checkFullSyncStatus()
public void onSyncIncomplete() {
}
}
public static interface ChannelRefreshHandler {
public void onComplete(ChannelRefreshResultSet resultSet);
}
/**
* Create a ChannelSyncManager for a set of Channels, an AppDotNetClient
* and a MessageManagerConfiguration. This constructor is convenient for use cases where you don't
* plan on creating a MessageManager for use outside of the ChannelSyncManager.
*
* Note that this constructor is not for use with Action Channels.
*
* @param appDotNetClient The AppDotNetClient used to make requests. This will be used to construct
* the MessageManager.
* @param configuration The MessageManagerConfiguration to be used to construct the MessageManager.
* @param channelSpecSet The ChannelSpecSet describing the Channels to be used with ChannelSyncManager
*
* @see com.alwaysallthetime.messagebeast.manager.ChannelSyncManager#ChannelSyncManager(ActionMessageManager, com.alwaysallthetime.messagebeast.model.TargetWithActionChannelsSpecSet)
*/
public ChannelSyncManager(AppDotNetClient appDotNetClient, MessageManager.MessageManagerConfiguration configuration, ChannelSpecSet channelSpecSet) {
mMessageManager = new MessageManager(appDotNetClient, configuration);
mChannelSpecSet = channelSpecSet;
}
/**
* Create a ChannelSyncManager for a set of Channels.
*
* Note that this constructor is not for use with Action Channels.
*
* @param messageManager An instance of MessageManager to be used for syncing the Channels.
* @param channelSpecSet The ChannelSpecSet describing the Channels to be used with ChannelSyncManager
*
* @see com.alwaysallthetime.messagebeast.manager.ChannelSyncManager#ChannelSyncManager(ActionMessageManager, com.alwaysallthetime.messagebeast.model.TargetWithActionChannelsSpecSet)
*/
public ChannelSyncManager(MessageManager messageManager, ChannelSpecSet channelSpecSet) {
mMessageManager = messageManager;
mChannelSpecSet = channelSpecSet;
}
/**
* Create a ChannelSyncManager to be used with a Channel and a set of Action Channels. This
* constructor creates a MessageManager and ActionMessageManager; it is convenient for use
* cases that don't require the use of these Managers outside of the ChannelSyncManager.
*
* @param appDotNetClient The AppDotNetClient used to make requests. This will be used to construct
* the MessageManager.
* @param configuration The MessageManagerConfiguration to be used to construct the MessageManager.
* @param channelSpecSet The TargetWithActionChannelsSpecSet describing the Channels to be used with ChannelSyncManager
*
* @see com.alwaysallthetime.messagebeast.manager.ChannelSyncManager#ChannelSyncManager(ActionMessageManager, com.alwaysallthetime.messagebeast.model.TargetWithActionChannelsSpecSet)
*/
public ChannelSyncManager(AppDotNetClient appDotNetClient, MessageManager.MessageManagerConfiguration configuration, TargetWithActionChannelsSpecSet channelSpecSet) {
mMessageManager = new MessageManager(appDotNetClient, configuration);
mActionMessageManager = ActionMessageManager.getInstance(mMessageManager);
mTargetWithActionChannelsSpecSet = channelSpecSet;
}
/**
* Create a ChannelSyncManager to be used with a Channel and a set of Action Channels.
*
* @param actionMessageManager An instance of ActionMessageManager.
* @param channelSpecSet The TargetWithActionChannelsSpecSet describing the Channels to be used with ChannelSyncManager
*/
public ChannelSyncManager(ActionMessageManager actionMessageManager, TargetWithActionChannelsSpecSet channelSpecSet) {
mActionMessageManager = actionMessageManager;
mMessageManager = mActionMessageManager.getMessageManager();
mTargetWithActionChannelsSpecSet = channelSpecSet;
}
/**
* Initialize the Channels described by the spec(s) passed when constructing this class.
*
* This method must be called before any operations can be performed with a ChannelSyncManager.
*
* @param initializedHandler a ChannelsInitializedHandler
*/
public void initChannels(final ChannelsInitializedHandler initializedHandler) {
if(mTargetWithActionChannelsSpecSet != null) {
mActionChannels = new HashMap<String, Channel>(mTargetWithActionChannelsSpecSet.getNumActionChannels());
initChannel(mTargetWithActionChannelsSpecSet.getTargetChannelSpec(), new ChannelInitializedHandler() {
@Override
public void onChannelInitialized(Channel channel) {
mTargetChannel = channel;
initActionChannels(0, initializedHandler);
}
@Override
public void onException() {
initializedHandler.onException();
}
});
} else {
//just multiple "regular" channels
mChannels = new HashMap<String, Channel>(mChannelSpecSet.getNumChannels());
initChannels(0, initializedHandler);
}
}
/**
* Check the FullSyncStatus for the Channels associated with this manager and begin syncing
* if all Channels do not already have a FullSyncState of COMPLETE.
*
* The MessageManager.retrieveAndPersistAllMessages() method is used to perform the sync.
*
* @param handler ChannelSyncStatusHandler
*
* @see com.alwaysallthetime.messagebeast.model.FullSyncState
* @see com.alwaysallthetime.messagebeast.manager.ChannelSyncManager#checkFullSyncStatus(boolean, com.alwaysallthetime.messagebeast.manager.ChannelSyncManager.ChannelSyncStatusHandler)
*/
public void checkFullSyncStatus(ChannelSyncStatusHandler handler) {
checkFullSyncStatus(true, handler);
}
/**
* Check the FullSyncStatus for the Channels associated with this manager.
*
* If the parameter automaticallyResumeSyncIfPreviouslyStarted is false, then you should override the
* ChannelSyncStatusHandler.onSyncIncomplete() method to handle a FullSyncState of STARTED
* (e.g. show a dialog "would you like to resume syncing these channels?").
*
* The MessageManager.retrieveAndPersistAllMessages() method is used to perform the sync.
*
* @param handler ChannelSyncStatusHandler
*
* @see com.alwaysallthetime.messagebeast.model.FullSyncState
* @see com.alwaysallthetime.messagebeast.manager.ChannelSyncManager#checkFullSyncStatus(boolean, com.alwaysallthetime.messagebeast.manager.ChannelSyncManager.ChannelSyncStatusHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#retrieveAndPersistAllMessages(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageManagerSyncResponseHandler)
*/
public void checkFullSyncStatus(boolean automaticallyResumeSyncIfPreviouslyStarted, ChannelSyncStatusHandler handler) {
FullSyncState state = mMessageManager.getFullSyncState(getChannelsArray());
if(state == FullSyncState.COMPLETE) {
handler.onSyncComplete();
} else if(state == FullSyncState.NOT_STARTED) {
startFullSync(handler);
handler.onSyncStarted();
} else {
if(automaticallyResumeSyncIfPreviouslyStarted) {
startFullSync(handler);
handler.onSyncStarted();
} else {
handler.onSyncIncomplete();
}
}
}
/**
* Start a full sync on the channels associated with this manager.
*
* The MessageManager.retrieveAndPersistAllMessages() method is used to perform the sync.
*
* @param handler ChannelSyncStatusHandler
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#retrieveAndPersistAllMessages(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageManagerSyncResponseHandler)
*/
public void startFullSync(final ChannelSyncStatusHandler handler) {
mMessageManager.retrieveAndPersistAllMessages(getChannelsArray(), new MessageManager.MessageManagerMultiChannelSyncResponseHandler() {
@Override
public void onSuccess() {
handler.onSyncComplete();
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
handler.onSyncException(exception);
}
});
}
/**
* Retrieve the newest messages in all channels associated with this manager.
*
* @param refreshHandler ChannelRefreshHandler the handler that will be passed
* a ChannelRefreshResultSet upon completion of this operation.
*/
public void retrieveNewestMessages(final ChannelRefreshHandler refreshHandler) {
if(mTargetWithActionChannelsSpecSet != null) {
final ChannelRefreshResultSet refreshResultSet = new ChannelRefreshResultSet();
retrieveNewestActionChannelMessages(0, refreshResultSet, new ChannelRefreshHandler() {
@Override
public void onComplete(ChannelRefreshResultSet result) {
MessageFilter messageFilter = mTargetWithActionChannelsSpecSet.getTargetChannelSpec().getMessageFilter();
boolean canRetrieve = mMessageManager.retrieveNewestMessages(mTargetChannel.getId(), messageFilter, new MessageManager.MessageManagerResponseHandler() {
@Override
public void onSuccess(List<MessagePlus> responseData) {
ChannelRefreshResult refreshResult = new ChannelRefreshResult(mTargetChannel, responseData, getExcludedResults());
refreshResultSet.addRefreshResult(refreshResult);
if(refreshHandler != null) {
refreshHandler.onComplete(refreshResultSet);
}
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
ChannelRefreshResult refreshResult = new ChannelRefreshResult(mTargetChannel, exception);
refreshResultSet.addRefreshResult(refreshResult);
if(refreshHandler != null) {
refreshHandler.onComplete(refreshResultSet);
}
}
});
if(!canRetrieve) {
refreshResultSet.addRefreshResult(new ChannelRefreshResult(mTargetChannel));
if(refreshHandler != null) {
refreshHandler.onComplete(refreshResultSet);
}
}
}
});
} else {
retrieveNewestMessagesInChannelsList(0, new ChannelRefreshResultSet(), refreshHandler);
}
}
private void retrieveNewestMessagesInChannelsList(final int index, final ChannelRefreshResultSet refreshResultSet, final ChannelRefreshHandler refreshHandler) {
if(index >= mChannelSpecSet.getNumChannels()) {
refreshHandler.onComplete(refreshResultSet);
} else {
final ChannelSpec spec = mChannelSpecSet.getChannelSpecAtIndex(index);
final Channel channel = mChannels.get(spec);
boolean canRetrieve = mMessageManager.retrieveNewestMessages(channel.getId(), spec.getMessageFilter(), new MessageManager.MessageManagerResponseHandler() {
@Override
public void onSuccess(List<MessagePlus> responseData) {
ChannelRefreshResult refreshResult = new ChannelRefreshResult(channel, responseData);
refreshResultSet.addRefreshResult(refreshResult);
retrieveNewestMessagesInChannelsList(index + 1, refreshResultSet, refreshHandler);
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
ChannelRefreshResult refreshResult = new ChannelRefreshResult(channel, exception);
refreshResultSet.addRefreshResult(refreshResult);
retrieveNewestMessagesInChannelsList(index + 1, refreshResultSet, refreshHandler);
}
});
if(!canRetrieve) {
refreshResultSet.addRefreshResult(new ChannelRefreshResult(channel));
retrieveNewestMessagesInChannelsList(index + 1, refreshResultSet, refreshHandler);
}
}
}
private void retrieveNewestActionChannelMessages(final int index, final ChannelRefreshResultSet refreshResultSet, final ChannelRefreshHandler refreshHandler) {
if(index >= mTargetWithActionChannelsSpecSet.getNumActionChannels()) {
refreshHandler.onComplete(refreshResultSet);
} else {
final Channel actionChannel = mActionChannels.get(mTargetWithActionChannelsSpecSet.getActionChannelActionTypeAtIndex(index));
boolean canRetrieve = mActionMessageManager.retrieveNewestMessages(actionChannel.getId(), new MessageManager.MessageManagerResponseHandler() {
@Override
public void onSuccess(List<MessagePlus> responseData) {
ChannelRefreshResult refreshResult = new ChannelRefreshResult(actionChannel, responseData);
refreshResultSet.addRefreshResult(refreshResult);
retrieveNewestActionChannelMessages(index + 1, refreshResultSet, refreshHandler);
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
ChannelRefreshResult refreshResult = new ChannelRefreshResult(actionChannel, exception);
refreshResultSet.addRefreshResult(refreshResult);
retrieveNewestActionChannelMessages(index + 1, refreshResultSet, refreshHandler);
}
});
if(!canRetrieve) {
refreshResultSet.addRefreshResult(new ChannelRefreshResult(actionChannel));
retrieveNewestActionChannelMessages(index + 1, refreshResultSet, refreshHandler);
}
}
}
/**
* Get the MessageManager used by this ChannelSyncManager.
*
* @return the MessageManager used by this ChannelSyncManager
*/
public MessageManager getMessageManager() {
return mMessageManager;
}
/**
* Get the ActionMessageManager used by this ChannelSyncManager. Will be null if this
* ChannelSyncManager was not constructed with a TargetWithActionChannelsSpecSet.
*
* @return the ActionMessageManager used by this ChannelSyncManager, or null if it does not
* use one.
*/
public ActionMessageManager getActionMessageManager() {
return mActionMessageManager;
}
/**
* Get the target Channel for this manager's Action Channels. This will be null if you did
* not construct this class with a TargetWithActionChannelsSpecSet. Note that you should be
* calling initChannels() before attempting to call this method.
*
* @return the target Channel for this manager's Action Channels, or null if none exists.
*/
public Channel getTargetChannel() {
return mTargetChannel;
}
/**
* Get an Action Channel initialized by this manager. This will be null if you did
* not construct this class with a TargetWithActionChannelsSpecSet. Note that you should be
* calling initChannels() before attempting to call this method.
*
* @param actionType the action_type value in the Action Channel's metadata Annotation.
* @return The Action Channel with the specified action type, or null if none exists.
*/
public Channel getActionChannel(String actionType) {
return mActionChannels.get(actionType);
}
/**
* Return a Map of Channels whose keys are Channel ids.
* This will be null if you constructed this manager with a TargetWithActionChannelsSpecSet.
* Note that you should be calling initChannels() before attempting to call this method.
*
* @return a Map of Channels whose keys are Channel ids, or null if none exists.
*
* @see ChannelSyncManager#getTargetChannel()
* @see ChannelSyncManager#getActionChannel(String)
*/
public HashMap<String, Channel> getChannels() {
return new HashMap<String, Channel>(mChannels);
}
/**
* @return true if this manager's Channels have been initialized, false otherwise.
*/
public boolean channelsInitialized() {
if(mTargetWithActionChannelsSpecSet != null) {
return mActionChannels != null && mTargetChannel != null &&
mTargetWithActionChannelsSpecSet.getNumActionChannels() == mActionChannels.size();
} else {
return mChannels != null && mChannelSpecSet.getNumChannels() == mChannels.size();
}
}
private void initChannels(final int index, final ChannelsInitializedHandler initializedHandler) {
if(index >= mChannelSpecSet.getNumChannels()) {
initializedHandler.onChannelsInitialized();
ADNApplication.getContext().sendBroadcast(new Intent(INTENT_ACTION_CHANNELS_INITIALIZED));
} else {
ChannelSpec spec = mChannelSpecSet.getChannelSpecAtIndex(index);
initChannel(spec, new ChannelInitializedHandler() {
@Override
public void onChannelInitialized(Channel channel) {
mChannels.put(channel.getId(), channel);
initChannels(index+1, initializedHandler);
}
@Override
public void onException() {
initializedHandler.onException();
}
});
}
}
private void initActionChannels(final int index, final ChannelsInitializedHandler initializedHandler) {
if(index >= mTargetWithActionChannelsSpecSet.getNumActionChannels()) {
initializedHandler.onChannelsInitialized();
ADNApplication.getContext().sendBroadcast(new Intent(INTENT_ACTION_CHANNELS_INITIALIZED));
} else {
final String actionType = mTargetWithActionChannelsSpecSet.getActionChannelActionTypeAtIndex(index);
initActionChannel(actionType, mTargetChannel, new Runnable() {
@Override
public void run() {
if(mActionChannels.get(actionType) != null) {
initActionChannels(index + 1, initializedHandler);
} else {
initializedHandler.onException();
}
}
});
}
}
private void initChannel(final ChannelSpec channelSpec, final ChannelInitializedHandler channelInitializedHandler) {
PrivateChannelUtility.getOrCreateChannel(mMessageManager.getClient(), channelSpec.getType(), new PrivateChannelUtility.PrivateChannelGetOrCreateHandler() {
@Override
public void onResponse(Channel channel, boolean createdNewChannel) {
mMessageManager.setParameters(channel.getId(), channelSpec.getQueryParameters());
channelInitializedHandler.onChannelInitialized(channel);
}
@Override
public void onError(Exception error) {
Log.e(TAG, error.getMessage(), error);
channelInitializedHandler.onException();
}
});
}
private void initActionChannel(final String actionType, Channel targetChannel, final Runnable completionRunnable) {
mActionMessageManager.initActionChannel(actionType, targetChannel, new ActionMessageManager.ActionChannelInitializedHandler() {
@Override
public void onInitialized(Channel channel) {
mActionChannels.put(actionType, channel);
completionRunnable.run();
}
@Override
public void onException(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
completionRunnable.run();
}
});
}
private Channel[] getChannelsArray() {
Channel[] channels = new Channel[(mTargetChannel != null ? 1 : 0) + mActionChannels.size()];
int i = 0;
if(mTargetChannel != null) {
channels[0] = mTargetChannel;
i++;
}
for(Channel c : mActionChannels.values()) {
channels[i] = c;
i++;
}
return channels;
}
}
|
package com.asolutions.scmsshd.commands.git;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
public class GitSCMRepositoryProvider {
protected final Logger log = LoggerFactory.getLogger(getClass());
private static HashMap<String, Repository> repositoryCache = new HashMap<String, Repository>();
public Repository provide(File base, String argument) throws IOException {
synchronized (repositoryCache) {
if (repositoryCache.containsKey(argument)){
log.info("Using Cached Repo " + argument);
return repositoryCache.get(argument);
}
File pathToRepo = new File(base, argument);
log.info("Creating Repo: " + pathToRepo.getAbsolutePath());
Repository repo = new Repository(pathToRepo);
log.info("...created");
repositoryCache.put(argument, repo);
return repo;
}
}
}
|
package com.darcstarsolutions.games.common.beans;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
public class GameObjectWithRules<G extends GameObject> extends GameObject
implements RuleContainer<G> {
private static final long serialVersionUID = 1L;
@JsonIgnore
private RuleContainer<G> ruleContainer;
protected GameObjectWithRules() {
this("", "");
}
@SuppressWarnings("unchecked")
protected GameObjectWithRules(String name, String description) {
super(name, description);
setRuleContainer(new StandardRuleContainer<G>((G) this));
}
protected GameObjectWithRules(String name, String description, RuleContainer<G> ruleContainer) {
super(name, description);
setRuleContainer(ruleContainer);
}
public RuleContainer<G> getRuleContainer() {
return ruleContainer;
}
public void setRuleContainer(RuleContainer<G> ruleContainer) {
this.ruleContainer = ruleContainer;
}
@Override
@JsonGetter
public List<Rule<G>> getRules() {
return ruleContainer.getRules();
}
@Override
public void setRules(List<Rule<G>> rules) {
ruleContainer.setRules(rules);
}
@Override
public <T extends Rule<G>> T getRule(int location) {
return ruleContainer.getRule(location);
}
@Override
public <T extends Rule<G>> T setRule(int location, T rule) {
return ruleContainer.setRule(location, rule);
}
@Override
public <T extends Rule<G>> T addRule(T rule) {
return ruleContainer.addRule(rule);
}
@Override
public <T extends Rule<G>> T removeRule(int location) {
return ruleContainer.removeRule(location);
}
@Override
public <T extends Rule<G>> boolean removeRule(T rule) {
return ruleContainer.removeRule(rule);
}
@Override
public void applyRule(int location) {
ruleContainer.applyRule(location);
}
@Override
public <T extends Rule<G>> void applyRule(T rule) {
ruleContainer.applyRule(rule);
}
@Override
public <T extends Rule<G>> T addAndApplyRule(T rule) {
return ruleContainer.addAndApplyRule(rule);
}
@Override
public void applyAllRules() {
ruleContainer.applyAllRules();
}
@Override
public String toString() {
return "GameObjectWithRules{" + "id=" + getId() + ", name='" + getName() + '\''
+ ", description='" + getDescription() + '\'' +
", rules=" + getRules() + '}';
}
}
|
package com.elmakers.mine.bukkit.plugins.magic.spell;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.plugins.magic.Spell;
import com.elmakers.mine.bukkit.plugins.magic.SpellResult;
import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode;
import com.elmakers.mine.bukkit.utility.NMSUtils;
public class ProjectileSpell extends Spell
{
private int defaultSize = 1;
private Random random = new Random();
@Override
public SpellResult onCast(ConfigurationNode parameters)
{
int count = parameters.getInt("count", 1);
int size = parameters.getInt("size", defaultSize);
int radius = parameters.getInt("radius", 0);
double damage = parameters.getDouble("damage", 0);
float speed = (float)parameters.getDouble("speed", 0.6f);
float spread = (float)parameters.getDouble("spread", 12);
Collection<PotionEffect> effects = null;
if (radius > 0) {
effects = getPotionEffects(parameters);
radius = (int)(mage.getRadiusMultiplier() * radius);
}
// Modify with wand power
// Turned some of this off for now
// count *= mage.getRadiusMultiplier();
size = (int)(mage.getRadiusMultiplier() * size);
float damageMultiplier = mage.getDamageMultiplier();
// speed *= damageMultiplier;
damage *= damageMultiplier;
spread /= damageMultiplier;
boolean useFire = parameters.getBoolean("fire", true);
int tickIncrease = parameters.getInteger("tick_increase", 1180);
String projectileTypeName = parameters.getString("projectile", "Arrow");
final Class<?> projectileClass = NMSUtils.getBukkitClass("net.minecraft.server.EntityProjectile");
final Class<?> fireballClass = NMSUtils.getBukkitClass("net.minecraft.server.EntityFireball");
final Class<?> arrowClass = NMSUtils.getBukkitClass("net.minecraft.server.EntityArrow");
final Class<?> worldClass = NMSUtils.getBukkitClass("net.minecraft.server.World");
final Class<?> entityClass = NMSUtils.getBukkitClass("net.minecraft.server.Entity");
final Class<?> craftArrowClass = NMSUtils.getBukkitClass("org.bukkit.craftbukkit.entity.CraftArrow");
if (projectileClass == null || worldClass == null || fireballClass == null || arrowClass == null || craftArrowClass == null) {
controller.getLogger().warning("Can't find NMS classess");
return SpellResult.FAIL;
}
Class<?> projectileType = NMSUtils.getBukkitClass("net.minecraft.server.Entity" + projectileTypeName);
if (projectileType == null
|| (!arrowClass.isAssignableFrom(projectileType)
&& !projectileClass.isAssignableFrom(projectileType)
&& !fireballClass.isAssignableFrom(projectileType))) {
controller.getLogger().warning("Bad projectile class: " + projectileTypeName);
return SpellResult.FAIL;
}
// Prevent explosive projectiles in no-build zones
if (fireballClass.isAssignableFrom(projectileType) && !hasBuildPermission(getLocation().getBlock())) {
return SpellResult.INSUFFICIENT_PERMISSION;
}
Constructor<? extends Object> constructor = null;
Method shootMethod = null;
Method setPositionRotationMethod = null;
Field dirXField = null;
Field dirYField = null;
Field dirZField = null;
Method addEntityMethod = null;
try {
constructor = projectileType.getConstructor(worldClass);
if (fireballClass.isAssignableFrom(projectileType)) {
dirXField = projectileType.getField("dirX");
dirYField = projectileType.getField("dirY");
dirZField = projectileType.getField("dirZ");
}
if (projectileClass.isAssignableFrom(projectileType) || arrowClass.isAssignableFrom(projectileType)) {
shootMethod = projectileType.getMethod("shoot", Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE);
}
setPositionRotationMethod = projectileType.getMethod("setPositionRotation", Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE);
addEntityMethod = worldClass.getMethod("addEntity", entityClass);
} catch (Throwable ex) {
ex.printStackTrace();
return SpellResult.FAIL;
}
// Prepare parameters
Location location = getEyeLocation();
Vector direction = getDirection().normalize();
// Track projectiles to remove them after some time.
List<Projectile> projectiles = new ArrayList<Projectile>();
// Spawn projectiles
Object nmsWorld = NMSUtils.getHandle(location.getWorld());
Player player = getPlayer();
for (int i = 0; i < count; i++) {
try {
// Spawn a new projectile
Object nmsProjectile = null;
nmsProjectile = constructor.newInstance(nmsWorld);
if (nmsProjectile == null) {
throw new Exception("Failed to spawn projectile of class " + projectileTypeName);
}
// Set position and rotation, and potentially velocity (direction)
// Velocity must be set manually- EntityFireball.setDirection applies a crazy-wide gaussian distribution!
if (dirXField != null && dirYField != null && dirZField != null) {
// Taken from EntityArrow
double spreadWeight = Math.min(0.4f, spread * 0.007499999832361937D);
double dx = speed * (direction.getX() + (random.nextGaussian() * spreadWeight));
double dy = speed * (direction.getY() + (random.nextGaussian() * spreadWeight));
double dz = speed * (direction.getZ() + (random.nextGaussian() * spreadWeight));
dirXField.set(nmsProjectile, dx * 0.1D);
dirYField.set(nmsProjectile, dy * 0.1D);
dirZField.set(nmsProjectile, dz * 0.1D);
}
Vector modifiedLocation = location.toVector().clone();
if (i > 0 && fireballClass.isAssignableFrom(projectileType) && spread > 0) {
modifiedLocation.setX(modifiedLocation.getX() + direction.getX() + (random.nextGaussian() * spread / 5));
modifiedLocation.setY(modifiedLocation.getY() + direction.getY() + (random.nextGaussian() * spread / 5));
modifiedLocation.setZ(modifiedLocation.getZ() + direction.getZ() + (random.nextGaussian() * spread / 5));
}
setPositionRotationMethod.invoke(nmsProjectile, modifiedLocation.getX(), modifiedLocation.getY(), modifiedLocation.getZ(), location.getYaw(), location.getPitch());
if (shootMethod != null) {
shootMethod.invoke(nmsProjectile, direction.getX(), direction.getY(), direction.getZ(), speed, spread);
}
Entity entity = NMSUtils.getBukkitEntity(nmsProjectile);
if (entity == null || !(entity instanceof Projectile)) {
throw new Exception("Got invalid bukkit entity from projectile of class " + projectileTypeName);
}
Projectile projectile = (Projectile)entity;
if (player != null) {
projectile.setShooter(player);
}
projectiles.add(projectile);
addEntityMethod.invoke(nmsWorld, nmsProjectile);
if (projectile instanceof Fireball) {
Fireball fireball = (Fireball)projectile;
fireball.setIsIncendiary(useFire);
fireball.setYield(size);
}
if (projectile instanceof Arrow) {
Arrow arrow = (Arrow)projectile;
if (useFire) {
arrow.setFireTicks(300);
}
// Hackily make this an infinite arrow and set damage
try {
if (arrowClass == null || craftArrowClass == null) {
controller.getLogger().warning("Can not access NMS EntityArrow class");
} else {
Method getHandleMethod = arrow.getClass().getMethod("getHandle");
Object handle = getHandleMethod.invoke(arrow);
Field fromPlayerField = arrowClass.getField("fromPlayer");
fromPlayerField.setInt(handle, 2);
if (damage > 0) {
Field damageField = arrowClass.getDeclaredField("damage");
damageField.setAccessible(true);
damageField.set(handle, damage);
}
}
} catch (Throwable ex) {
ex.printStackTrace();
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
if (tickIncrease > 0 && projectiles.size() > 0 && arrowClass != null) {
scheduleProjectileCheck(projectiles, tickIncrease, effects, radius, arrowClass, craftArrowClass, 5);
}
return SpellResult.CAST;
}
protected void scheduleProjectileCheck(final Collection<Projectile> projectiles, final int tickIncrease,
final Collection<PotionEffect> effects, final int radius, final Class<?> arrowClass, final Class<?> craftArrowClass, final int retries) {
Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), new Runnable() {
public void run() {
checkProjectiles(projectiles, tickIncrease, effects, radius, arrowClass, craftArrowClass, retries);
}
}, 40);
}
protected void checkProjectiles(final Collection<Projectile> projectiles, final int tickIncrease,
final Collection<PotionEffect> effects, final int radius, final Class<?> arrowClass, final Class<?> craftArrowClass, int retries) {
Field lifeField = null;
Method getHandleMethod = null;
try {
lifeField = arrowClass.getDeclaredField("j");
getHandleMethod = craftArrowClass.getMethod("getHandle");
} catch (Exception ex) {
lifeField = null;
getHandleMethod = null;
controller.getLogger().warning("Failed to create short-lived arrow. Are you running bukkit? Set tick_increase to 0 to avoid this message");
}
final Collection<Projectile> remaining = new ArrayList<Projectile>();
for (Projectile projectile : projectiles) {
if (projectile.isDead()) {
// Apply potion effects if configured
applyPotionEffects(projectile.getLocation(), radius, effects);
} else {
remaining.add(projectile);
if (projectile instanceof Arrow && tickIncrease > 0 && lifeField != null && getHandleMethod != null) {
try {
Object handle = getHandleMethod.invoke(projectile);
lifeField.setAccessible(true);
int currentLife = (Integer)lifeField.get(handle);
if (currentLife < tickIncrease) {
lifeField.set(handle, tickIncrease);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
if (remaining.size() > 0 && retries > 0) {
scheduleProjectileCheck(remaining, tickIncrease, effects, radius, arrowClass, craftArrowClass, retries - 1);
}
}
}
|
package music_thing;
import java.io.File;
import java.io.IOException;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.sound.midi.*;
/**
*
* @author joshuakaplan
*/
public class MusicController {
private static boolean playing = false;
private static Track currentTrack;
private static MediaPlayer mp3player;
private static Media mp3;
private static Sequencer midiSequencer;
private static Sequence midiSequence;
private static Synthesizer midiSynthesizer;
public static void setSong(Track track){
stop();
File file = new File("music/"+track.getPath());
SongType type = track.getType();
if(type==SongType.MP3 || type==SongType.AAC || type==SongType.WAV || type==SongType.AIFF){
mp3 = new Media(file.toURI().toString());
mp3player = new MediaPlayer(mp3);
}else if(type==SongType.MIDI){
try{
midiSequence = MidiSystem.getSequence(file);
midiSequencer.setSequence(midiSequence);
}catch(InvalidMidiDataException | IOException e){System.out.println(e);}
}
}
public static double getCurrentTime(){
SongType type = currentTrack.getType();
if(type==SongType.MP3 || type==SongType.AAC || type==SongType.WAV || type==SongType.AIFF){
if(mp3player!=null && mp3!=null){
return mp3player.getCurrentTime().toSeconds();
}
}else if(type==SongType.MIDI){
if(midiSequence!=null && midiSequencer!=null){
return midiSequencer.getMicrosecondPosition()/1000000.0;
}
}
return 0.0;
}
public static void play(Track track, double volume){
SongType type = track.getType();
if(type==SongType.MP3 || type==SongType.AAC || type==SongType.WAV || type==SongType.AIFF){
if(mp3==null || track!=currentTrack){
setSong(track);
}
mp3player.play();
}else if(type==SongType.MIDI){
try{
if(midiSequencer==null)midiSequencer = MidiSystem.getSequencer(false);
if(midiSequence==null || track!=currentTrack)setSong(track);
midiSynthesizer = MidiSystem.getSynthesizer();
Soundbank soundbank = midiSynthesizer.getDefaultSoundbank();
if(soundbank == null) {
midiSequencer.getTransmitter().setReceiver(MidiSystem.getReceiver());
}
else {
midiSynthesizer.loadAllInstruments(soundbank);
midiSequencer.getTransmitter().setReceiver(midiSynthesizer.getReceiver());
}
midiSynthesizer.open();
midiSequencer.open();
midiSequencer.start();
}catch(Exception e){}
}
playing = true;
currentTrack = track;
setVolume(volume);
}
public static void pause(){
SongType type = currentTrack.getType();
if(type==SongType.MP3 || type==SongType.AAC || type==SongType.WAV || type==SongType.AIFF){
mp3player.pause();
}else if(type==SongType.MIDI){
midiSequencer.stop();
}
playing = false;
}
public static boolean getPlaying(){
return playing;
}
public static Track getCurrentTrack() {
return currentTrack;
}
public static void stop(){
if(midiSequencer!=null)midiSequencer.close();
if(midiSynthesizer!=null)midiSynthesizer.close();
if(mp3player!=null){
if(mp3player.getStatus()!=MediaPlayer.Status.STOPPED) mp3player.stop();
mp3player.dispose();
}
playing=false;
}
public static void setVolume(double volume){
if(currentTrack!=null){
SongType type = currentTrack.getType();
if(type==SongType.MP3 || type==SongType.AAC || type==SongType.WAV || type==SongType.AIFF){
mp3player.setVolume(volume);
}else if(type==SongType.MIDI){
try{
if(midiSynthesizer.getDefaultSoundbank()==null) {
for ( int i = 0; i < 16; i++ ) {
midiSynthesizer.getReceiver().send(new ShortMessage(ShortMessage.CONTROL_CHANGE, i, 7, (int)(volume*127)), -1 );
}
}
else {
for(MidiChannel c : midiSynthesizer.getChannels()) {
if(c != null)c.controlChange(7, (int)(volume*127));
}
}
}catch(Exception e){}
}
}
}
}
|
package com.github.ithildir.liferay.mobile.windows;
import com.liferay.mobile.sdk.BaseBuilder;
import com.liferay.mobile.sdk.http.Discovery;
import com.liferay.mobile.sdk.util.CharPool;
import com.liferay.mobile.sdk.util.LanguageUtil;
import com.liferay.mobile.sdk.util.Validator;
import com.liferay.mobile.sdk.velocity.VelocityUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.tools.generic.EscapeTool;
/**
* @author Andrea Di Giorgi
*/
public class WindowsSDKBuilder extends BaseBuilder {
@Override
public void build(
Discovery discovery, String packageName, int version, String filter,
String destination)
throws Exception {
copyResource("windows", destination);
generateService(discovery, packageName, version, filter, destination);
}
protected void copyJarResource(
JarURLConnection jarConnection, File destinationDir)
throws IOException {
String jarConnectionEntryName = jarConnection.getEntryName();
JarFile jarFile = jarConnection.getJarFile();
Enumeration<JarEntry> enu = jarFile.entries();
while (enu.hasMoreElements()) {
JarEntry jarEntry = enu.nextElement();
String jarEntryName = jarEntry.getName();
if (jarEntryName.startsWith(jarConnectionEntryName)) {
String fileName = jarEntryName;
if (fileName.startsWith(jarConnectionEntryName)) {
fileName = fileName.substring(
jarConnectionEntryName.length());
}
File file = new File(destinationDir, fileName);
if (file.exists()) {
continue;
}
if (jarEntry.isDirectory()) {
file.mkdirs();
}
else {
InputStream is = null;
OutputStream os = null;
try {
is = jarFile.getInputStream(jarEntry);
os = FileUtils.openOutputStream(file);
IOUtils.copy(is, os);
}
finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
}
}
}
protected void copyResource(String name, String destination)
throws IOException {
File destinationDir = new File(destination);
destinationDir = destinationDir.getAbsoluteFile();
URL sourceURL = getClass().getResource(CharPool.SLASH + name);
URLConnection sourceConnection = sourceURL.openConnection();
if (sourceConnection instanceof JarURLConnection) {
copyJarResource((JarURLConnection)sourceConnection, destinationDir);
}
else {
File sourceDir = new File(sourceURL.getPath());
FileUtils.copyDirectory(sourceDir, destinationDir);
}
Iterator<File> itr = FileUtils.iterateFiles(
destinationDir, new String[] {"copy"}, true);
while (itr.hasNext()) {
File file = itr.next();
String cleanPath = FilenameUtils.removeExtension(
file.getAbsolutePath());
File cleanFile = new File(cleanPath);
if (!cleanFile.exists()) {
FileUtils.moveFile(file, new File(cleanPath));
}
else {
file.delete();
}
}
}
protected void generateService(
Discovery discovery, String packageName, int version, String filter,
String destination)
throws Exception {
StringBuilder sb = new StringBuilder();
if (Validator.isNotNull(destination)) {
sb.append(destination);
sb.append(CharPool.SLASH);
}
sb.append("Liferay.SDK/Service");
destination = sb.toString();
packageName = "Liferay.SDK.Service";
VelocityContext context = getVelocityContext(
discovery, packageName, version, filter);
String templatePath = "templates/windows/service.vm";
String filePath = getServiceFilePath(
context, version, destination, filter);
VelocityUtil.generate(context, templatePath, filePath, true);
}
protected String getServiceFilePath(
VelocityContext context, int version, String destination,
String filter) {
String className = (String)context.get(CLASS_NAME);
CSharpUtil cSharpUtil = (CSharpUtil)context.get(LANGUAGE_UTIL);
StringBuilder sb = new StringBuilder();
sb.append(destination);
sb.append("/V");
sb.append(version);
sb.append(CharPool.SLASH);
sb.append(cSharpUtil.getServicePackageName(filter));
sb.append(CharPool.SLASH);
File file = new File(sb.toString());
file.mkdirs();
sb.append(className);
sb.append(".cs");
return sb.toString();
}
protected VelocityContext getVelocityContext(
Discovery discovery, String packageName, int version, String filter) {
VelocityContext context = new VelocityContext();
CSharpUtil cSharpUtil = new CSharpUtil();
StringBuilder sb = new StringBuilder(packageName);
sb.append(".V");
sb.append(version);
sb.append(CharPool.PERIOD);
sb.append(cSharpUtil.getServicePackageName(filter));
packageName = sb.toString();
context.put(BYTE_ARRAY, LanguageUtil.BYTE_ARRAY);
context.put(CLASS_NAME, cSharpUtil.getServiceClassName(filter));
context.put(DISCOVERY, discovery);
context.put(ESCAPE_TOOL, new EscapeTool());
context.put(JSON_OBJECT_WRAPPER, CSharpUtil.JSON_OBJECT_WRAPPER);
context.put(LANGUAGE_UTIL, cSharpUtil);
context.put(PACKAGE, packageName);
context.put(VOID, LanguageUtil.VOID);
return context;
}
protected static final String PACKAGE = "package";
}
|
package com.github.markusbernhardt.selenium2library.keywords;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.robotframework.javalib.annotation.ArgumentNames;
import org.robotframework.javalib.annotation.Autowired;
import org.robotframework.javalib.annotation.RobotKeyword;
import org.robotframework.javalib.annotation.RobotKeywordOverload;
import org.robotframework.javalib.annotation.RobotKeywords;
import com.github.markusbernhardt.selenium2library.RunOnFailureKeywordsAdapter;
import com.github.markusbernhardt.selenium2library.Selenium2LibraryNonFatalException;
import com.github.markusbernhardt.selenium2library.locators.ElementFinder;
import com.github.markusbernhardt.selenium2library.utils.Python;
@RobotKeywords
public class Element extends RunOnFailureKeywordsAdapter {
/**
* Instantiated BrowserManagement keyword bean
*/
@Autowired
protected BrowserManagement browserManagement;
/**
* Instantiated FormElement keyword bean
*/
@Autowired
protected FormElement formElement;
/**
* Instantiated Logging keyword bean
*/
@Autowired
protected Logging logging;
//
// Keywords - Element Lookups
//
@RobotKeywordOverload
@ArgumentNames({ "text" })
public void currentFrameContains(String text) {
currentFrameContains(text, "INFO");
}
/**
* Verifies the current frame contains <b>text</b>.<br>
* <br>
* See `Introduction` for details about log levels.<br>
*
* @param text
* The text to verify.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "text", "loglevel=INFO" })
public void currentFrameContains(String text, String logLevel) {
if (!isTextPresent(text)) {
logging.log(String.format("Current Frame Contains: %s => FAILED", text), logLevel);
throw new Selenium2LibraryNonFatalException(String.format(
"Page should have contained text '%s', but did not.", text));
} else {
logging.log(String.format("Current Frame Contains: %s => OK", text), logLevel);
}
}
@RobotKeywordOverload
public void currentFrameShouldNotContain(String text) {
currentFrameShouldNotContain(text, "INFO");
}
/**
* Verifies the current frame does not contain <b>text</b>.<br>
* <br>
* See `Introduction` for details about log levels.<br>
*
* @param text
* The text to verify.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "text", "loglevel=INFO" })
public void currentFrameShouldNotContain(String text, String logLevel) {
if (isTextPresent(text)) {
logging.log(String.format("Current Frame Should Not Contain: %s => FAILED", text), logLevel);
throw new Selenium2LibraryNonFatalException(String.format(
"Page should have not contained text '%s', but did.", text));
} else {
logging.log(String.format("Current Frame Should Not Contain: %s => OK", text), logLevel);
}
}
@RobotKeywordOverload
public void elementShouldContain(String locator, String text) {
elementShouldContain(locator, text, "");
}
/**
* Verifies the element identified by <b>locator</b> contains <b>text</b>.<br>
* <br>
* See `Introduction` for details about locators.
*
* @param locator
* The locator to locate the element.
* @param text
* The text to verify.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "text", "message=NONE" })
public void elementShouldContain(String locator, String text, String message) {
String actual = getText(locator);
if (!actual.toLowerCase().contains(text.toLowerCase())) {
logging.info(String.format("Element Should Contain: %s => FAILED", text));
throw new Selenium2LibraryNonFatalException(String.format(
"Element should have contained text '%s', but its text was %s.", text, actual));
} else {
logging.info(String.format("Element Should Contain: %s => OK", text));
}
}
@RobotKeywordOverload
public void elementShouldNotContain(String locator, String text) {
elementShouldNotContain(locator, text, "");
}
/**
* Verifies the element identified by <b>locator</b> does not contain
* <b>text</b>.<br>
* <br>
* See `Introduction` for details about locators.
*
* @param locator
* The locator to locate the element.
* @param text
* The text to verify.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "text", "message=NONE" })
public void elementShouldNotContain(String locator, String text, String message) {
String actual = getText(locator);
if (actual.toLowerCase().contains(text.toLowerCase())) {
logging.info(String.format("Element Should Not Contain: %s => FAILED", text));
throw new Selenium2LibraryNonFatalException(String.format(
"Element should not have contained text '%s', but its text was %s.", text, actual));
} else {
logging.info(String.format("Element Should Not Contain: %s => OK", text));
}
}
@RobotKeywordOverload
public void frameShouldContain(String locator, String text) {
frameShouldContain(locator, text, "INFO");
}
/**
* Verifies the frame identified by <b>locator</b> contains <b>text</b>.<br>
* <br>
* See `Introduction` for details about locators.
*
* @param locator
* The locator to locate the frame.
* @param text
* The text to verify.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "text", "loglevel=INFO" })
public void frameShouldContain(String locator, String text, String logLevel) {
if (!frameContains(locator, text)) {
logging.log(String.format("Frame Should Contain: %s => FAILED", text), logLevel);
throw new Selenium2LibraryNonFatalException(String.format(
"Frame should have contained text '%s', but did not.", text));
} else {
logging.log(String.format("Frame Should Contain: %s => OK", text), logLevel);
}
}
/**
* Verifies the frame identified by <b>locator</b> does not contain
* <b>text</b>.<br>
* <br>
* See `Introduction` for details about locators.
*
* @param locator
* The locator to locate the frame.
* @param text
* The text to verify.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "text", "loglevel=INFO" })
public void frameShouldNotContain(String locator, String text, String logLevel) {
if (frameContains(locator, text)) {
logging.log(String.format("Frame Should Not Contain: %s => FAILED", text), logLevel);
throw new Selenium2LibraryNonFatalException(String.format(
"Frame should not have contained text '%s', but did.", text));
} else {
logging.log(String.format("Frame Should Not Contain: %s => OK", text), logLevel);
}
}
@RobotKeywordOverload
public void pageShouldContain(String text) {
pageShouldContain(text, "INFO");
}
/**
* Verifies the current page contains <b>text</b>.<br>
* <br>
* See `Introduction` for details about log levels.<br>
*
* @param text
* The text to verify.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "text", "loglevel=INFO" })
public void pageShouldContain(String text, String logLevel) {
if (!pageContains(text)) {
logging.log(String.format("Page Should Contain: %s => FAILED", text), logLevel);
throw new Selenium2LibraryNonFatalException(String.format(
"Page should have contained text '%s' but did not.", text));
} else {
logging.log(String.format("Page Should Contain: %s => OK", text), logLevel);
}
}
@RobotKeywordOverload
public void pageShouldNotContain(String text) {
pageShouldNotContain(text, "INFO");
}
/**
* Verifies the current page does not contain <b>text</b>.<br>
* <br>
* See `Introduction` for details about log levels.<br>
*
* @param text
* The text to verify.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "text", "loglevel=INFO" })
public void pageShouldNotContain(String text, String logLevel) {
if (pageContains(text)) {
logging.log(String.format("Page Should Not Contain: %s => FAILED", text), logLevel);
throw new Selenium2LibraryNonFatalException(String.format(
"Page should not have contained text '%s' but did.", text));
} else {
logging.log(String.format("Page Should Not Contain: %s => OK", text), logLevel);
}
}
@RobotKeywordOverload
public void pageShouldContainElement(String locator) {
pageShouldContainElement(locator, "", "INFO");
}
@RobotKeywordOverload
public void pageShouldContainElement(String locator, String message) {
pageShouldContainElement(locator, message, "INFO");
}
/**
* Verifies the element identified by <b>locator</b> is found on the current
* page.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE", "loglevel=INFO" })
public void pageShouldContainElement(String locator, String message, String logLevel) {
pageShouldContainElement(locator, null, message, "INFO");
}
protected void pageShouldContainElement(String locator, String tag, String message, String logLevel) {
String name = tag != null ? tag : "element";
if (!isElementPresent(locator, tag)) {
if (message == null || message.equals("")) {
message = String.format("Page should have contained %s '%s' but did not", name, locator);
}
logging.log(message, logLevel);
throw new Selenium2LibraryNonFatalException(message);
} else {
logging.log(String.format("Current page contains %s '%s'.", name, locator), logLevel);
}
}
@RobotKeywordOverload
public void pageShouldNotContainElement(String locator) {
pageShouldNotContainElement(locator, "", "INFO");
}
@RobotKeywordOverload
public void pageShouldNotContainElement(String locator, String message) {
pageShouldNotContainElement(locator, message, "INFO");
}
/**
* Verifies the element identified by <b>locator</b> is not found on the
* current page.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE", "loglevel=INFO" })
public void pageShouldNotContainElement(String locator, String message, String logLevel) {
pageShouldNotContainElement(locator, null, message, "INFO");
}
protected void pageShouldNotContainElement(String locator, String tag, String message, String logLevel) {
String name = tag != null ? tag : "element";
if (isElementPresent(locator, tag)) {
if (message == null || message.equals("")) {
message = String.format("Page should not have contained %s '%s' but did", name, locator);
}
logging.log(message, logLevel);
throw new Selenium2LibraryNonFatalException(message);
} else {
logging.log(String.format("Current page does not contain %s '%s'.", name, locator), logLevel);
}
}
//
// Keywords - Attributes
//
/**
* Assigns a temporary identifier to the element identified by
* <b>locator</b><br>
* <br>
* This is mainly useful, when the locator is a complicated and slow XPath
* expression. The identifier expires when the page is reloaded.<br>
* <br>
* Example:
* <table border="1" cellspacing="0">
* <tr>
* <td>Assign ID to Element</td>
* <td>xpath=//div[@id=\"first_div\"]</td>
* <td>my id</td>
* </tr>
* <tr>
* <td>Page Should Contain Element</td>
* <td>my id</td>
* <td></td>
* </tr>
* </table>
*
* @param locator
* The locator to locate the element.
* @param id
* The id to assign.
*/
@RobotKeyword
@ArgumentNames({ "locator", "id" })
public void assignIdToElement(String locator, String id) {
logging.info(String.format("Assigning temporary id '%s' to element '%s'", id, locator));
List<WebElement> elements = elementFind(locator, true, true);
((JavascriptExecutor) browserManagement.getCurrentWebDriver()).executeScript(
String.format("arguments[0].id = '%s';", id), elements.get(0));
}
/**
* Verifies the element identified by <b>locator</b> is enabled.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void elementShouldBeEnabled(String locator) {
if (!isEnabled(locator)) {
throw new Selenium2LibraryNonFatalException(String.format("Element %s is disabled.", locator));
}
}
/**
* Verifies the element identified by <b>locator</b> is disabled.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void elementShouldBeDisabled(String locator) {
if (isEnabled(locator)) {
throw new Selenium2LibraryNonFatalException(String.format("Element %s is enabled.", locator));
}
}
@RobotKeywordOverload
public void elementShouldBeSelected(String locator) {
elementShouldBeSelected(locator, "");
}
/**
* Verifies the element identified by <b>locator</b> is selected.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE" })
public void elementShouldBeSelected(String locator, String message) {
logging.info(String.format("Verifying element '%s' is selected.", locator));
boolean selected = isSelected(locator);
if (!selected) {
if (message == null || message.equals("")) {
message = String.format("Element '%s' should be selected, but it is not.", locator);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementShouldNotBeSelected(String locator) {
elementShouldNotBeSelected(locator, "");
}
/**
* Verifies the element identified by <b>locator</b> is not selected.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE" })
public void elementShouldNotBeSelected(String locator, String message) {
logging.info(String.format("Verifying element '%s' is not selected.", locator));
boolean selected = isSelected(locator);
if (selected) {
if (message == null || message.equals("")) {
message = String.format("Element '%s' should not be selected, but it is.", locator);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementShouldBeVisible(String locator) {
elementShouldBeVisible(locator, "");
}
/**
* Verifies the element identified by <b>locator</b> is visible.<br>
* <br>
* Herein, visible means that the element is logically visible, not
* optically visible in the current browser viewport. For example, an
* element that carries display:none is not logically visible, so using this
* keyword on that element would fail.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE" })
public void elementShouldBeVisible(String locator, String message) {
logging.info(String.format("Verifying element '%s' is visible.", locator));
boolean visible = isVisible(locator);
if (!visible) {
if (message == null || message.equals("")) {
message = String.format("Element '%s' should be visible, but it is not.", locator);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementShouldNotBeVisible(String locator) {
elementShouldNotBeVisible(locator, "");
}
/**
* Verifies the element identified by <b>locator</b> is not visible.<br>
* <br>
* Herein, visible means that the element is logically visible, not
* optically visible in the current browser viewport. For example, an
* element that carries display:none is not logically visible, so using this
* keyword on that element would fail.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE" })
public void elementShouldNotBeVisible(String locator, String message) {
logging.info(String.format("Verifying element '%s' is not visible.", locator));
boolean visible = isVisible(locator);
if (visible) {
if (message == null || message.equals("")) {
message = String.format("Element '%s' should not be visible, but it is.", locator);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementShouldBeClickable(String locator) {
elementShouldBeClickable(locator, "");
}
/**
* Verifies the element identified by <b>locator</b> is clickable.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE" })
public void elementShouldBeClickable(String locator, String message) {
logging.info(String.format("Verifying element '%s' is clickable.", locator));
boolean clickable = isClickable(locator);
if (!clickable) {
if (message == null || message.equals("")) {
message = String.format("Element '%s' should be clickable, but it is not.", locator);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementShouldNotBeClickable(String locator) {
elementShouldNotBeClickable(locator, "");
}
/**
* Verifies the element identified by <b>locator</b> is not clickable.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE" })
public void elementShouldNotBeClickable(String locator, String message) {
logging.info(String.format("Verifying element '%s' is not clickable.", locator));
boolean clickable = isClickable(locator);
if (clickable) {
if (message == null || message.equals("")) {
message = String.format("Element '%s' should not be clickable, but it is.", locator);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementTextShouldBe(String locator, String expected) {
elementTextShouldBe(locator, expected, "");
}
/**
* Verifies the text of the element identified by <b>locator</b> is exactly
* <b>text</b>.<br>
* <br>
* In contrast to `Element Should Contain`, this keyword does not try a
* substring match but an exact match on the element identified by locator.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param text
* The text to verify.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "text", "message=NONE" })
public void elementTextShouldBe(String locator, String text, String message) {
List<WebElement> elements = elementFind(locator, true, true);
String actual = elements.get(0).getText();
if (!text.equals(actual)) {
if (message == null || message.equals("")) {
message = String.format("The text of element '%s' should have been '%s', but it was '%s'.", locator,
text, actual);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
@RobotKeywordOverload
public void elementTextShouldNotBe(String locator, String expected) {
elementTextShouldNotBe(locator, expected, "");
}
/**
* Verifies the text of the element identified by <b>locator</b> is not
* exactly <b>text</b>.<br>
* <br>
* In contrast to `Element Should Not Contain`, this keyword does not try a
* substring match but an exact match on the element identified by locator.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param text
* The text to verify.
* @param message
* Default=NONE. Optional custom error message.
*/
@RobotKeyword
@ArgumentNames({ "locator", "text", "message=NONE" })
public void elementTextShouldNotBe(String locator, String text, String message) {
List<WebElement> elements = elementFind(locator, true, true);
String actual = elements.get(0).getText();
if (text.equals(actual)) {
if (message == null || message.equals("")) {
message = String.format("The text of element '%s' should have been '%s', but it was '%s'.", locator,
text, actual);
}
throw new Selenium2LibraryNonFatalException(message);
}
}
/**
* Returns the value of an element attribute.<br>
* <br>
* The <b>attribute_locator</b> consists of element locator followed by an @
* sign and attribute name.<br>
* Example: element_id@class<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param attributeLocator
* The attribute locator.
* @return The attribute value.
*/
@RobotKeyword
@ArgumentNames({ "attributeLocator" })
public String getElementAttribute(String attributeLocator) {
String[] parts = parseAttributeLocator(attributeLocator);
List<WebElement> elements = elementFind(parts[0], true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(String.format("Element '%s' not found.", parts[0]));
}
return elements.get(0).getAttribute(parts[1]);
}
/**
* Clears the text from element identified by <b>locator</b>.<br>
* <br>
* This keyword does not execute any checks on whether or not the clear
* method has succeeded, so if any subsequent checks are needed, they should
* be executed using method `Element Text Should Be`.<br>
* <br>
* Also, this method will use WebDriver's internal _element.clear()_ method,
* i.e. it will not send any keypresses, and it will not have any effect
* whatsoever on elements other than input textfields or input textareas.
* Clients relying on keypresses should implement their own methods.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void clearElementText(String locator) {
List<WebElement> elements = elementFind(locator, true, true);
elements.get(0).clear();
}
/**
* Returns horizontal position of element identified by <b>locator</b>.<br>
* <br>
* The position is returned in pixels off the left side of the page, as an
* integer. Fails if the matching element is not found.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @return The horizontal position
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public int getHorizontalPosition(String locator) {
List<WebElement> elements = elementFind(locator, true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(
String.format("Could not determine position for '%s'.", locator));
}
return elements.get(0).getLocation().getX();
}
/**
* Returns the value attribute of the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @return The value attribute of the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public String getValue(String locator) {
return getValue(locator, null);
}
protected String getValue(String locator, String tag) {
List<WebElement> elements = elementFind(locator, true, false, tag);
if (elements.size() == 0) {
return null;
}
return elements.get(0).getAttribute("value");
}
/**
* Returns the text of the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @return The text of the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public String getText(String locator) {
List<WebElement> elements = elementFind(locator, true, true);
if (elements.size() == 0) {
return null;
}
return elements.get(0).getText();
}
/**
* Returns vertical position of element identified by <b>locator</b>.<br>
* <br>
* The position is returned in pixels off the top of the page, as an
* integer. Fails if the matching element is not found.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @return The vertical position
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public int getVerticalPosition(String locator) {
List<WebElement> elements = elementFind(locator, true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(
String.format("Could not determine position for '%s'.", locator));
}
return elements.get(0).getLocation().getY();
}
//
// Keywords - Mouse Input/Events
//
/**
* Click on the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void clickElement(String locator) {
logging.info(String.format("Clicking element '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, true);
elements.get(0).click();
}
/**
* Double-Click on the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void doubleClickElement(String locator) {
logging.info(String.format("Double clicking element '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, true);
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.doubleClick(elements.get(0)).perform();
}
/**
* Set the focus to the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void focus(String locator) {
List<WebElement> elements = elementFind(locator, true, true);
((JavascriptExecutor) browserManagement.getCurrentWebDriver()).executeScript("arguments[0].focus();",
elements.get(0));
}
/**
* Drag the element identified by the locator <b>source</b> and move it on
* top of the element identified by the locator <b>target</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
* <br>
* Example:
* <table border="1" cellspacing="0">
* <tr>
* <td>Drag And Drop</td>
* <td>elem1</td>
* <td>elem2</td>
* <td># Move elem1 over elem2</td>
* </tr>
* </table>
*
* @param source
* The locator to locate the element to drag.
* @param target
* The locator to locate the element where to drop the dragged
* element.
*/
@RobotKeyword
@ArgumentNames({ "source", "target" })
public void dragAndDrop(String source, String target) {
List<WebElement> sourceElements = elementFind(source, true, true);
List<WebElement> targetElements = elementFind(target, true, true);
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.dragAndDrop(sourceElements.get(0), targetElements.get(0)).perform();
}
/**
* Drag the element identified by the locator <b>source</b> and move it by
* <b>xOffset</b> and <b>yOffset</b>.<br>
* <br>
* Both offsets are specified as negative (left/up) or positive (right/down)
* number.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
* <br>
* Example:
* <table border="1" cellspacing="0">
* <tr>
* <td>Drag And Drop By Offset</td>
* <td>elem1</td>
* <td>50</td>
* <td>35</td>
* <td># Move elem1 50px right and 35px down.</td>
* </tr>
* </table>
*
* @param source
* The locator to locate the element to drag.
* @param xOffset
* The horizontal offset in pixel. Negative means left, positive
* right.
* @param yOffset
* The vertical offset in pixel. Negative means up, positive
* down.
*/
@RobotKeyword
@ArgumentNames({ "source", "xOffset", "yOffset" })
public void dragAndDropByOffset(String source, int xOffset, int yOffset) {
List<WebElement> elements = elementFind(source, true, true);
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.dragAndDropBy(elements.get(0), xOffset, yOffset).perform();
}
/**
* Simulates pressing the left mouse button on the element identified by
* <b>locator</b>.<br>
* <br>
* The element is pressed without releasing the mouse button.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @see Element#mouseDownOnImage
* @see Element#mouseDownOnLink
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void mouseDown(String locator) {
logging.info(String.format("Simulating Mouse Down on element '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(String.format("ERROR: Element %s not found.", locator));
}
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.clickAndHold(elements.get(0)).perform();
}
/**
* Simulates moving the mouse away from the element identified by
* <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void mouseOut(String locator) {
logging.info(String.format("Simulating Mouse Out on element '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(String.format("ERROR: Element %s not found.", locator));
}
WebElement element = elements.get(0);
Dimension size = element.getSize();
int offsetX = size.getWidth() / 2 + 1;
int offsetY = size.getHeight() / 2 + 1;
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.moveToElement(element).moveByOffset(offsetX, offsetY).perform();
}
/**
* Simulates moving the mouse over the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void mouseOver(String locator) {
logging.info(String.format("Simulating Mouse Over on element '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(String.format("ERROR: Element %s not found.", locator));
}
WebElement element = elements.get(0);
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.moveToElement(element).perform();
}
/**
* Simulates releasing the left mouse button on the element identified by
* <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void mouseUp(String locator) {
logging.info(String.format("Simulating Mouse Up on element '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, false);
if (elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(String.format("ERROR: Element %s not found.", locator));
}
WebElement element = elements.get(0);
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.clickAndHold(element).release(element).perform();
}
/**
* Opens the context menu on the element identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void openContextMenu(String locator) {
List<WebElement> elements = elementFind(locator, true, true);
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.contextClick(elements.get(0)).perform();
}
/**
* Simulates the given <b>event</b> on the element identified by
* <b>locator</b>.<br>
* <br>
* This keyword is especially useful, when the element has an OnEvent
* handler that needs to be explicitly invoked.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @param event
* The event to invoke.
*/
@RobotKeyword
@ArgumentNames({ "locator", "event" })
public void simulate(String locator, String event) {
List<WebElement> elements = elementFind(locator, true, true);
String script = "element = arguments[0];" + "eventName = arguments[1];" + "if (document.createEventObject) {"
+ "return element.fireEvent('on' + eventName, document.createEventObject());" + "}"
+ "var evt = document.createEvent(\"HTMLEvents\");" + "evt.initEvent(eventName, true, true);"
+ "return !element.dispatchEvent(evt);";
((JavascriptExecutor) browserManagement.getCurrentWebDriver()).executeScript(script, elements.get(0), event);
}
/**
* Simulates pressing <b>key</b> on the element identified by
* <b>locator</b>.<br>
* <br>
* Key is either a single character, or a numerical ASCII code of the key
* lead by '\\'.<br>
* <br>
* Key attributes for arbitrary elements are id and name. See `Introduction`
* for details about log levels and locators.<br>
* <br>
* Example:
* <table border="1" cellspacing="0">
* <tr>
* <td>Press Key</td>
* <td>text_field</td>
* <td>q</td>
* <td># Press 'q'</td>
* </tr>
* <tr>
* <td>Press Key</td>
* <td>login_button</td>
* <td>\\13</td>
* <td># ASCII code for enter key</td>
* </tr>
* </table>
*
* @param locator
* The locator to locate the element.
* @param key
* The key to press.
*/
@RobotKeyword
@ArgumentNames({ "locator", "key" })
public void pressKey(String locator, String key) {
if (key.startsWith("\\") && key.length() > 1) {
key = mapAsciiKeyCodeToKey(Integer.parseInt(key.substring(1))).toString();
}
List<WebElement> element = elementFind(locator, true, true);
element.get(0).sendKeys(key);
}
//
// Keywords - Links
//
/**
* Click on the link identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary links are id, name, href and link text. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the link.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void clickLink(String locator) {
logging.info(String.format("Clicking link '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, true, "a");
elements.get(0).click();
}
/**
* Returns a list containing ids of all links found in current page.<br>
* <br>
* If a link has no id, an empty string will be in the list instead.<br>
*
* @return The list of link ids.
*/
@RobotKeyword
public ArrayList<String> getAllLinks() {
ArrayList<String> ret = new ArrayList<String>();
List<WebElement> elements = elementFind("tag=a", false, false, "a");
for (WebElement element : elements) {
ret.add(element.getAttribute("id"));
}
return ret;
}
/**
* Simulates pressing the left mouse button on the link identified by
* <b>locator</b>.<br>
* <br>
* The element is pressed without releasing the mouse button.<br>
* <br>
* Key attributes for arbitrary links are id, name, href and link text. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @see Element#mouseDown
* @see Element#mouseDownOnImage
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void mouseDownOnLink(String locator) {
List<WebElement> elements = elementFind(locator, true, true, "link");
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.clickAndHold(elements.get(0)).perform();
}
@RobotKeywordOverload
@ArgumentNames({ "locator" })
public void pageShouldContainLink(String locator) {
pageShouldContainLink(locator, "", "INFO");
}
@RobotKeywordOverload
@ArgumentNames({ "locator", "message=NONE" })
public void pageShouldContainLink(String locator, String message) {
pageShouldContainLink(locator, message, "INFO");
}
/**
* Verifies the link identified by <b>locator</b> is found on the current
* page.<br>
* <br>
* Key attributes for arbitrary links are id, name, href and link text. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the link.
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE", "loglevel=INFO" })
public void pageShouldContainLink(String locator, String message, String logLevel) {
pageShouldContainElement(locator, "link", message, logLevel);
}
@RobotKeywordOverload
public void pageShouldNotContainLink(String locator) {
pageShouldNotContainLink(locator, "", "INFO");
}
@RobotKeywordOverload
public void pageShouldNotContainLink(String locator, String message) {
pageShouldNotContainLink(locator, message, "INFO");
}
/**
* Verifies the link identified by <b>locator</b> is not found on the
* current page.<br>
* <br>
* Key attributes for arbitrary links are id, name, href and link text. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the link.
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE", "loglevel=INFO" })
public void pageShouldNotContainLink(String locator, String message, String logLevel) {
pageShouldNotContainElement(locator, "link", message, logLevel);
}
//
// Keywords - Images
//
/**
* Click on the image identified by <b>locator</b>.<br>
* <br>
* Key attributes for arbitrary images are id, src and alt. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void clickImage(String locator) {
logging.info(String.format("Clicking image '%s'.", locator));
List<WebElement> elements = elementFind(locator, true, false, "image");
if (elements.size() == 0) {
elements = elementFind(locator, true, true, "input");
}
WebElement element = elements.get(0);
element.click();
}
/**
* Simulates pressing the left mouse button on the image identified by
* <b>locator</b>.<br>
* <br>
* The element is pressed without releasing the mouse button.<br>
* <br>
* Key attributes for arbitrary images are id, src and alt. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the element.
* @see Element#mouseDown
* @see Element#mouseDownOnLink
*/
@RobotKeyword
@ArgumentNames({ "locator" })
public void mouseDownOnImage(String locator) {
List<WebElement> elements = elementFind(locator, true, true, "image");
Actions action = new Actions(browserManagement.getCurrentWebDriver());
action.clickAndHold(elements.get(0)).perform();
}
@RobotKeywordOverload
@ArgumentNames({ "locator" })
public void pageShouldContainImage(String locator) {
pageShouldContainImage(locator, "", "INFO");
}
@RobotKeywordOverload
@ArgumentNames({ "locator", "message=NONE" })
public void pageShouldContainImage(String locator, String message) {
pageShouldContainImage(locator, message, "INFO");
}
/**
* Verifies the image identified by <b>locator</b> is found on the current
* page.<br>
* <br>
* Key attributes for arbitrary images are id, src and alt. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the link.
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE", "loglevel=INFO" })
public void pageShouldContainImage(String locator, String message, String logLevel) {
pageShouldContainElement(locator, "image", message, logLevel);
}
@RobotKeywordOverload
@ArgumentNames({ "locator" })
public void pageShouldNotContainImage(String locator) {
pageShouldNotContainImage(locator, "", "INFO");
}
@RobotKeywordOverload
@ArgumentNames({ "locator", "message=NONE" })
public void pageShouldNotContainImage(String locator, String message) {
pageShouldNotContainImage(locator, message, "INFO");
}
/**
* Verifies the image identified by <b>locator</b> is not found on the
* current page.<br>
* <br>
* Key attributes for arbitrary images are id, src and alt. See
* `Introduction` for details about log levels and locators.<br>
*
* @param locator
* The locator to locate the link.
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "locator", "message=NONE", "loglevel=INFO" })
public void pageShouldNotContainImage(String locator, String message, String logLevel) {
pageShouldNotContainElement(locator, "image", message, logLevel);
}
//
// Keywords - Xpath
//
/**
* Returns the number of elements located the given <b>xpath</b>.<br>
* <br>
* If you wish to assert the number of located elements, use `Xpath Should
* Match X Times`.<br>
*
* @param xpath
* The XPath to match page elements
* @return The number of located elements
*/
@RobotKeyword
@ArgumentNames({ "xpath" })
public int getMatchingXpathCount(String xpath) {
if (!xpath.startsWith("xpath=")) {
xpath = "xpath=" + xpath;
}
List<WebElement> elements = elementFind(xpath, false, false);
return elements.size();
}
@RobotKeywordOverload
@ArgumentNames({ "xpath", "expectedXpathCount" })
public void xpathShouldMatchXTimes(String xpath, int expectedXpathCount) {
xpathShouldMatchXTimes(xpath, expectedXpathCount, "");
}
@RobotKeywordOverload
@ArgumentNames({ "xpath", "expectedXpathCount", "message=NONE" })
public void xpathShouldMatchXTimes(String xpath, int expectedXpathCount, String message) {
xpathShouldMatchXTimes(xpath, expectedXpathCount, message, "INFO");
}
/**
* Verifies that the page contains the <b>expectedXpathCount</b> of elements
* located by the given <b>xpath</b>.<br>
*
* @param xpath
* The XPath to match page elements
* @param expectedXpathCount
* The expected number of located elements
* @param message
* Default=NONE. Optional custom error message.
* @param logLevel
* Default=INFO. Optional log level.
*/
@RobotKeyword
@ArgumentNames({ "xpath", "expectedXpathCount", "message=NONE", "logLevel=INFO" })
public void xpathShouldMatchXTimes(String xpath, int expectedXpathCount, String message, String logLevel) {
if (!xpath.startsWith("xpath=")) {
xpath = "xpath=" + xpath;
}
List<WebElement> elements = elementFind(xpath, false, false);
int actualXpathCount = elements.size();
if (actualXpathCount != expectedXpathCount) {
if (message == null || message.equals("")) {
message = String.format("Xpath %s should have matched %s times but matched %s times.", xpath,
expectedXpathCount, actualXpathCount);
}
throw new Selenium2LibraryNonFatalException(message);
}
logging.log(String.format("Current page contains %s elements matching '%s'.", actualXpathCount, xpath),
logLevel);
}
//
// Internal Methods
//
protected List<WebElement> elementFind(String locator, boolean firstOnly, boolean required) {
return elementFind(locator, firstOnly, required, null);
}
protected List<WebElement> elementFind(String locator, boolean firstOnly, boolean required, String tag) {
List<WebElement> elements = ElementFinder.find(browserManagement.getCurrentWebDriver(), locator, tag);
if (required && elements.size() == 0) {
throw new Selenium2LibraryNonFatalException(String.format(
"Element locator '%s' did not match any elements.", locator));
}
if (firstOnly) {
if (elements.size() > 1) {
List<WebElement> tmp = new ArrayList<WebElement>();
tmp.add(elements.get(0));
elements = tmp;
}
}
return elements;
}
protected boolean frameContains(String locator, String text) {
WebDriver current = browserManagement.getCurrentWebDriver();
List<WebElement> elements = elementFind(locator, true, true);
current.switchTo().frame(elements.get(0));
logging.info(String.format("Searching for text from frame '%s'.", locator));
boolean found = isTextPresent(text);
current.switchTo().defaultContent();
return found;
}
protected boolean isTextPresent(String text) {
|
package com.googlecode.mp4parser.authoring.tracks;
import com.coremedia.iso.boxes.*;
import com.googlecode.mp4parser.authoring.AbstractTrack;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.TrackMetaData;
import java.nio.ByteBuffer;
import java.util.AbstractList;
import java.util.LinkedList;
import java.util.List;
/**
* Generates a Track where a single sample has been replaced by a given <code>ByteBuffer</code>.
*/
public class ReplaceSampleTrack extends AbstractTrack {
Track origTrack;
private long sampleNumber;
private ByteBuffer sampleContent;
private List<ByteBuffer> samples;
public ReplaceSampleTrack(Track origTrack, long sampleNumber, ByteBuffer content) {
this.origTrack = origTrack;
this.sampleNumber = sampleNumber;
this.sampleContent = content;
this.samples = new ReplaceASingleEntryList();
}
public List<ByteBuffer> getSamples() {
return samples;
}
public SampleDescriptionBox getSampleDescriptionBox() {
return origTrack.getSampleDescriptionBox();
}
public List<TimeToSampleBox.Entry> getDecodingTimeEntries() {
return origTrack.getDecodingTimeEntries();
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return origTrack.getCompositionTimeEntries();
}
synchronized public long[] getSyncSamples() {
return origTrack.getSyncSamples();
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
return origTrack.getSampleDependencies();
}
public TrackMetaData getTrackMetaData() {
return origTrack.getTrackMetaData();
}
public String getHandler() {
return origTrack.getHandler();
}
public AbstractMediaHeaderBox getMediaHeaderBox() {
return origTrack.getMediaHeaderBox();
}
public SubSampleInformationBox getSubsampleInformationBox() {
return origTrack.getSubsampleInformationBox();
}
private class ReplaceASingleEntryList extends AbstractList<ByteBuffer> {
@Override
public ByteBuffer get(int index) {
if (ReplaceSampleTrack.this.sampleNumber == index) {
return ReplaceSampleTrack.this.sampleContent;
} else {
return ReplaceSampleTrack.this.origTrack.getSamples().get(index);
}
}
@Override
public int size() {
return ReplaceSampleTrack.this.origTrack.getSamples().size();
}
}
}
|
package com.insightfullogic.java_final_benchmarks;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.openjdk.jmh.annotations.CompilerControl.Mode.DONT_INLINE;
import static org.openjdk.jmh.annotations.Mode.AverageTime;
import static org.openjdk.jmh.annotations.Scope.Thread;
@BenchmarkMode(AverageTime)
@Warmup(iterations = 5, time = 1, timeUnit = SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = SECONDS)
@Fork(5)
@OutputTimeUnit(NANOSECONDS)
@State(Thread)
public class JavaFinalBenchmark {
// Deliberately a field, JMH avoids constant folding
private double x = Math.PI;
private TargetClass1 target;
private InlinableTargetClass1 inlinableTarget;
@Setup
public void setup() {
target = new TargetClass1();
inlinableTarget = new InlinableTargetClass1();
}
@GenerateMicroBenchmark
public void virtualInvoke() {
target.targetVirtual();
}
@GenerateMicroBenchmark
public void finalInvoke() {
target.targetFinal();
}
@GenerateMicroBenchmark
public void inlinableVirtualInvoke() {
inlinableTarget.targetVirtual();
}
@GenerateMicroBenchmark
public void inlinableFinalInvoke() {
inlinableTarget.targetFinal();
}
/**
* Inherited Methods
* <p/>
* Test the hypothesis of distance up the class hierarchy affects the invoke performance.
* Numbers refer to how far up the class hierarchy the inherited method is from
*/
@GenerateMicroBenchmark
public void parentMethod1() {
target.inheritedTarget1();
}
@GenerateMicroBenchmark
public void parentMethod2() {
target.inheritedTarget2();
}
@GenerateMicroBenchmark
public void parentMethod3() {
target.inheritedTarget3();
}
@GenerateMicroBenchmark
public void parentMethod4() {
target.inheritedTarget4();
}
@GenerateMicroBenchmark
public void parentFinalMethod1() {
target.inheritedFinalTarget1();
}
@GenerateMicroBenchmark
public void parentFinalMethod2() {
target.inheritedFinalTarget2();
}
@GenerateMicroBenchmark
public void parentFinalMethod3() {
target.inheritedFinalTarget3();
}
@GenerateMicroBenchmark
public void parentFinalMethod4() {
target.inheritedFinalTarget4();
}
@GenerateMicroBenchmark
public void alwaysOverriddenMethod() {
target.alwaysOverriddenTarget();
}
@GenerateMicroBenchmark
public double inlinableParentMethod1() {
return inlinableTarget.inheritedTarget1();
}
@GenerateMicroBenchmark
public double inlinableParentMethod2() {
return inlinableTarget.inheritedTarget2();
}
@GenerateMicroBenchmark
public double inlinableParentMethod3() {
return inlinableTarget.inheritedTarget3();
}
@GenerateMicroBenchmark
public double inlinableParentMethod4() {
return inlinableTarget.inheritedTarget4();
}
@GenerateMicroBenchmark
public double inlinableParentFinalMethod1() {
return inlinableTarget.inheritedFinalTarget1();
}
@GenerateMicroBenchmark
public double inlinableParentFinalMethod2() {
return inlinableTarget.inheritedFinalTarget2();
}
@GenerateMicroBenchmark
public double inlinableParentFinalMethod3() {
return inlinableTarget.inheritedFinalTarget3();
}
@GenerateMicroBenchmark
public double inlinableParentFinalMethod4() {
return inlinableTarget.inheritedFinalTarget4();
}
@GenerateMicroBenchmark
public double inlinableAlwaysOverriddenMethod() {
return inlinableTarget.alwaysOverriddenTarget();
}
public class InlinableTargetClass1 extends InlinableTargetClass2 {
public double alwaysOverriddenTarget() {
return x;
}
public double inheritedTarget1() {
return x;
}
public final double inheritedFinalTarget1() {
return x;
}
public double targetVirtual() {
return x;
}
public final double targetFinal() {
return x;
}
}
public class InlinableTargetClass2 extends InlinableTargetClass3 {
public double alwaysOverriddenTarget() {
return x;
}
public double inheritedTarget2() {
return x;
}
public final double inheritedFinalTarget2() {
return x;
}
}
public class InlinableTargetClass3 extends InlinableTargetClass4 {
public double alwaysOverriddenTarget() {
return x;
}
public double inheritedTarget3() {
return x;
}
public final double inheritedFinalTarget3() {
return x;
}
}
public class InlinableTargetClass4 {
public double alwaysOverriddenTarget() {
return x;
}
public double inheritedTarget4() {
return x;
}
public final double inheritedFinalTarget4() {
return x;
}
}
@CompilerControl(DONT_INLINE)
public static class TargetClass1 extends TargetClass2 {
public void alwaysOverriddenTarget() {
}
public void inheritedTarget1() {
}
public final void inheritedFinalTarget1() {
}
public void targetVirtual() {
}
public final void targetFinal() {
}
}
@CompilerControl(DONT_INLINE)
public static class TargetClass2 extends TargetClass3 {
public void alwaysOverriddenTarget() {
}
public void inheritedTarget2() {
}
public final void inheritedFinalTarget2() {
}
}
@CompilerControl(DONT_INLINE)
public static class TargetClass3 extends TargetClass {
public void alwaysOverriddenTarget() {
}
public void inheritedTarget3() {
}
public final void inheritedFinalTarget3() {
}
}
@CompilerControl(DONT_INLINE)
public static class TargetClass {
public void alwaysOverriddenTarget() {
}
public void inheritedTarget4() {
}
public final void inheritedFinalTarget4() {
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + JavaFinalBenchmark.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
|
package com.sri.ai.praise.inference.representation.Table;
import static com.sri.ai.util.Util.in;
import static com.sri.ai.util.Util.mapIntoArrayList;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sri.ai.praise.inference.representation.api.Factor;
import com.sri.ai.praise.inference.representation.api.Variable;
import com.sri.ai.praise.lang.grounded.common.FunctionTable;
import com.sri.ai.util.Util;
import com.sri.ai.util.base.NullaryFunction;
import com.sri.ai.util.collect.CartesianProductIterator;
import com.sri.ai.util.math.MixedRadixNumber;
/**
* @author gabriel
*
*/
public class TableFactor implements Factor{
List<TableVariable> listOfVariables;
LinkedHashSet<TableVariable> setOfVariables;
FunctionTable table;
Map<TableVariable, Integer> mapFromVariableToItsIndexOnTheList;//TODO initialize
public TableFactor(ArrayList<TableVariable> listOfVariables, FunctionTable table) {
this.listOfVariables =listOfVariables;
this.setOfVariables = new LinkedHashSet<>(listOfVariables);
this.table = table;
mapFromVariableToItsIndexOnTheList = new LinkedHashMap<>();
for (int i = 0; i < listOfVariables.size(); i++) {
mapFromVariableToItsIndexOnTheList.put(listOfVariables.get(i),i);
}
}
public TableFactor(ArrayList<TableVariable> listOfVariables, FunctionTable table,
LinkedHashMap<TableVariable, Integer> mapFromVariableToItsIndexOnTheList) {
this.listOfVariables =listOfVariables;
this.setOfVariables = new LinkedHashSet<>(listOfVariables);
this.table = table;
this.mapFromVariableToItsIndexOnTheList = mapFromVariableToItsIndexOnTheList;
}
@Override
public boolean contains(Variable variable) {
boolean res = setOfVariables.contains(variable);
return res;
}
@Override
public List<TableVariable> getVariables() {
ArrayList<TableVariable> res = new ArrayList<>(listOfVariables);
return res;
}
@Override
public Factor multiply(Factor another) {
//Check if the class is the same
if(another.getClass() != this.getClass()) {
Util.println("Trying to multiply different types of factors: this is a " +
this.getClass() + "and another is a " + another.getClass());
}
TableFactor anotherTable = (TableFactor)another;
/*Conventions:
* A = Var(this) \ Var(another)
* B = Var(another) \ Var(this)
* C = Var(another) cap Var(this)
* In other words: Var(this) = AC ; Var(another) = BC
* OR: this = phi(A,C) ; another = phi(B,C), returned type = phi(ABC)
*/
//Defining A, listA and cardA (list with the cardinalities of A)
Set<TableVariable> A = new LinkedHashSet<>(this.setOfVariables);
A.removeAll(anotherTable.setOfVariables);
List<TableVariable> listA = new ArrayList<>(A);
List<Integer> cardA = fillWithCardinality(listA);
//Defining B, listB and cardB
Set<TableVariable> B = new LinkedHashSet<>(anotherTable.setOfVariables);
B.removeAll(this.setOfVariables);
List<TableVariable> listB = new ArrayList<>(B);
List<Integer> cardB = fillWithCardinality(listB);
//Defining C, listC and card
Set<TableVariable> C = new LinkedHashSet<>(anotherTable.setOfVariables);
C.removeAll(B);
List<TableVariable> listC = new ArrayList<>(C);
List<Integer> cardC = fillWithCardinality(listC);
//DefiningABC
ArrayList<TableVariable> listABC = new ArrayList<>();
listABC.addAll(listA);
listABC.addAll(listB);
listABC.addAll(listC);
List<Integer> cardABC = fillWithCardinality(listABC);
LinkedHashMap<TableVariable, Integer> mapFromVariablesAtABCToItsIdxs = new LinkedHashMap<>();
for(int i = 0;i<listABC.size();i++) {
mapFromVariablesAtABCToItsIdxs.put(listABC.get(i), i);
}
//Entry index allows to a find the entry (probability) for a specific instance
//It is tricky without it because the entries are stored as a list
if(cardA.isEmpty()) {
cardA.add(1);
}
if(cardB.isEmpty()) {
cardB.add(1);
}
if(cardC.isEmpty()) {
cardC.add(1);
}
MixedRadixNumber entryIndexA = new MixedRadixNumber(BigInteger.ZERO, cardA);
MixedRadixNumber entryIndexB = new MixedRadixNumber(BigInteger.ZERO, cardB);
MixedRadixNumber entryIndexC = new MixedRadixNumber(BigInteger.ZERO, cardC);
MixedRadixNumber entryIndexABC = new MixedRadixNumber(BigInteger.ZERO, cardABC);
//Initializing entryC with an empty array
Integer nEntriesABC =1;
for(Integer card : cardABC) {
nEntriesABC = nEntriesABC * card;
}
Double[] entryABC = new Double[nEntriesABC];
// For each instance of A,B,C (noted as iA,iB,iC) we do \phi(iA,iB,iC) = \phi(iB,iC) * \phi(iA,iC)
do{
do {
do {
int[] instantiationAtAC = new int[this.listOfVariables.size()];
//Getting the entry at "this"
transferInstantiationsAtOneSubListToAFullList(this.mapFromVariableToItsIndexOnTheList,
listA, entryIndexA, instantiationAtAC);
transferInstantiationsAtOneSubListToAFullList(this.mapFromVariableToItsIndexOnTheList,
listC, entryIndexC, instantiationAtAC);
Double entryAtThis = this.table.entryFor(instantiationAtAC);
//Getting the entry at "another"
int[] instantiationAtBC = new int[anotherTable.listOfVariables.size()];
transferInstantiationsAtOneSubListToAFullList(anotherTable.mapFromVariableToItsIndexOnTheList,
listB, entryIndexB, instantiationAtBC);
transferInstantiationsAtOneSubListToAFullList(anotherTable.mapFromVariableToItsIndexOnTheList,
listC, entryIndexC, instantiationAtBC);
Double entryAtAnother = anotherTable.table.entryFor(instantiationAtBC);
//putting the product of those 2 entries at the right place at ABC
int[] instantiationAtABC = new int[listABC.size()];
transferInstantiationsAtOneSubListToAFullList(mapFromVariablesAtABCToItsIdxs,
listA, entryIndexA, instantiationAtABC);
transferInstantiationsAtOneSubListToAFullList(mapFromVariablesAtABCToItsIdxs,
listB, entryIndexB, instantiationAtABC);
transferInstantiationsAtOneSubListToAFullList(mapFromVariablesAtABCToItsIdxs,
listC, entryIndexC, instantiationAtABC);
Double product = entryAtThis * entryAtAnother;
entryABC[entryIndexABC.getValueFor(instantiationAtABC).intValue()] = product;
}while(entryIndexC.increment());
entryIndexC = new MixedRadixNumber(BigInteger.ZERO, cardC);
}while(entryIndexB.increment());
entryIndexB = new MixedRadixNumber(BigInteger.ZERO, cardB);
}while(entryIndexA.increment());
//TODO return
FunctionTable tableABC = new FunctionTable(cardABC, Arrays.asList(entryABC));
TableFactor result = new TableFactor(listABC, tableABC);
return result;
}
private void transferInstantiationsAtOneSubListToAFullList(Map<TableVariable,Integer> mapFromVariableToItsIndexOnTheList,
List<TableVariable> partialListOfVariables, MixedRadixNumber entryIndexAtPartialList,
int[] instantiationsAtFullList) {
for (int i = 0; i < partialListOfVariables.size(); i++) {
Integer valueAtI = entryIndexAtPartialList.getCurrentNumeralValue(i);
Variable varAtI = partialListOfVariables.get(i);
Integer indexOfVarAtI = mapFromVariableToItsIndexOnTheList.get(varAtI);
instantiationsAtFullList[indexOfVarAtI] = valueAtI;
}
}
private List<Integer> fillWithCardinality(List<TableVariable> list) {
List<Integer> card = new ArrayList<>();
for(TableVariable v:list) {
card.add(v.getCardinality());
}
return card;
}
@Override
public Factor sumOut(List<? extends Variable> variablesToSumOut) {
// redo this function using "valuefor"
//remove var not in set of variables...
//Check if is Table Variable
if(variablesToSumOut == null || variablesToSumOut.isEmpty()) {
return this;
}
if(!(variablesToSumOut.get(0) instanceof TableVariable)){
//TODO error message
}
List<List<Integer>> listOfInstantiationsForTheVariablesToSumOut = getListOfListOfInstantiations(variablesToSumOut);
//List<Integer> cardinalitiesOfVariablesToSumOut = getCardinalitiesOfVarToSumOut(variablesToSumOut);
List<Integer> positionOfEachVariableOnTheListOfVariablesToSumOut = getPositionOfEachVar(variablesToSumOut);
ArrayList<TableVariable> variablesNotToSumOut = getVariablesNotToSumOut(variablesToSumOut);
List<List<Integer>> listOfInstantiationsForTheVariablesNotToSumOut = getListOfListOfInstantiations(variablesNotToSumOut);
List<Integer> cardinalitiesOfVariablesNotToSumOut = getCardinalitiesOfVarToSumOut(variablesNotToSumOut);
List<Integer> positionOfEachVariableOnTheListOfVariablesNotToSumOut = getPositionOfEachVar(variablesNotToSumOut);
Iterator<ArrayList<Integer>> cartesianProductOfVariablesNotToSumOut = getCartesianProductWithValuesOfVariablesToSum(listOfInstantiationsForTheVariablesNotToSumOut);
List<Double> entries = new ArrayList<>();
for(List<Integer> instantiationOfVariablesNotToSumOut : in(cartesianProductOfVariablesNotToSumOut)) {
Double summedEntry = 0.;
Iterator<ArrayList<Integer>> cartesianProductOfVariablesToSumOut = getCartesianProductWithValuesOfVariablesToSum(listOfInstantiationsForTheVariablesToSumOut);
for(List<Integer> instantiationOfVariablesToSumOut : in(cartesianProductOfVariablesToSumOut)) {
List<Integer> instantiationOnListOfAllValues = mappingInstantiationsIntoOneInstantiationAtTheWholeListOfVariables(
positionOfEachVariableOnTheListOfVariablesToSumOut,
positionOfEachVariableOnTheListOfVariablesNotToSumOut,
instantiationOfVariablesNotToSumOut,
instantiationOfVariablesToSumOut);
Double entry = this.table.entryFor(instantiationOnListOfAllValues);
summedEntry = summedEntry + entry;
}
entries.add(summedEntry);
}
FunctionTable resultTable= new FunctionTable(cardinalitiesOfVariablesNotToSumOut, entries);
Factor result = new TableFactor(variablesNotToSumOut, resultTable);
return result;
}
private List<Integer> mappingInstantiationsIntoOneInstantiationAtTheWholeListOfVariables(
List<Integer> positionOfEachVariableOnTheListOfVariablesToSumOut,
List<Integer> positionOfEachVariableOnTheListOfVariablesNotToSumOut,
List<Integer> instantiationOfVariablesNotToSumOut, List<Integer> instantiationOfVariablesToSumOut) {
Integer[] varValues = new Integer[this.listOfVariables.size()];//This is an instantiation in the list of all variables (bigList)
for(int i = 0;i < instantiationOfVariablesNotToSumOut.size();i++){
int correpondentPositionAtBigList = positionOfEachVariableOnTheListOfVariablesNotToSumOut.get(i);
varValues[correpondentPositionAtBigList]=instantiationOfVariablesNotToSumOut.get(i);
}
for(int i = 0;i < instantiationOfVariablesToSumOut.size();i++){
int correpondentPositionAtBigList = positionOfEachVariableOnTheListOfVariablesToSumOut.get(i);
varValues[correpondentPositionAtBigList]=instantiationOfVariablesToSumOut.get(i);
}
List<Integer> instantiationOnListOfAllValues = Arrays.asList(varValues);
return instantiationOnListOfAllValues;
}
private ArrayList<TableVariable> getVariablesNotToSumOut(List<? extends Variable> variablesToSumOut) {
ArrayList<TableVariable> listOfVariablesNotToSumOut = new ArrayList<>();
Set<Variable> setOfvariablesToSumOut = new LinkedHashSet<>(variablesToSumOut);
for(TableVariable v :listOfVariables) {
if(!setOfvariablesToSumOut.contains(v)) {
listOfVariablesNotToSumOut.add(v);
}
}
return listOfVariablesNotToSumOut;
}
private List<Integer> getPositionOfEachVar(List<? extends Variable> variablesToSumOut) {
List<Integer> positionOfEachVariableOnTheList = new ArrayList<>();
for(Variable v:variablesToSumOut) {
positionOfEachVariableOnTheList.add(mapFromVariableToItsIndexOnTheList.get(v));
}
return positionOfEachVariableOnTheList;
}
private List<Integer> getCardinalitiesOfVarToSumOut(List<? extends Variable> variablesToSumOut) {
List<Integer> cardinalitiesOfVariablesToSumOut = new ArrayList<>();
for(Variable v:variablesToSumOut) {
int variableCardinality = ((TableVariable)v).getCardinality();
cardinalitiesOfVariablesToSumOut.add(variableCardinality);
}
return cardinalitiesOfVariablesToSumOut;
}
private List<List<Integer>> getListOfListOfInstantiations(List<? extends Variable> variablesToSumOut) {
List<List<Integer>> listOfValuesForTheVariables = new ArrayList<>();
for(Variable v:variablesToSumOut) {
int variableCardinality = ((TableVariable)v).getCardinality();
ArrayList<Integer> l = new ArrayList<>();
listOfValuesForTheVariables.add(l);
for(int i = 0;i<variableCardinality;i++) {
l.add(i);
}
}
return listOfValuesForTheVariables;
}
private Iterator<ArrayList<Integer>> getCartesianProductWithValuesOfVariablesToSum(List<List<Integer>> listOfValuesForTheVariables) {
ArrayList<NullaryFunction<Iterator<Integer>>> iteratorForListOfVariableValues =
mapIntoArrayList(listOfValuesForTheVariables, element -> () -> element.iterator());
Iterator<ArrayList<Integer>> cartesianProduct = new CartesianProductIterator<Integer>(iteratorForListOfVariableValues);
return cartesianProduct;
}
@Override
public boolean isIdentity() {
List<Double> entries = table.getEntries();
if(entries.size() == 0 || entries.get(0) == 0) {
return false;
}
double valueAtZero = entries.get(0);
for(Double v : entries) {
if (v != valueAtZero) {
return false;
}
}
return true;
}
@Override
public String toString() {
String result = "";
MixedRadixNumber radix = new MixedRadixNumber(BigInteger.ZERO,fillWithCardinality(listOfVariables));
for(int j = 0; j < table.numberEntries();j++) {
if(j != 0) {
result = result + " | ";
}
int nCols = listOfVariables.size();
String s = "";
for (int i = 0; i < nCols; i++) {
s = s + " " + radix.getCurrentNumeralValue(i);
}
radix.increment();
result = result + s + " : " + table.getEntries().get(j);
}
return result;
}
}
|
/*
* Owl2VowlController.java
*
*/
package de.uni_stuttgart.vis.vowl.owl2vowl.server;
import de.uni_stuttgart.vis.vowl.owl2vowl.Owl2Vowl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@RestController
public class Owl2VowlController {
private static final Logger conversionLogger = LogManager.getLogger("conversion");
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Parameter not correct")
@ExceptionHandler(IllegalArgumentException.class)
public void parameterException(Exception e) {
System.out.println("--- Parameter exception: " + e.getMessage());
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Ontology could not be created")
@ExceptionHandler(OWLOntologyCreationException.class)
public void ontologyCreationException(Exception e) {
System.out.println("--- Parameter exception: " + e.getMessage());
}
@RequestMapping(value = {"/owl2vowl", "/converter.php"}, method = RequestMethod.POST)
public String uploadOntology(@RequestParam("ontology") MultipartFile[] files) throws IOException, OWLOntologyCreationException {
if (files == null || files.length == 0) {
throw new IllegalArgumentException("No file uploaded!");
}
List<File> createdFiles = new ArrayList<>();
for (MultipartFile file : files) {
byte[] bytes = file.getBytes();
File serverFile = new File(UUID.randomUUID().toString().replace(" ", "%20"));
while (serverFile.exists()) {
serverFile = new File(UUID.randomUUID().toString().replace(" ", "%20"));
}
try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
stream.write(bytes);
createdFiles.add(serverFile);
} catch (Exception e) {
System.err.println("Error creating file: External file name <" + file.getName() + "> | local file name <" + serverFile.getName() + ">. Reason: " + e.getMessage());
throw new IOException();
}
}
IRI mainIri = IRI.create(createdFiles.get(0));
List<IRI> dependencies = new ArrayList<>();
if (createdFiles.size() > 1) {
for (int i = 1; i < createdFiles.size(); i++) {
File dependency = createdFiles.get(i);
dependencies.add(IRI.create(dependency));
}
}
String jsonAsString;
try {
Owl2Vowl owl2Vowl = new Owl2Vowl(mainIri, dependencies);
jsonAsString = owl2Vowl.getJsonAsString();
} catch (Exception e) {
conversionLogger.info(mainIri + " " + 0);
throw e;
}
return jsonAsString;
}
@RequestMapping(value = {"/owl2vowl", "/converter.php"}, method = RequestMethod.GET)
public String convertIRI(@RequestParam("iri") String iri) throws IOException, OWLOntologyCreationException {
String jsonAsString;
try {
Owl2Vowl owl2Vowl = new Owl2Vowl(IRI.create(iri));
jsonAsString = owl2Vowl.getJsonAsString();
} catch (Exception e) {
conversionLogger.info(iri + " " + 1);
throw e;
}
conversionLogger.info(iri + " " + 0);
return jsonAsString;
}
}
|
package edu.ucar.unidata.rosetta.repository.wizard;
import edu.ucar.unidata.rosetta.domain.wizard.CfTypeData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class JdbcCfTypeDataDao extends JdbcDaoSupport implements CfTypeDataDao {
protected static Logger logger = Logger.getLogger(JdbcCfTypeDataDao.class);
private SimpleJdbcInsert insertActor;
@Override
public CfTypeData lookupCfDataById(String id) throws DataRetrievalFailureException {
String sql = "SELECT * FROM cfTypeData WHERE id = ?";
List<CfTypeData> cfTypeData = getJdbcTemplate().query(sql, new CfTypeDataMapper(), id);
if (cfTypeData.isEmpty()) {
String message = "Unable to find persisted CF type data corresponding to id " + id;
logger.error(message);
throw new DataRetrievalFailureException(message);
}
return cfTypeData.get(0);
}
@Override
public void persistCfTypeData(CfTypeData cfTypeData) throws DataRetrievalFailureException {
// Verify entry doesn't already exist (it shouldn't).
String sql = "SELECT * FROM cfTypeData WHERE id = ?";
List<CfTypeData> persisted = getJdbcTemplate()
.query(sql, new CfTypeDataMapper(), cfTypeData.getId());
// If there is an entry, see that it doesn't contain the data we are about to persist.
if (!persisted.isEmpty()) {
CfTypeData persistedData = persisted.get(0);
if (persistedData.getCfType() != null && persistedData.getCommunity() != null
&& persistedData.getPlatform() != null) {
throw new DataRetrievalFailureException(
"CF type data corresponding to id " + cfTypeData.getId() + " already exists.");
}
} else {
// Persist the CF type data object.
this.insertActor = new SimpleJdbcInsert(getDataSource()).withTableName("cfTypeData");
SqlParameterSource parameters = new BeanPropertySqlParameterSource(cfTypeData);
int rowsAffected = insertActor.execute(parameters);
if (rowsAffected <= 0) {
String message = "Unable to persist CF type data corresponding to id " + cfTypeData.getId();
logger.error(message);
throw new DataRetrievalFailureException(message);
} else {
logger.info("CF type data corresponding to id " + cfTypeData.getId() + " persisted.");
}
}
}
@Override
public void updatePersistedCfTypeData(CfTypeData cfTypeData)
throws DataRetrievalFailureException {
String sql = "UPDATE cfTypeData SET " +
"cfType = ?, " +
"community = ?, " +
"metadataProfile = ?," +
"platform = ? " +
"WHERE id = ?";
int rowsAffected = getJdbcTemplate().update(sql, new Object[]{
// order matters here
cfTypeData.getCfType(),
cfTypeData.getCommunity(),
cfTypeData.getMetadataProfile(),
cfTypeData.getPlatform(),
cfTypeData.getId()
});
if (rowsAffected <= 0) {
String message =
"Unable to update persisted CF type data corresponding to id " + cfTypeData.getId();
logger.error(message);
throw new DataRetrievalFailureException(message);
} else {
logger.info("Updated persisted CF type data corresponding to id " + cfTypeData.getId());
}
}
private static class CfTypeDataMapper implements RowMapper<CfTypeData> {
/**
* Maps each row of data in the ResultSet to the CfTypeData object.
*
* @param rs The ResultSet to be mapped.
* @param rowNum The number of the current row.
* @return The populated CfTypeData object.
* @throws SQLException If an SQLException is encountered getting column values.
*/
public CfTypeData mapRow(ResultSet rs, int rowNum) throws SQLException {
CfTypeData cfTypeData = new CfTypeData();
cfTypeData.setId(rs.getString("id"));
cfTypeData.setCfType(rs.getString("cfType"));
cfTypeData.setCommunity(rs.getString("community"));
cfTypeData.setMetadataProfile(rs.getString("metadataProfile"));
cfTypeData.setPlatform(rs.getString("platform"));
return cfTypeData;
}
}
}
|
package eu.socialsensor.framework.client.search.visual;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class JsonResultSet {
private static DecimalFormat df = new DecimalFormat("
@Expose
@SerializedName(value = "results")
List<JsonResult> results = new ArrayList<JsonResult>();
public void addResult(String id, int rank, double distance) {
JsonResult result = new JsonResult(id, rank, distance);
results.add(result);
}
public List<JsonResult> getResults() {
return results;
}
public class JsonResult {
@Expose
@SerializedName(value = "id")
private String id;
@Expose
@SerializedName(value = "rank")
private int rank;
@Expose
@SerializedName(value = "score")
private String score;
public JsonResult(String id, int rank, double distance) {
this.id = id;
this.rank = rank;
// transform distance into similarity
double similarity = (2.0 - Math.sqrt(distance)) / 2.0;
// format the score
this.score = df.format(similarity);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
public String toJSON() {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
return gson.toJson(this);
}
public static void main(String...args) {
JsonResultSet s = new JsonResultSet();
s.addResult("X", 1, 0.2);
s.addResult("Y", 2, 0.4);
s.addResult("Z", 3, 0.8);
System.out.println(s.toJSON());
}
}
|
package fi.otavanopisto.kuntaapi.server.persistence.model;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.NotEmpty;
/**
* JPA entity representing mapping for external source id to Kunta API Id
*
* @author Otavan Opisto
*/
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "type", "source", "sourceId" }),
@UniqueConstraint(columnNames = { "type", "source", "kuntaApiId" })
})
@Cacheable(true)
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class Identifier {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
@NotNull
@NotEmpty
private String kuntaApiId;
@Column(nullable = false)
@NotNull
@NotEmpty
private String type;
@Column(nullable = false)
@NotNull
@NotEmpty
private String source;
@Column(nullable = false)
@NotNull
@NotEmpty
private String sourceId;
public Long getId() {
return id;
}
public String getKuntaApiId() {
return kuntaApiId;
}
public void setKuntaApiId(String kuntaApiId) {
this.kuntaApiId = kuntaApiId;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package io.github.vcuswimlab.stackintheflow.view;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.ide.browsers.WebBrowserManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.project.Project;
import com.intellij.util.ui.UIUtil;
import io.github.vcuswimlab.stackintheflow.controller.QueryExecutor;
import io.github.vcuswimlab.stackintheflow.model.JerseyGet;
import io.github.vcuswimlab.stackintheflow.model.JerseyResponse;
import io.github.vcuswimlab.stackintheflow.model.Question;
import io.github.vcuswimlab.stackintheflow.model.personalsearch.PersonalSearchModel;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.util.Pair;
import netscape.javascript.JSObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;
public class SearchToolWindowGUI {
private JPanel content;
private Logger logger = LogManager.getLogger("ROLLING_FILE_APPENDER");
private Project project;
private PersonalSearchModel searchModel;
private WebView webView;
private JFXPanel jfxPanel;
private WebEngine engine;
private JSObject window;
private JavaBridge bridge;
private SearchToolWindowGUI(JPanel content, Project project,
PersonalSearchModel searchModel) {
this.content = content;
this.project = project;
this.searchModel = searchModel;
bridge = new JavaBridge(this);
initComponents();
}
private void initComponents(){
ApplicationManager.getApplication().getMessageBus().connect().subscribe(EditorColorsManager.TOPIC, scheme -> updateUISettings());
jfxPanel = new JFXPanel();
createScene();
content.setLayout(new BorderLayout());
content.add(jfxPanel, BorderLayout.CENTER);
Platform.setImplicitExit(false);
}
private void createScene(){
Platform.runLater(() -> {
StackPane root = new StackPane();
Scene scene = new Scene(root);
webView = new WebView();
engine = webView.getEngine();
String htmlFileURL = this.getClass().getClassLoader().getResource("SearchToolWindow.html").toExternalForm();
engine.load(htmlFileURL);
engine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
if(newState == Worker.State.SUCCEEDED) {
window = (JSObject) engine.executeScript("window");
window.setMember("JavaBridge", bridge);
window.call("initialize");
updateUISettings();
}
});
root.getChildren().add(webView);
jfxPanel.setScene(scene);
});
}
public void updateUISettings(){
Platform.runLater(() -> {
boolean isDark = UIUtil.isUnderDarcula();
window.call("updateUISettings", isDark);
});
}
public void autoQuery(String query, boolean backoff, String reasoning){ //reasoning is either "action" or "difficulty"
Platform.runLater(() -> {
window.call("autoSearch", query, backoff, reasoning);
window.call("updateUISearchType", "Relevance");
});
}
public void errorQuery(List<String> parsedMessages, boolean backoff, String reasoning){ //Reasoning is either "runtime" or "compiler"
Platform.runLater(() -> {
Pair<String, List<Question>> questionListPair = retrieveResults(parsedMessages.get(1), "", backoff, JerseyGet.SortType.RELEVANCE);
if(questionListPair.getValue().isEmpty()) {
questionListPair = retrieveResults(parsedMessages.get(0), "", backoff, JerseyGet.SortType.RELEVANCE);
}
window.call("reset");
window.call("resetSearchTags");
window.call("showAutoQueryIcon", reasoning);
window.call("updateUISearchType", "Relevance");
window.call("setSearchBox", questionListPair.getKey());
window.call("addCurrentQueryToHistory");
window.call("logQuery", reasoning);
updateQuestionList(questionListPair.getValue());
});
}
public void executeQuery(String query, String tags, boolean backoff, JerseyGet.SortType sortType, boolean addToQueryHistory, String reasoning) {
Platform.runLater(() -> {
Pair<String, List<Question>> questionListPair = retrieveResults(query, tags, backoff, sortType);
window.call("setSearchBox", questionListPair.getKey());
window.call("logQuery", reasoning);
if(addToQueryHistory) {
window.call("addCurrentQueryToHistory");
}
updateQuestionList(questionListPair.getValue());
});
}
private Pair<String, List<Question>> retrieveResults(String query, String tags, boolean backoff, JerseyGet.SortType sortType) {
String searchQuery = query;
JerseyResponse jerseyResponse = QueryExecutor.executeQuery(searchQuery + " " + tags, sortType);
List<Question> questionList = jerseyResponse.getItems();
if(backoff && questionList.isEmpty()) {
Deque<String> queryStack = new ArrayDeque<>();
queryStack.addAll(Arrays.asList(searchQuery.split("\\s")));
while (questionList.isEmpty() && queryStack.size() > 1) {
queryStack.pop();
searchQuery = queryStack.stream().collect(Collectors.joining(" "));
jerseyResponse = QueryExecutor.executeQuery(searchQuery + " " + tags);
questionList = jerseyResponse.getItems();
}
}
if(sortType.equals(JerseyGet.SortType.RELEVANCE)) {
questionList = searchModel.rankQuestionList(questionList);
}
return new Pair<>(searchQuery, questionList);
}
private void updateQuestionList(List<Question> questions) {
for(Question question : questions){
window.call("getQuestion", question.getTitle(), question.getBody(), question.getTags().toArray(), question.getLink());
}
window.call("displayQuestions");
window.call("generateListeners");
}
public void log(String message){
logger.info(message);
}
public void openBrowser(String url) {
BrowserLauncher.getInstance().browse(url, WebBrowserManager.getInstance().getFirstActiveBrowser());
}
public JPanel getContentPanel() {
return content;
}
public Project getProject() {
return project;
}
public static class SearchToolWindowGUIBuilder {
private JPanel content;
private PersonalSearchModel searchModel;
private Project project;
public SearchToolWindowGUIBuilder setContent(JPanel content) {
this.content = content;
return this;
}
public SearchToolWindowGUIBuilder setSearchModel(PersonalSearchModel searchModel) {
this.searchModel = searchModel;
return this;
}
public SearchToolWindowGUIBuilder setProject(Project project) {
this.project = project;
return this;
}
public SearchToolWindowGUI build() {
return new SearchToolWindowGUI(
content,
project,
searchModel
);
}
}
}
|
package main.flowstoneenergy.items.tools;
import ic2.api.tile.IWrenchable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import main.flowstoneenergy.ModInfo;
import main.flowstoneenergy.interfaces.IFlowWrenchable;
import main.flowstoneenergy.utils.KeyboardHelper;
import main.flowstoneenergy.utils.TextHelper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockButton;
import net.minecraft.block.BlockChest;
import net.minecraft.block.BlockLever;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import api.java.buildcraft.api.tools.IToolWrench;
public class ItemToolPneumaticFlowwrench extends ItemToolFlowwrench implements IToolWrench{
Random rand = new Random();
private int maxFE = 10000;
public int currentFE = 0;
private final Set<Class<? extends Block>> shiftRotations = new HashSet<Class<? extends Block>>();
public ItemToolPneumaticFlowwrench() {
super();
this.setUnlocalizedName(ModInfo.MODID + ".pneumatic.flowwrench");
this.setTextureName(ModInfo.MODID + ":tools/pneumaticFlowwrench");
shiftRotations.add(BlockLever.class);
shiftRotations.add(BlockButton.class);
shiftRotations.add(BlockChest.class);
}
private boolean isShiftRotation(Class<? extends Block> cls) {
for (Class<? extends Block> shift : shiftRotations) {
if (shift.isAssignableFrom(cls)) {
return true;
}
}
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) {
list.add(TextHelper.shiftForMoreInfo);
if (!KeyboardHelper.isShiftDown()) {
return;
}
list.remove(1);
list.add(currentFE + "/" + maxFE + "FE Stored");
}
@Override
public boolean canWrench(EntityPlayer player, int x, int y, int z) {
return true;
}
@Override
public void wrenchUsed(EntityPlayer player, int x, int y, int z) {
}
@Override
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int hitSide, float hitX, float hitY, float hitZ) {
Block block = world.getBlock(x, y, z);
TileEntity te = world.getTileEntity(x, y, z);
if (block instanceof IFlowWrenchable) {
if (player.isSneaking()) {
world.setBlock(x, y, z, Blocks.air);
if (!world.isRemote) {
world.spawnEntityInWorld(new EntityItem(world, (double) x, (double) y, (double) z, new ItemStack(block)));
}
itemStack.damageItem(1, player);
}
}
//IC2
if (te instanceof IWrenchable) {
System.out.println("Test");
IWrenchable wrenchable = (IWrenchable)te;
ItemStack wrenchDrop = wrenchable.getWrenchDrop(player);
ArrayList<ItemStack> drops = block.getDrops(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
if (player.isSneaking()) {
hitSide = opposite[hitSide];
}
if (wrenchable.wrenchCanSetFacing(player, hitSide)) {
if (!world.isRemote) {
wrenchable.setFacing((short) hitSide);
}
} else if (wrenchable.wrenchCanRemove(player)) {
if (wrenchDrop != null) {
if (drops.isEmpty()) {
drops.add(wrenchDrop);
} else {
drops.set(0, wrenchDrop);
}
}
world.setBlockToAir(x, y, z);
if (!world.isRemote) {
for (ItemStack drop: drops) {
world.spawnEntityInWorld(new EntityItem(world, (double) x, (double) y, (double) z, drop));
}
}
}
}
if (block == null) {
return false;
}
if (player.isSneaking() != isShiftRotation(block.getClass())) {
return false;
}
if (block.rotateBlock(world, x, y, z, ForgeDirection.getOrientation(hitSide))) {
player.swingItem();
return !world.isRemote;
}
return true;
}
}
|
package mcjty.lostcities.dimensions.world;
import mcjty.lostcities.dimensions.world.lost.*;
import mcjty.lostcities.dimensions.world.lost.cityassets.AssetRegistries;
import mcjty.lostcities.dimensions.world.lost.cityassets.BuildingPart;
import mcjty.lostcities.dimensions.world.lost.cityassets.CompiledPalette;
import mcjty.lostcities.varia.GeometryTools;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Biomes;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.ChunkPrimer;
import java.util.*;
import java.util.function.BiFunction;
public class LostCitiesTerrainGenerator extends NormalTerrainGenerator {
private final byte groundLevel;
private final byte waterLevel;
private static IBlockState bedrock;
public static IBlockState air;
public static IBlockState hardAir; // Used in parts to carve out
public static IBlockState water;
private IBlockState baseBlock;
private IBlockState street;
private IBlockState streetBase;
private IBlockState street2;
private IBlockState bricks;
private int streetBorder;
public LostCitiesTerrainGenerator(LostCityChunkGenerator provider) {
super(provider);
this.groundLevel = (byte) provider.profile.GROUNDLEVEL;
this.waterLevel = (byte) (provider.profile.WATERLEVEL);
}
// Use this random when it doesn't really matter i fit is generated the same every time
public static Random globalRandom = new Random();
// Note that for normal chunks this is called with a pre-filled in landscape primer
public void generate(int chunkX, int chunkZ, ChunkPrimer primer) {
baseBlock = Blocks.STONE.getDefaultState();
BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider);
air = Blocks.AIR.getDefaultState();
hardAir = Blocks.COMMAND_BLOCK.getDefaultState();
water = Blocks.WATER.getDefaultState();
bedrock = Blocks.BEDROCK.getDefaultState();
street = info.getCompiledPalette().get(info.getCityStyle().getStreetBlock());
streetBase = info.getCompiledPalette().get(info.getCityStyle().getStreetBaseBlock());
street2 = info.getCompiledPalette().get(info.getCityStyle().getStreetVariantBlock());
streetBorder = (16 - info.getCityStyle().getStreetWidth()) / 2;
// @todo This should not be hardcoded here
bricks = info.getCompiledPalette().get('
if (info.isCity) {
doCityChunk(chunkX, chunkZ, primer, info);
} else {
// We already have a prefilled core chunk (as generated from doCoreChunk)
doNormalChunk(chunkX, chunkZ, primer, info);
}
// We make a new random here because the primer for a normal chunk may have
// been cached and we want to be able to do the same when returning from a cached
// primer vs generating it here
provider.rand.setSeed(chunkX * 257017164707L + chunkZ * 101754694003L);
if (info.getDamageArea().hasExplosions()) {
breakBlocksForDamage(chunkX, chunkZ, primer, info);
fixAfterExplosion(primer, chunkX, chunkZ, info, provider.rand);
}
generateDebris(primer, provider.rand, info);
}
public void doCoreChunk(int chunkX, int chunkZ, ChunkPrimer primer) {
int cx = chunkX * 16;
int cz = chunkZ * 16;
char base = (char) Block.BLOCK_STATE_IDS.get(baseBlock);
char liquid = (char) Block.BLOCK_STATE_IDS.get(water);
generateHeightmap(chunkX * 4, 0, chunkZ * 4);
for (int x4 = 0; x4 < 4; ++x4) {
int l = x4 * 5;
int i1 = (x4 + 1) * 5;
for (int z4 = 0; z4 < 4; ++z4) {
int k1 = (l + z4) * 33;
int l1 = (l + z4 + 1) * 33;
int i2 = (i1 + z4) * 33;
int j2 = (i1 + z4 + 1) * 33;
for (int height32 = 0; height32 < 32; ++height32) {
double d1 = heightMap[k1 + height32];
double d2 = heightMap[l1 + height32];
double d3 = heightMap[i2 + height32];
double d4 = heightMap[j2 + height32];
double d5 = (heightMap[k1 + height32 + 1] - d1) * 0.125D;
double d6 = (heightMap[l1 + height32 + 1] - d2) * 0.125D;
double d7 = (heightMap[i2 + height32 + 1] - d3) * 0.125D;
double d8 = (heightMap[j2 + height32 + 1] - d4) * 0.125D;
for (int h = 0; h < 8; ++h) {
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * 0.25D;
double d13 = (d4 - d2) * 0.25D;
int height = (height32 * 8) + h;
for (int x = 0; x < 4; ++x) {
int index = ((x + (x4 * 4)) << 12) | ((0 + (z4 * 4)) << 8) | height;
short maxheight = 256;
index -= maxheight;
double d16 = (d11 - d10) * 0.25D;
double d15 = d10 - d16;
for (int z = 0; z < 4; ++z) {
index += maxheight;
if ((d15 += d16) > 0.0D) {
BaseTerrainGenerator.setBlockState(primer, index, base);
} else if (height < waterLevel) {
BaseTerrainGenerator.setBlockState(primer, index, liquid);
}
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
}
public void doNormalChunk(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info) {
flattenChunkToCityBorder(chunkX, chunkZ, primer, info);
generateBridges(chunkX, chunkZ, primer, info);
generateHighways(chunkX, chunkZ, primer, info);
}
private void breakBlocksForDamage(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info) {
int cx = chunkX * 16;
int cz = chunkZ * 16;
DamageArea damageArea = info.getDamageArea();
char air = (char) Block.BLOCK_STATE_IDS.get(LostCitiesTerrainGenerator.air);
char liquid = (char) Block.BLOCK_STATE_IDS.get(water);
for (int yy = 0; yy < 16; yy++) {
if (damageArea.hasExplosions(yy)) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int index = (x << 12) | (z << 8) + yy * 16;
for (int y = 0 ; y < 16 ; y++) {
char d = primer.data[index];
if (d != air && d != liquid) {
IBlockState b = Block.BLOCK_STATE_IDS.getByValue(d);
IBlockState newb = damageArea.damageBlock(b, provider, cx + x, y, cz + z, info.getCompiledPalette());
if (newb != b) {
BaseTerrainGenerator.setBlockState(primer, index, b);
}
}
index++;
}
}
}
}
}
}
private void generateHighways(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info) {
int levelX = Highway.getXHighwayLevel(chunkX, chunkZ, provider);
int levelZ = Highway.getZHighwayLevel(chunkX, chunkZ, provider);
if (levelX == levelZ && levelX >= 0) {
// Crossing
generateHighwayPart(chunkX, chunkZ, primer, info, levelX, Rotation.ROTATE_NONE, info.getXmax(), info.getZmax(), "_bi");
} else if (levelX >= 0 && levelZ >= 0) {
// There are two highways on different level. Make sure the lowest one is done first because it
// will clear out what is above it
if (levelX == 0) {
generateHighwayPart(chunkX, chunkZ, primer, info, levelX, Rotation.ROTATE_NONE, info.getZmin(), info.getZmax(), "");
generateHighwayPart(chunkX, chunkZ, primer, info, levelZ, Rotation.ROTATE_90, info.getXmax(), info.getXmax(), "");
} else {
generateHighwayPart(chunkX, chunkZ, primer, info, levelZ, Rotation.ROTATE_90, info.getXmax(), info.getXmax(), "");
generateHighwayPart(chunkX, chunkZ, primer, info, levelX, Rotation.ROTATE_NONE, info.getZmin(), info.getZmax(), "");
}
} else {
if (levelX >= 0) {
generateHighwayPart(chunkX, chunkZ, primer, info, levelX, Rotation.ROTATE_NONE, info.getZmin(), info.getZmax(), "");
} else if (levelZ >= 0) {
generateHighwayPart(chunkX, chunkZ, primer, info, levelZ, Rotation.ROTATE_90, info.getXmax(), info.getXmax(), "");
}
}
}
private void generateHighwayPart(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info, int level, Rotation rotation, BuildingInfo adjacent1, BuildingInfo adjacent2, String suffix) {
char a = (char) Block.BLOCK_STATE_IDS.get(LostCitiesTerrainGenerator.air);
char l = (char) Block.BLOCK_STATE_IDS.get(water);
int cx = chunkX * 16;
int cz = chunkZ * 16;
int highwayGroundLevel = provider.profile.GROUNDLEVEL + level * 6;
int height;
if (info.isTunnel(level)) {
// We know we need a tunnel
height = generatePart(primer, info, AssetRegistries.PARTS.get("highway_tunnel" + suffix), rotation, chunkX, chunkZ, 0, highwayGroundLevel, 0);
} else if (info.isCity && level <= adjacent1.cityLevel && level <= adjacent2.cityLevel && adjacent1.isCity && adjacent2.isCity) {
// Simple highway in the city
height = generatePart(primer, info, AssetRegistries.PARTS.get("highway_open" + suffix), rotation, chunkX, chunkZ, 0, highwayGroundLevel, 0);
// Clear a bit more above the highway
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int index = (x << 12) | (z << 8) + height;
BaseTerrainGenerator.setBlockStateRange(primer, index, index + 15, air);
}
}
} else {
height = generatePart(primer, info, AssetRegistries.PARTS.get("highway_bridge" + suffix), rotation, chunkX, chunkZ, 0, highwayGroundLevel, 0);
// Clear a bit more above the highway
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int index = (x << 12) | (z << 8) + height;
BaseTerrainGenerator.setBlockStateRange(primer, index, index + 15, air);
}
}
}
// Make sure the bridge is supported if needed
if (rotation == Rotation.ROTATE_NONE) {
int index = highwayGroundLevel - 1; // (coordinate 0,0)
height = index;
for (int y = 0; y < 40; y++) {
boolean done = false;
if (primer.data[index] == a || primer.data[index] == l) {
BaseTerrainGenerator.setBlockState(primer, index, Blocks.STONEBRICK.getDefaultState());
done = true;
}
if (primer.data[index + (15 << 8)] == a || primer.data[index + (15 << 8)] == l) {
BaseTerrainGenerator.setBlockState(primer, index + (15 << 8), Blocks.STONEBRICK.getDefaultState());
done = true;
}
index
height
if (!done) {
break;
}
}
} else {
int index = highwayGroundLevel - 1; // (coordinate 0,0)
height = index;
for (int y = 0; y < 40; y++) {
boolean done = false;
if (primer.data[index] == a || primer.data[index] == l) {
BaseTerrainGenerator.setBlockState(primer, index, Blocks.STONEBRICK.getDefaultState());
done = true;
}
if (primer.data[index + (15 << 12)] == a || primer.data[index + (15 << 12)] == l) {
BaseTerrainGenerator.setBlockState(primer, index + (15 << 12), Blocks.STONEBRICK.getDefaultState());
done = true;
}
index
height
if (!done) {
break;
}
}
}
}
private void generateBridges(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info) {
if (info.getHighwayXLevel() == 0 || info.getHighwayZLevel() == 0) {
// If there is a highway at level 0 we cannot generate bridge parts. If there
// is no highway or a highway at level 1 then bridge sections can generate just fine
return;
}
BuildingPart bt = info.hasXBridge(provider);
if (bt != null) {
generateBridge(chunkX, chunkZ, primer, info, bt, Orientation.X);
} else {
bt = info.hasZBridge(provider);
if (bt != null) {
generateBridge(chunkX, chunkZ, primer, info, bt, Orientation.Z);
}
}
}
private void generateBridge(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info, BuildingPart bt, Orientation orientation) {
int cx = chunkX * 16;
int cz = chunkZ * 16;
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int index = (x << 12) | (z << 8) + groundLevel + 1;
int height = groundLevel + 1;
int l = 0;
while (l < bt.getSliceCount()) {
IBlockState b = orientation == Orientation.X ? bt.get(info, x, l, z) : bt.get(info, z, l, x); // @todo general rotation system?
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
l++;
}
}
}
BuildingInfo minDir = orientation.getMinDir().get(info);
BuildingInfo maxDir = orientation.getMaxDir().get(info);
if (minDir.hasBridge(provider, orientation) != null && maxDir.hasBridge(provider, orientation) != null) {
// Needs support
for (int y = waterLevel - 10; y <= groundLevel; y++) {
setBridgeSupport(primer, cx, cz, 7, y, 7);
setBridgeSupport(primer, cx, cz, 7, y, 8);
setBridgeSupport(primer, cx, cz, 8, y, 7);
setBridgeSupport(primer, cx, cz, 8, y, 8);
}
}
if (minDir.hasBridge(provider, orientation) == null) {
// Connection to the side section
if (orientation == Orientation.X) {
int x = 0;
for (int z = 6; z <= 9; z++) {
int index = (x << 12) | (z << 8) + groundLevel;
IBlockState b = Blocks.STONEBRICK.getDefaultState();
BaseTerrainGenerator.setBlockState(primer, index, b);
}
} else {
int z = 0;
for (int x = 6; x <= 9; x++) {
int index = (x << 12) | (z << 8) + groundLevel;
IBlockState b = Blocks.STONEBRICK.getDefaultState();
BaseTerrainGenerator.setBlockState(primer, index, b);
}
}
}
if (maxDir.hasBridge(provider, orientation) == null) {
// Connection to the side section
if (orientation == Orientation.X) {
int x = 15;
for (int z = 6; z <= 9; z++) {
int index = (x << 12) | (z << 8) + groundLevel;
IBlockState b = Blocks.STONEBRICK.getDefaultState();
BaseTerrainGenerator.setBlockState(primer, index, b);
}
} else {
int z = 15;
for (int x = 6; x <= 9; x++) {
int index = (x << 12) | (z << 8) + groundLevel;
IBlockState b = Blocks.STONEBRICK.getDefaultState();
BaseTerrainGenerator.setBlockState(primer, index, b);
}
}
}
}
private void setBridgeSupport(ChunkPrimer primer, int cx, int cz, int x, int y, int z) {
int index = (x << 12) | (z << 8) + y;
IBlockState b = Blocks.STONEBRICK.getDefaultState();
BaseTerrainGenerator.setBlockState(primer, index, b);
}
private void flattenChunkToCityBorder(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info) {
int cx = chunkX * 16;
int cz = chunkZ * 16;
List<GeometryTools.AxisAlignedBB2D> boxes = new ArrayList<>();
List<GeometryTools.AxisAlignedBB2D> boxesDownwards = new ArrayList<>();
for (int x = -1; x <= 1; x++) {
for (int z = -1; z <= 1; z++) {
if (x != 0 || z != 0) {
int ccx = chunkX + x;
int ccz = chunkZ + z;
BuildingInfo info2 = BuildingInfo.getBuildingInfo(ccx, ccz, provider);
if (info2.isCity) {
GeometryTools.AxisAlignedBB2D box = new GeometryTools.AxisAlignedBB2D(ccx * 16, ccz * 16, ccx * 16 + 15, ccz * 16 + 15);
box.height = info2.getCityGroundLevel();
boxes.add(box);
} else if (info2.getMaxHighwayLevel() >= 0 && !info2.isTunnel(info2.getMaxHighwayLevel())) {
// There is a highway but no tunnel. So we need to smooth downwards
GeometryTools.AxisAlignedBB2D box = new GeometryTools.AxisAlignedBB2D(ccx * 16, ccz * 16, ccx * 16 + 15, ccz * 16 + 15);
box.height = provider.profile.GROUNDLEVEL + info2.getMaxHighwayLevel() * 6;
boxesDownwards.add(box);
}
}
}
}
if (!boxes.isEmpty()) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
double mindist = 1000000000.0;
int minheight = 1000000000;
for (GeometryTools.AxisAlignedBB2D box : boxes) {
double dist = GeometryTools.squaredDistanceBoxPoint(box, cx + x, cz + z);
if (dist < mindist) {
mindist = dist;
}
if (box.height < minheight) {
minheight = box.height;
}
}
int height = minheight;//info.getCityGroundLevel();
if (isOcean(provider.biomesForGeneration)) {
// We have an ocean biome here. Flatten to a lower level
height = waterLevel + 4;
}
int offset = (int) (Math.sqrt(mindist) * 2);
flattenChunkBorder(primer, x, offset, z, provider.rand, info, cx, cz, height);
}
}
}
if (!boxesDownwards.isEmpty()) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
double mindist = 1000000000.0;
int minheight = 1000000000;
for (GeometryTools.AxisAlignedBB2D box : boxesDownwards) {
double dist = GeometryTools.squaredDistanceBoxPoint(box, cx + x, cz + z);
if (dist < mindist) {
mindist = dist;
}
if (box.height < minheight) {
minheight = box.height;
}
}
int height = minheight;//info.getCityGroundLevel();
if (isOcean(provider.biomesForGeneration)) {
// We have an ocean biome here. Flatten to a lower level
height = waterLevel + 4;
}
int offset = (int) (Math.sqrt(mindist) * 2);
flattenChunkBorderDownwards(primer, x, offset, z, provider.rand, info, cx, cz, height);
}
}
}
}
public static boolean isOcean(Biome[] biomes) {
for (Biome biome : biomes) {
if (biome != Biomes.OCEAN && biome != Biomes.DEEP_OCEAN && biome != Biomes.FROZEN_OCEAN) {
return false;
}
}
return true;
}
public static boolean isWaterBiome(LostCityChunkGenerator provider, int chunkX, int chunkZ) {
Biome[] biomes = provider.worldObj.getBiomeProvider().getBiomesForGeneration(null, (chunkX - 1) * 4 - 2, chunkZ * 4 - 2, 10, 10);
return isWaterBiome(biomes[55]) || isWaterBiome(biomes[54]) || isWaterBiome(biomes[56]);
// return isWaterBiome(biomes);
}
public static boolean isWaterBiome(Biome[] biomes) {
for (Biome biome : biomes) {
if (!isWaterBiome(biome)) {
return false;
}
}
return true;
}
private static boolean isWaterBiome(Biome biome) {
return !(biome != Biomes.OCEAN && biome != Biomes.DEEP_OCEAN && biome != Biomes.FROZEN_OCEAN
&& biome != Biomes.RIVER && biome != Biomes.FROZEN_RIVER && biome != Biomes.BEACH && biome != Biomes.COLD_BEACH);
}
private void flattenChunkBorder(ChunkPrimer primer, int x, int offset, int z, Random rand, BuildingInfo info, int cx, int cz, int level) {
int index = (x << 12) | (z << 8);
for (int y = 0; y <= (level - offset - rand.nextInt(2)); y++) {
IBlockState b = BaseTerrainGenerator.getBlockState(primer, index);
if (b != bedrock) {
if (b != baseBlock) {
b = baseBlock;
BaseTerrainGenerator.setBlockState(primer, index, b);
}
}
index++;
}
int r = rand.nextInt(2);
index = (x << 12) | (z << 8) + level + offset + r;
for (int y = level + offset + 3; y < 256; y++) {
IBlockState b = BaseTerrainGenerator.getBlockState(primer, index);
if (b != air) {
BaseTerrainGenerator.setBlockState(primer, index, air);
}
index++;
}
}
private void flattenChunkBorderDownwards(ChunkPrimer primer, int x, int offset, int z, Random rand, BuildingInfo info, int cx, int cz, int level) {
int r = rand.nextInt(2);
int index = (x << 12) | (z << 8) + level + offset + r;
for (int y = level + offset + 3; y < 256; y++) {
IBlockState b = BaseTerrainGenerator.getBlockState(primer, index);
if (b != air) {
BaseTerrainGenerator.setBlockState(primer, index, air);
}
index++;
}
}
private void doCityChunk(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info) {
boolean building = info.hasBuilding;
Random rand = new Random(provider.seed * 377 + chunkZ * 341873128712L + chunkX * 132897987541L);
rand.nextFloat();
rand.nextFloat();
int index = 0;
for (int x = 0; x < 16; ++x) {
for (int z = 0; z < 16; ++z) {
int height = 0;
while (height < provider.profile.BEDROCK_LAYER) {
BaseTerrainGenerator.setBlockState(primer, index++, bedrock);
height++;
}
while (height < provider.profile.BEDROCK_LAYER + 30 + rand.nextInt(3)) {
BaseTerrainGenerator.setBlockState(primer, index++, baseBlock);
height++;
}
if (building) {
index = generateBuilding(primer, info, rand, chunkX, chunkZ, index, x, z, height);
} else {
index = generateStreet(primer, info, rand, chunkX, chunkZ, index, x, z, height);
}
}
}
if (!building) {
int levelX = info.getHighwayXLevel();
int levelZ = info.getHighwayZLevel();
if (levelX < 0 && levelZ < 0) {
generateStreetDecorations(chunkX, chunkZ, primer, info, rand);
} else {
generateHighways(chunkX, chunkZ, primer, info);
}
}
}
private void generateStreetDecorations(int chunkX, int chunkZ, ChunkPrimer primer, BuildingInfo info, Random rand) {
Direction stairDirection = info.getActualStairDirection();
if (stairDirection != null) {
BuildingPart stairs = info.stairType;
Rotation rotation;
int oy = info.getCityGroundLevel() + 1;
switch (stairDirection) {
case XMIN:
rotation = Rotation.ROTATE_NONE;
break;
case XMAX:
rotation = Rotation.ROTATE_180;
break;
case ZMIN:
rotation = Rotation.ROTATE_90;
break;
case ZMAX:
rotation = Rotation.ROTATE_270;
break;
default:
throw new RuntimeException("Cannot happen!");
}
generatePart(primer, info, stairs, rotation, chunkX, chunkZ, 0, oy, 0);
}
}
private static class Blob {
private final int starty;
private final int endy;
private Set<Integer> connectedBlocks = new HashSet<>();
private final Map<Integer, Integer> blocksPerY = new HashMap<>();
private int connections = 0;
private int lowestY;
private int highestY;
private float avgdamage;
private int cntMindamage; // Number of blocks that receive almost no damage
public Blob(int starty, int endy) {
this.starty = starty;
this.endy = endy;
lowestY = 256;
highestY = 0;
}
public float getAvgdamage() {
return avgdamage;
}
public int getCntMindamage() {
return cntMindamage;
}
public boolean contains(int index) {
return connectedBlocks.contains(index);
}
public int getLowestY() {
return lowestY;
}
public int getHighestY() {
return highestY;
}
public Set<Integer> cut(int y) {
Set<Integer> toRemove = new HashSet<>();
for (Integer block : connectedBlocks) {
if ((block & 255) >= y) {
toRemove.add(block);
}
}
connectedBlocks.removeAll(toRemove);
return toRemove;
}
public int needsSplitting() {
float averageBlocksPerLevel = (float) connectedBlocks.size() / (highestY - lowestY + 1);
int connectionThresshold = (int) (averageBlocksPerLevel / 10);
if (connectionThresshold <= 0) {
// Too small to split
return -1;
}
int cuttingY = -1; // Where we will cut
int cuttingCount = 1000000;
int below = 0;
for (int y = lowestY; y <= highestY; y++) {
if (y >= 3 && blocksPerY.get(y) <= connectionThresshold) {
if (blocksPerY.get(y) < cuttingCount) {
cuttingCount = blocksPerY.get(y);
cuttingY = y;
} else if (blocksPerY.get(y) > cuttingCount * 4) {
return cuttingY;
}
}
}
return -1;
}
public boolean destroyOrMoveThis(LostCityChunkGenerator provider) {
return connections < 5 || (((float) connections / connectedBlocks.size()) < provider.profile.DESTROY_LONE_BLOCKS_FACTOR);
}
private boolean isOutside(BuildingInfo info, int x, int y, int z) {
if (x < 0) {
if (y <= info.getXmin().getMaxHeight() + 3) {
connections++;
}
return true;
}
if (x > 15) {
if (y <= info.getXmax().getMaxHeight() + 3) {
connections++;
}
return true;
}
if (z < 0) {
if (y <= info.getZmin().getMaxHeight() + 3) {
connections++;
}
return true;
}
if (z > 15) {
if (y <= info.getZmax().getMaxHeight() + 3) {
connections++;
}
return true;
}
if (y < starty) {
connections += 5;
return true;
}
return false;
}
public void scan(BuildingInfo info, ChunkPrimer primer, char air, char liquid, BlockPos pos) {
DamageArea damageArea = info.getDamageArea();
avgdamage = 0;
cntMindamage = 0;
Queue<BlockPos> todo = new ArrayDeque<>();
todo.add(pos);
while (!todo.isEmpty()) {
pos = todo.poll();
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
int index = calcIndex(x, y, z);
if (connectedBlocks.contains(index)) {
continue;
}
if (isOutside(info, x, y, z)) {
continue;
}
if (primer.data[index] == air || primer.data[index] == liquid) {
continue;
}
connectedBlocks.add(index);
float damage = damageArea.getDamage(x, y, z);
if (damage < 0.01f) {
cntMindamage++;
}
avgdamage += damage;
if (!blocksPerY.containsKey(y)) {
blocksPerY.put(y, 1);
} else {
blocksPerY.put(y, blocksPerY.get(y) + 1);
}
if (y < lowestY) {
lowestY = y;
}
if (y > highestY) {
highestY = y;
}
todo.add(pos.up());
todo.add(pos.down());
todo.add(pos.east());
todo.add(pos.west());
todo.add(pos.south());
todo.add(pos.north());
}
avgdamage /= (float) connectedBlocks.size();
}
public static int calcIndex(int x, int y, int z) {
return (x << 12) | (z << 8) + y;
}
}
private Blob findBlob(List<Blob> blobs, int index) {
for (Blob blob : blobs) {
if (blob.contains(index)) {
return blob;
}
}
return null;
}
/// Fix floating blocks after an explosion
private void fixAfterExplosion(ChunkPrimer primer, int chunkX, int chunkZ, BuildingInfo info, Random rand) {
// int start = info.getCityGroundLevel() - info.floorsBelowGround * 6;
int start = info.getDamageArea().getLowestExplosionHeight();
// int end = info.getMaxHeight() + 20;//@todo 6;
int end = info.getDamageArea().getHighestExplosionHeight();
char air = (char) Block.BLOCK_STATE_IDS.get(LostCitiesTerrainGenerator.air);
char liquid = (char) Block.BLOCK_STATE_IDS.get(water);
List<Blob> blobs = new ArrayList<>();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int index = (x << 12) | (z << 8) + start;
for (int y = start; y < end; y++) {
char p = primer.data[index];
if (p != air) {
Blob blob = findBlob(blobs, index);
if (blob == null) {
blob = new Blob(start, end + 6);
blob.scan(info, primer, air, liquid, new BlockPos(x, y, z));
blobs.add(blob);
}
}
index++;
}
}
}
// Split large blobs that have very thin connections in Y direction
for (Blob blob : blobs) {
if (blob.getAvgdamage() > .3f && blob.getCntMindamage() < 10) { // @todo configurable?
int y = blob.needsSplitting();
if (y != -1) {
Set<Integer> toRemove = blob.cut(y);
for (Integer index : toRemove) {
primer.data[index] = ((index & 0xff) < waterLevel) ? liquid : air;
}
}
}
}
// Sort all blobs we delete with lowest first
blobs.sort((o1, o2) -> {
int y1 = o1.destroyOrMoveThis(provider) ? o1.lowestY : 1000;
int y2 = o2.destroyOrMoveThis(provider) ? o2.lowestY : 1000;
return y1 - y2;
});
Blob blocksToMove = new Blob(0, 256);
for (Blob blob : blobs) {
if (!blob.destroyOrMoveThis(provider)) {
// The rest of the blobs doesn't have to be destroyed anymore
break;
}
if (rand.nextFloat() < provider.profile.DESTROY_OR_MOVE_CHANCE || blob.connectedBlocks.size() < provider.profile.DESTROY_SMALL_SECTIONS_SIZE
|| blob.connections < 5) {
for (Integer index : blob.connectedBlocks) {
primer.data[index] = ((index & 0xff) < waterLevel) ? liquid : air;
}
} else {
blocksToMove.connectedBlocks.addAll(blob.connectedBlocks);
}
}
for (Integer index : blocksToMove.connectedBlocks) {
char c = primer.data[index];
primer.data[index] = ((index & 0xff) < waterLevel) ? liquid : air;
index
int y = index & 255;
while (y > 2 && (blocksToMove.contains(index) || primer.data[index] == air || primer.data[index] == liquid)) {
index
y
}
index++;
primer.data[index] = c;
}
}
private int generateStreet(ChunkPrimer primer, BuildingInfo info, Random rand, int chunkX, int chunkZ, int index, int x, int z, int height) {
int cx = chunkX * 16;
int cz = chunkZ * 16;
boolean xRail = info.hasXCorridor();
boolean zRail = info.hasZCorridor();
boolean doOceanBorder = isDoOceanBorder(info, chunkX, chunkZ, x, z);
IBlockState railx = Blocks.RAIL.getDefaultState().withProperty(BlockRail.SHAPE, BlockRailBase.EnumRailDirection.EAST_WEST);
IBlockState railz = Blocks.RAIL.getDefaultState();
while (height < info.getCityGroundLevel()) {
IBlockState b = baseBlock;
if (doOceanBorder) {
b = Blocks.STONEBRICK.getDefaultState();
} else if (height >= groundLevel - 5 && height <= groundLevel - 1) { // This uses actual ground level for now
if (height <= groundLevel - 2 && ((xRail && z >= 7 && z <= 10) || (zRail && x >= 7 && x <= 10))) {
b = air;
if (height == groundLevel - 5 && xRail && z == 10) {
b = railx;
}
if (height == groundLevel - 5 && zRail && x == 10) {
b = railz;
}
if (height == groundLevel - 2) {
if ((xRail && x == 7 && (z == 8 || z == 9)) || (zRail && z == 7 && (x == 8 || x == 9))) {
b = Blocks.GLASS.getDefaultState();
} else {
b = Blocks.STONEBRICK.getDefaultState();
}
}
} else if (height == groundLevel - 1 && ((xRail && x == 7 && (z == 8 || z == 9)) || (zRail && z == 7 && (x == 8 || x == 9)))) {
b = Blocks.GLOWSTONE.getDefaultState();
}
}
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
IBlockState b;
if (info.getHighwayXLevel() != info.cityLevel && info.getHighwayZLevel() != info.cityLevel) {
BuildingInfo.StreetType streetType = info.streetType;
boolean elevated = info.isElevatedParkSection();
if (elevated) {
streetType = BuildingInfo.StreetType.PARK;
BaseTerrainGenerator.setBlockState(primer, index++, Blocks.STONEBRICK.getDefaultState());
height++;
}
b = streetBase;
switch (streetType) {
case NORMAL:
if (isStreetBorder(x, z)) {
if (x <= streetBorder && z > streetBorder && z < (15 - streetBorder)
&& (BuildingInfo.hasRoadConnection(info, info.getXmin()) || (info.getXmin().hasXBridge(provider) != null))) {
b = street;
} else if (x >= (15 - streetBorder) && z > streetBorder && z < (15 - streetBorder)
&& (BuildingInfo.hasRoadConnection(info, info.getXmax()) || (info.getXmax().hasXBridge(provider) != null))) {
b = street;
} else if (z <= streetBorder && x > streetBorder && x < (15 - streetBorder)
&& (BuildingInfo.hasRoadConnection(info, info.getZmin()) || (info.getZmin().hasZBridge(provider) != null))) {
b = street;
} else if (z >= (15 - streetBorder) && x > streetBorder && x < (15 - streetBorder)
&& (BuildingInfo.hasRoadConnection(info, info.getZmax()) || (info.getZmax().hasZBridge(provider) != null))) {
b = street;
}
} else {
b = street;
}
break;
case FULL:
if (isSide(x, z)) {
b = street;
} else {
b = street2;
}
break;
case PARK:
if (x == 0 || x == 15 || z == 0 || z == 15) {
b = street;
if (elevated) {
boolean el00 = info.getXmin().getZmin().isElevatedParkSection();
boolean el10 = info.getZmin().isElevatedParkSection();
boolean el20 = info.getXmax().getZmin().isElevatedParkSection();
boolean el01 = info.getXmin().isElevatedParkSection();
boolean el21 = info.getXmax().isElevatedParkSection();
boolean el02 = info.getXmin().getZmax().isElevatedParkSection();
boolean el12 = info.getZmax().isElevatedParkSection();
boolean el22 = info.getXmax().getZmax().isElevatedParkSection();
if (x == 0 && z == 0) {
if (el01 && el00 && el10) {
b = Blocks.GRASS.getDefaultState();
}
} else if (x == 15 && z == 0) {
if (el21 && el20 && el10) {
b = Blocks.GRASS.getDefaultState();
}
} else if (x == 0 && z == 15) {
if (el01 && el02 && el12) {
b = Blocks.GRASS.getDefaultState();
}
} else if (x == 15 && z == 15) {
if (el12 && el22 && el21) {
b = Blocks.GRASS.getDefaultState();
}
} else if (x == 0) {
if (el01) {
b = Blocks.GRASS.getDefaultState();
}
} else if (x == 15) {
if (el21) {
b = Blocks.GRASS.getDefaultState();
}
} else if (z == 0) {
if (el10) {
b = Blocks.GRASS.getDefaultState();
}
} else if (z == 15) {
if (el12) {
b = Blocks.GRASS.getDefaultState();
}
}
}
} else {
b = Blocks.GRASS.getDefaultState();
}
break;
}
if (doOceanBorder) {
b = Blocks.STONEBRICK.getDefaultState();
}
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
if (streetType == BuildingInfo.StreetType.PARK || info.fountainType != null) {
int l = 0;
BuildingPart part;
if (streetType == BuildingInfo.StreetType.PARK) {
part = info.parkType;
} else {
part = info.fountainType;
}
while (l < part.getSliceCount()) {
if (l == 0 && doOceanBorder && !borderNeedsConnectionToAdjacentChunk(info, x, z)) {
b = Blocks.COBBLESTONE_WALL.getDefaultState();
} else {
b = part.get(info, x, l, z);
}
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
l++;
}
} else if (doOceanBorder) {
if (!borderNeedsConnectionToAdjacentChunk(info, x, z)) {
b = Blocks.COBBLESTONE_WALL.getDefaultState();
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
}
char a = (char) Block.BLOCK_STATE_IDS.get(air);
// Go back to groundlevel
while (primer.data[index - 1] == a) {
index
height
}
// Only generate random leaf blocks on top of normal stone
if (primer.data[index - 1] == (char) Block.BLOCK_STATE_IDS.get(baseBlock)) {
if (info.getXmin().hasBuilding && x <= 2) {
while (rand.nextFloat() < (provider.profile.CHANCE_OF_RANDOM_LEAFBLOCKS * (3 - x))) {
b = Blocks.LEAVES.getDefaultState().withProperty(BlockLeaves.DECAYABLE, false);
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
}
if (info.getXmax().hasBuilding && x >= 13) {
while (rand.nextFloat() < (provider.profile.CHANCE_OF_RANDOM_LEAFBLOCKS * (x - 12))) {
b = Blocks.LEAVES.getDefaultState().withProperty(BlockLeaves.DECAYABLE, false);
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
}
if (info.getZmin().hasBuilding && z <= 2) {
while (rand.nextFloat() < (provider.profile.CHANCE_OF_RANDOM_LEAFBLOCKS * (3 - z))) {
b = Blocks.LEAVES.getDefaultState().withProperty(BlockLeaves.DECAYABLE, false);
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
}
if (info.getZmax().hasBuilding && z <= 13) {
while (rand.nextFloat() < (provider.profile.CHANCE_OF_RANDOM_LEAFBLOCKS * (z - 12))) {
b = Blocks.LEAVES.getDefaultState().withProperty(BlockLeaves.DECAYABLE, false);
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
}
while (rand.nextFloat() < (provider.profile.CHANCE_OF_RANDOM_LEAFBLOCKS / 6)) {
b = Blocks.LEAVES.getDefaultState().withProperty(BlockLeaves.DECAYABLE, false);
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
}
}
int blocks = 256 - height;
BaseTerrainGenerator.setBlockStateRange(primer, index, index + blocks, air);
index += blocks;
return index;
}
private boolean borderNeedsConnectionToAdjacentChunk(BuildingInfo info, int x, int z) {
boolean needOpening = false;
for (Direction direction : Direction.VALUES) {
BuildingInfo adjacent = direction.get(info);
if (direction.atSide(x, z) && adjacent.getActualStairDirection() == direction.getOpposite()) {
BuildingPart stairType = adjacent.stairType;
Integer z1 = stairType.getMetaInteger("z1");
Integer z2 = stairType.getMetaInteger("z2");
Rotation rotation = direction.getOpposite().getRotation();
int xx1 = rotation.rotateX(15, z1);
int zz1 = rotation.rotateZ(15, z1);
int xx2 = rotation.rotateX(15, z2);
int zz2 = rotation.rotateZ(15, z2);
if (x >= Math.min(xx1, xx2) && x <= Math.max(xx1, xx2) && z >= Math.min(zz1, zz2) && z <= Math.max(zz1, zz2)) {
needOpening = true;
break;
}
}
}
return needOpening;
}
private int generatePart(ChunkPrimer primer, BuildingInfo info, BuildingPart part,
Rotation rotation,
int chunkX, int chunkZ,
int ox, int oy, int oz) {
int cx = chunkX * 16;
int cz = chunkZ * 16;
for (int x = 0; x < part.getXSize(); x++) {
for (int z = 0; z < part.getZSize(); z++) {
int rx = ox + rotation.rotateX(x, z);
int rz = oz + rotation.rotateZ(x, z);
int index = (rx << 12) | (rz << 8) + oy;
for (int y = 0; y < part.getSliceCount(); y++) {
IBlockState b = part.get(info, x, y, z);
if (rotation != Rotation.ROTATE_NONE && b.getBlock() instanceof BlockStairs) {
b = b.withRotation(rotation.getMcRotation());
}
// We don't replace the world where the part is empty (air)
if (b != air) {
if (b == hardAir) {
b = air;
}
BaseTerrainGenerator.setBlockState(primer, index, b);
}
index++;
}
}
}
return oy + part.getSliceCount();
}
private void generateDebris(ChunkPrimer primer, Random rand, BuildingInfo info) {
generateDebrisFromChunk(primer, rand, info.getXmin(), (xx, zz) -> (15.0f - xx) / 16.0f);
generateDebrisFromChunk(primer, rand, info.getXmax(), (xx, zz) -> xx / 16.0f);
generateDebrisFromChunk(primer, rand, info.getZmin(), (xx, zz) -> (15.0f - zz) / 16.0f);
generateDebrisFromChunk(primer, rand, info.getZmax(), (xx, zz) -> zz / 16.0f);
generateDebrisFromChunk(primer, rand, info.getXmin().getZmin(), (xx, zz) -> ((15.0f - xx) * (15.0f - zz)) / 256.0f);
generateDebrisFromChunk(primer, rand, info.getXmax().getZmax(), (xx, zz) -> (xx * zz) / 256.0f);
generateDebrisFromChunk(primer, rand, info.getXmin().getZmax(), (xx, zz) -> ((15.0f - xx) * zz) / 256.0f);
generateDebrisFromChunk(primer, rand, info.getXmax().getZmin(), (xx, zz) -> (xx * (15.0f - zz)) / 256.0f);
}
private void generateDebrisFromChunk(ChunkPrimer primer, Random rand, BuildingInfo adjacentInfo, BiFunction<Integer, Integer, Float> locationFactor) {
if (adjacentInfo.hasBuilding) {
char air = (char) Block.BLOCK_STATE_IDS.get(LostCitiesTerrainGenerator.air);
char liquid = (char) Block.BLOCK_STATE_IDS.get(water);
float damageFactor = adjacentInfo.getDamageArea().getDamageFactor();
if (damageFactor > .5f) {
// An estimate of the amount of blocks
int blocks = (1 + adjacentInfo.getNumFloors()) * 1000;
float damage = Math.max(1.0f, damageFactor * DamageArea.BLOCK_DAMAGE_CHANCE);
int destroyedBlocks = (int) (blocks * damage);
// How many go this direction (approx, based on cardinal directions from building as well as number that simply fall down)
destroyedBlocks /= provider.profile.DEBRIS_TO_NEARBYCHUNK_FACTOR;
for (int i = 0; i < destroyedBlocks; i++) {
int x = rand.nextInt(16);
int z = rand.nextInt(16);
if (rand.nextFloat() < locationFactor.apply(x, z)) {
int index = (x << 12) | (z << 8) + 254; // Start one lower for safety
while (primer.data[index] == air || primer.data[index] == liquid) {
index
}
index++;
IBlockState b;
switch (rand.nextInt(5)) {
case 0:
b = Blocks.IRON_BARS.getDefaultState();
break;
default:
b = adjacentInfo.getCompiledPalette().get('#'); // @todo hardcoded!
break;
}
BaseTerrainGenerator.setBlockState(primer, index, b);
}
}
}
}
}
private boolean isDoOceanBorder(BuildingInfo info, int chunkX, int chunkZ, int x, int z) {
if (x == 0 && doBorder(info, Direction.XMIN, chunkX, chunkZ)) {
return true;
} else if (x == 15 && doBorder(info, Direction.XMAX, chunkX, chunkZ)) {
return true;
}
if (z == 0 && doBorder(info, Direction.ZMIN, chunkX, chunkZ)) {
return true;
} else if (z == 15 && doBorder(info, Direction.ZMAX, chunkX, chunkZ)) {
return true;
}
return false;
}
private boolean doBorder(BuildingInfo info, Direction direction, int chunkX, int chunkZ) {
BuildingInfo adjacent = direction.get(info);
if (isHigherThenNearbyStreetChunk(info, adjacent)) {
return true;
} else if (!adjacent.isCity && adjacent.hasBridge(provider, direction.getOrientation()) == null) {
if (adjacent.cityLevel <= info.cityLevel) {
return true;
}
}
return false;
}
private boolean isHigherThenNearbyStreetChunk(BuildingInfo info, BuildingInfo adjacent) {
return adjacent.isCity && !adjacent.hasBuilding && adjacent.cityLevel < info.cityLevel;
}
private int generateBuilding(ChunkPrimer primer, BuildingInfo info, Random rand, int chunkX, int chunkZ, int index, int x, int z, int height) {
DamageArea damageArea = info.getDamageArea();
int cx = chunkX * 16;
int cz = chunkZ * 16;
int lowestLevel = info.getCityGroundLevel() - info.floorsBelowGround * 6;
int buildingtop = info.getMaxHeight();
boolean corridor;
if (isSide(x, z)) {
BuildingInfo adjacent = info.getAdjacent(x, z);
corridor = (adjacent.hasXCorridor() || adjacent.hasZCorridor()) && isRailDoorway(x, z);
} else {
corridor = false;
}
while (height < lowestLevel) {
BaseTerrainGenerator.setBlockState(primer, index++, baseBlock);
height++;
}
while (height < buildingtop + 6) {
IBlockState b;
// Make a connection to a corridor if needed
if (corridor && height >= groundLevel - 5 && height <= groundLevel - 3) { // This uses actual groundLevel
b = air;
} else {
b = getBlockForLevel(info, x, z, height);
}
BaseTerrainGenerator.setBlockState(primer, index++, b);
height++;
}
int blocks = 256 - height;
BaseTerrainGenerator.setBlockStateRange(primer, index, index + blocks, air);
index += blocks;
return index;
}
private IBlockState getBlockForLevel(BuildingInfo info, int x, int z, int height) {
int f = getFloor(height);
int localLevel = getLevel(info, height);
boolean isTop = localLevel == info.getNumFloors(); // The top does not need generated doors
BuildingPart part = info.getFloor(localLevel);
if (f >= part.getSliceCount()) { // @todo avoid this?
return air;
}
IBlockState b = part.get(info, x, f, z);
// If we are underground, the block is glass, we are on the side and the chunk next to
// us doesn't have a building or floor there we replace the glass with a solid block
BuildingInfo adjacent = info.getAdjacent(x, z);
if (localLevel < 0 && CompiledPalette.isGlass(b) && isSide(x, z) && (!adjacent.hasBuilding || adjacent.floorsBelowGround < -localLevel)) {
// However, if there is a street next to us and the city level is lower then we generate windows like normal anyway
if (!(adjacent.isCity && (!adjacent.hasBuilding) && (info.cityLevel + localLevel) >= adjacent.cityLevel)) {
b = bricks;
}
}
// For buildings that have a style which causes gaps at the side we fill in that gap if we are
// at ground level
if (b == air && isSide(x, z) && adjacent.isCity && height == adjacent.getCityGroundLevel()) {
b = baseBlock;
}
// for buildings that have a hole in the bottom floor we fill that hole if we are
// at the bottom of the building
if (b == air && f == 0 && (localLevel + info.floorsBelowGround) == 0) {
b = bricks;
}
if (!isTop) {
if (x == 0 && (z >= 6 && z <= 9) && f >= 1 && f <= 3 && info.hasConnectionAtX(localLevel + info.floorsBelowGround)) {
if (hasConnectionWithBuilding(localLevel, info, adjacent)) {
if (f == 3 || z == 6 || z == 9) {
b = bricks;
} else {
b = air;
}
} else if (hasConnectionToTopOrOutside(localLevel, info, adjacent)) {
if (f == 3 || z == 6 || z == 9) {
b = bricks;
} else {
b = info.doorBlock.getDefaultState()
.withProperty(BlockDoor.HALF, f == 1 ? BlockDoor.EnumDoorHalf.LOWER : BlockDoor.EnumDoorHalf.UPPER)
.withProperty(BlockDoor.HINGE, z == 7 ? BlockDoor.EnumHingePosition.LEFT : BlockDoor.EnumHingePosition.RIGHT)
.withProperty(BlockDoor.FACING, EnumFacing.EAST);
}
}
} else if (x == 15 && (z >= 6 && z <= 9) && f >= 1 && f <= 3) {
if (hasConnectionWithBuildingMax(localLevel, info, adjacent, Orientation.X)) {
if (f == 3 || z == 6 || z == 9) {
b = bricks;
} else {
b = air;
}
} else if ((hasConnectionToTopOrOutside(localLevel, info, adjacent)) && adjacent.hasConnectionAtX(localLevel + adjacent.floorsBelowGround)) {
if (f == 3 || z == 6 || z == 9) {
b = bricks;
} else {
b = info.doorBlock.getDefaultState()
.withProperty(BlockDoor.HALF, f == 1 ? BlockDoor.EnumDoorHalf.LOWER : BlockDoor.EnumDoorHalf.UPPER)
.withProperty(BlockDoor.HINGE, z == 8 ? BlockDoor.EnumHingePosition.LEFT : BlockDoor.EnumHingePosition.RIGHT)
.withProperty(BlockDoor.FACING, EnumFacing.WEST);
}
}
}
if (z == 0 && (x >= 6 && x <= 9) && f >= 1 && f <= 3 && info.hasConnectionAtZ(localLevel + info.floorsBelowGround)) {
if (hasConnectionWithBuilding(localLevel, info, adjacent)) {
if (f == 3 || x == 6 || x == 9) {
b = bricks;
} else {
b = air;
}
} else if (hasConnectionToTopOrOutside(localLevel, info, adjacent)) {
if (f == 3 || x == 6 || x == 9) {
b = bricks;
} else {
b = info.doorBlock.getDefaultState()
.withProperty(BlockDoor.HALF, f == 1 ? BlockDoor.EnumDoorHalf.LOWER : BlockDoor.EnumDoorHalf.UPPER)
.withProperty(BlockDoor.HINGE, x == 8 ? BlockDoor.EnumHingePosition.LEFT : BlockDoor.EnumHingePosition.RIGHT)
.withProperty(BlockDoor.FACING, EnumFacing.SOUTH);
}
}
} else if (z == 15 && (x >= 6 && x <= 9) && f >= 1 && f <= 3) {
if (hasConnectionWithBuildingMax(localLevel, info, adjacent, Orientation.Z)) {
if (f == 3 || x == 6 || x == 9) {
b = bricks;
} else {
b = air;
}
} else if ((hasConnectionToTopOrOutside(localLevel, info, adjacent)) && adjacent.hasConnectionAtZ(localLevel + adjacent.floorsBelowGround)) {
if (f == 3 || x == 6 || x == 9) {
b = bricks;
} else {
b = info.doorBlock.getDefaultState()
.withProperty(BlockDoor.HALF, f == 1 ? BlockDoor.EnumDoorHalf.LOWER : BlockDoor.EnumDoorHalf.UPPER)
.withProperty(BlockDoor.HINGE, x == 7 ? BlockDoor.EnumHingePosition.LEFT : BlockDoor.EnumHingePosition.RIGHT)
.withProperty(BlockDoor.FACING, EnumFacing.NORTH);
}
}
}
}
boolean down = f == 0 && (localLevel + info.floorsBelowGround) == 0;
if (b.getBlock() == Blocks.LADDER && down) {
b = bricks;
}
// If this is a spawner we put it on a todo so that the world generator can put the correct mob in it
// @todo support this system in other places too
if (b.getBlock() == Blocks.MOB_SPAWNER) {
String mobid = part.getMobID(info, x, f, z);
info.addSpawnerTodo(new BlockPos(x, height, z), mobid);
} else if (b.getBlock() == Blocks.CHEST) {
info.addChestTodo(new BlockPos(x, height, z));
}
return b;
}
private boolean hasConnectionWithBuildingMax(int localLevel, BuildingInfo info, BuildingInfo info2, Orientation x) {
int globalLevel = info.localToGlobal(localLevel);
int localAdjacent = info2.globalToLocal(globalLevel);
int level = localAdjacent + info2.floorsBelowGround;
return info2.hasBuilding && ((localAdjacent >= 0 && localAdjacent < info2.getNumFloors()) || (localAdjacent < 0 && (-localAdjacent) <= info2.floorsBelowGround)) && info2.hasConnectionAt(level, x);
}
private boolean hasConnectionToTopOrOutside(int localLevel, BuildingInfo info, BuildingInfo info2) {
int globalLevel = info.localToGlobal(localLevel);
int localAdjacent = info2.globalToLocal(globalLevel);
return (!info2.hasBuilding && localLevel == 0 && localAdjacent == 0) || (info2.hasBuilding && localAdjacent == info2.getNumFloors());
}
private boolean hasConnectionWithBuilding(int localLevel, BuildingInfo info, BuildingInfo info2) {
int globalLevel = info.localToGlobal(localLevel);
int localAdjacent = info2.globalToLocal(globalLevel);
return info2.hasBuilding && ((localAdjacent >= 0 && localAdjacent < info2.getNumFloors()) || (localAdjacent < 0 && (-localAdjacent) <= info2.floorsBelowGround));
}
public int getFloor(int height) {
return (height - provider.profile.GROUNDLEVEL + 600) % 6;
}
public static int getLevel(BuildingInfo info, int height) {
return ((height - info.getCityGroundLevel() + 600) / 6) - 100;
}
private boolean isCorner(int x, int z) {
return (x == 0 && z == 0) || (x == 0 && z == 15) || (x == 15 && z == 0) || (x == 15 && z == 15);
}
private boolean isSide(int x, int z) {
return x == 0 || x == 15 || z == 0 || z == 15;
}
private boolean isStreetBorder(int x, int z) {
return x <= streetBorder || x >= (15 - streetBorder) || z <= streetBorder || z >= (15 - streetBorder);
}
private boolean isRailDoorway(int x, int z) {
if (x == 0 || x == 15) {
return z >= 7 && z <= 10;
}
if (z == 0 || z == 15) {
return x >= 7 && x <= 10;
}
return false;
}
}
|
package replicant;
import arez.Arez;
import arez.ArezContext;
import arez.Component;
import arez.Disposable;
import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentNameRef;
import arez.annotations.ComponentRef;
import arez.annotations.ContextRef;
import arez.annotations.Observable;
import arez.annotations.ObservableRef;
import arez.annotations.PreDispose;
import arez.component.ComponentObservable;
import arez.component.Identifiable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import replicant.spy.SubscriptionCreatedEvent;
import static org.realityforge.braincheck.Guards.*;
/**
* A class that records the subscriptions within the system.
*/
@ArezComponent
abstract class SubscriptionService
extends ReplicantService
{
//ChannelType => InstanceID
private final HashMap<Enum, Map<Object, Subscription>> _instanceSubscriptions = new HashMap<>();
//ChannelType => Type
private final HashMap<Enum, SubscriptionEntry> _typeSubscriptions = new HashMap<>();
static SubscriptionService create( @Nullable final ReplicantContext context )
{
return new Arez_SubscriptionService( context );
}
SubscriptionService( @Nullable final ReplicantContext context )
{
super( context );
}
/**
* Return the context associated with the service.
*
* @return the context associated with the service.
*/
@ContextRef
@Nonnull
protected abstract ArezContext getContext();
/**
* Return the name associated with the service.
*
* @return the name associated with the service.
*/
@ComponentNameRef
@Nonnull
protected abstract String getComponentName();
/**
* Return the component associated with service if native components enabled.
*
* @return the component associated with service if native components enabled.
*/
@ComponentRef
@Nonnull
protected abstract Component component();
/**
* Return the collection of type subscriptions.
*
* @return the collection of type subscriptions.
*/
@Nonnull
@Observable( expectSetter = false )
List<Subscription> getTypeSubscriptions()
{
return _typeSubscriptions
.values()
.stream()
.filter( s -> !Disposable.isDisposed( s ) )
.map( SubscriptionEntry::getSubscription )
.collect( Collectors.toList() );
}
@ObservableRef
protected abstract arez.Observable getTypeSubscriptionsObservable();
/**
* Return the collection of instance subscriptions.
*
* @return the collection of instance subscriptions.
*/
@Nonnull
@Observable( expectSetter = false )
Collection<Subscription> getInstanceSubscriptions()
{
return _instanceSubscriptions
.values()
.stream()
.flatMap( s -> s.values().stream() )
.filter( s -> !Disposable.isDisposed( s ) )
.collect( Collectors.toList() );
}
@ObservableRef
protected abstract arez.Observable getInstanceSubscriptionsObservable();
/**
* Return the collection of instance subscriptions for channel.
*
* @param channelType the channel type.
* @return the set of ids for all instance subscriptions with specified channel type.
*/
@Nonnull
Set<Object> getInstanceSubscriptionIds( @Nonnull final Enum channelType )
{
getInstanceSubscriptionsObservable().reportObserved();
final Map<Object, Subscription> map = _instanceSubscriptions.get( channelType );
if ( null == map )
{
return Collections.emptySet();
}
else
{
final Set<Object> results =
map
.entrySet()
.stream()
.filter( e -> !Disposable.isDisposed( e.getValue() ) )
.map( Map.Entry::getKey )
.collect( Collectors.toSet() );
return Arez.areRepositoryResultsModifiable() ? results : Collections.unmodifiableSet( results );
}
}
/**
* Create a subscription.
* This method should not be invoked if a subscription with the existing name already exists.
*
* @param address the channel address.
* @param filter the filter if subscription is filterable.
* @param explicitSubscription if subscription was explicitly requested by the client.
* @return the subscription.
*/
@Nonnull
final Subscription createSubscription( @Nonnull final ChannelAddress address,
@Nullable final Object filter,
final boolean explicitSubscription )
{
if ( Replicant.shouldCheckApiInvariants() )
{
apiInvariant( () -> null == findSubscription( address ),
() -> "createSubscription invoked with address " + address +
" but a subscription with that address already exists." );
}
final Object id = address.getId();
if ( null == id )
{
getTypeSubscriptionsObservable().preReportChanged();
}
else
{
getInstanceSubscriptionsObservable().preReportChanged();
}
final Subscription subscription =
Subscription.create( this, Channel.create( address, filter ), explicitSubscription );
final SubscriptionEntry entry = createSubscriptionEntry( subscription );
if ( null == id )
{
_typeSubscriptions.put( address.getChannelType(), entry );
getTypeSubscriptionsObservable().reportChanged();
}
else
{
_instanceSubscriptions
.computeIfAbsent( address.getChannelType(), k -> new HashMap<>() )
.put( id, subscription );
getInstanceSubscriptionsObservable().reportChanged();
}
if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() )
{
getReplicantContext().getSpy().reportSpyEvent( new SubscriptionCreatedEvent( subscription ) );
}
return subscription;
}
@Nonnull
private SubscriptionEntry createSubscriptionEntry( @Nonnull final Subscription subscription )
{
final SubscriptionEntry entry = new SubscriptionEntry( subscription );
final Object arezId = Identifiable.getArezId( subscription );
final Observer monitor =
getContext().when( Arez.areNativeComponentsEnabled() ? component() : null,
Arez.areNamesEnabled() ? getComponentName() + ".SubscriptionWatcher." + arezId : null,
true,
() -> !ComponentObservable.observe( subscription ),
() -> unlinkSubscription( subscription.getChannel().getAddress() ),
true,
true );
entry.setMonitor( monitor );
return entry;
}
/**
* Return the subscription for the specified address.
* This method will observe the <code>typeSubscriptions</code> or <code>instanceSubscriptions</code>
* property if not found and the result {@link Subscription} if found. This ensures that if an observer
* invokes this method then the observer will be rescheduled when the result changes.
*
* @param address the channel address.
* @return the subscription if it exists, null otherwise.
*/
@Nullable
final Subscription findSubscription( @Nonnull final ChannelAddress address )
{
final Enum channelType = address.getChannelType();
final Object id = address.getId();
return null == id ? findTypeSubscription( channelType ) : findInstanceSubscription( channelType, id );
}
/**
* Return the type subscription for the specified channelType.
* This method will observe the <code>typeSubscriptions</code> property if not
* found and the result {@link Subscription} if found. This ensures that if an observer
* invokes this method then the observer will be rescheduled when the result changes.
*
* @param channelType the channel type.
* @return the subscription if any matches.
*/
@Nullable
private Subscription findTypeSubscription( @Nonnull final Enum channelType )
{
final SubscriptionEntry entry = _typeSubscriptions.get( channelType );
if ( null == entry || Disposable.isDisposed( entry.getSubscription() ) )
{
getTypeSubscriptionsObservable().reportObserved();
return null;
}
else
{
final Subscription subscription = entry.getSubscription();
ComponentObservable.observe( subscription );
return subscription;
}
}
/**
* Return the instance subscription for the specified channelType and id.
* This method will observe the <code>instanceSubscriptions</code> property if not
* found and the result {@link Subscription} if found. This ensures that if an observer
* invokes this method then the observer will be rescheduled when the result changes.
*
* @param channelType the channel type.
* @param id the channel id.
* @return the subscription if any matches.
*/
@Nullable
private Subscription findInstanceSubscription( @Nonnull final Enum channelType, @Nonnull final Object id )
{
final Map<Object, Subscription> instanceMap = _instanceSubscriptions.get( channelType );
if ( null == instanceMap )
{
getInstanceSubscriptionsObservable().reportObserved();
return null;
}
else
{
final Subscription subscription = instanceMap.get( id );
if ( null == subscription || Disposable.isDisposed( subscription ) )
{
getInstanceSubscriptionsObservable().reportObserved();
return null;
}
else
{
ComponentObservable.observe( subscription );
return subscription;
}
}
}
/**
* Remove subscription on channel specified by address.
* This method should only be invoked if a subscription exists
*
* @param address the channel address.
* @return the subscription.
*/
@Nonnull
final Subscription unlinkSubscription( @Nonnull final ChannelAddress address )
{
final Object id = address.getId();
if ( null == id )
{
getTypeSubscriptionsObservable().preReportChanged();
final SubscriptionEntry entry = _typeSubscriptions.remove( address.getChannelType() );
if ( Replicant.shouldCheckInvariants() )
{
invariant( () -> null != entry,
() -> "unlinkSubscription invoked with address " + address +
" but no subscription with that address exists." );
invariant( () -> Disposable.isDisposed( entry ),
() -> "unlinkSubscription invoked with address " + address +
" but subscription has not already been disposed." );
}
getTypeSubscriptionsObservable().reportChanged();
return entry.getSubscription();
}
else
{
getInstanceSubscriptionsObservable().preReportChanged();
final Map<Object, Subscription> instanceMap = _instanceSubscriptions.get( address.getChannelType() );
if ( Replicant.shouldCheckInvariants() )
{
invariant( () -> null != instanceMap,
() -> "unlinkSubscription invoked with address " + address +
" but no subscription with that address exists." );
}
final Subscription subscription = instanceMap.remove( id );
if ( Replicant.shouldCheckInvariants() )
{
invariant( () -> null != subscription,
() -> "unlinkSubscription invoked with address " + address +
" but no subscription with that address exists." );
invariant( () -> Disposable.isDisposed( subscription ),
() -> "unlinkSubscription invoked with address " + address +
" but subscription has not already been disposed." );
}
getInstanceSubscriptionsObservable().reportChanged();
return subscription;
}
}
@PreDispose
final void preDispose()
{
_typeSubscriptions.values().forEach( s -> Disposable.dispose( s ) );
_instanceSubscriptions.values().stream().flatMap( t -> t.values().stream() ).forEach( Disposable::dispose );
}
}
|
package org.pfaa.chemica.integration;
import java.util.List;
import org.pfaa.chemica.model.Strength;
import org.pfaa.chemica.processing.TemperatureLevel;
import org.pfaa.chemica.registration.RecipeRegistration;
import org.pfaa.chemica.util.ChanceStack;
import blusunrize.immersiveengineering.api.crafting.ArcFurnaceRecipe;
import blusunrize.immersiveengineering.api.crafting.BlastFurnaceRecipe;
import blusunrize.immersiveengineering.api.crafting.CrusherRecipe;
import blusunrize.immersiveengineering.common.IEContent;
import cpw.mods.fml.common.Loader;
import net.minecraft.item.ItemStack;
public class ImmersiveEngineeringIntegration {
public static void init() {
if (Loader.isModLoaded(ModIds.IMMERSIVE_ENGINEERING)) {
RecipeRegistration.addRegistry(ModIds.IMMERSIVE_ENGINEERING,
new ImmersiveEngineeringRecipeRegistry());
}
}
public static class ImmersiveEngineeringRecipeRegistry extends AbstractRecipeRegistry {
private static final int ARC_ENERGY_PER_TICK = 512;
@Override
public void registerGrindingRecipe(ItemStack input, ItemStack output, List<ChanceStack> secondaries,
Strength strength) {
int energy = RecipeCostUtils.grindingEnergyForStrength(strength);
CrusherRecipe recipe = CrusherRecipe.addRecipe(output, input, energy / 2);
for (ChanceStack secondary : secondaries) {
recipe.addToSecondaryOutput(secondary.itemStack, secondary.chance);
}
}
@Override
public void registerSmeltingRecipe(ItemStack input, ItemStack output, ItemStack flux, TemperatureLevel temp) {
ItemStack slag = new ItemStack(IEContent.itemMaterial, 1, 13);
BlastFurnaceRecipe.addRecipe(output, input, RecipeCostUtils.blastTicksForTemperatureLevel(temp), slag);
}
@Override
public void registerCastingRecipe(ItemStack input, ItemStack output, ItemStack flux, int temp) {
int time = RecipeCostUtils.arcTicksForTemperature(temp);
if (flux != null) {
ArcFurnaceRecipe.addRecipe(output, input, null, time, ARC_ENERGY_PER_TICK, flux);
} else {
ArcFurnaceRecipe.addRecipe(output, input, null, time, ARC_ENERGY_PER_TICK);
}
}
@Override
public void registerAlloyingRecipe(ItemStack output, ItemStack base, List<ItemStack> solutes, int temp) {
if (solutes.size() > 4) {
return;
}
int time = RecipeCostUtils.arcTicksForTemperature(temp) * output.stackSize;
ArcFurnaceRecipe recipe = ArcFurnaceRecipe.addRecipe(output, base, null, time, ARC_ENERGY_PER_TICK,
solutes.toArray(new Object[0]));
recipe.setSpecialRecipeType("Alloying");
}
@Override
public void registerRoastingRecipe(List<ItemStack> inputs, ItemStack output, int temp) {
int time = RecipeCostUtils.arcTicksForTemperature(temp);
Object[] additives = inputs.subList(1, inputs.size()).toArray();
ArcFurnaceRecipe.addRecipe(output, inputs.get(0), null, time, ARC_ENERGY_PER_TICK, additives);
}
// Other machines: coke oven
}
}
|
package org.spongepowered.common.mixin.core.block;
import com.google.common.collect.ImmutableList;
import net.minecraft.block.BlockRail;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.BlockRailDetector;
import net.minecraft.block.BlockRailPowered;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.manipulator.immutable.block.ImmutableRailDirectionData;
import org.spongepowered.api.data.type.RailDirection;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.common.data.ImmutableDataCachingUtil;
import org.spongepowered.common.data.manipulator.immutable.block.ImmutableSpongeRailDirectionData;
import java.util.Map;
import java.util.Optional;
@Mixin(BlockRailBase.class)
public abstract class MixinBlockRailBase extends MixinBlock {
@Override
public ImmutableList<ImmutableDataManipulator<?, ?>> getManipulators(IBlockState blockState) {
final ImmutableRailDirectionData railDirection = getRailDirectionFor(blockState);
if (railDirection == null) { // Extra safety check
return ImmutableList.of();
}
return ImmutableList.of(railDirection);
}
@Override
public boolean supports(Class<? extends ImmutableDataManipulator<?, ?>> immutable) {
return ImmutableRailDirectionData.class.isAssignableFrom(immutable);
}
@Override
public Optional<BlockState> getStateWithData(IBlockState blockState, ImmutableDataManipulator<?, ?> manipulator) {
if (manipulator instanceof ImmutableRailDirectionData) {
final BlockRailBase.EnumRailDirection railDirection = (BlockRailBase.EnumRailDirection) (Object) ((ImmutableRailDirectionData) manipulator).type().get();
if (blockState.getBlock() instanceof BlockRail) {
return Optional.of((BlockState) blockState.withProperty(BlockRail.SHAPE, railDirection));
} else if (blockState.getBlock() instanceof BlockRailPowered) {
if (!BlockRailPowered.SHAPE.getAllowedValues().contains(railDirection)) {
return Optional.empty();
}
return Optional.of((BlockState) blockState.withProperty(BlockRailPowered.SHAPE, railDirection));
} else if (blockState.getBlock() instanceof BlockRailDetector) {
if (!BlockRailDetector.SHAPE.getAllowedValues().contains(railDirection)) {
return Optional.empty();
}
return Optional.of((BlockState) blockState.withProperty(BlockRailDetector.SHAPE, railDirection));
} else { // For mods that extend BlockRailBase
for (Map.Entry<IProperty, Comparable> entry : blockState.getProperties().entrySet()) {
if (entry.getValue() instanceof BlockRailBase.EnumRailDirection) {
if (entry.getKey().getAllowedValues().contains(railDirection)) {
return Optional.of((BlockState) blockState.withProperty(entry.getKey(), railDirection));
}
}
}
}
}
return super.getStateWithData(blockState, manipulator);
}
@Override
public <E> Optional<BlockState> getStateWithValue(IBlockState blockState, Key<? extends BaseValue<E>> key, E value) {
if (key.equals(Keys.RAIL_DIRECTION)) {
final BlockRailBase.EnumRailDirection railDirection = (BlockRailBase.EnumRailDirection) value;
if (blockState.getBlock() instanceof BlockRail) {
return Optional.of((BlockState) blockState.withProperty(BlockRail.SHAPE, railDirection));
} else if (blockState.getBlock() instanceof BlockRailPowered) {
if (!BlockRailPowered.SHAPE.getAllowedValues().contains(railDirection)) {
return Optional.empty();
}
return Optional.of((BlockState) blockState.withProperty(BlockRailPowered.SHAPE, railDirection));
} else if (blockState.getBlock() instanceof BlockRailDetector) {
if (!BlockRailDetector.SHAPE.getAllowedValues().contains(railDirection)) {
return Optional.empty();
}
return Optional.of((BlockState) blockState.withProperty(BlockRailDetector.SHAPE, railDirection));
}
}
return super.getStateWithValue(blockState, key, value);
}
private ImmutableRailDirectionData getRailDirectionFor(IBlockState blockState) {
if (blockState.getBlock() instanceof BlockRail) {
return ImmutableDataCachingUtil.getManipulator(ImmutableSpongeRailDirectionData.class,
blockState.getValue(BlockRail.SHAPE));
} else if (blockState.getBlock() instanceof BlockRailPowered) {
return ImmutableDataCachingUtil.getManipulator(ImmutableSpongeRailDirectionData.class,
blockState.getValue(BlockRailPowered.SHAPE));
} else if (blockState.getBlock() instanceof BlockRailDetector) {
return ImmutableDataCachingUtil.getManipulator(ImmutableSpongeRailDirectionData.class,
blockState.getValue(BlockRailDetector.SHAPE));
} else { // For mods extending BlockRailBase
for (Map.Entry<IProperty, Comparable> entry : blockState.getProperties().entrySet()) {
if (entry.getValue() instanceof BlockRailBase.EnumRailDirection) {
return ImmutableDataCachingUtil.getManipulator(ImmutableSpongeRailDirectionData.class,
entry.getValue());
}
}
}
return null;
}
}
|
package pl.edu.mimuw.changeanalyzer.extraction;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Stack;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.LogCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import pl.edu.mimuw.changeanalyzer.exceptions.ChangeAnalyzerException;
import ch.uzh.ifi.seal.changedistiller.ChangeDistiller;
import ch.uzh.ifi.seal.changedistiller.ChangeDistiller.Language;
import ch.uzh.ifi.seal.changedistiller.distilling.FileDistiller;
import ch.uzh.ifi.seal.changedistiller.model.entities.ClassHistory;
/**
* Class responsible for extraction of class histories. It contains reference
* to a local Git repository. Each class is identified by a relative (to the repository
* root directory) path to the .java file which cotains it.
*
* @author Adam Wierzbicki
*/
public class ClassHistoryExtractor {
private Repository repository;
private Git git;
/**
* Construct a new ClassHistoryExtractor.
*
* @param repository Repository to extract class histories from
*/
public ClassHistoryExtractor(Repository repository) {
this.repository = repository;
this.git = new Git(repository);
}
/**
* Construct a new ClassHistoryExtractor.
*
* @param repoDir Directory with a repository to extract class histories from
* @throws IOException When the given directory doesn't contain a proper repository
*/
public ClassHistoryExtractor(File repoDir) throws IOException {
FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
this.repository = repoBuilder.setWorkTree(repoDir).build();
this.git = new Git(this.repository);
}
/**
* Construct a new ClassHistoryExtractor.
*
* @param repoPath Path to a repository to extract class histories from
* @throws IOException When the given path doesn't point to a proper repository
*/
public ClassHistoryExtractor(String repoPath) throws IOException {
this(new File(repoPath));
}
/**
* Get all commits modifying the given file (as with 'git log' command)
*
* @param filePath Path to the file (relative to the main directory of the repository)
* @return Commits modifying the given file
* @throws IOException
* @throws ChangeAnalyzerException
*/
public Iterable<RevCommit> getFileRevisions(String filePath) throws IOException, ChangeAnalyzerException {
ObjectId head = Utils.getHead(this.repository);
LogCommand logCommand = this.git.log().add(head).addPath(filePath);
try {
return logCommand.call();
} catch (GitAPIException e) {
throw new ChangeAnalyzerException("Failed to execute LOG command", e);
}
//TODO: Handle renamed/moved files
}
/**
* Analyze all commits modyfing a given file (in a linear time order) and extract
* history of the class represented by this file.
*
* @param filePath Path to the file which history is to be extracted (relative to the main
* directory of the repository). This should be a .java file.
* @return History of the given file
* @throws IOException
* @throws ChangeAnalyzerException
*/
public ClassHistory extractClassHistory(String filePath) throws IOException, ChangeAnalyzerException {
Stack<RevCommit> commits = new Stack<RevCommit>();
for (RevCommit commit: this.getFileRevisions(filePath)) {
commits.add(commit);
}
if (commits.size() < 2) {
return null;
}
FileDistiller distiller = ChangeDistiller.createFileDistiller(Language.JAVA);
File tmpOldFile = File.createTempFile(filePath.replace('/', '.'), ".old");
File tmpNewFile = File.createTempFile(filePath.replace('/', '.'), ".new");
RevCommit oldCommit = null;
RevCommit newCommit = commits.pop();
while (!commits.empty()) {
oldCommit = newCommit;
newCommit = commits.pop();
this.storeFileRevision(oldCommit, filePath, tmpOldFile);
this.storeFileRevision(newCommit, filePath, tmpNewFile);
distiller.extractClassifiedSourceCodeChanges(tmpOldFile, tmpNewFile, newCommit.name());
}
if (!tmpOldFile.delete()) {
throw new IOException("Failed to delete file " + tmpOldFile.getAbsolutePath());
}
if (!tmpNewFile.delete()) {
throw new IOException("Failed to delete file " + tmpNewFile.getAbsolutePath());
}
return distiller.getClassHistory();
}
/**
* Copy the content of a git versioned file into another file. Retrieved content
* is identical to the state of the versioned file after a given commit.
*
* @param commit Commit from which file version is retrieved
* @param versionedFilePath Path to the versioned file (relative to the main directory of the repository)
* @param destFile Destination file
* @throws IOException
*/
private void storeFileRevision(RevCommit commit, String versionedFilePath, File destFile) throws IOException {
RevTree revTree = commit.getTree();
PathFilter filter = PathFilter.create(versionedFilePath);
TreeWalk treeWalk = new TreeWalk(this.repository);
treeWalk.addTree(revTree);
treeWalk.setRecursive(true);
treeWalk.setFilter(filter);
if (!treeWalk.next()) {
return;
}
ObjectId fileId = treeWalk.getObjectId(0);
ObjectLoader loader = this.repository.open(fileId, Constants.OBJ_BLOB);
OutputStream stream = new FileOutputStream(destFile);
try {
loader.copyTo(stream);
} catch (IOException e) {
throw e;
} finally {
stream.close();
}
}
}
|
package org.gridsphere.services.core.security.role.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gridsphere.portlet.service.PortletServiceUnavailableException;
import org.gridsphere.portlet.service.spi.PortletServiceConfig;
import org.gridsphere.portlet.service.spi.PortletServiceFactory;
import org.gridsphere.portlet.service.spi.PortletServiceProvider;
import org.gridsphere.services.core.persistence.PersistenceManagerRdbms;
import org.gridsphere.services.core.persistence.PersistenceManagerService;
import org.gridsphere.services.core.persistence.QueryFilter;
import org.gridsphere.services.core.security.role.PortletRole;
import org.gridsphere.services.core.security.role.RoleManagerService;
import org.gridsphere.services.core.user.User;
import org.gridsphere.services.core.user.impl.UserImpl;
import java.util.ArrayList;
import java.util.List;
public class RoleManagerServiceImpl implements PortletServiceProvider, RoleManagerService {
private Log log = LogFactory.getLog(RoleManagerServiceImpl.class);
private PersistenceManagerRdbms pm = null;
private String jdoUserRoles = UserRole.class.getName();
private String jdoUser = UserImpl.class.getName();
public RoleManagerServiceImpl() {}
public void init(PortletServiceConfig config) throws PortletServiceUnavailableException {
PersistenceManagerService pmservice = (PersistenceManagerService) PortletServiceFactory.createPortletService(PersistenceManagerService.class, true);
pm = pmservice.createGridSphereRdbms();
// create user role if none exists
PortletRole userRole = getRole("USER");
if (userRole == null) {
userRole = new PortletRole();
userRole.setName("USER");
userRole.setDescription("portal user");
saveRole(userRole);
}
// create admin role if none exists
PortletRole adminRole = getRole("ADMIN");
if (adminRole == null) {
adminRole = new PortletRole();
adminRole.setName("ADMIN");
adminRole.setDescription("portal administrator");
saveRole(adminRole);
}
}
public void destroy() {
log.info("Calling destroy()");
}
public boolean isUserInRole(User user, PortletRole role) {
return (getUserRole(user, role) != null);
}
public int getNumUsersInRole(PortletRole role) {
if (role == null) throw new IllegalArgumentException("role cannot be null!");
String oql = "select count(*) from "
+ this.jdoUserRoles;
return pm.count(oql);
}
public List<PortletRole> getRolesForUser(User user) {
if (user == null) throw new IllegalArgumentException("user can't be null");
List<PortletRole> roles = null;
String oql = "select userRole.role from "
+ jdoUserRoles
+ " userRole where userRole.user.oid='" + user.getID() + "'";
roles = pm.restoreList(oql);
return (roles != null) ? roles : new ArrayList<PortletRole>();
}
public List<User> getUsersInRole(PortletRole role) {
if (role == null) throw new IllegalArgumentException("role cannot be null!");
List<User> users = null;
String oql = "select userRole.user from "
+ jdoUserRoles
+ " userRole where userRole.role.Name='" + role.getName() + "'";
users = pm.restoreList(oql);
return (users != null) ? users : new ArrayList<User>();
}
public List<User> getUsersInRole(PortletRole role, QueryFilter filter) {
if (role == null) throw new IllegalArgumentException("role cannot be null!");
if (filter == null) throw new IllegalArgumentException("query filter cannot be null!");
List<User> users = null;
String oql = "select userRole.user from "
+ jdoUserRoles
+ " userRole where userRole.role.Name='" + role.getName() + "'";
users = (List<User>)pm.restoreList(oql, filter);
return (users != null) ? users : new ArrayList<User>();
}
public List<User> getUsersNotInRole(PortletRole role, QueryFilter filter) {
if (role == null) throw new IllegalArgumentException("role cannot be null!");
if (filter == null) throw new IllegalArgumentException("query filter cannot be null!");
List<User> users = null;
String oql = "select uzer from "
+ this.jdoUser
+ " uzer left join fetch userRole.user where userRole.role.Name!='" + role.getName() + "'";
users = (List<User>)pm.restoreList(oql, filter);
return (users != null) ? users : new ArrayList<User>();
}
public void addUserToRole(User user, PortletRole role) {
if (user == null) throw new IllegalArgumentException("user cannot be null!");
if (role == null) throw new IllegalArgumentException("role cannot be null!");
UserRole userRole = new UserRole();
if (role.getOid() == null) role = getRole(role.getName());
if (!isUserInRole(user, role)) {
userRole.setRole(role);
userRole.setUser(user);
pm.saveOrUpdate(userRole);
}
}
public void deleteUserInRole(User user, PortletRole role) {
UserRole userRole = getUserRole(user, role);
if (userRole != null) pm.delete(userRole);
}
private UserRole getUserRole(User user, PortletRole role) {
if (user == null) throw new IllegalArgumentException("user cannot be null!");
if (role == null) throw new IllegalArgumentException("role cannot be null!");
UserRole userRole = null;
String oql = "select userRole from "
+ jdoUserRoles
+ " userRole where userRole.user.oid='" + user.getID() + "'"
+ " and userRole.role.Name='" + role.getName() + "'";
userRole = (UserRole)pm.restore(oql);
return userRole;
}
public List<PortletRole> getRoles() {
List<PortletRole> roles = null;
roles = pm.restoreList("select prole from " + PortletRole.class.getName() + " prole");
return (roles != null) ? roles : new ArrayList<PortletRole>();
}
public void deleteRole(PortletRole role) {
if (role == null) throw new IllegalArgumentException("role cannot be null!");
pm.delete(role);
}
public PortletRole getRole(String roleName) {
if (roleName == null) throw new IllegalArgumentException("role name cannot be null!");
return (PortletRole)pm.restore("select prole from " + PortletRole.class.getName() + " prole where prole.Name='" + roleName + "'");
}
public void saveRole(PortletRole role) {
if (role == null) throw new IllegalArgumentException("role cannot be null!");
pm.saveOrUpdate(role);
}
}
|
package Control;
import Model.Case;
import Model.Chrono;
public abstract class Control
{
protected Case case_;
protected Chrono chrono;
protected ControlMenu controlMenu;
public Control() {}
public Control(Case case_, Chrono chrono, ControlMenu controlMenu)
{
this.case_ = case_;
this.chrono = chrono;
this.controlMenu = controlMenu;
}
}
|
package io.spine.code.proto;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.util.JsonFormat.TypeRegistry;
import io.spine.type.EnumType;
import io.spine.type.MessageType;
import io.spine.type.ServiceType;
import io.spine.type.Type;
import io.spine.type.TypeName;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newHashMapWithExpectedSize;
import static com.google.common.collect.Maps.uniqueIndex;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
/**
* A set of Protobuf types.
*/
@Immutable
public final class TypeSet {
private final ImmutableMap<TypeName, MessageType> messageTypes;
private final ImmutableMap<TypeName, EnumType> enumTypes;
private final ImmutableMap<TypeName, ServiceType> serviceTypes;
/** Creates a new empty set. */
private TypeSet() {
this(ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of());
}
private TypeSet(ImmutableMap<TypeName, MessageType> messageTypes,
ImmutableMap<TypeName, EnumType> enumTypes,
ImmutableMap<TypeName, ServiceType> serviceTypes) {
this.messageTypes = messageTypes;
this.enumTypes = enumTypes;
this.serviceTypes = serviceTypes;
}
private TypeSet(Builder builder) {
this(ImmutableMap.copyOf(builder.messageTypes),
ImmutableMap.copyOf(builder.enumTypes),
ImmutableMap.copyOf(builder.serviceTypes));
}
/**
* Obtains message and enum types declared in the passed file.
*/
public static TypeSet from(FileDescriptor file) {
TypeSet messages = MessageType.allFrom(file);
TypeSet enums = EnumType.allFrom(file);
TypeSet services = ServiceType.allFrom(file);
return new TypeSet(messages.messageTypes, enums.enumTypes, services.serviceTypes);
}
/**
* Obtains message and enum types declared in the files represented by the passed set.
*/
public static TypeSet from(FileSet fileSet) {
TypeSet result = new TypeSet();
for (FileDescriptor file : fileSet.files()) {
result = result.union(from(file));
}
return result;
}
public static ImmutableCollection<MessageType> topLevelMessages(FileSet fileSet) {
ImmutableSet<MessageType> result = onlyMessages(fileSet)
.stream()
.filter(MessageType::isTopLevel)
.collect(toImmutableSet());
return result;
}
/**
* Obtains message types declared in the passed file set.
*/
public static ImmutableCollection<MessageType> onlyMessages(FileSet fileSet) {
TypeSet result = new TypeSet();
for (FileDescriptor file : fileSet.files()) {
TypeSet messageTypes = MessageType.allFrom(file);
result = result.union(messageTypes);
}
return result.messageTypes.values();
}
/**
* Obtains message types declared in the passed file.
*/
public static ImmutableCollection<MessageType> onlyMessages(FileDescriptor file) {
TypeSet typeSet = MessageType.allFrom(file);
return typeSet.messageTypes.values();
}
/**
* Obtains the size of the set.
*/
public int size() {
int messagesCount = messageTypes.size();
int enumsCount = enumTypes.size();
int servicesCount = serviceTypes.size();
int result = messagesCount + enumsCount + servicesCount;
return result;
}
/**
* Obtains a type by its name.
*
* @param name the name of the type to find
* @return the type with the given name or {@code Optional.empty()} if there is no such type in
* this set
* @see #contains(TypeName)
*/
public Optional<Type<?, ?>> find(TypeName name) {
checkNotNull(name);
Type<?, ?> messageType = messageTypes.get(name);
if (messageType != null) {
return Optional.of(messageType);
}
Type<?, ?> enumType = enumTypes.get(name);
if (enumType != null) {
return Optional.of(enumType);
}
Type<?, ?> serviceType = serviceTypes.get(name);
return Optional.ofNullable(serviceType);
}
/**
* Checks if a type with the given name is present in this set.
*
* <p>It is guaranteed that if this method returns {@code true}, then {@link #find(TypeName)}
* will successfully find the type by the same name, and otherwise, if
* {@code contains(TypeName)} returns {@code false}, then {@code find(TypeName)} will return
* an empty value.
*
* @param typeName the name to look by
* @return {@code true} if the set contains a type with the given name, {@code false} otherwise
* @see #find(TypeName)
*/
public boolean contains(TypeName typeName) {
boolean result = find(typeName).isPresent();
return result;
}
/**
* Verifies if the set is empty.
*/
public boolean isEmpty() {
boolean empty = size() == 0;
return empty;
}
/**
* Writes all the types in this set into a {@link TypeRegistry JsonFormat.TypeRegistry}.
*/
public TypeRegistry toJsonPrinterRegistry() {
TypeRegistry.Builder registry = TypeRegistry.newBuilder();
messageTypes.values()
.stream()
.map(Type::descriptor)
.forEach(registry::add);
return registry.build();
}
/**
* Creates a new set which is a union of this and the passed one.
*/
public TypeSet union(TypeSet another) {
if (another.isEmpty()) {
return this;
}
if (this.isEmpty()) {
return another;
}
ImmutableMap<TypeName, MessageType> messages =
unite(this.messageTypes, another.messageTypes);
ImmutableMap<TypeName, EnumType> enums =
unite(this.enumTypes, another.enumTypes);
ImmutableMap<TypeName, ServiceType> services =
unite(this.serviceTypes, another.serviceTypes);
TypeSet result = new TypeSet(messages, enums, services);
return result;
}
private static <T extends Type<?, ?>> ImmutableMap<TypeName, T>
unite(Map<TypeName, T> left, Map<TypeName, T> right) {
// Use HashMap instead of ImmutableMap.Builder to deal with duplicates.
Map<TypeName, T> union = newHashMapWithExpectedSize(left.size() + right.size());
union.putAll(left);
union.putAll(right);
return ImmutableMap.copyOf(union);
}
/**
* Obtains all the types contained in this set.
*/
public ImmutableSet<Type<?, ?>> allTypes() {
ImmutableSet<Type<?, ?>> types = ImmutableSet
.<Type<?, ?>>builder()
.addAll(messagesAndEnums())
.addAll(serviceTypes.values())
.build();
return types;
}
/**
* Obtains message and enum types contained in this set.
*/
public Set<Type<?, ?>> messagesAndEnums() {
ImmutableSet<Type<?, ?>> types = ImmutableSet
.<Type<?, ?>>builder()
.addAll(messageTypes.values())
.addAll(enumTypes.values())
.build();
return types;
}
/**
* Obtains message types from this set.
*/
public ImmutableSet<MessageType> messageTypes() {
return ImmutableSet.copyOf(messageTypes.values());
}
/**
* Obtains enum types from this set.
*/
public ImmutableSet<EnumType> enumTypes() {
return ImmutableSet.copyOf(enumTypes.values());
}
/**
* Obtains service types from this set.
*/
public ImmutableSet<ServiceType> serviceTypes() {
return ImmutableSet.copyOf(serviceTypes.values());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TypeSet)) {
return false;
}
TypeSet typeSet = (TypeSet) o;
return Objects.equal(messageTypes, typeSet.messageTypes) &&
Objects.equal(enumTypes, typeSet.enumTypes);
}
@Override
public int hashCode() {
return Objects.hashCode(messageTypes, enumTypes);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("messageTypes", namesForDisplay(messageTypes))
.add("enumTypes", namesForDisplay(enumTypes))
.add("serviceTypes", namesForDisplay(serviceTypes))
.toString();
}
private static String namesForDisplay(Map<TypeName, ?> types) {
return types.keySet()
.stream()
.map(TypeName::value)
.sorted()
.collect(joining(lineSeparator()));
}
/**
* Creates a new instance of {@code Builder} for {@code TypeSet} instances.
*
* @return new instance of {@code Builder}
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* A builder for the {@code TypeSet} instances.
*/
public static final class Builder {
private final Map<TypeName, MessageType> messageTypes = newHashMap();
private final Map<TypeName, EnumType> enumTypes = newHashMap();
private final Map<TypeName, ServiceType> serviceTypes = newHashMap();
/**
* Prevents direct instantiation.
*/
private Builder() {
}
@CanIgnoreReturnValue
public Builder add(MessageType type) {
TypeName name = type.name();
messageTypes.put(name, type);
return this;
}
@CanIgnoreReturnValue
public Builder add(EnumType type) {
TypeName name = type.name();
enumTypes.put(name, type);
return this;
}
@CanIgnoreReturnValue
public Builder add(ServiceType type) {
TypeName name = type.name();
serviceTypes.put(name, type);
return this;
}
@CanIgnoreReturnValue
public Builder addAll(Iterable<MessageType> types) {
checkNotNull(types);
ImmutableMap<TypeName, MessageType> map = uniqueIndex(types, MessageType::name);
messageTypes.putAll(map);
return this;
}
/**
* Creates a new instance of {@code TypeSet}.
*
* @return new instance of {@code TypeSet}
*/
public TypeSet build() {
return new TypeSet(this);
}
}
}
|
package org.jetel.util;
import java.util.Properties;
public class CommandBuilder {
private final char EQUAL_CHAR = '=';
private final char DEFAULT_PARAMETER_DELIMITER = ' ';
private final char DEFAULT_END_CHARACTER = '\n';
private final static String DEFAULT_SWITCH_MARK = "-";
private final String TRUE = "true";
StringBuilder command;
char parameterDelimiter;
char endCharacter;
String switchMark;
Properties params;
/**
* Creates command object
*
* @param command input command as string
* @param parameterDelimiter char, which will be used as parameter delimiter
* @param endCharacter char, which will be used as last char
*/
public CommandBuilder(String command, char parameterDelimiter, char endCharacter){
this.command = new StringBuilder(command);
this.parameterDelimiter = parameterDelimiter;
this.endCharacter = endCharacter;
this.switchMark = DEFAULT_SWITCH_MARK;
}
/**
* Creates command object with default parameter delimiter (' '), end char ('\n') and switch mark ("-")
*
* @param command char, which will be used as
*/
public CommandBuilder(String command){
this.command = new StringBuilder(command);
this.parameterDelimiter = DEFAULT_PARAMETER_DELIMITER;
this.endCharacter = DEFAULT_END_CHARACTER;
this.switchMark = DEFAULT_SWITCH_MARK;
}
/**
* Creates command object
*
* @param command input command as string
* @param switchMark String, which will be used as switchMark; for example "-" or "--"
*/
public CommandBuilder(String command, String switchMark){
this(command);
this.switchMark = switchMark;
}
/**
* @return parameters
*/
public Properties getParams() {
return params;
}
/**
* Sets parameters
*
* @param params
*/
public void setParams(Properties params) {
this.params = params;
}
/**
* @return complete command
*/
public String getCommand(){
return command.toString() + endCharacter;
}
/**
* if paramName is in properties adds to the end of command:
* " paramName=paramValue"
*
* @param paramName
*/
public void addParameter(String paramName) {
if (params.containsKey(paramName)) {
command.append(parameterDelimiter);
command.append(paramName);
command.append(EQUAL_CHAR);
command.append(params.getProperty(paramName));
}
}
/**
* if paramName is in properties adds to the end of command:
* " paramName=paramValue"
* if doesn't exist:
* " paramName=defaultValue"
*
* @param paramName
* @param defaultValue
*/
public void addParameter(String paramName, String defaultValue){
command.append(parameterDelimiter);
command.append(paramName);
command.append(EQUAL_CHAR);
command.append(params.getProperty(paramName, defaultValue));
}
/**
* if paramName is in properties adds to the end of command:
* "[ prefix] paramName=paramValue"
*
* @param prefix string to write before paramName
* @param addPrefix indicates if write prefix or not
* @param paramName
* @return true if prefix was written (parmName is among parameters)
*/
public boolean addParameterWithPrefixClauseConditionally(String prefix, boolean addPrefix,
String paramName){
if (params.containsKey(paramName)) {
if (addPrefix) {
command.append(parameterDelimiter);
command.append(prefix);
}
command.append(parameterDelimiter);
command.append(paramName);
command.append(EQUAL_CHAR);
command.append(params.getProperty(paramName));
return true;
}else{
return false;
}
}
/**
* if paramName is in properties adds to the end of command:
* "[ prefix] paramName<i>equalChar</i>paramValue"
*
* @param prefix string to write before paramName
* @param addPrefix indicates if write prefix or not
* @param paramName
* @param equalChar string, which will be written between paramName and paramValue
* @return true if prefix was written (parmName is among parameters)
*/
public boolean addParameterSpecialWithPrefixClauseConditionally(String prefix, boolean addPrefix,
String paramName, String equalChar){
if (params.containsKey(paramName)) {
if (addPrefix) {
command.append(parameterDelimiter);
command.append(prefix);
}
command.append(parameterDelimiter);
command.append(paramName);
command.append(equalChar);
command.append(params.getProperty(paramName));
return true;
}else{
return false;
}
}
/**
* if paramName is in properties adds to the end of command:
* "[ prefix] paramName="paramValue""
*
* @param prefix string to write before paramName
* @param addPrefix indicates if write prefix or not
* @param paramName
* @return true if prefix was written (parmName is among parameters)
*/
public boolean addAndQuoteParameterWithPrefixClauseConditionally(String prefix, boolean addPrefix,
String paramName){
if (params.containsKey(paramName)) {
if (addPrefix) {
command.append(parameterDelimiter);
command.append(prefix);
}
command.append(parameterDelimiter);
command.append(paramName);
command.append(EQUAL_CHAR);
String tmp = params.getProperty(paramName);
if (StringUtils.isQuoted(tmp)) {
command.append(tmp);
}else{
command.append(StringUtils.quote(tmp));
}
return true;
}else{
return false;
}
}
/**
* if paramName is in properties and has TRUE value adds to the end of command:
* "[ prefix] paramName"
*
* @param prefix string to write before paramName
* @param addPrefix indicates if write prefix or not
* @param paramName
* @return true if prefix was written (= paramName found and has "true" value)
*/
public boolean addBooleanParameterWithPrefixClauseConditionally(String prefix, boolean addPrefix,
String paramName){
if (params.containsKey(paramName) && params.getProperty(paramName).equalsIgnoreCase(TRUE)) {
if (addPrefix) {
command.append(parameterDelimiter);
command.append(prefix);
}
command.append(parameterDelimiter);
command.append(paramName);
return true;
}else{
return false;
}
}
/**
* if paramName is in properties adds to the end of command:
* " prefix<i>paramValue</i>
*
* @param prefix
* @param paramName
*/
public void addParameterWithPrefix(String prefix, String paramName){
if (params.containsKey(paramName)) {
command.append(parameterDelimiter);
command.append(prefix);
command.append(params.getProperty(paramName));
}
}
/**
* if paramName is in properties and has TRUE value adds to the end of command:
* " paramName"
*
* @param paramName
*/
public void addBooleanParameter(String paramName){
if (params.containsKey(paramName) && params.getProperty(paramName).equalsIgnoreCase(TRUE)) {
command.append(parameterDelimiter);
command.append(paramName);
}
}
/**
* if paramName is in properties adds to the end of command:
* " paramName<i>equalChar</i>paramValue"
*
* @param paramName
* @param equalChar
*/
public void addParameterSpecial(String paramName, String equalChar){
if (params.containsKey(paramName)) {
command.append(parameterDelimiter);
command.append(paramName);
command.append(equalChar);
command.append(params.getProperty(paramName));
}
}
/**
* if paramName is in properties adds to the end of command:
* " <i><b>switchMark</b>switchChar</i>paramValue"<br>
* for exmaple: -P"password"
*
* @param paramName
* @param switchChar
*/
public void addParameterSwitch(String paramName, char switchChar) {
if (params.containsKey(paramName)) {
command.append(parameterDelimiter);
command.append(switchMark);
command.append(switchChar);
command.append(StringUtils.quote(params.getProperty(paramName)));
}
}
/**
* if paramName is in properties adds to the end of command:
* " <i><b>switchMark</b>switchString</i>paramValue"<br>
* for exmaple: -PASSWORD password
*
* @param paramName
* @param switchString
*/
public boolean addParameterSwitch(String paramName, String switchString) {
if (params.containsKey(paramName)) {
command.append(parameterDelimiter);
command.append(switchMark);
command.append(switchString);
command.append(" ");
command.append(StringUtils.quote(params.getProperty(paramName)));
return true;
}
return false;
}
/**
* if value isn;t null adds to the end of command:
* " <i><b>switchMark</b>switchChar</i>value"<br>
* for exmaple: -P"password"
*
* @param switchChar
* @param value
*/
public void addSwitch(char switchChar, String value) {
if (value != null) {
command.append(parameterDelimiter);
command.append(switchMark);
command.append(switchChar);
command.append(StringUtils.quote(value));
}
}
/**
* if paramName is in properties adds to the end of command:
* " <i><b>switchMark</b>switchChar</i>"<br>
* for exmaple: -P
*
* @param paramName
* @param switchChar
*/
public boolean addParameterBooleanSwitch(String paramName, char switchChar) {
return addParameterBooleanSwitch(paramName, String.valueOf(switchChar));
}
/**
* if paramValue isn't null or paramName is in properties adds to the end of command:
* " <i><b>switchMark</b>switchChar</i>paramValue"<br>
* for exmaple: --host="localhost"
*
* @param paramName
* @param switchString
* @param paramValue
*/
public void addParameterSwitchWithEqualChar(String paramName, String switchString, String paramValue) {
if (paramValue == null && (paramName == null || !params.containsKey(paramName))) {
return;
}
command.append(parameterDelimiter);
command.append(switchMark);
command.append(switchString);
command.append(EQUAL_CHAR);
if (paramValue != null) {
command.append(StringUtils.specCharToString(paramValue));
} else {
command.append(StringUtils.specCharToString(params.getProperty(paramName)));
}
}
/**
* if paramName is in properties adds to the end of command:
* " <i><b>switchMark</b>switchChar</i>"<br>
* for exmaple: --compress
*
* @param paramName
* @param switchString
*/
public boolean addParameterBooleanSwitch(String paramName, String switchString) {
if (params.containsKey(paramName) && !"false".equalsIgnoreCase(params.getProperty(paramName))) {
addBooleanSwitch(switchString);
return true;
}
return false;
}
/**
* if paramName is in properties adds to the end of command:
* " <i><b>switchMark</b>switchChar</i>"<br>
* for exmaple: --compress
*
* @param paramName
* @param switchString
* @param defaultValue
*/
public boolean addParameterBooleanSwitch(String paramName, String switchString, boolean defaultValue) {
if (params.containsKey(paramName)) {
addParameterBooleanSwitch(paramName, switchString);
return true;
}
if (defaultValue) {
addBooleanSwitch(switchString);
}
return defaultValue;
}
private void addBooleanSwitch(String switchString) {
command.append(parameterDelimiter);
command.append(switchMark);
command.append(switchString);
}
/**
* appends given string to the end of command
*
* @param str
*/
public void append(String str){
command.append(str);
}
@Override
public String toString() {
return command.toString();
}
}
|
public class DecryptTextMain {
public static void main(String[] args) {
String hasloDoKeystora = "ala ma kota";
String aliasHasla = "mojAlias";
String sciezkaDoKeyStore = "D:\\eclipse\\Semestr4\\SzyfrStrumieniowy\\keyStore.ks";
String wiadomosc = "between the hammer and the anvil.";
byte[] kryptogram = RC4wersjaWlasciwa.zakoduj(wiadomosc,
RC4wersjaWlasciwa.pobierzKlucz(sciezkaDoKeyStore, aliasHasla,
hasloDoKeystora));
RC4wersjaWlasciwa.zapiszZakodowanaWiadomoscDoPilku(kryptogram);
String wiadomosc2 = "nobody was hurt in the incident.";
byte[] kryptogram2 = RC4wersjaWlasciwa.zakoduj(wiadomosc2,
RC4wersjaWlasciwa.pobierzKlucz(sciezkaDoKeyStore, aliasHasla,
hasloDoKeystora));
// System.out.println(wiadomosc);
// System.out.println(new String(kryptogram));
// System.out.println(wiadomosc2);
// System.out.println(new String(kryptogram2));
// System.out.println("Xor kryptogramow: ");
byte[] xorKryptogramow = DecryptText
.wykonajXor(kryptogram, kryptogram2);
// DecryptText.wyswietlenie(xorKryptogramow);
System.out.println("");
/* tablice najczesciej wystepujacych liter */
byte[] tablicaE = new byte[xorKryptogramow.length];
for (int i = 0; i < xorKryptogramow.length; i++) {
tablicaE[i] = 'e';
}
System.out.println("tablicaE: " + new String(tablicaE));
byte[] xorXorIWyrazenie2 = DecryptText.wykonajXor(xorKryptogramow,
tablicaE);
System.out
.println("Wartosc xora (xorKryptogramow i tablicyLiterE): "
+ new String(xorXorIWyrazenie2));
}
}
|
package org.mozartoz.truffle.translator;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.mozartoz.bootcompiler.BootCompiler;
import org.mozartoz.bootcompiler.ast.Statement;
import org.mozartoz.bootcompiler.symtab.Program;
import org.mozartoz.bootcompiler.transform.ConstantFolding;
import org.mozartoz.bootcompiler.transform.Desugar;
import org.mozartoz.bootcompiler.transform.DesugarClass;
import org.mozartoz.bootcompiler.transform.DesugarFunctor;
import org.mozartoz.bootcompiler.transform.Namer;
import org.mozartoz.bootcompiler.transform.Simplify;
import org.mozartoz.bootcompiler.transform.TailCallMarking;
import org.mozartoz.truffle.Options;
import org.mozartoz.truffle.nodes.DerefNode;
import org.mozartoz.truffle.nodes.OzRootNode;
import org.mozartoz.truffle.nodes.builtins.BuiltinsManager;
import org.mozartoz.truffle.nodes.control.SequenceNode;
import org.mozartoz.truffle.nodes.literal.LiteralNode;
import org.mozartoz.truffle.nodes.local.InitializeTmpNode;
import org.mozartoz.truffle.nodes.local.InitializeVarNode;
import org.mozartoz.truffle.nodes.local.ReadLocalVariableNode;
import org.mozartoz.truffle.runtime.OzArguments;
import org.mozartoz.truffle.runtime.OzLanguage;
import org.mozartoz.truffle.runtime.OzProc;
import org.mozartoz.truffle.runtime.OzThread;
import org.mozartoz.truffle.runtime.PropertyRegistry;
import com.oracle.truffle.api.RootCallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.MaterializedFrame;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.source.Source;
public class Loader {
public static final String PROJECT_ROOT = getProjectRoot();
public static final String MOZART2_DIR = new File(PROJECT_ROOT).getParent() + "/mozart2";
public static final String LOCAL_LIB_DIR = PROJECT_ROOT + "/lib";
static final String LIB_DIR = MOZART2_DIR + "/lib";
static final String MAIN_LIB_DIR = LIB_DIR + "/main";
static final String TOOLS_DIR = LIB_DIR + "/tools";
static final String BASE_FILE_NAME = MAIN_LIB_DIR + "/base/Base.oz";
static final String INIT_FUNCTOR = MAIN_LIB_DIR + "/init/Init.oz";
static final String MAIN_IMAGE = PROJECT_ROOT + "/Main.image";
public static final String OZWISH = MOZART2_DIR + "/wish/ozwish";
public static final String[] SYSTEM_LOAD_PATH = new String[] {
MAIN_LIB_DIR + "/sys",
MAIN_LIB_DIR + "/support",
MOZART2_DIR + "/vm/boostenv/lib/",
MAIN_LIB_DIR + "/sp",
MAIN_LIB_DIR + "/op",
MAIN_LIB_DIR + "/cp",
MAIN_LIB_DIR + "/ap",
MAIN_LIB_DIR + "/wp",
TOOLS_DIR + "/panel",
TOOLS_DIR + "/browser",
LIB_DIR + "/compiler",
};
public static final Source MAIN_SOURCE = Source.newBuilder("").name("main").mimeType(OzLanguage.MIME_TYPE).internal().build();
// public static final PolyglotEngine ENGINE = PolyglotEngine.newBuilder().build();
private static long last = System.currentTimeMillis();
private static void tick(String desc) {
if (Options.MEASURE_STARTUP) {
long now = System.currentTimeMillis();
long duration = now - last;
if (duration > 5) {
System.out.println(String.format("%4d", duration) + " " + desc);
}
last = now;
}
}
private static final Loader INSTANCE = new Loader();
public static Loader getInstance() {
return INSTANCE;
}
private DynamicObject base = null;
private final PropertyRegistry propertyRegistry;
private Loader() {
BuiltinsManager.defineBuiltins();
propertyRegistry = PropertyRegistry.INSTANCE;
propertyRegistry.initialize();
}
public DynamicObject loadBase() {
if (base == null) {
tick("start loading Base");
OzRootNode baseRootNode = parseBase();
tick("translated Base");
Object baseFunctor = execute(baseRootNode);
OzRootNode applyBase = BaseFunctor.apply(baseFunctor);
Object result = execute(applyBase);
assert result instanceof DynamicObject;
base = (DynamicObject) result;
}
return base;
}
private OzRootNode parseBase() {
tick("enter parseBase");
Program program = BootCompiler.buildBaseEnvProgram(createSource(BASE_FILE_NAME),
BuiltinsRegistry.getBuiltins(), BaseDeclarations.getDeclarations());
tick("parse Base");
Statement ast = compile(program, "the base environment");
Translator translator = new Translator();
FrameSlot topLevelResultSlot = translator.addRootSymbol(program.topLevelResultSymbol());
return translator.translateAST("<Base>", ast, node -> {
return SequenceNode.sequence(
new InitializeVarNode(topLevelResultSlot),
node,
DerefNode.create(new ReadLocalVariableNode(topLevelResultSlot)));
});
}
public OzRootNode parseMain(Source source) {
DynamicObject base = loadBase();
String fileName = new File(source.getPath()).getName();
Program program = BootCompiler.buildMainProgram(source,
BuiltinsRegistry.getBuiltins(), BaseDeclarations.getDeclarations());
Statement ast = compile(program, fileName);
Translator translator = new Translator();
FrameSlot baseSlot = translator.addRootSymbol(program.baseEnvSymbol());
return translator.translateAST(fileName, ast, node -> {
return SequenceNode.sequence(
new InitializeTmpNode(baseSlot, new LiteralNode(base)),
node);
});
}
private boolean eagerLoad = false;
public OzRootNode parseFunctor(Source source) {
DynamicObject base = loadBase();
String fileName = new File(source.getPath()).getName();
System.out.println("Loading " + fileName);
tick("start parse");
Program program = BootCompiler.buildProgram(source, false, eagerLoad,
BuiltinsRegistry.getBuiltins(), BaseDeclarations.getDeclarations());
tick("parse functor " + fileName);
Statement ast = compile(program, fileName);
tick("compiled functor " + fileName);
Translator translator = new Translator();
FrameSlot baseSlot = translator.addRootSymbol(program.baseEnvSymbol());
FrameSlot topLevelResultSlot = translator.addRootSymbol(program.topLevelResultSymbol());
OzRootNode rootNode = translator.translateAST(fileName, ast, node -> {
return SequenceNode.sequence(
new InitializeTmpNode(baseSlot, new LiteralNode(base)),
new InitializeVarNode(topLevelResultSlot),
node,
DerefNode.create(new ReadLocalVariableNode(topLevelResultSlot)));
});
tick("translated functor " + fileName);
return rootNode;
}
public void run(Source source) {
execute(parseMain(source));
}
public void runFunctor(Source source, String... args) {
tick("start loading Main");
final OzProc main;
if (new File(MAIN_IMAGE).exists()) {
try {
main = OzSerializer.deserialize(MAIN_IMAGE, OzProc.class);
} catch (Throwable t) {
System.err.println("Got " + t.getClass().getSimpleName() + " while deserializing, removing Main.image");
new File(MAIN_IMAGE).delete();
throw t;
}
tick("deserialized Main");
base = getBaseFromMain(main);
} else {
eagerLoad = true;
try {
Object initFunctor = execute(parseFunctor(createSource(INIT_FUNCTOR)));
Object applied = execute(InitFunctor.apply(initFunctor));
main = (OzProc) ((DynamicObject) applied).get("main");
OzSerializer.serialize(main, MAIN_IMAGE);
} finally {
eagerLoad = false;
}
}
propertyRegistry.setApplicationURL(source.getPath());
propertyRegistry.setApplicationArgs(args);
main.rootCall("main");
waitThreads();
}
private void waitThreads() {
while (OzThread.getNumberOfThreadsRunnable() > 1) {
OzThread.getCurrent().yield(null);
}
}
private DynamicObject getBaseFromMain(OzProc main) {
MaterializedFrame topFrame = OzArguments.getParentFrame(main.declarationFrame);
FrameSlot baseSlot = topFrame.getFrameDescriptor().getSlots().get(0);
assert baseSlot.getIdentifier().toString().contains("<Base>");
return (DynamicObject) topFrame.getValue(baseSlot);
}
// Shutdown
private List<Process> childProcesses = new LinkedList<>();
public void registerChildProcess(Process process) {
childProcesses.add(process);
}
public void shutdown(int exitCode) {
for (Process process : childProcesses) {
process.destroyForcibly();
}
System.exit(exitCode);
}
// Helpers
public static Source createSource(String path) {
File file = new File(path);
try {
return Source.newBuilder(file).name(file.getName()).mimeType(OzLanguage.MIME_TYPE).build();
} catch (IOException e) {
throw new Error(e);
}
}
public Object execute(OzRootNode rootNode) {
RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(rootNode);
Object[] arguments = OzArguments.pack(null, new Object[0]);
Object value = callTarget.call(arguments);
tick("executed " + rootNode.getName());
return value;
}
private Statement compile(Program program, String fileName) {
Statement ast = applyTransformations(program);
BootCompiler.checkCompileErrors(program, fileName);
return ast;
}
private Statement applyTransformations(Program program) {
Namer.apply(program);
DesugarFunctor.apply(program);
DesugarClass.apply(program);
Desugar.apply(program);
ConstantFolding.apply(program);
Simplify.apply(program);
TailCallMarking.apply(program);
return program.rawCode();
}
private static String getProjectRoot() {
String thisFile = Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String path = new File(thisFile).getParent();
return path;
}
}
|
package org.codeforest;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.behaviors.vp.OrbitBehavior;
import com.sun.j3d.utils.geometry.ColorCube;
import javax.media.j3d.*;
import javax.vecmath.*;
import org.codeforest.model.VertexSceneContext;
import org.codeforest.scenegraph.BoxTreeLayout;
import org.codeforest.scenegraph.EdgeNodeFactory;
import org.codeforest.scenegraph.LineEdgeFactory;
import org.codeforest.scenegraph.OneLineLayout;
import org.codeforest.scenegraph.TreePlanter;
import org.codeforest.scenegraph.TreeWidthCalculator;
import org.codeforest.scenegraph.VertexNodeFactory;
import org.codeforest.scenegraph.VertexTreeSceneBuilder;
import org.jgrapht.DirectedGraph;
import org.jgrapht.EdgeFactory;
import org.jgrapht.graph.DefaultDirectedGraph;
import java.awt.GraphicsConfiguration;
import java.util.ArrayList;
import java.util.List;
/**
* First test: Display a simple JGraph
*/
public class CodeForest extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;
private static final String A = "A";
private static final String B = "B";
private static final String C = "C";
private static final String D = "D";
private static final String E = "E";
private static final String F = "F";
private static final String G = "G";
private static final String H = "H";
private static final String I = "I";
private static final String J = "J";
private static final String K = "K";
private static final String L = "L";
private static final String M = "M";
private static final String N = "N";
private static final String O = "O";
private SimpleUniverse univ = null;
private BranchGroup scene = null;
private javax.swing.JPanel drawingPanel;
public CodeForest() {
// Initialize the GUI components
initComponents();
// Create Canvas3D and SimpleUniverse; add canvas to drawing panel
Canvas3D c = createUniverse();
drawingPanel.add(c, java.awt.BorderLayout.CENTER);
// Create the content branch and add it to the universe
scene = createSceneGraph();
univ.addBranchGraph(scene);
OrbitBehavior orbit = new OrbitBehavior(c);
orbit.setSchedulingBounds(new BoundingSphere(
new Point3d(0.0, 0.0, 0.0), Double.MAX_VALUE));
univ.getViewingPlatform().setViewPlatformBehavior(orbit);
}
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
DirectedGraph<String, String> graph = new DefaultDirectedGraph<String, String>(
new EdgeFactory<String, String>() {
public String createEdge(String sourceVertex,
String targetVertex) {
return sourceVertex + targetVertex;
};
});
graph.addVertex(A);
graph.addVertex(B);
graph.addVertex(C);
graph.addVertex(D);
graph.addVertex(E);
graph.addVertex(F);
graph.addVertex(G);
graph.addVertex(H);
graph.addVertex(I);
graph.addVertex(J);
graph.addVertex(K);
graph.addVertex(L);
graph.addVertex(M);
graph.addVertex(N);
graph.addVertex(O);
graph.addEdge(A, B);
graph.addEdge(A, C);
graph.addEdge(B, D);
graph.addEdge(B, E);
graph.addEdge(B, F);
graph.addEdge(C, G);
graph.addEdge(D, H);
graph.addEdge(D, I);
graph.addEdge(D, J);
graph.addEdge(E, K);
graph.addEdge(E, L);
graph.addEdge(F, M);
graph.addEdge(F, N);
graph.addEdge(G, O);
VertexSceneContext<String> context = new VertexSceneContext<String>();
// calculate vertex widths for subgraph
new TreeWidthCalculator<String, String>(context, graph).calculateVertexWidth(A);
VertexNodeFactory<String> shapeFactory = new VertexNodeFactory<String>() {
public Node createNode(String vertex) {
return new ColorCube(0.4);
}
};
EdgeNodeFactory<String, String> edgeNodeFactory = new LineEdgeFactory<String, String>();
VertexTreeSceneBuilder<String, String> treeBuilder = new VertexTreeSceneBuilder<String, String>(
context, graph, shapeFactory, edgeNodeFactory, new BoxTreeLayout<String>(context, 2d, 3d));
TreePlanter<String> planter = new TreePlanter<String>(context, treeBuilder, new OneLineLayout<String>(context, 2d, 2d));
List<String> trees = new ArrayList<String>(4);
trees.add(A);
trees.add(B);
trees.add(C);
trees.add(D);
trees.add(E);
trees.add(F);
trees.add(G);
TransformGroup transformGroup = planter.createScene(trees);
objRoot.addChild(transformGroup);
// Have Java 3D perform optimizations on this scene graph.
objRoot.compile();
return objRoot;
}
private Canvas3D createUniverse() {
// Get the preferred graphics configuration for the default screen
GraphicsConfiguration config = SimpleUniverse
.getPreferredConfiguration();
// Create a Canvas3D using the preferred configuration
Canvas3D c = new Canvas3D(config);
// Create simple universe with view branch
univ = new SimpleUniverse(c);
// This will move the ViewPlatform back a bit so the
// objects in the scene can be viewed.
ViewingPlatform viewingPlatform = univ.getViewingPlatform();
TransformGroup viewTransform = viewingPlatform
.getViewPlatformTransform();
Transform3D t3d = new Transform3D();
t3d.lookAt(new Point3d(0, 0, 150), new Point3d(0, 0, 0), new Vector3d(
0, 1, 0));
t3d.invert();
viewTransform.setTransform(t3d);
View view = univ.getViewer().getView();
view.setBackClipDistance(100.0);
view.setMinimumFrameCycleTime(5);
return c;
}
private void initComponents() {
drawingPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("HelloUniverse");
drawingPanel.setLayout(new java.awt.BorderLayout());
drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500));
getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER);
pack();
}
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CodeForest().setVisible(true);
}
});
}
}
|
package org.codeforest;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.behaviors.vp.OrbitBehavior;
import com.sun.j3d.utils.geometry.ColorCube;
import javax.media.j3d.*;
import javax.vecmath.*;
import org.codeforest.graph.NodeFactory;
import org.codeforest.graph.VertexTreeSceneBuilder;
import org.codeforest.model.VertexSceneContext;
import org.jgrapht.DirectedGraph;
import org.jgrapht.EdgeFactory;
import org.jgrapht.graph.DefaultDirectedGraph;
import java.awt.GraphicsConfiguration;
/**
* First test: Display a simple JGraph
*/
public class CodeForest extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;
private static final String A = "A";
private static final String B = "B";
private static final String C = "C";
private static final String D = "D";
private static final String E = "E";
private static final String F = "F";
private static final String G = "G";
private static final String H = "H";
private static final String I = "I";
private static final String J = "J";
private static final String K = "K";
private static final String L = "L";
private static final String M = "M";
private static final String N = "N";
private static final String O = "O";
private SimpleUniverse univ = null;
private BranchGroup scene = null;
private javax.swing.JPanel drawingPanel;
/**
* Creates new form HelloUniverse
*/
public CodeForest() {
// Initialize the GUI components
initComponents();
// Create Canvas3D and SimpleUniverse; add canvas to drawing panel
Canvas3D c = createUniverse();
drawingPanel.add(c, java.awt.BorderLayout.CENTER);
// Create the content branch and add it to the universe
scene = createSceneGraph();
univ.addBranchGraph(scene);
OrbitBehavior orbit = new OrbitBehavior(c);
orbit.setSchedulingBounds(new BoundingSphere(
new Point3d(0.0, 0.0, 0.0), Double.MAX_VALUE));
univ.getViewingPlatform().setViewPlatformBehavior(orbit);
}
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
DirectedGraph<String, String> graph = new DefaultDirectedGraph<String, String>(
new EdgeFactory<String, String>() {
public String createEdge(String sourceVertex,
String targetVertex) {
return sourceVertex + targetVertex;
};
});
graph.addVertex(A);
graph.addVertex(B);
graph.addVertex(C);
graph.addVertex(D);
graph.addVertex(E);
graph.addVertex(F);
graph.addVertex(G);
graph.addVertex(H);
graph.addVertex(I);
graph.addVertex(J);
graph.addVertex(K);
graph.addVertex(L);
graph.addVertex(M);
graph.addVertex(N);
graph.addVertex(O);
graph.addEdge(A, B);
graph.addEdge(A, C);
graph.addEdge(B, D);
graph.addEdge(B, E);
graph.addEdge(B, F);
graph.addEdge(C, G);
graph.addEdge(D, H);
graph.addEdge(D, I);
graph.addEdge(D, J);
graph.addEdge(E, K);
graph.addEdge(E, L);
graph.addEdge(F, M);
graph.addEdge(F, N);
graph.addEdge(G, O);
NodeFactory<String> shapeFactory = new NodeFactory<String>() {
public Node createNode(String vertex) {
return new ColorCube(0.4);
}
};
VertexSceneContext<String> context = new VertexSceneContext<String>();
VertexTreeSceneBuilder<String, String> sceneBuilder = new VertexTreeSceneBuilder<String, String>(
context, graph, shapeFactory, 2d, 3d);
TransformGroup transformGroup = sceneBuilder.createScene(A);
objRoot.addChild(transformGroup);
// Have Java 3D perform optimizations on this scene graph.
objRoot.compile();
return objRoot;
}
private Canvas3D createUniverse() {
// Get the preferred graphics configuration for the default screen
GraphicsConfiguration config = SimpleUniverse
.getPreferredConfiguration();
// Create a Canvas3D using the preferred configuration
Canvas3D c = new Canvas3D(config);
// Create simple universe with view branch
univ = new SimpleUniverse(c);
// This will move the ViewPlatform back a bit so the
// objects in the scene can be viewed.
ViewingPlatform viewingPlatform = univ.getViewingPlatform();
TransformGroup viewTransform = viewingPlatform
.getViewPlatformTransform();
Transform3D t3d = new Transform3D();
t3d.lookAt(new Point3d(0, 0, 150), new Point3d(0, 0, 0), new Vector3d(
0, 1, 0));
t3d.invert();
viewTransform.setTransform(t3d);
View view = univ.getViewer().getView();
view.setBackClipDistance(100.0);
view.setMinimumFrameCycleTime(5);
return c;
}
private void initComponents() {
drawingPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("HelloUniverse");
drawingPanel.setLayout(new java.awt.BorderLayout());
drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500));
getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER);
pack();
}
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CodeForest().setVisible(true);
}
});
}
}
|
package org.nutz.castor;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.nutz.castor.castor.Array2Array;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.TypeExtractor;
/**
* Castor
*
* <pre>
* Castors.me().cast(obj, fromType, toType);
* </pre>
*
*
* @author zozoh(zozohtnt@gmail.com)
* @author Wendal(wendal1985@gmail.com)
*/
public class Castors {
// find the jar file where contains Castors
private static String[] findCastorsInJar(Class<?> baseClass) {
String fpath = getBasePath(baseClass);
if (fpath == null)
return null;
int posBegin = fpath.indexOf("file:");
int posEnd = fpath.lastIndexOf('!');
if (posBegin > 0 && (posEnd - posBegin - 5) > 0) {
String jarPath = fpath.substring(posBegin + 5, posEnd);
try {
ZipEntry[] entrys = Files.findEntryInZip(new ZipFile(jarPath), baseClass
.getPackage().getName().replace('.', '/')
+ "/\\w*.class");
if (null != entrys && entrys.length > 0) {
String[] classNames = new String[entrys.length];
for (int i = 0; i < entrys.length; i++) {
String ph = entrys[i].getName();
classNames[i] = ph.substring(0, ph.lastIndexOf('.')).replaceAll("[\\\\|/]",
".");
}
return classNames;
}
} catch (Throwable e) {
throw Lang.wrapThrow(e);
}
}
return null;
}
private static String[] findCastorsInClassPath(Class<?> classZ) {
String basePath = getBasePath(classZ);
if (basePath == null)
return null;
try {
File[] files = Files.findFile(basePath).listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
if (null != files && files.length > 0) {
String[] classNames = new String[files.length];
Package packageA = classZ.getPackage();
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
String classShortName = fileName.substring(0, fileName.length()
- ".class".length());
classNames[i] = packageA.getName() + "." + classShortName;
}
return classNames;
}
} catch (SecurityException e) {
// In GAE, it will case SecurityException, because you can't use
// listFiles()
} catch (NullPointerException e) {
// if this class store in a jar, it will throw this Exception,
// because Files.findFile(basePath) will return null
}
return null;
}
private static Castors one;
private static TypeExtractor typeExtractor = null;
private static List<Class<?>> castorPaths = null;
private static Object castorSetting;
public static synchronized Castors resetSetting(Object setting) {
return setSetting(new CastorSetting());
}
public static synchronized Castors setSetting(Object setting) {
if (setting != null) {
castorSetting = setting;
one = new Castors(setting);
}
return me();
}
public static synchronized Castors setCastorPaths(List<Class<?>> paths) {
castorPaths = paths;
return setSetting(castorSetting);
}
public static synchronized Castors resetCastorPaths() {
List<Class<?>> list = new ArrayList<Class<?>>();
list.add(Array2Array.class);
return setCastorPaths(list);
}
public static synchronized Castors addCastorPaths(Class<?>... paths) {
if (null != paths) {
for (Class<?> path : paths)
castorPaths.add(path);
}
return setSetting(castorSetting);
}
public static synchronized Castors setTypeExtractor(TypeExtractor te) {
typeExtractor = te;
return me();
}
public static Castors me() {
if (null == one)
synchronized (Castors.class) {
if (null == one)
one = new Castors(castorSetting);
}
return one;
}
private Castors(Object setting) {
if (null == setting)
setting = new CastorSetting();
// make setting map
HashMap<Class<?>, Method> settingMap = new HashMap<Class<?>, Method>();
for (Method m1 : setting.getClass().getMethods()) {
Class<?>[] pts = m1.getParameterTypes();
if (pts.length == 1 && Castor.class.isAssignableFrom(pts[0])) {
settingMap.put(pts[0], m1);
}
}
// build castors
this.map = new HashMap<String, Map<String, Castor<?, ?>>>();
if (null == castorPaths) {
castorPaths = new ArrayList<Class<?>>();
castorPaths.add(Array2Array.class);
}
for (Iterator<Class<?>> it = castorPaths.iterator(); it.hasNext();) {
Class<?> baseClass = it.next();
if (baseClass == null)
continue;
String[] classNames = findCastorsInClassPath(baseClass);
if (null == classNames) {
classNames = findCastorsInJar(baseClass);
}
if (null == classNames)
continue;
for (String className : classNames) {
try {
Castor<?, ?> castor = null;
Class<?> klass = Class.forName(className);
if (Modifier.isAbstract(klass.getModifiers()))
continue;
castor = (Castor<?, ?>) klass.newInstance();
Map<String, Castor<?, ?>> map2 = this.map.get(castor.getFromClass().getName());
if (null == map2) {
map2 = new HashMap<String, Castor<?, ?>>();
this.map.put(castor.getFromClass().getName(), map2);
}
if (!map2.containsKey(castor.getToClass().getName())) {
Method m = settingMap.get(castor.getClass());
if (null == m) {
for (Iterator<Class<?>> mit = settingMap.keySet().iterator(); mit
.hasNext();) {
Class<?> cc = mit.next();
if (cc.isAssignableFrom(klass)) {
m = settingMap.get(cc);
break;
}
}
}
if (null != m)
m.invoke(castorSetting, castor);
map2.put(castor.getToClass().getName(), castor);
}
} catch (Throwable e) {
System.err.println(String.format("Fail to create castor [%s] because: %s",
className, e.getMessage()));
}
}
}
}
/**
* First index is "from" (source) The second index is "to" (target)
*/
private Map<String, Map<String, Castor<?, ?>>> map;
@SuppressWarnings("unchecked")
public <F, T> T cast(Object src, Class<F> fromType, Class<T> toType, String... args)
throws FailToCastObjectException {
if (null == src) {
if (toType.isPrimitive())
return cast(0, int.class, toType);
return null;
}
if (fromType == toType || toType == null || fromType == null)
return (T) src;
if (fromType.getName().equals(toType.getName()))
return (T) src;
if (toType.isAssignableFrom(fromType))
return (T) src;
Mirror<?> from = Mirror.me(fromType, typeExtractor);
if (from.canCastToDirectly(toType)) // Use language built-in cases
return (T) src;
Mirror<T> to = Mirror.me(toType, typeExtractor);
Castor c = null;
Class<?>[] fets = from.extractTypes();
Class<?>[] tets = to.extractTypes();
for (Class<?> ft : fets) {
Map<String, Castor<?, ?>> m2 = map.get(ft.getName());
if (null != m2)
for (Class<?> tt : tets) {
c = m2.get(tt.getName());
if (null != c)
break;
}
if (null != c)
break;
}
if (null == c)
throw new FailToCastObjectException(String.format(
"Can not find castor for '%s'=>'%s' because:\n%s", fromType.getName(), toType
.getName(), "Fail to find matched castor"));
try {
return (T) c.cast(src, toType, args);
} catch (FailToCastObjectException e) {
throw e;
} catch (Exception e) {
throw new FailToCastObjectException(String.format(
"Fail to cast from <%s> to <%s> for {%s} because:\n%s:%s", fromType.getName(),
toType.getName(), src, e.getClass().getSimpleName(), e.getMessage()));
}
}
public <T> T castTo(Object src, Class<T> toType) throws FailToCastObjectException {
return cast(src, null == src ? null : src.getClass(), toType);
}
public String castToString(Object src) {
try {
return castTo(src, String.class);
} catch (FailToCastObjectException e) {
return String.valueOf(src);
}
}
/**
* The function try to return the file path of one class. If it exists in
* regular directory, it will return as "D:/folder/folder/name.class" in
* windows, and "/folder/folder/name.class" in unix like system. <br>
* If the class file exists in one jar file, it will return the path like:
* "XXXXXXfile:\XXXXXX\XXX.jar!\XX\XX\XX"
* <p>
* use ClassLoader.getResources(String) to search resources in classpath
* <p>
* <b>Using new ClassLoader(){} , not classZ.getClassLoader()</b>
* <p>
* In GAE , it will fail if you call getClassLoader()
*
* @author Wendal Chen
* @author zozoh
* @param classZ
* @return path or null if nothing found
*
* @see java.lang.ClassLoader
* @see java.io.File
*/
private static String getBasePath(Class<?> classZ) {
try {
String path = classZ.getName().replace('.', '/') + ".class";
Enumeration<URL> urls = new ClassLoader() {}.getResources(path);
// zozoh: In eclipse tomcat debug env, the urls is always empty
if (null != urls && urls.hasMoreElements()) {
URL url = urls.nextElement();
if (url != null)
return new File(url.getFile()).getParentFile().getAbsolutePath();
}
// Then I will find the class in classpath
File f = Files.findFile(path);
if (null != f)
return f.getParentFile().getAbsolutePath();
} catch (IOException e) {}
return null;
}
}
|
package org.objectweb.asm;
/**
* Information about the input and output stack map frames of a basic block.
*
* @author Eric Bruneton
*/
final class Frame {
/*
* Frames are computed in a two steps process: during the visit of each
* instruction, the state of the frame at the end of current basic block is
* updated by simulating the action of the instruction on the previous state
* of this so called "output frame". In visitMaxs, a fix point algorithm is
* used to compute the "input frame" of each basic block, i.e. the stack map
* frame at the beginning of the basic block, starting from the input frame
* of the first basic block (which is computed from the method descriptor),
* and by using the previously computed output frames to compute the input
* state of the other blocks.
*
* All output and input frames are stored as arrays of integers. Reference
* and array types are represented by an index into a type table (which is
* not the same as the constant pool of the class, in order to avoid adding
* unnecessary constants in the pool - not all computed frames will end up
* being stored in the stack map table). This allows very fast type
* comparisons.
*
* Output stack map frames are computed relatively to the input frame of the
* basic block, which is not yet known when output frames are computed. It
* is therefore necessary to be able to represent abstract types such as
* "the type at position x in the input frame locals" or "the type at
* position x from the top of the input frame stack" or even "the type at
* position x in the input frame, with y more (or less) array dimensions".
* This explains the rather complicated type format used in output frames.
*
* This format is the following: DIM KIND VALUE (4, 4 and 24 bits). DIM is a
* signed number of array dimensions (from -8 to 7). KIND is either BASE,
* LOCAL or STACK. BASE is used for types that are not relative to the input
* frame. LOCAL is used for types that are relative to the input local
* variable types. STACK is used for types that are relative to the input
* stack types. VALUE depends on KIND. For LOCAL types, it is an index in
* the input local variable types. For STACK types, it is a position
* relatively to the top of input frame stack. For BASE types, it is either
* one of the constants defined below, or for OBJECT and UNINITIALIZED
* types, a tag and an index in the type table.
*
* Output frames can contain types of any kind and with a positive or
* negative dimension (and even unassigned types, represented by 0 - which
* does not correspond to any valid type value). Input frames can only
* contain BASE types of positive or null dimension. In all cases the type
* table contains only internal type names (array type descriptors are
* forbidden - dimensions must be represented through the DIM field).
*
* The LONG and DOUBLE types are always represented by using two slots (LONG
* + TOP or DOUBLE + TOP), for local variable types as well as in the
* operand stack. This is necessary to be able to simulate DUPx_y
* instructions, whose effect would be dependent on the actual type values
* if types were always represented by a single slot in the stack (and this
* is not possible, since actual type values are not always known - cf LOCAL
* and STACK type kinds).
*/
/**
* Mask to get the dimension of a frame type. This dimension is a signed
* integer between -8 and 7.
*/
static final int DIM = 0xF0000000;
/**
* Constant to be added to a type to get a type with one more dimension.
*/
static final int ARRAY_OF = 0x10000000;
/**
* Constant to be added to a type to get a type with one less dimension.
*/
static final int ELEMENT_OF = 0xF0000000;
/**
* Mask to get the kind of a frame type.
*
* @see #BASE
* @see #LOCAL
* @see #STACK
*/
static final int KIND = 0xF000000;
/**
* Flag used for LOCAL and STACK types. Indicates that if this type happens
* to be a long or double type (during the computations of input frames),
* then it must be set to TOP because the second word of this value has been
* reused to store other data in the basic block. Hence the first word no
* longer stores a valid long or double value.
*/
static final int TOP_IF_LONG_OR_DOUBLE = 0x800000;
/**
* Mask to get the value of a frame type.
*/
static final int VALUE = 0x7FFFFF;
/**
* Mask to get the kind of base types.
*/
static final int BASE_KIND = 0xFF00000;
/**
* Mask to get the value of base types.
*/
static final int BASE_VALUE = 0xFFFFF;
/**
* Kind of the types that are not relative to an input stack map frame.
*/
static final int BASE = 0x1000000;
/**
* Base kind of the base reference types. The BASE_VALUE of such types is an
* index into the type table.
*/
static final int OBJECT = BASE | 0x700000;
/**
* Base kind of the uninitialized base types. The BASE_VALUE of such types
* in an index into the type table (the Item at that index contains both an
* instruction offset and an internal class name).
*/
static final int UNINITIALIZED = BASE | 0x800000;
/**
* Kind of the types that are relative to the local variable types of an
* input stack map frame. The value of such types is a local variable index.
*/
private static final int LOCAL = 0x2000000;
/**
* Kind of the the types that are relative to the stack of an input stack
* map frame. The value of such types is a position relatively to the top of
* this stack.
*/
private static final int STACK = 0x3000000;
/**
* The TOP type. This is a BASE type.
*/
static final int TOP = BASE | 0;
/**
* The BOOLEAN type. This is a BASE type mainly used for array types.
*/
static final int BOOLEAN = BASE | 9;
/**
* The BYTE type. This is a BASE type mainly used for array types.
*/
static final int BYTE = BASE | 10;
/**
* The CHAR type. This is a BASE type mainly used for array types.
*/
static final int CHAR = BASE | 11;
/**
* The SHORT type. This is a BASE type mainly used for array types.
*/
static final int SHORT = BASE | 12;
/**
* The INTEGER type. This is a BASE type.
*/
static final int INTEGER = BASE | 1;
/**
* The FLOAT type. This is a BASE type.
*/
static final int FLOAT = BASE | 2;
/**
* The DOUBLE type. This is a BASE type.
*/
static final int DOUBLE = BASE | 3;
/**
* The LONG type. This is a BASE type.
*/
static final int LONG = BASE | 4;
/**
* The NULL type. This is a BASE type.
*/
static final int NULL = BASE | 5;
/**
* The UNINITIALIZED_THIS type. This is a BASE type.
*/
static final int UNINITIALIZED_THIS = BASE | 6;
/**
* The stack size variation corresponding to each JVM instruction. This
* stack variation is equal to the size of the values produced by an
* instruction, minus the size of the values consumed by this instruction.
*/
static final int[] SIZE;
/**
* Computes the stack size variation corresponding to each JVM instruction.
*/
static {
int i;
int[] b = new int[202];
String s = "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDD"
+ "CDCDEEEEEEEEEEEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCD"
+ "CDCEEEEDDDDDDDCDCDCEFEFDDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFED"
+ "DDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE";
for (i = 0; i < b.length; ++i) {
b[i] = s.charAt(i) - 'E';
}
SIZE = b;
// code to generate the above string
// int NA = 0; // not applicable (unused opcode or variable size opcode)
// b = new int[] {
// 0, //NOP, // visitInsn
// 1, //ACONST_NULL, // -
// 1, //ICONST_M1, // -
// 1, //ICONST_0, // -
// 1, //ICONST_1, // -
// 1, //ICONST_2, // -
// 1, //ICONST_3, // -
// 1, //ICONST_4, // -
// 1, //ICONST_5, // -
// 2, //LCONST_0, // -
// 2, //LCONST_1, // -
// 1, //FCONST_0, // -
// 1, //FCONST_1, // -
// 1, //FCONST_2, // -
// 2, //DCONST_0, // -
// 2, //DCONST_1, // -
// 1, //BIPUSH, // visitIntInsn
// 1, //SIPUSH, // -
// 1, //LDC, // visitLdcInsn
// NA, //LDC_W, // -
// NA, //LDC2_W, // -
// 1, //ILOAD, // visitVarInsn
// 2, //LLOAD, // -
// 1, //FLOAD, // -
// 2, //DLOAD, // -
// 1, //ALOAD, // -
// NA, //ILOAD_0, // -
// NA, //ILOAD_1, // -
// NA, //ILOAD_2, // -
// NA, //ILOAD_3, // -
// NA, //LLOAD_0, // -
// NA, //LLOAD_1, // -
// NA, //LLOAD_2, // -
// NA, //LLOAD_3, // -
// NA, //FLOAD_0, // -
// NA, //FLOAD_1, // -
// NA, //FLOAD_2, // -
// NA, //FLOAD_3, // -
// NA, //DLOAD_0, // -
// NA, //DLOAD_1, // -
// NA, //DLOAD_2, // -
// NA, //DLOAD_3, // -
// NA, //ALOAD_0, // -
// NA, //ALOAD_1, // -
// NA, //ALOAD_2, // -
// NA, //ALOAD_3, // -
// -1, //IALOAD, // visitInsn
// 0, //LALOAD, // -
// -1, //FALOAD, // -
// 0, //DALOAD, // -
// -1, //AALOAD, // -
// -1, //BALOAD, // -
// -1, //CALOAD, // -
// -1, //SALOAD, // -
// -1, //ISTORE, // visitVarInsn
// -2, //LSTORE, // -
// -1, //FSTORE, // -
// -2, //DSTORE, // -
// -1, //ASTORE, // -
// NA, //ISTORE_0, // -
// NA, //ISTORE_1, // -
// NA, //ISTORE_2, // -
// NA, //ISTORE_3, // -
// NA, //LSTORE_0, // -
// NA, //LSTORE_1, // -
// NA, //LSTORE_2, // -
// NA, //LSTORE_3, // -
// NA, //FSTORE_0, // -
// NA, //FSTORE_1, // -
// NA, //FSTORE_2, // -
// NA, //FSTORE_3, // -
// NA, //DSTORE_0, // -
// NA, //DSTORE_1, // -
// NA, //DSTORE_2, // -
// NA, //DSTORE_3, // -
// NA, //ASTORE_0, // -
// NA, //ASTORE_1, // -
// NA, //ASTORE_2, // -
// NA, //ASTORE_3, // -
// -3, //IASTORE, // visitInsn
// -4, //LASTORE, // -
// -3, //FASTORE, // -
// -4, //DASTORE, // -
// -3, //AASTORE, // -
// -3, //BASTORE, // -
// -3, //CASTORE, // -
// -3, //SASTORE, // -
// -1, //POP, // -
// -2, //POP2, // -
// 1, //DUP, // -
// 1, //DUP_X1, // -
// 1, //DUP_X2, // -
// 2, //DUP2, // -
// 2, //DUP2_X1, // -
// 2, //DUP2_X2, // -
// 0, //SWAP, // -
// -1, //IADD, // -
// -2, //LADD, // -
// -1, //FADD, // -
// -2, //DADD, // -
// -1, //ISUB, // -
// -2, //LSUB, // -
// -1, //FSUB, // -
// -2, //DSUB, // -
// -1, //IMUL, // -
// -2, //LMUL, // -
// -1, //FMUL, // -
// -2, //DMUL, // -
// -1, //IDIV, // -
// -2, //LDIV, // -
// -1, //FDIV, // -
// -2, //DDIV, // -
// -1, //IREM, // -
// -2, //LREM, // -
// -1, //FREM, // -
// -2, //DREM, // -
// 0, //INEG, // -
// 0, //LNEG, // -
// 0, //FNEG, // -
// 0, //DNEG, // -
// -1, //ISHL, // -
// -1, //LSHL, // -
// -1, //ISHR, // -
// -1, //LSHR, // -
// -1, //IUSHR, // -
// -1, //LUSHR, // -
// -1, //IAND, // -
// -2, //LAND, // -
// -1, //IOR, // -
// -2, //LOR, // -
// -1, //IXOR, // -
// -2, //LXOR, // -
// 0, //IINC, // visitIincInsn
// 1, //I2L, // visitInsn
// 0, //I2F, // -
// 1, //I2D, // -
// -1, //L2I, // -
// -1, //L2F, // -
// 0, //L2D, // -
// 0, //F2I, // -
// 1, //F2L, // -
// 1, //F2D, // -
// -1, //D2I, // -
// 0, //D2L, // -
// -1, //D2F, // -
// 0, //I2B, // -
// 0, //I2C, // -
// 0, //I2S, // -
// -3, //LCMP, // -
// -1, //FCMPL, // -
// -1, //FCMPG, // -
// -3, //DCMPL, // -
// -3, //DCMPG, // -
// -1, //IFEQ, // visitJumpInsn
// -1, //IFNE, // -
// -1, //IFLT, // -
// -1, //IFGE, // -
// -1, //IFGT, // -
// -1, //IFLE, // -
// -2, //IF_ICMPEQ, // -
// -2, //IF_ICMPNE, // -
// -2, //IF_ICMPLT, // -
// -2, //IF_ICMPGE, // -
// -2, //IF_ICMPGT, // -
// -2, //IF_ICMPLE, // -
// -2, //IF_ACMPEQ, // -
// -2, //IF_ACMPNE, // -
// 0, //GOTO, // -
// 1, //JSR, // -
// 0, //RET, // visitVarInsn
// -1, //TABLESWITCH, // visiTableSwitchInsn
// -1, //LOOKUPSWITCH, // visitLookupSwitch
// -1, //IRETURN, // visitInsn
// -2, //LRETURN, // -
// -1, //FRETURN, // -
// -2, //DRETURN, // -
// -1, //ARETURN, // -
// 0, //RETURN, // -
// NA, //GETSTATIC, // visitFieldInsn
// NA, //PUTSTATIC, // -
// NA, //GETFIELD, // -
// NA, //PUTFIELD, // -
// NA, //INVOKEVIRTUAL, // visitMethodInsn
// NA, //INVOKESPECIAL, // -
// NA, //INVOKESTATIC, // -
// NA, //INVOKEINTERFACE, // -
// NA, //INVOKEDYNAMIC, // visitInvokeDynamicInsn
// 1, //NEW, // visitTypeInsn
// 0, //NEWARRAY, // visitIntInsn
// 0, //ANEWARRAY, // visitTypeInsn
// 0, //ARRAYLENGTH, // visitInsn
// NA, //ATHROW, // -
// 0, //CHECKCAST, // visitTypeInsn
// 0, //INSTANCEOF, // -
// -1, //MONITORENTER, // visitInsn
// -1, //MONITOREXIT, // -
// NA, //WIDE, // NOT VISITED
// NA, //MULTIANEWARRAY, // visitMultiANewArrayInsn
// -1, //IFNULL, // visitJumpInsn
// -1, //IFNONNULL, // -
// NA, //GOTO_W, // -
// NA, //JSR_W, // -
// for (i = 0; i < b.length; ++i) {
// System.err.print((char)('E' + b[i]));
// System.err.println();
}
/**
* The label (i.e. basic block) to which these input and output stack map
* frames correspond.
*/
Label owner;
/**
* The input stack map frame locals.
*/
int[] inputLocals;
/**
* The input stack map frame stack.
*/
int[] inputStack;
/**
* The output stack map frame locals.
*/
private int[] outputLocals;
/**
* The output stack map frame stack.
*/
private int[] outputStack;
/**
* Relative size of the output stack. The exact semantics of this field
* depends on the algorithm that is used.
*
* When only the maximum stack size is computed, this field is the size of
* the output stack relatively to the top of the input stack.
*
* When the stack map frames are completely computed, this field is the
* actual number of types in {@link #outputStack}.
*/
private int outputStackTop;
/**
* Number of types that are initialized in the basic block.
*
* @see #initializations
*/
private int initializationCount;
/**
* The types that are initialized in the basic block. A constructor
* invocation on an UNINITIALIZED or UNINITIALIZED_THIS type must replace
* <i>every occurence</i> of this type in the local variables and in the
* operand stack. This cannot be done during the first phase of the
* algorithm since, during this phase, the local variables and the operand
* stack are not completely computed. It is therefore necessary to store the
* types on which constructors are invoked in the basic block, in order to
* do this replacement during the second phase of the algorithm, where the
* frames are fully computed. Note that this array can contain types that
* are relative to input locals or to the input stack (see below for the
* description of the algorithm).
*/
private int[] initializations;
/**
* Returns the output frame local variable type at the given index.
*
* @param local
* the index of the local that must be returned.
* @return the output frame local variable type at the given index.
*/
private int get(final int local) {
if (outputLocals == null || local >= outputLocals.length) {
// this local has never been assigned in this basic block,
// so it is still equal to its value in the input frame
return LOCAL | local;
} else {
int type = outputLocals[local];
if (type == 0) {
// this local has never been assigned in this basic block,
// so it is still equal to its value in the input frame
type = outputLocals[local] = LOCAL | local;
}
return type;
}
}
/**
* Sets the output frame local variable type at the given index.
*
* @param local
* the index of the local that must be set.
* @param type
* the value of the local that must be set.
*/
private void set(final int local, final int type) {
// creates and/or resizes the output local variables array if necessary
if (outputLocals == null) {
outputLocals = new int[10];
}
int n = outputLocals.length;
if (local >= n) {
int[] t = new int[Math.max(local + 1, 2 * n)];
System.arraycopy(outputLocals, 0, t, 0, n);
outputLocals = t;
}
// sets the local variable
outputLocals[local] = type;
}
/**
* Pushes a new type onto the output frame stack.
*
* @param type
* the type that must be pushed.
*/
private void push(final int type) {
// creates and/or resizes the output stack array if necessary
if (outputStack == null) {
outputStack = new int[10];
}
int n = outputStack.length;
if (outputStackTop >= n) {
int[] t = new int[Math.max(outputStackTop + 1, 2 * n)];
System.arraycopy(outputStack, 0, t, 0, n);
outputStack = t;
}
// pushes the type on the output stack
outputStack[outputStackTop++] = type;
// updates the maximun height reached by the output stack, if needed
int top = owner.inputStackTop + outputStackTop;
if (top > owner.outputStackMax) {
owner.outputStackMax = top;
}
}
/**
* Pushes a new type onto the output frame stack.
*
* @param cw
* the ClassWriter to which this label belongs.
* @param desc
* the descriptor of the type to be pushed. Can also be a method
* descriptor (in this case this method pushes its return type
* onto the output frame stack).
*/
private void push(final ClassWriter cw, final String desc) {
int type = type(cw, desc);
if (type != 0) {
push(type);
if (type == LONG || type == DOUBLE) {
push(TOP);
}
}
}
/**
* Returns the int encoding of the given type.
*
* @param cw
* the ClassWriter to which this label belongs.
* @param desc
* a type descriptor.
* @return the int encoding of the given type.
*/
private static int type(final ClassWriter cw, final String desc) {
String t;
int index = desc.charAt(0) == '(' ? desc.indexOf(')') + 1 : 0;
switch (desc.charAt(index)) {
case 'V':
return 0;
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
return INTEGER;
case 'F':
return FLOAT;
case 'J':
return LONG;
case 'D':
return DOUBLE;
case 'L':
// stores the internal name, not the descriptor!
t = desc.substring(index + 1, desc.length() - 1);
return OBJECT | cw.addType(t);
// case '[':
default:
// extracts the dimensions and the element type
int data;
int dims = index + 1;
while (desc.charAt(dims) == '[') {
++dims;
}
switch (desc.charAt(dims)) {
case 'Z':
data = BOOLEAN;
break;
case 'C':
data = CHAR;
break;
case 'B':
data = BYTE;
break;
case 'S':
data = SHORT;
break;
case 'I':
data = INTEGER;
break;
case 'F':
data = FLOAT;
break;
case 'J':
data = LONG;
break;
case 'D':
data = DOUBLE;
break;
// case 'L':
default:
// stores the internal name, not the descriptor
t = desc.substring(dims + 1, desc.length() - 1);
data = OBJECT | cw.addType(t);
}
return (dims - index) << 28 | data;
}
}
/**
* Pops a type from the output frame stack and returns its value.
*
* @return the type that has been popped from the output frame stack.
*/
private int pop() {
if (outputStackTop > 0) {
return outputStack[--outputStackTop];
} else {
// if the output frame stack is empty, pops from the input stack
return STACK | -(--owner.inputStackTop);
}
}
/**
* Pops the given number of types from the output frame stack.
*
* @param elements
* the number of types that must be popped.
*/
private void pop(final int elements) {
if (outputStackTop >= elements) {
outputStackTop -= elements;
} else {
// if the number of elements to be popped is greater than the number
// of elements in the output stack, clear it, and pops the remaining
// elements from the input stack.
owner.inputStackTop -= elements - outputStackTop;
outputStackTop = 0;
}
}
/**
* Pops a type from the output frame stack.
*
* @param desc
* the descriptor of the type to be popped. Can also be a method
* descriptor (in this case this method pops the types
* corresponding to the method arguments).
*/
private void pop(final String desc) {
char c = desc.charAt(0);
if (c == '(') {
pop((Type.getArgumentsAndReturnSizes(desc) >> 2) - 1);
} else if (c == 'J' || c == 'D') {
pop(2);
} else {
pop(1);
}
}
/**
* Adds a new type to the list of types on which a constructor is invoked in
* the basic block.
*
* @param var
* a type on a which a constructor is invoked.
*/
private void init(final int var) {
// creates and/or resizes the initializations array if necessary
if (initializations == null) {
initializations = new int[2];
}
int n = initializations.length;
if (initializationCount >= n) {
int[] t = new int[Math.max(initializationCount + 1, 2 * n)];
System.arraycopy(initializations, 0, t, 0, n);
initializations = t;
}
// stores the type to be initialized
initializations[initializationCount++] = var;
}
/**
* Replaces the given type with the appropriate type if it is one of the
* types on which a constructor is invoked in the basic block.
*
* @param cw
* the ClassWriter to which this label belongs.
* @param t
* a type
* @return t or, if t is one of the types on which a constructor is invoked
* in the basic block, the type corresponding to this constructor.
*/
private int init(final ClassWriter cw, final int t) {
int s;
if (t == UNINITIALIZED_THIS) {
s = OBJECT | cw.addType(cw.thisName);
} else if ((t & (DIM | BASE_KIND)) == UNINITIALIZED) {
String type = cw.typeTable[t & BASE_VALUE].strVal1;
s = OBJECT | cw.addType(type);
} else {
return t;
}
for (int j = 0; j < initializationCount; ++j) {
int u = initializations[j];
int dim = u & DIM;
int kind = u & KIND;
if (kind == LOCAL) {
u = dim + inputLocals[u & VALUE];
} else if (kind == STACK) {
u = dim + inputStack[inputStack.length - (u & VALUE)];
}
if (t == u) {
return s;
}
}
return t;
}
/**
* Initializes the input frame of the first basic block from the method
* descriptor.
*
* @param cw
* the ClassWriter to which this label belongs.
* @param access
* the access flags of the method to which this label belongs.
* @param args
* the formal parameter types of this method.
* @param maxLocals
* the maximum number of local variables of this method.
*/
void initInputFrame(final ClassWriter cw, final int access,
final Type[] args, final int maxLocals) {
inputLocals = new int[maxLocals];
inputStack = new int[0];
int i = 0;
if ((access & Opcodes.ACC_STATIC) == 0) {
if ((access & MethodWriter.ACC_CONSTRUCTOR) == 0) {
inputLocals[i++] = OBJECT | cw.addType(cw.thisName);
} else {
inputLocals[i++] = UNINITIALIZED_THIS;
}
}
for (int j = 0; j < args.length; ++j) {
int t = type(cw, args[j].getDescriptor());
inputLocals[i++] = t;
if (t == LONG || t == DOUBLE) {
inputLocals[i++] = TOP;
}
}
while (i < maxLocals) {
inputLocals[i++] = TOP;
}
}
/**
* Simulates the action of the given instruction on the output stack frame.
*
* @param opcode
* the opcode of the instruction.
* @param arg
* the operand of the instruction, if any.
* @param cw
* the class writer to which this label belongs.
* @param item
* the operand of the instructions, if any.
*/
void execute(final int opcode, final int arg, final ClassWriter cw,
final Item item) {
int t1, t2, t3, t4;
switch (opcode) {
case Opcodes.NOP:
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
case Opcodes.GOTO:
case Opcodes.RETURN:
break;
case Opcodes.ACONST_NULL:
push(NULL);
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
case Opcodes.ILOAD:
push(INTEGER);
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
case Opcodes.LLOAD:
push(LONG);
push(TOP);
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
case Opcodes.FLOAD:
push(FLOAT);
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
case Opcodes.DLOAD:
push(DOUBLE);
push(TOP);
break;
case Opcodes.LDC:
switch (item.type) {
case ClassWriter.INT:
push(INTEGER);
break;
case ClassWriter.LONG:
push(LONG);
push(TOP);
break;
case ClassWriter.FLOAT:
push(FLOAT);
break;
case ClassWriter.DOUBLE:
push(DOUBLE);
push(TOP);
break;
case ClassWriter.CLASS:
push(OBJECT | cw.addType("java/lang/Class"));
break;
case ClassWriter.STR:
push(OBJECT | cw.addType("java/lang/String"));
break;
case ClassWriter.MTYPE:
push(OBJECT | cw.addType("java/lang/invoke/MethodType"));
break;
// case ClassWriter.HANDLE_BASE + [1..9]:
default:
push(OBJECT | cw.addType("java/lang/invoke/MethodHandle"));
}
break;
case Opcodes.ALOAD:
push(get(arg));
break;
case Opcodes.IALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
pop(2);
push(INTEGER);
break;
case Opcodes.LALOAD:
case Opcodes.D2L:
pop(2);
push(LONG);
push(TOP);
break;
case Opcodes.FALOAD:
pop(2);
push(FLOAT);
break;
case Opcodes.DALOAD:
case Opcodes.L2D:
pop(2);
push(DOUBLE);
push(TOP);
break;
case Opcodes.AALOAD:
pop(1);
t1 = pop();
push(ELEMENT_OF + t1);
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
case Opcodes.ASTORE:
t1 = pop();
set(arg, t1);
if (arg > 0) {
t2 = get(arg - 1);
// if t2 is of kind STACK or LOCAL we cannot know its size!
if (t2 == LONG || t2 == DOUBLE) {
set(arg - 1, TOP);
} else if ((t2 & KIND) != BASE) {
set(arg - 1, t2 | TOP_IF_LONG_OR_DOUBLE);
}
}
break;
case Opcodes.LSTORE:
case Opcodes.DSTORE:
pop(1);
t1 = pop();
set(arg, t1);
set(arg + 1, TOP);
if (arg > 0) {
t2 = get(arg - 1);
// if t2 is of kind STACK or LOCAL we cannot know its size!
if (t2 == LONG || t2 == DOUBLE) {
set(arg - 1, TOP);
} else if ((t2 & KIND) != BASE) {
set(arg - 1, t2 | TOP_IF_LONG_OR_DOUBLE);
}
}
break;
case Opcodes.IASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
pop(3);
break;
case Opcodes.LASTORE:
case Opcodes.DASTORE:
pop(4);
break;
case Opcodes.POP:
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
case Opcodes.TABLESWITCH:
case Opcodes.LOOKUPSWITCH:
case Opcodes.ATHROW:
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
pop(1);
break;
case Opcodes.POP2:
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
pop(2);
break;
case Opcodes.DUP:
t1 = pop();
push(t1);
push(t1);
break;
case Opcodes.DUP_X1:
t1 = pop();
t2 = pop();
push(t1);
push(t2);
push(t1);
break;
case Opcodes.DUP_X2:
t1 = pop();
t2 = pop();
t3 = pop();
push(t1);
push(t3);
push(t2);
push(t1);
break;
case Opcodes.DUP2:
t1 = pop();
t2 = pop();
push(t2);
push(t1);
push(t2);
push(t1);
break;
case Opcodes.DUP2_X1:
t1 = pop();
t2 = pop();
t3 = pop();
push(t2);
push(t1);
push(t3);
push(t2);
push(t1);
break;
case Opcodes.DUP2_X2:
t1 = pop();
t2 = pop();
t3 = pop();
t4 = pop();
push(t2);
push(t1);
push(t4);
push(t3);
push(t2);
push(t1);
break;
case Opcodes.SWAP:
t1 = pop();
t2 = pop();
push(t1);
push(t2);
break;
case Opcodes.IADD:
case Opcodes.ISUB:
case Opcodes.IMUL:
case Opcodes.IDIV:
case Opcodes.IREM:
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
case Opcodes.L2I:
case Opcodes.D2I:
case Opcodes.FCMPL:
case Opcodes.FCMPG:
pop(2);
push(INTEGER);
break;
case Opcodes.LADD:
case Opcodes.LSUB:
case Opcodes.LMUL:
case Opcodes.LDIV:
case Opcodes.LREM:
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
pop(4);
push(LONG);
push(TOP);
break;
case Opcodes.FADD:
case Opcodes.FSUB:
case Opcodes.FMUL:
case Opcodes.FDIV:
case Opcodes.FREM:
case Opcodes.L2F:
case Opcodes.D2F:
pop(2);
push(FLOAT);
break;
case Opcodes.DADD:
case Opcodes.DSUB:
case Opcodes.DMUL:
case Opcodes.DDIV:
case Opcodes.DREM:
pop(4);
push(DOUBLE);
push(TOP);
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
pop(3);
push(LONG);
push(TOP);
break;
case Opcodes.IINC:
set(arg, INTEGER);
break;
case Opcodes.I2L:
case Opcodes.F2L:
pop(1);
push(LONG);
push(TOP);
break;
case Opcodes.I2F:
pop(1);
push(FLOAT);
break;
case Opcodes.I2D:
case Opcodes.F2D:
pop(1);
push(DOUBLE);
push(TOP);
break;
case Opcodes.F2I:
case Opcodes.ARRAYLENGTH:
case Opcodes.INSTANCEOF:
pop(1);
push(INTEGER);
break;
case Opcodes.LCMP:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
pop(4);
push(INTEGER);
break;
case Opcodes.JSR:
case Opcodes.RET:
throw new RuntimeException(
"JSR/RET are not supported with computeFrames option");
case Opcodes.GETSTATIC:
push(cw, item.strVal3);
break;
case Opcodes.PUTSTATIC:
pop(item.strVal3);
break;
case Opcodes.GETFIELD:
pop(1);
push(cw, item.strVal3);
break;
case Opcodes.PUTFIELD:
pop(item.strVal3);
pop();
break;
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEINTERFACE:
pop(item.strVal3);
if (opcode != Opcodes.INVOKESTATIC) {
t1 = pop();
if (opcode == Opcodes.INVOKESPECIAL
&& item.strVal2.charAt(0) == '<') {
init(t1);
}
}
push(cw, item.strVal3);
break;
case Opcodes.INVOKEDYNAMIC:
pop(item.strVal2);
push(cw, item.strVal2);
break;
case Opcodes.NEW:
push(UNINITIALIZED | cw.addUninitializedType(item.strVal1, arg));
break;
case Opcodes.NEWARRAY:
pop();
switch (arg) {
case Opcodes.T_BOOLEAN:
push(ARRAY_OF | BOOLEAN);
break;
case Opcodes.T_CHAR:
push(ARRAY_OF | CHAR);
break;
case Opcodes.T_BYTE:
push(ARRAY_OF | BYTE);
break;
case Opcodes.T_SHORT:
push(ARRAY_OF | SHORT);
break;
case Opcodes.T_INT:
push(ARRAY_OF | INTEGER);
break;
case Opcodes.T_FLOAT:
push(ARRAY_OF | FLOAT);
break;
case Opcodes.T_DOUBLE:
push(ARRAY_OF | DOUBLE);
break;
// case Opcodes.T_LONG:
default:
push(ARRAY_OF | LONG);
break;
}
break;
case Opcodes.ANEWARRAY:
String s = item.strVal1;
pop();
if (s.charAt(0) == '[') {
push(cw, '[' + s);
} else {
push(ARRAY_OF | OBJECT | cw.addType(s));
}
break;
case Opcodes.CHECKCAST:
s = item.strVal1;
pop();
if (s.charAt(0) == '[') {
push(cw, s);
} else {
push(OBJECT | cw.addType(s));
}
break;
// case Opcodes.MULTIANEWARRAY:
default:
pop(arg);
push(cw, item.strVal1);
break;
}
}
/**
* Merges the input frame of the given basic block with the input and output
* frames of this basic block. Returns <tt>true</tt> if the input frame of
* the given label has been changed by this operation.
*
* @param cw
* the ClassWriter to which this label belongs.
* @param frame
* the basic block whose input frame must be updated.
* @param edge
* the kind of the {@link Edge} between this label and 'label'.
* See {@link Edge#info}.
* @return <tt>true</tt> if the input frame of the given label has been
* changed by this operation.
*/
boolean merge(final ClassWriter cw, final Frame frame, final int edge) {
boolean changed = false;
int i, s, dim, kind, t;
int nLocal = inputLocals.length;
int nStack = inputStack.length;
if (frame.inputLocals == null) {
frame.inputLocals = new int[nLocal];
changed = true;
}
for (i = 0; i < nLocal; ++i) {
if (outputLocals != null && i < outputLocals.length) {
s = outputLocals[i];
if (s == 0) {
t = inputLocals[i];
} else {
dim = s & DIM;
kind = s & KIND;
if (kind == BASE) {
t = s;
} else {
if (kind == LOCAL) {
t = dim + inputLocals[s & VALUE];
} else {
t = dim + inputStack[nStack - (s & VALUE)];
}
if ((s & TOP_IF_LONG_OR_DOUBLE) != 0
&& (t == LONG || t == DOUBLE)) {
t = TOP;
}
}
}
} else {
t = inputLocals[i];
}
if (initializations != null) {
t = init(cw, t);
}
changed |= merge(cw, t, frame.inputLocals, i);
}
if (edge > 0) {
for (i = 0; i < nLocal; ++i) {
t = inputLocals[i];
changed |= merge(cw, t, frame.inputLocals, i);
}
if (frame.inputStack == null) {
frame.inputStack = new int[1];
changed = true;
}
changed |= merge(cw, edge, frame.inputStack, 0);
return changed;
}
int nInputStack = inputStack.length + owner.inputStackTop;
if (frame.inputStack == null) {
frame.inputStack = new int[nInputStack + outputStackTop];
changed = true;
}
for (i = 0; i < nInputStack; ++i) {
t = inputStack[i];
if (initializations != null) {
t = init(cw, t);
}
changed |= merge(cw, t, frame.inputStack, i);
}
for (i = 0; i < outputStackTop; ++i) {
s = outputStack[i];
dim = s & DIM;
kind = s & KIND;
if (kind == BASE) {
t = s;
} else {
if (kind == LOCAL) {
t = dim + inputLocals[s & VALUE];
} else {
t = dim + inputStack[nStack - (s & VALUE)];
}
if ((s & TOP_IF_LONG_OR_DOUBLE) != 0
&& (t == LONG || t == DOUBLE)) {
t = TOP;
}
}
if (initializations != null) {
t = init(cw, t);
}
changed |= merge(cw, t, frame.inputStack, nInputStack + i);
}
return changed;
}
private static boolean merge(final ClassWriter cw, int t,
final int[] types, final int index) {
int u = types[index];
if (u == t) {
// if the types are equal, merge(u,t)=u, so there is no change
return false;
}
if ((t & ~DIM) == NULL) {
if (u == NULL) {
return false;
}
t = NULL;
}
if (u == 0) {
// if types[index] has never been assigned, merge(u,t)=t
types[index] = t;
return true;
}
int v;
if ((u & BASE_KIND) == OBJECT || (u & DIM) != 0) {
// if u is a reference type of any dimension
if (t == NULL) {
// if t is the NULL type, merge(u,t)=u, so there is no change
return false;
} else if ((t & (DIM | BASE_KIND)) == (u & (DIM | BASE_KIND))) {
// if t and u have the same dimension and same base kind
if ((u & BASE_KIND) == OBJECT) {
// if t is also a reference type, and if u and t have the
// same dimension merge(u,t) = dim(t) | common parent of the
// element types of u and t
v = (t & DIM) | OBJECT
| cw.getMergedType(t & BASE_VALUE, u & BASE_VALUE);
} else {
// if u and t are array types, but not with the same element
// type, merge(u,t)=java/lang/Object
v = OBJECT | cw.addType("java/lang/Object");
}
} else if ((t & BASE_KIND) == OBJECT || (t & DIM) != 0) {
// if t is any other reference or array type, the merged type
// is Object, or min(dim(u), dim(t)) | java/lang/Object is u
// and t have different array dimensions
int tdim = t & DIM;
int udim = u & DIM;
v = (udim != tdim ? Math.min(tdim, udim) : 0) | OBJECT
| cw.addType("java/lang/Object");
} else {
// if t is any other type, merge(u,t)=TOP
v = TOP;
}
} else if (u == NULL) {
// if u is the NULL type, merge(u,t)=t,
// or TOP if t is not a reference type
v = (t & BASE_KIND) == OBJECT || (t & DIM) != 0 ? t : TOP;
} else {
// if u is any other type, merge(u,t)=TOP whatever t
v = TOP;
}
if (u != v) {
types[index] = v;
return true;
}
return false;
}
}
|
package net.minecraftforge.common;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeMultiset;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import net.minecraft.src.Chunk;
import net.minecraft.src.ChunkCoordIntPair;
import net.minecraft.src.CompressedStreamTools;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.MathHelper;
import net.minecraft.src.NBTBase;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NBTTagList;
import net.minecraft.src.World;
import net.minecraft.src.WorldServer;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.event.Event;
/**
* Manages chunkloading for mods.
*
* The basic principle is a ticket based system.
* 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)}
* 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket.
* 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}.
* 4. When a world unloads, the tickets associated with that world are saved by the chunk manager.
* 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register
* chunks to stay loaded (and maybe take other actions).
*
* The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod
* specific override section.
*
* @author cpw
*
*/
public class ForgeChunkManager
{
private static int defaultMaxCount;
private static int defaultMaxChunks;
private static boolean overridesEnabled;
private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap();
private static Map<String, Integer> ticketConstraints = Maps.newHashMap();
private static Map<String, Integer> chunkConstraints = Maps.newHashMap();
private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create();
private static Map<String, LoadingCallback> callbacks = Maps.newHashMap();
private static Map<World, ImmutableSetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap();
private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create();
private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap();
private static File cfgFile;
private static Configuration config;
private static int playerTicketLength;
private static int dormantChunkCacheSize;
/**
* All mods requiring chunkloading need to implement this to handle the
* re-registration of chunk tickets at world loading time
*
* @author cpw
*
*/
public interface LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to re-register the chunks associated with those tickets. The list supplied
* here is truncated to length prior to use. Tickets unwanted by the
* mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance
* in which case, they will have been disposed of by the earlier callback.
*
* @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world the world
*/
public void ticketsLoaded(List<Ticket> tickets, World world);
}
/**
* This is a special LoadingCallback that can be implemented as well as the
* LoadingCallback to provide access to additional behaviour.
* Specifically, this callback will fire prior to Forge dropping excess
* tickets. Tickets in the returned list are presumed ordered and excess will
* be truncated from the returned list.
* This allows the mod to control not only if they actually <em>want</em> a ticket but
* also their preferred ticket ordering.
*
* @author cpw
*
*/
public interface OrderedLoadingCallback extends LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to decide if it wants the ticket still, and prioritise overflow
* based on the ticket count.
* WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod
* to be more selective in which tickets it wishes to preserve in an overflow situation
*
* @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world The world
* @param maxTicketCount The maximum number of tickets that will be allowed.
* @return A list of the tickets this mod wishes to continue using. This list will be truncated
* to "maxTicketCount" size after the call returns and then offered to the other callback
* method
*/
public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount);
}
public enum Type
{
/**
* For non-entity registrations
*/
NORMAL,
/**
* For entity registrations
*/
ENTITY
}
public static class Ticket
{
private String modId;
private Type ticketType;
private LinkedHashSet<ChunkCoordIntPair> requestedChunks;
private NBTTagCompound modData;
public final World world;
private int maxDepth;
private String entityClazz;
private int entityChunkX;
private int entityChunkZ;
private Entity entity;
private String player;
Ticket(String modId, Type type, World world)
{
this.modId = modId;
this.ticketType = type;
this.world = world;
this.maxDepth = getMaxChunkDepthFor(modId);
this.requestedChunks = Sets.newLinkedHashSet();
}
Ticket(String modId, Type type, World world, String player)
{
this(modId, type, world);
if (player != null)
{
this.player = player;
}
else
{
FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player");
throw new RuntimeException();
}
}
/**
* The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached,
* the least recently forced chunk, by original registration time, is removed from the forced chunk list.
*
* @param depth The new depth to set
*/
public void setChunkListDepth(int depth)
{
if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0))
{
FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId));
}
else
{
this.maxDepth = depth;
}
}
/**
* Gets the current max depth for this ticket.
* Should be the same as getMaxChunkListDepth()
* unless setChunkListDepth has been called.
*
* @return Current max depth
*/
public int getChunkListDepth()
{
return maxDepth;
}
/**
* Get the maximum chunk depth size
*
* @return The maximum chunk depth size
*/
public int getMaxChunkListDepth()
{
return getMaxChunkDepthFor(modId);
}
/**
* Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception.
*
* @param entity The entity to bind
*/
public void bindEntity(Entity entity)
{
if (ticketType!=Type.ENTITY)
{
throw new RuntimeException("Cannot bind an entity to a non-entity ticket");
}
this.entity = entity;
}
/**
* Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket.
* Example data to store would be a TileEntity or Block location. This is persisted with the ticket and
* provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover
* useful state information for the forced chunks.
*
* @return The custom compound tag for mods to store additional chunkloading data
*/
public NBTTagCompound getModData()
{
if (this.modData == null)
{
this.modData = new NBTTagCompound();
}
return modData;
}
/**
* Get the entity associated with this {@link Type#ENTITY} type ticket
* @return
*/
public Entity getEntity()
{
return entity;
}
/**
* Is this a player associated ticket rather than a mod associated ticket?
*/
public boolean isPlayerTicket()
{
return player != null;
}
/**
* Get the player associated with this ticket
*/
public String getPlayerName()
{
return player;
}
/**
* Get the associated mod id
*/
public String getModId()
{
return modId;
}
/**
* Gets the ticket type
*/
public Type getType()
{
return ticketType;
}
/**
* Gets a list of requested chunks for this ticket.
*/
public ImmutableSet getChunkList()
{
return ImmutableSet.copyOf(requestedChunks);
}
}
public static class ForceChunkEvent extends Event {
public final Ticket ticket;
public final ChunkCoordIntPair location;
public ForceChunkEvent(Ticket ticket, ChunkCoordIntPair location)
{
this.ticket = ticket;
this.location = location;
}
}
public static class UnforceChunkEvent extends Event {
public final Ticket ticket;
public final ChunkCoordIntPair location;
public UnforceChunkEvent(Ticket ticket, ChunkCoordIntPair location)
{
this.ticket = ticket;
this.location = location;
}
}
static void loadWorld(World world)
{
ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create();
tickets.put(world, newTickets);
forcedChunks.put(world, ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of());
if (!(world instanceof WorldServer))
{
return;
}
dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build());
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
if (chunkLoaderData.exists() && chunkLoaderData.isFile())
{
ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create();
ArrayListMultimap<String, Ticket> playerLoadedTickets = ArrayListMultimap.<String, Ticket>create();
NBTTagCompound forcedChunkData;
try
{
forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath());
return;
}
NBTTagList ticketList = forcedChunkData.getTagList("TicketList");
for (int i = 0; i < ticketList.tagCount(); i++)
{
NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i);
String modId = ticketHolder.getString("Owner");
boolean isPlayer = "Forge".equals(modId);
if (!isPlayer && !Loader.isModLoaded(modId))
{
FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId);
continue;
}
if (!isPlayer && !callbacks.containsKey(modId))
{
FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
continue;
}
NBTTagList tickets = ticketHolder.getTagList("Tickets");
for (int j = 0; j < tickets.tagCount(); j++)
{
NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j);
modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
Type type = Type.values()[ticket.getByte("Type")];
byte ticketChunkDepth = ticket.getByte("ChunkListDepth");
Ticket tick = new Ticket(modId, type, world);
if (ticket.hasKey("ModData"))
{
tick.modData = ticket.getCompoundTag("ModData");
}
if (ticket.hasKey("Player"))
{
tick.player = ticket.getString("Player");
playerLoadedTickets.put(tick.modId, tick);
playerTickets.put(tick.player, tick);
}
else
{
loadedTickets.put(modId, tick);
}
if (type == Type.ENTITY)
{
tick.entityChunkX = ticket.getInteger("chunkX");
tick.entityChunkZ = ticket.getInteger("chunkZ");
UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB"));
// add the ticket to the "pending entity" list
pendingEntities.put(uuid, tick);
}
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
// force the world to load the entity's chunk
// the load will come back through the loadEntity method and attach the entity
// to the ticket
world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick));
loadedTickets.remove(tick.modId, tick);
}
}
pendingEntities.clear();
// send callbacks
for (String modId : loadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
int maxTicketLength = getMaxTicketLengthFor(modId);
List<Ticket> tickets = loadedTickets.get(modId);
if (loadingCallback instanceof OrderedLoadingCallback)
{
OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback;
tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength);
}
if (tickets.size() > maxTicketLength)
{
FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size());
tickets.subList(maxTicketLength, tickets.size()).clear();
}
ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
}
for (String modId : playerLoadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
List<Ticket> tickets = playerLoadedTickets.get(modId);
ForgeChunkManager.tickets.get(world).putAll("Forge", tickets);
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
}
}
}
/**
* Set a chunkloading callback for the supplied mod object
*
* @param mod The mod instance registering the callback
* @param callback The code to call back when forced chunks are loaded
*/
public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return;
}
callbacks.put(container.getModId(), callback);
}
/**
* Discover the available tickets for the mod in the world
*
* @param mod The mod that will own the tickets
* @param world The world
* @return The count of tickets left for the mod in the supplied world
*/
public static int ticketCountAvailableFor(Object mod, World world)
{
ModContainer container = getContainer(mod);
if (container!=null)
{
String modId = container.getModId();
int allowedCount = getMaxTicketLengthFor(modId);
return allowedCount - tickets.get(world).get(modId).size();
}
else
{
return 0;
}
}
private static ModContainer getContainer(Object mod)
{
ModContainer container = Loader.instance().getModObjectList().inverse().get(mod);
return container;
}
public static int getMaxTicketLengthFor(String modId)
{
int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount;
return allowedCount;
}
public static int getMaxChunkDepthFor(String modId)
{
int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks;
return allowedCount;
}
public static int ticketCountAvaliableFor(String username)
{
return playerTickets.get(username).size() - playerTicketLength;
}
@Deprecated
public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type)
{
return requestPlayerTicket(mod, player.getEntityName(), world, type);
}
public static Ticket requestPlayerTicket(Object mod, String player, World world, Type type)
{
ModContainer mc = getContainer(mod);
if (mc == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
if (playerTickets.get(player).size()>playerTicketLength)
{
FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player, mc.getModId());
return null;
}
Ticket ticket = new Ticket(mc.getModId(),type,world,player);
playerTickets.put(player, ticket);
tickets.get(world).put("Forge", ticket);
return ticket;
}
/**
* Request a chunkloading ticket of the appropriate type for the supplied mod
*
* @param mod The mod requesting a ticket
* @param world The world in which it is requesting the ticket
* @param type The type of ticket
* @return A ticket with which to register chunks for loading, or null if no further tickets are available
*/
public static Ticket requestTicket(Object mod, World world, Type type)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
String modId = container.getModId();
if (!callbacks.containsKey(modId))
{
FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId);
throw new RuntimeException("Invalid ticket request");
}
int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount;
if (tickets.get(world).get(modId).size() >= allowedCount)
{
FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount);
return null;
}
Ticket ticket = new Ticket(modId, type, world);
tickets.get(world).put(modId, ticket);
return ticket;
}
/**
* Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking.
*
* @param ticket The ticket to release
*/
public static void releaseTicket(Ticket ticket)
{
if (ticket == null)
{
return;
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
return;
}
if (ticket.requestedChunks!=null)
{
for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks))
{
unforceChunk(ticket, chunk);
}
}
if (ticket.isPlayerTicket())
{
playerTickets.remove(ticket.player, ticket);
tickets.get(ticket.world).remove("Forge",ticket);
}
else
{
tickets.get(ticket.world).remove(ticket.modId, ticket);
}
}
/**
* Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least
* recently registered chunk is unforced and may be unloaded.
* It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering.
*
* @param ticket The ticket registering the chunk
* @param chunk The chunk to force
*/
public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
if (ticket.ticketType == Type.ENTITY && ticket.entity == null)
{
throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity");
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
return;
}
ticket.requestedChunks.add(chunk);
MinecraftForge.EVENT_BUS.post(new ForceChunkEvent(ticket, chunk));
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> newMap = ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>builder().putAll(forcedChunks.get(ticket.world)).put(chunk, ticket).build();
forcedChunks.put(ticket.world, newMap);
if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth)
{
ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next();
unforceChunk(ticket,removed);
}
}
/**
* Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list
* This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks
* in the ticket list
*
* @param ticket The ticket holding the chunk list
* @param chunk The chunk you wish to push to the end (so that it would be unloaded last)
*/
public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk))
{
return;
}
ticket.requestedChunks.remove(chunk);
ticket.requestedChunks.add(chunk);
}
/**
* Unforce the supplied chunk, allowing it to be unloaded and stop ticking.
*
* @param ticket The ticket holding the chunk
* @param chunk The chunk to unforce
*/
public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
ticket.requestedChunks.remove(chunk);
MinecraftForge.EVENT_BUS.post(new UnforceChunkEvent(ticket, chunk));
LinkedHashMultimap<ChunkCoordIntPair, Ticket> copy = LinkedHashMultimap.create(forcedChunks.get(ticket.world));
copy.remove(chunk, ticket);
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> newMap = ImmutableSetMultimap.copyOf(copy);
forcedChunks.put(ticket.world,newMap);
}
static void loadConfiguration()
{
for (String mod : config.categories.keySet())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
ticketConstraints.put(mod, modTC.getInt(200));
chunkConstraints.put(mod, modCPT.getInt(25));
}
config.save();
}
/**
* The list of persistent chunks in the world. This set is immutable.
* @param world
* @return
*/
public static ImmutableSetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world)
{
return forcedChunks.containsKey(world) ? forcedChunks.get(world) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of();
}
static void saveWorld(World world)
{
// only persist persistent worlds
if (!(world instanceof WorldServer)) { return; }
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
NBTTagCompound forcedChunkData = new NBTTagCompound();
NBTTagList ticketList = new NBTTagList();
forcedChunkData.setTag("TicketList", ticketList);
Multimap<String, Ticket> ticketSet = tickets.get(worldServer);
for (String modId : ticketSet.keySet())
{
NBTTagCompound ticketHolder = new NBTTagCompound();
ticketList.appendTag(ticketHolder);
ticketHolder.setString("Owner", modId);
NBTTagList tickets = new NBTTagList();
ticketHolder.setTag("Tickets", tickets);
for (Ticket tick : ticketSet.get(modId))
{
NBTTagCompound ticket = new NBTTagCompound();
ticket.setByte("Type", (byte) tick.ticketType.ordinal());
ticket.setByte("ChunkListDepth", (byte) tick.maxDepth);
if (tick.isPlayerTicket())
{
ticket.setString("ModId", tick.modId);
ticket.setString("Player", tick.player);
}
if (tick.modData != null)
{
ticket.setCompoundTag("ModData", tick.modData);
}
if (tick.ticketType == Type.ENTITY && tick.entity != null && tick.entity.addEntityID(new NBTTagCompound()))
{
ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX));
ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ));
ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
tickets.appendTag(ticket);
}
else if (tick.ticketType != Type.ENTITY)
{
tickets.appendTag(ticket);
}
}
}
try
{
CompressedStreamTools.write(forcedChunkData, chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath());
return;
}
}
static void loadEntity(Entity entity)
{
UUID id = entity.getPersistentID();
Ticket tick = pendingEntities.get(id);
if (tick != null)
{
tick.bindEntity(entity);
pendingEntities.remove(id);
}
}
public static void putDormantChunk(long coords, Chunk chunk)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj);
if (cache != null)
{
cache.put(coords, chunk);
}
}
public static Chunk fetchDormantChunk(long coords, World world)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(world);
return cache == null ? null : cache.getIfPresent(coords);
}
static void captureConfig(File configDir)
{
cfgFile = new File(configDir,"forgeChunkLoading.cfg");
config = new Configuration(cfgFile, true);
try
{
config.load();
}
catch (Exception e)
{
File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak");
if (dest.exists())
{
dest.delete();
}
cfgFile.renameTo(dest);
FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak");
}
config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control");
Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200);
maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" +
"in this file. This is the number of chunk loading requests a mod is allowed to make.";
defaultMaxCount = maxTicketCount.getInt(200);
Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25);
maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" +
"for a mod without an override. This is the maximum number of chunks a single ticket can force.";
defaultMaxChunks = maxChunks.getInt(25);
Property playerTicketCount = config.get("defaults", "playetTicketCount", 500);
playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it.";
playerTicketLength = playerTicketCount.getInt(500);
Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0);
dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" +
"loading times. Specify the size of that cache here";
dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0);
FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0));
Property modOverridesEnabled = config.get("defaults", "enabled", true);
modOverridesEnabled.comment = "Are mod overrides enabled?";
overridesEnabled = modOverridesEnabled.getBoolean(true);
config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" +
"Copy this section and rename the with the modid for the mod you wish to override.\n" +
"A value of zero in either entry effectively disables any chunkloading capabilities\n" +
"for that mod");
Property sampleTC = config.get("Forge", "maximumTicketCount", 200);
sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities.";
sampleTC = config.get("Forge", "maximumChunksPerTicket", 25);
sampleTC.comment = "Maximum chunks per ticket for the mod.";
for (String mod : config.categories.keySet())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
}
}
public static Map<String,Property> getConfigMapFor(Object mod)
{
ModContainer container = getContainer(mod);
if (container != null)
{
return config.getCategory(container.getModId()).getValues();
}
return null;
}
public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type)
{
ModContainer container = getContainer(mod);
if (container != null)
{
Map<String, Property> props = config.getCategory(container.getModId()).getValues();
props.put(propertyName, new Property(propertyName, value, type));
}
}
}
|
package pie.watchface;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import java.util.Date;
public class PieWatchFace {
public static final String TAG = PieWatchFace.class.getSimpleName();
private Context mContext;
@SuppressWarnings("unused")
private boolean mLowBitAmbientMode;
@SuppressWarnings("unused")
private boolean mBurnInProtectionMode;
private Bitmap mBackgroundImg;
// all paint brushes
private Paint mPiePaint;
private Paint mTextPaint;
private Paint mDialPaint;
private Paint mDotPaint;
private Paint mHorizonPaint;
private Paint mTimeLeftTextPaint;
// watchface variables calculated on every draw() call
private Canvas mCanvas;
private Rect mWatchFaceBounds;
private boolean mAmbientMode;
private float mCurrentAngle;
private PointF mWatchFaceCenter;
public PieWatchFace(Context context) {
this.mContext = context;
createPaintBrushes();
}
public void draw(Canvas canvas, Rect watchFaceBounds, Rect peekCardBounds, boolean ambientMode) {
// TODO: account for screen bounds, otherwise, events get drawn outside the screen view
this.mCanvas = canvas;
this.mWatchFaceBounds = watchFaceBounds;
this.mAmbientMode = ambientMode;
this.mCurrentAngle = PieUtils.getAngleForDate(new Date(), true);
this.mWatchFaceCenter = new PointF(mWatchFaceBounds.exactCenterX(), mWatchFaceBounds.exactCenterY());
drawBgImage();
drawEvents();
// drawHorizon();
drawBasicClock();
drawPeekCardBounds(peekCardBounds);
}
private void drawBasicClock() {
int width = mWatchFaceBounds.width();
int height = mWatchFaceBounds.height();
double radius = width / 2;
// drawing current time indicator
Point nowPoint = PieUtils.getPointOnTheCircleCircumference(radius, mCurrentAngle, mWatchFaceCenter.x, mWatchFaceCenter.y);
mCanvas.drawLine(mWatchFaceCenter.x, mWatchFaceCenter.y, nowPoint.x, nowPoint.y, mDialPaint);
// drawing center dot
mCanvas.drawCircle(mWatchFaceCenter.x, mWatchFaceCenter.y, PieUtils.getPixelsForDips(mContext, 5), mDotPaint);
// drawing hour markers
float markerLength = PieUtils.getPixelsForDips(mContext, 10);
mCanvas.drawLine(mWatchFaceCenter.x, height, mWatchFaceCenter.x, height - markerLength, mDialPaint);
mCanvas.drawLine(mWatchFaceCenter.x, 0, mWatchFaceCenter.x, markerLength, mDialPaint);
mCanvas.drawLine(width, mWatchFaceCenter.y, width - markerLength, mWatchFaceCenter.y, mDialPaint);
mCanvas.drawLine(0, mWatchFaceCenter.y, markerLength, mWatchFaceCenter.y, mDialPaint);
}
private void drawPeekCardBounds(Rect peekCardBounds) {
if (mAmbientMode) {
Paint bgPaint = new Paint();
bgPaint.setColor(Color.BLACK);
mCanvas.drawRect(peekCardBounds, bgPaint);
Paint linePaint = new Paint();
linePaint.setColor(Color.WHITE);
mCanvas.drawLine(peekCardBounds.left, peekCardBounds.top, peekCardBounds.right, peekCardBounds.top, linePaint);
}
}
private void drawEvents() {
if (mAmbientMode)
return;
RectF floatingPointBounds = new RectF(mWatchFaceBounds);
for (CalendarEvent event : CalendarEvent.allEvents()) {
// draw even piece background
mPiePaint.setColor(event.Color);
mCanvas.drawArc(floatingPointBounds, event.startAngle, event.durationInDegrees, true, mPiePaint);
// draw event text
double radius = mWatchFaceBounds.width() / 2;
Point endPoint = PieUtils.getPointOnTheCircleCircumference(radius, event.endAngle, mWatchFaceCenter.x, mWatchFaceCenter.y);
Point startPoint = PieUtils.getPointOnTheCircleCircumference(radius, event.startAngle, mWatchFaceCenter.x, mWatchFaceCenter.y);
// title text
Path eventTitlePath = new Path();
float titleTextVOffset;
float titleTextHOffset;
if (event.drawTitleOnStartingEdge) {
if ((event.startAngle >= 270 && event.startAngle <= 360) || (event.startAngle >= 0 && event.startAngle < 90)) {
// drawing text on the starting edge when you're on the first half of circle
mTextPaint.setTextAlign(Paint.Align.RIGHT);
eventTitlePath.moveTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
eventTitlePath.lineTo(startPoint.x, startPoint.y);
titleTextVOffset = PieUtils.getPixelsForDips(mContext, 15);
titleTextHOffset = PieUtils.getPixelsForDips(mContext, -5);
} else {
// drawing text on the starting edge when you're on the second half of circle
mTextPaint.setTextAlign(Paint.Align.LEFT);
eventTitlePath.moveTo(startPoint.x, startPoint.y);
eventTitlePath.lineTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
titleTextVOffset = PieUtils.getPixelsForDips(mContext, -5);
titleTextHOffset = PieUtils.getPixelsForDips(mContext, 5);
}
} else {
if (event.endAngle >= 90 && event.endAngle < 270) {
// drawing text on the ending edge when you're on the second half of circle
eventTitlePath.moveTo(endPoint.x, endPoint.y);
eventTitlePath.lineTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
mTextPaint.setTextAlign(Paint.Align.LEFT);
titleTextVOffset = PieUtils.getPixelsForDips(mContext, 15);
titleTextHOffset = PieUtils.getPixelsForDips(mContext, 5);
} else {
// drawing text on the ending edge when you're on the first half of circle
eventTitlePath.moveTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
eventTitlePath.lineTo(endPoint.x, endPoint.y);
mTextPaint.setTextAlign(Paint.Align.RIGHT);
titleTextVOffset = PieUtils.getPixelsForDips(mContext, -5);
titleTextHOffset = PieUtils.getPixelsForDips(mContext, -5);
}
}
mCanvas.drawTextOnPath(event.Title, eventTitlePath, titleTextHOffset, titleTextVOffset, mTextPaint);
}
// double radius = mWatchFaceBounds.width() / 2;
// int nowMinutes = PieUtils.getDateInMinutes(new Date());
// // assume the start is the current time
// float baselineAngle = mCurrentAngle;
// // looping through the stored events
// for (CalendarEvent event : events) {
// //TODO: for all day events, these should be added just behind the current time indicator, and be "dragged along" for the rest of the day. The downside is we lose some of our events horizon.
// // draw background piece
// mPiePaint.setColor(event.Color);
// mCanvas.drawArc(floatingPointBounds, event.startAngle, event.durationInDegrees, true, mPiePaint);
// /*if (nowMinutes > startMinutes &&
// nowMinutes < endMinutes &&
// baselineAngle == mCurrentAngle) {
// // we are currently in progress of this event, use the start as baseline
// baselineAngle = startAngle;
//
// // cut the duration short
// duration = duration - (mCurrentAngle - startAngle);
//
// // drawing the pie piece from now for the rest of the duration
// mCanvas.drawArc(boundsF, mCurrentAngle, duration, true, mPiePaint);
// } else {
// // drawing the pie piece fully
// }*/
// /*// drawing the title inside the pie piece
// int MIN_DEG_FOR_TITLE = 12;
// // draw Text
// if (duration >= MIN_DEG_FOR_TITLE) {
// Path path = new Path();
// Path timePath = new Path();
// Point endPoint = PieUtils.getPointOnTheCircleCircumference(radius, endAngle, mWatchFaceCenter.x, mWatchFaceCenter.y);
// Point startPoint = PieUtils.getPointOnTheCircleCircumference(radius, startAngle, mWatchFaceCenter.x, mWatchFaceCenter.y);
// float titleTextVOffset;
// float titleTextHOffset;
// float timeTextVOffset;
// float timeTextHOffset;
// //Log.d(TAG, "Event " + event.Title + ", start angle " + startAngle + " - end angle " + endAngle);
// if (endAngle <= POS_DIAL_6_OCLOCK
// || (endAngle <= POS_DIAL_3_OCLOCK_ALT && endAngle > POS_DIAL_12_OCLOCK)) {
// // draw the text at the end of the slice
// mTextPaint.setTextAlign(Paint.Align.RIGHT);
// path.moveTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
// path.lineTo(endPoint.x, endPoint.y);
// titleTextVOffset = PieUtils.getPixelsForDips(mContext, -5);
// titleTextHOffset = PieUtils.getPixelsForDips(mContext, -5);
// mTimeLeftTextPaint.setTextAlign(Paint.Align.RIGHT);
// timePath.moveTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
// timePath.lineTo(startPoint.x, startPoint.y);
// timeTextVOffset = PieUtils.getPixelsForDips(mContext, 13);
// timeTextHOffset = PieUtils.getPixelsForDips(mContext, -5);
// } else if (endAngle <= POS_DIAL_12_OCLOCK) {
// // draw the text at the end of the slice
// mTextPaint.setTextAlign(Paint.Align.LEFT);
// path.moveTo(endPoint.x, endPoint.y);
// path.lineTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
// titleTextVOffset = PieUtils.getPixelsForDips(mContext, 20);
// titleTextHOffset = PieUtils.getPixelsForDips(mContext, 5);
// mTimeLeftTextPaint.setTextAlign(Paint.Align.LEFT);
// timePath.moveTo(startPoint.x, startPoint.y);
// timePath.lineTo(mWatchFaceCenter.x, mWatchFaceCenter.y);
// timeTextVOffset = PieUtils.getPixelsForDips(mContext, -5);
// timeTextHOffset = PieUtils.getPixelsForDips(mContext, 5);
// } else {
// // draw the text at the beginning of the slice
// //mTitlePaint.setTextAlign(Paint.Align.LEFT);
// //path.moveTo(startPoint.x, startPoint.y);
// //path.lineTo(centerX, centerY);
// Log.d(TAG, "Can't determine pie title placing. Start angle is " + startAngle + " and end angle is " + endAngle);
// // FIXME: 11/26/15 it would be much better to skip drawing event rather than crashing the whole app
// mCanvas.drawTextOnPath(event.Title, path, titleTextHOffset, titleTextVOffset, mTextPaint);
// // TODO: 11/26/15 stop drawing when event has started, aka 'in 0min'
// // TODO: 11/26/15 only draw this for next upcoming event
// mCanvas.drawTextOnPath("in 38min", timePath
// , timeTextHOffset
// , timeTextVOffset
// , mTimeLeftTextPaint);
// } // for each event
}
public void drawBgImage() {
if (mBackgroundImg == null)
mBackgroundImg = Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(mContext.getResources(), R.drawable.bg)
, mWatchFaceBounds.width()
, mWatchFaceBounds.height()
, true /* filter */
);
mCanvas.drawBitmap(mBackgroundImg, 0, 0, null);
}
private void drawHorizon() {
// drawing horizon separator
int horizonSeparatorLength = 40;
int[] colors = {Color.TRANSPARENT, Color.BLACK};
float[] positions = {(mCurrentAngle - horizonSeparatorLength) / 360f, mCurrentAngle / 360f};
SweepGradient horizonGradient = new SweepGradient(mWatchFaceCenter.x, mWatchFaceCenter.y, colors, positions);
mHorizonPaint.setShader(horizonGradient);
mCanvas.drawArc(new RectF(mWatchFaceBounds)
, mCurrentAngle - horizonSeparatorLength
, horizonSeparatorLength
, true
, mHorizonPaint);
}
private void createPaintBrushes() {
// the brush used to paint the pie pieces
mPiePaint = new Paint();
mPiePaint.setARGB(120, 100, 240, 200);
mPiePaint.setStrokeWidth(5.0f);
mPiePaint.setAntiAlias(true);
mPiePaint.setStrokeCap(Paint.Cap.ROUND);
mPiePaint.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// the brush used to paint the text on the pie pieces
mTextPaint = new Paint();
mTextPaint.setColor(Color.WHITE);
mTextPaint.setStrokeWidth(5.0f);
mTextPaint.setAntiAlias(true);
mTextPaint.setStrokeCap(Paint.Cap.ROUND);
mTextPaint.setTextSize(24);
Typeface plain = Typeface.create("sans-serif-condensed", Typeface.NORMAL);
mTextPaint.setTypeface(plain);
// the brush used to paint the time left till next event piece
mTimeLeftTextPaint = new Paint(mTextPaint);
mTimeLeftTextPaint.setTextSize(19);
mTimeLeftTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.ITALIC));
// the brush used to paint the hour markers and current time marker
mDialPaint = new Paint();
mDialPaint.setColor(Color.WHITE);
mDialPaint.setAlpha(180);
mDialPaint.setStrokeWidth(6.0f);
mDialPaint.setAntiAlias(true);
mDialPaint.setStrokeCap(Paint.Cap.ROUND);
mDialPaint.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// the brush used to paint the hour markers and current time marker
mDotPaint = new Paint();
mDotPaint.setColor(Color.parseColor("#C9C9C9"));
mDotPaint.setAlpha(255);
mDotPaint.setStrokeWidth(6.0f);
mDotPaint.setAntiAlias(true);
mDotPaint.setStrokeCap(Paint.Cap.ROUND);
mDotPaint.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// the brush used to paint the horizon separator
mHorizonPaint = new Paint();
mHorizonPaint.setColor(Color.BLACK);
mHorizonPaint.setStrokeWidth(5.0f);
mHorizonPaint.setAntiAlias(true);
mHorizonPaint.setStrokeCap(Paint.Cap.ROUND);
}
public void setLowBitAmbientMode(boolean lowBitAmbientMode) {
this.mLowBitAmbientMode = lowBitAmbientMode;
}
// MARK: property setters
public void setBurnInProtectionMode(boolean burnInProtectionMode) {
this.mBurnInProtectionMode = burnInProtectionMode;
}
// for easy use, the primary positions of the dial
public enum Pos {
DIAL_12_OCLOCK(270),
DIAL_3_OCLOCK(0),
DIAL_3_OCLOCK_ALT(360),
DIAL_6_OCLOCK(90),
DIAL_9_OCLOCK(180);
final int nativeInt;
Pos(int nativeInt) {
this.nativeInt = nativeInt;
}
}
}
|
package main;
import lpn.gui.*;
import lpn.parser.LhpnFile;
import lpn.parser.Lpn2verilog;
import lpn.parser.Translator;
import graph.Graph;
//import lpn.parser.properties.BuildProperty;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.Point;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.AbstractAction;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.TreeModel;
import javax.mail.*;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.*;
import analysis.AnalysisView;
import analysis.Run;
import lpn.parser.properties.BuildProperty;
import biomodel.annotation.AnnotationUtility;
import biomodel.annotation.SBOLAnnotation;
import biomodel.gui.ModelEditor;
import biomodel.gui.movie.MovieContainer;
import biomodel.gui.textualeditor.ElementsPanel;
import biomodel.parser.BioModel;
import biomodel.parser.GCM2SBML;
import biomodel.util.GlobalConstants;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.Application;
import java.io.Writer;
import learn.LearnGCM;
import learn.LearnLHPN;
import learn.datamanager.DataManager;
import main.util.Utility;
import main.util.tabs.CloseAndMaxTabbedPane;
import synthesis.Synthesis;
import verification.*;
import verification.platu.lpn.io.PlatuGrammarLexer;
import verification.platu.lpn.io.PlatuGrammarParser;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
import org.jlibsedml.Curve;
import org.jlibsedml.Libsedml;
import org.jlibsedml.Model;
import org.jlibsedml.Output;
import org.jlibsedml.Plot2D;
import org.jlibsedml.SEDMLDocument;
import org.jlibsedml.SedML;
import org.jlibsedml.SedMLError;
import org.jlibsedml.Task;
//import org.antlr.runtime.TokenStream;
import org.sbml.libsbml.*;
import org.sbolstandard.core.SBOLDocument;
//import lpn.parser.properties.*;
import sbol.SBOLBrowser;
import sbol.SBOLUtility;
import java.net.*;
import uk.ac.ebi.biomodels.*;
/**
* This class creates a GUI for the Tstubd program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* are selected.
*
* @author Curtis Madsen
*/
public class Gui implements MouseListener, ActionListener, MouseMotionListener, MouseWheelListener {
public static JFrame frame; // Frame where components of the GUI are
// displayed
private JMenuBar menuBar;
private JMenu file, openRecent, edit, view, tools, help, importMenu, exportMenu, newMenu, viewModel;
private JMenuItem newProj; // The new menu item
private JMenuItem newSBMLModel; // The new menu item
private JMenuItem newGridModel;
private JMenuItem newVhdl; // The new vhdl menu item
private JMenuItem newS; // The new assembly file menu item
private JMenuItem newInst; // The new instruction file menu item
private JMenuItem newLhpn; // The new lhpn menu item
private JMenuItem newProperty; // The new lhpn menu item DK
private JMenuItem newG; // The new petri net menu item
private JMenuItem newCsp; // The new csp menu item
private JMenuItem newHse; // The new handshaking extension menu item
private JMenuItem newUnc; // The new extended burst mode menu item
private JMenuItem newRsg; // The new rsg menu item
private JMenuItem newSpice; // The new spice circuit item
private JMenuItem exit; // The exit menu item
private JMenuItem importSbol;
private JMenuItem importSedml;
private JMenuItem importSbml; // The import sbml menu item
private JMenuItem importBioModel; // The import sbml menu item
//private JMenuItem importDot; // The import dot menu item
private JMenuItem importVhdl; // The import vhdl menu item
private JMenuItem importS; // The import assembly file menu item
private JMenuItem importInst; // The import instruction file menu item
private JMenuItem importLpn; // The import lpn menu item
private JMenuItem importG; // The import .g file menu item
private JMenuItem importCsp; // The import csp menu item
private JMenuItem importHse; // The import handshaking extension menu
private JMenuItem importUnc; // The import extended burst mode menu item
private JMenuItem importRsg; // The import rsg menu item
private JMenuItem importSpice; // The import spice circuit item
private JMenuItem manual; // The manual menu item
private JMenuItem bugReport; // The manual menu item
private JMenuItem about; // The about menu item
private JMenuItem openProj; // The open menu item
private JMenuItem clearRecent; // Clear recent project list
private JMenuItem pref; // The preferences menu item
private JMenuItem graph; // The graph menu item
private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng, exportSvg, exportTsd,
exportSBML, exportFlatSBML, exportSBOL, exportAvi, exportMp4;
private JMenu exportDataMenu, exportMovieMenu, exportImageMenu;
private String root; // The root directory
private FileTree tree; // FileTree
private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools
private JToolBar toolbar; // Tool bar for common options
private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool
// Bar
// options
private JPanel mainPanel; // the main panel
private JSplitPane topSplit;
private JSplitPane mainSplit;
private Boolean LPN2SBML = true;
public Log log; // the log
private JPopupMenu popup; // popup menu
private String separator;
private KeyEventDispatcher dispatcher;
private JMenuItem recentProjects[];
private String recentProjectPaths[];
private int numberRecentProj;
private int ShortCutKey;
public static String SBMLLevelVersion;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean async;
// treeSelected
// = false;
public boolean atacs, lema;
private String viewer;
private boolean runGetNames;
private String[] BioModelIds = null;
private JMenuItem addCompartment, addSpecies, addReaction, addComponent, addPromoter, addVariable, addBoolean, addPlace,
addTransition, addRule, addConstraint, addEvent, addSelfInfl, cut, select,undo, redo, copy, rename, delete,
moveLeft, moveRight, moveUp, moveDown;
private JMenuItem save, saveAs, saveSBOL, check, run, refresh, viewCircuit, viewRules, viewTrace, viewLog, viewCoverage,
viewLHPN, saveModel, saveAsVerilog, viewSG, viewModGraph, viewLearnedModel, viewModBrowser, createAnal, createLearn,
createSbml, createSynth, createVer, close, closeAll, saveAll, convertToLPN;
public String ENVVAR;
public static int SBML_LEVEL = 3;
public static int SBML_VERSION = 1;
public static final Object[] OPTIONS = { "Yes", "No", "Yes To All", "No To All", "Cancel" };
public static final int YES_OPTION = JOptionPane.YES_OPTION;
public static final int NO_OPTION = JOptionPane.NO_OPTION;
public static final int YES_TO_ALL_OPTION = JOptionPane.CANCEL_OPTION;
public static final int NO_TO_ALL_OPTION = 3;
public static final int CANCEL_OPTION = 4;
public static Object ICON_EXPAND = UIManager.get("Tree.expandedIcon");
public static Object ICON_COLLAPSE = UIManager.get("Tree.collapsedIcon");
private static final String[] bugReportTypes = new String[] { "BUG", "CHANGE", "FEATURE" };
public static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
String message;
//Implements Thread.UncaughtExceptionHandler.uncaughtException()
public void uncaughtException(Thread th, Throwable ex) {
final JFrame exp = new JFrame("Unhandled Exception");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
ex.printStackTrace();
message = sw.toString(); // stack trace as a string
JLabel error = new JLabel("Program has thrown an exception of the type:");
JLabel errMsg = new JLabel(ex.toString());
JButton details = new JButton("Details");
details.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Close" };
JOptionPane.showOptionDialog(exp, message, "Details", JOptionPane.YES_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
});
JButton report = new JButton("Send Bug Report");
report.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
submitBugReport("\n\nStack trace:\n"+message);
}
});
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exp.dispose();
}
});
JPanel errMessage = new JPanel();
errMessage.add(error);
JPanel errMsgPanel = new JPanel();
errMsgPanel.add(errMsg);
JPanel buttons = new JPanel();
buttons.add(details);
buttons.add(report);
buttons.add(close);
JPanel expPanel = new JPanel(new BorderLayout());
expPanel.add(errMessage,"North");
expPanel.add(errMsgPanel,"Center");
expPanel.add(buttons,"South");
exp.setContentPane(expPanel);
exp.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = exp.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
exp.setLocation(x, y);
exp.setVisible(true);
}
}
private static void submitBugReport(String message) {
JPanel reportBugPanel = new JPanel(new GridLayout(4,1));
JLabel typeLabel = new JLabel("Type of Report:");
JComboBox reportType = new JComboBox(bugReportTypes);
if (!message.equals("")) {
typeLabel.setEnabled(false);
reportType.setEnabled(false);
}
JPanel typePanel = new JPanel(new GridLayout(1,2));
typePanel.add(typeLabel);
typePanel.add(reportType);
JLabel emailLabel = new JLabel("Email address:");
JTextField emailAddr = new JTextField(30);
JPanel emailPanel = new JPanel(new GridLayout(1,2));
emailPanel.add(emailLabel);
emailPanel.add(emailAddr);
JLabel bugSubjectLabel = new JLabel("Brief Description:");
JTextField bugSubject = new JTextField(30);
JPanel bugSubjectPanel = new JPanel(new GridLayout(1,2));
bugSubjectPanel.add(bugSubjectLabel);
bugSubjectPanel.add(bugSubject);
JLabel bugDetailLabel = new JLabel("Detailed Description:");
JTextArea bugDetail = new JTextArea(5,30);
bugDetail.setLineWrap(true);
bugDetail.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(100, 100));
scroll.setPreferredSize(new Dimension(100, 100));
scroll.setViewportView(bugDetail);
JPanel bugDetailPanel = new JPanel(new GridLayout(1,2));
bugDetailPanel.add(bugDetailLabel);
bugDetailPanel.add(scroll);
reportBugPanel.add(typePanel);
reportBugPanel.add(emailPanel);
reportBugPanel.add(bugSubjectPanel);
reportBugPanel.add(bugDetailPanel);
Object[] options = { "Send", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, reportBugPanel, "Bug Report",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value==0) {
String to = "atacs-bugs@vlsigroup.ece.utah.edu";
Properties props = new Properties();
props.put("mail.smtp.user", "ibiosim@gmail.com");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
MyAuthenticator authentication = new MyAuthenticator("ibiosim@gmail.com","lambda123");
Session session = Session.getDefaultInstance(props,authentication);
MimeMessage mimeMessage = new MimeMessage(session);
try {
mimeMessage.setFrom(new InternetAddress(emailAddr.getText().trim()));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(reportType.getSelectedItem() + ": "+bugSubject.getText().trim());
mimeMessage.setText("Bug reported by: "+emailAddr.getText().trim()+"\n\nDescription:\n"+
bugDetail.getText().trim()+message);
Transport.send(mimeMessage);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
public static class MyAuthenticator extends javax.mail.Authenticator {
String User;
String Password;
public MyAuthenticator (String user, String password) {
User = user;
Password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(User, Password);
}
}
public class MacOSAboutHandler extends Application {
public MacOSAboutHandler() {
addApplicationListener(new AboutBoxHandler());
}
class AboutBoxHandler extends ApplicationAdapter {
public void handleAbout(ApplicationEvent event) {
about();
event.setHandled(true);
}
}
}
public class MacOSPreferencesHandler extends Application {
public MacOSPreferencesHandler() {
addApplicationListener(new PreferencesHandler());
}
class PreferencesHandler extends ApplicationAdapter {
public void handlePreferences(ApplicationEvent event) {
EditPreferences editPreferences = new EditPreferences(frame,async,tree);
editPreferences.preferences();
event.setHandled(true);
}
}
}
public class MacOSQuitHandler extends Application {
public MacOSQuitHandler() {
addApplicationListener(new QuitHandler());
}
class QuitHandler extends ApplicationAdapter {
public void handleQuit(ApplicationEvent event) {
if (exit())
event.setHandled(true);
}
}
}
/**
* This is the constructor for the Proj class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*
* @throws Exception
*/
public Gui(boolean lema, boolean atacs, boolean LPN2SBML) {
this.lema = lema;
this.atacs = atacs;
this.LPN2SBML = LPN2SBML;
async = lema || atacs;
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
if (atacs) {
ENVVAR = System.getenv("ATACSGUI");
}
else if (lema) {
ENVVAR = System.getenv("LEMA");
}
else {
ENVVAR = System.getenv("BIOSIM");
}
// Creates a new frame
if (lema) {
frame = new JFrame("LEMA");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "LEMA.png").getImage());
}
else if (atacs) {
frame = new JFrame("ATACS");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "ATACS.png").getImage());
}
else {
frame = new JFrame("iBioSim");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage());
}
// Makes it so that clicking the x in the corner closes the program
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
exit.doClick();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
frame.addWindowListener(w);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
popup = new JPopupMenu();
popup.addMouseListener(this);
// popup.addFocusListener(this);
// popup.addComponentListener(this);
// Sets up the Tool Bar
toolbar = new JToolBar();
String imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "save.png";
saveButton = makeToolButton(imgName, "save", "Save", "Save");
// toolButton = new JButton("Save");
toolbar.add(saveButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "saveas.png";
saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As");
toolbar.add(saveasButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "savecheck.png";
checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check");
toolbar.add(checkButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "export.jpg";
exportButton = makeToolButton(imgName, "export", "Export", "Export");
toolbar.add(exportButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "run-icon.jpg";
runButton = makeToolButton(imgName, "run", "Save and Run", "Run");
toolbar.add(runButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "refresh.jpg";
refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh");
toolbar.add(refreshButton);
saveButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
saveasButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// Creates a menu for the frame
menuBar = new JMenuBar();
file = new JMenu("File");
help = new JMenu("Help");
edit = new JMenu("Edit");
openRecent = new JMenu("Open Recent");
importMenu = new JMenu("Import");
exportMenu = new JMenu("Export");
exportDataMenu = new JMenu("Data");
exportImageMenu = new JMenu("Image");
exportMovieMenu = new JMenu("Movie");
newMenu = new JMenu("New");
view = new JMenu("View");
viewModel = new JMenu("Model");
tools = new JMenu("Tools");
menuBar.add(file);
menuBar.add(edit);
if (lema) {
menuBar.add(view);
}
menuBar.add(tools);
menuBar.add(help);
select = new JMenuItem("Select Mode");
cut = new JMenuItem("Delete");
addCompartment = new JMenuItem("Add Compartment");
addSpecies = new JMenuItem("Add Species");
addReaction = new JMenuItem("Add Reaction");
addComponent = new JMenuItem("Add Component");
addPromoter = new JMenuItem("Add Promoter");
addVariable = new JMenuItem("Add Variable");
addBoolean = new JMenuItem("Add Boolean");
addPlace = new JMenuItem("Add Place");
addTransition = new JMenuItem("Add Transition");
addRule = new JMenuItem("Add Rule");
addConstraint = new JMenuItem("Add Constraint");
addEvent = new JMenuItem("Add Event");
addSelfInfl = new JMenuItem("Add Self Influence");
moveLeft = new JMenuItem("Move Left");
moveRight = new JMenuItem("Move Right");
moveUp = new JMenuItem("Move Up");
moveDown = new JMenuItem("Move Down");
undo = new JMenuItem("Undo");
redo = new JMenuItem("Redo");
copy = new JMenuItem("Copy File");
rename = new JMenuItem("Rename File");
delete = new JMenuItem("Delete File");
manual = new JMenuItem("Manual");
bugReport = new JMenuItem("Submit Bug Report");
about = new JMenuItem("About");
openProj = new JMenuItem("Open Project");
clearRecent = new JMenuItem("Clear Recent");
close = new JMenuItem("Close");
closeAll = new JMenuItem("Close All");
saveAll = new JMenuItem("Save All");
pref = new JMenuItem("Preferences");
newProj = new JMenuItem("Project");
newSBMLModel = new JMenuItem("Model");
newGridModel = new JMenuItem("Grid Model");
newSpice = new JMenuItem("Spice Circuit");
newVhdl = new JMenuItem("VHDL Model");
newS = new JMenuItem("Assembly File");
newInst = new JMenuItem("Instruction File");
newLhpn = new JMenuItem("LPN Model");
newProperty = new JMenuItem("Property");
newG = new JMenuItem("Petri Net");
newCsp = new JMenuItem("CSP Model");
newHse = new JMenuItem("Handshaking Expansion");
newUnc = new JMenuItem("Extended Burst Mode Machine");
newRsg = new JMenuItem("Reduced State Graph");
graph = new JMenuItem("TSD Graph");
probGraph = new JMenuItem("Histogram");
importSbol = new JMenuItem("SBOL File");
importSedml = new JMenuItem("SED-ML File");
importSbml = new JMenuItem("SBML Model");
importBioModel = new JMenuItem("BioModel");
convertToLPN= new JMenuItem("Convert To LPN"); //convert
//importDot = new JMenuItem("iBioSim Model");
importG = new JMenuItem("Petri Net");
importLpn = new JMenuItem("LPN Model");
importVhdl = new JMenuItem("VHDL Model");
importS = new JMenuItem("Assembly File");
importInst = new JMenuItem("Instruction File");
importSpice = new JMenuItem("Spice Circuit");
importCsp = new JMenuItem("CSP Model");
importHse = new JMenuItem("Handshaking Expansion");
importUnc = new JMenuItem("Extended Burst Mode Machine");
importRsg = new JMenuItem("Reduced State Graph");
exportSBML = new JMenuItem("SBML");
exportFlatSBML = new JMenuItem("Flat SBML");
exportSBOL = new JMenuItem("SBOL");
exportCsv = new JMenuItem("CSV");
exportDat = new JMenuItem("DAT");
exportEps = new JMenuItem("EPS");
exportJpg = new JMenuItem("JPG");
exportPdf = new JMenuItem("PDF");
exportPng = new JMenuItem("PNG");
exportSvg = new JMenuItem("SVG");
exportTsd = new JMenuItem("TSD");
exportAvi = new JMenuItem("AVI");
exportMp4 = new JMenuItem("MP4");
save = new JMenuItem("Save");
if (async) {
saveModel = new JMenuItem("Save Learned LPN");
}
else {
saveModel = new JMenuItem("Save Learned Model");
}
saveAsVerilog = new JMenuItem("Save as Verilog");
saveAsVerilog.addActionListener(this);
saveAsVerilog.setActionCommand("saveAsVerilog");
saveAsVerilog.setEnabled(false);
saveAs = new JMenuItem("Save As");
run = new JMenuItem("Save and Run");
check = new JMenuItem("Save and Check");
saveSBOL = new JMenuItem("Save SBOL");
refresh = new JMenuItem("Refresh");
viewCircuit = new JMenuItem("Circuit");
viewRules = new JMenuItem("Production Rules");
viewTrace = new JMenuItem("Error Trace");
viewLog = new JMenuItem("Log");
viewCoverage = new JMenuItem("Coverage Report");
viewLHPN = new JMenuItem("Model");
viewModGraph = new JMenuItem("Model");
viewLearnedModel = new JMenuItem("Learned Model");
viewModBrowser = new JMenuItem("Model in Browser");
viewSG = new JMenuItem("State Graph");
createAnal = new JMenuItem("Analysis Tool");
createLearn = new JMenuItem("Learn Tool");
createSbml = new JMenuItem("Create SBML File");
createSynth = new JMenuItem("Synthesis Tool");
createVer = new JMenuItem("Verification Tool");
exit = new JMenuItem("Exit");
select.addActionListener(this);
cut.addActionListener(this);
addCompartment.addActionListener(this);
addSpecies.addActionListener(this);
addReaction.addActionListener(this);
addComponent.addActionListener(this);
addPromoter.addActionListener(this);
addVariable.addActionListener(this);
addBoolean.addActionListener(this);
addPlace.addActionListener(this);
addTransition.addActionListener(this);
addRule.addActionListener(this);
addConstraint.addActionListener(this);
addEvent.addActionListener(this);
addSelfInfl.addActionListener(this);
moveLeft.addActionListener(this);
moveRight.addActionListener(this);
moveUp.addActionListener(this);
moveDown.addActionListener(this);
undo.addActionListener(this);
redo.addActionListener(this);
copy.addActionListener(this);
rename.addActionListener(this);
delete.addActionListener(this);
openProj.addActionListener(this);
clearRecent.addActionListener(this);
close.addActionListener(this);
closeAll.addActionListener(this);
saveAll.addActionListener(this);
pref.addActionListener(this);
manual.addActionListener(this);
bugReport.addActionListener(this);
newProj.addActionListener(this);
newSBMLModel.addActionListener(this);
newGridModel.addActionListener(this);
newVhdl.addActionListener(this);
newS.addActionListener(this);
newInst.addActionListener(this);
newLhpn.addActionListener(this);
newProperty.addActionListener(this);
convertToLPN.addActionListener(this);
newG.addActionListener(this);
newCsp.addActionListener(this);
newHse.addActionListener(this);
newUnc.addActionListener(this);
newRsg.addActionListener(this);
newSpice.addActionListener(this);
exit.addActionListener(this);
about.addActionListener(this);
importSbol.addActionListener(this);
importSedml.addActionListener(this);
importSbml.addActionListener(this);
importBioModel.addActionListener(this);
//importDot.addActionListener(this);
importVhdl.addActionListener(this);
importS.addActionListener(this);
importInst.addActionListener(this);
importLpn.addActionListener(this);
importG.addActionListener(this);
importCsp.addActionListener(this);
importHse.addActionListener(this);
importUnc.addActionListener(this);
importRsg.addActionListener(this);
importSpice.addActionListener(this);
exportSBML.addActionListener(this);
exportFlatSBML.addActionListener(this);
exportSBOL.addActionListener(this);
exportCsv.addActionListener(this);
exportDat.addActionListener(this);
exportEps.addActionListener(this);
exportJpg.addActionListener(this);
exportPdf.addActionListener(this);
exportPng.addActionListener(this);
exportSvg.addActionListener(this);
exportTsd.addActionListener(this);
exportAvi.addActionListener(this);
exportMp4.addActionListener(this);
graph.addActionListener(this);
probGraph.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
saveSBOL.addActionListener(this);
run.addActionListener(this);
check.addActionListener(this);
refresh.addActionListener(this);
saveModel.addActionListener(this);
viewCircuit.addActionListener(this);
viewRules.addActionListener(this);
viewTrace.addActionListener(this);
viewLog.addActionListener(this);
viewCoverage.addActionListener(this);
viewLHPN.addActionListener(this);
viewModGraph.addActionListener(this);
viewLearnedModel.addActionListener(this);
viewModBrowser.addActionListener(this);
viewSG.addActionListener(this);
createAnal.addActionListener(this);
createLearn.addActionListener(this);
createSbml.addActionListener(this);
createSynth.addActionListener(this);
createVer.addActionListener(this);
save.setActionCommand("save");
saveAs.setActionCommand("saveas");
saveSBOL.setActionCommand("saveSBOL");
run.setActionCommand("run");
check.setActionCommand("check");
refresh.setActionCommand("refresh");
if (atacs) {
viewModGraph.setActionCommand("viewModel");
}
else {
viewModGraph.setActionCommand("graph");
}
viewLHPN.setActionCommand("viewModel");
viewModBrowser.setActionCommand("browse");
viewSG.setActionCommand("stateGraph");
createLearn.setActionCommand("createLearn");
createSbml.setActionCommand("createSBML");
createSynth.setActionCommand("createSynthesis");
createVer.setActionCommand("createVerify");
ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ShortCutKey));
openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey));
close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey));
closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey | KeyEvent.SHIFT_MASK));
saveAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_MASK));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey));
saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.SHIFT_MASK));
run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey));
if (lema) {
newSBMLModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey));
}
else {
check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey));
saveSBOL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_MASK));
refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
newSBMLModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey));
newGridModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ShortCutKey | KeyEvent.ALT_MASK));
createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey | KeyEvent.SHIFT_MASK));
createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey | KeyEvent.SHIFT_MASK));
}
newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey));
graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ShortCutKey));
probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ShortCutKey | KeyEvent.SHIFT_MASK));
select.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0));
addCompartment.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.ALT_MASK));
addSpecies.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0));
addReaction.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0));
addComponent.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 0));
addPromoter.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.SHIFT_MASK));
addVariable.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, 0));
addBoolean.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, 0));
addPlace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0));
addTransition.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, 0));
addRule.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.SHIFT_MASK));
addConstraint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.SHIFT_MASK));
addEvent.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0));
addSelfInfl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, 0));
moveLeft.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.SHIFT_MASK));
moveRight.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.SHIFT_MASK));
moveUp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.SHIFT_MASK));
moveDown.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.SHIFT_MASK));
undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ShortCutKey));
redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ShortCutKey | KeyEvent.SHIFT_MASK));
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey | KeyEvent.SHIFT_MASK));
rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ShortCutKey | KeyEvent.SHIFT_MASK));
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey | KeyEvent.SHIFT_MASK));
manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.SHIFT_MASK));
bugReport.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, ShortCutKey));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey));
pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey));
importSbol.setEnabled(false);
importSedml.setEnabled(false);
importSbml.setEnabled(false);
importBioModel.setEnabled(false);
importVhdl.setEnabled(false);
importS.setEnabled(false);
importInst.setEnabled(false);
importLpn.setEnabled(false);
importG.setEnabled(false);
importCsp.setEnabled(false);
importHse.setEnabled(false);
importUnc.setEnabled(false);
importRsg.setEnabled(false);
importSpice.setEnabled(false);
exportMenu.setEnabled(false);
exportSBML.setEnabled(false);
exportFlatSBML.setEnabled(false);
exportSBOL.setEnabled(false);
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportEps.setEnabled(false);
exportJpg.setEnabled(false);
exportPdf.setEnabled(false);
exportPng.setEnabled(false);
exportSvg.setEnabled(false);
exportTsd.setEnabled(false);
exportAvi.setEnabled(false);
exportMp4.setEnabled(false);
newSBMLModel.setEnabled(false);
newGridModel.setEnabled(false);
newVhdl.setEnabled(false);
newS.setEnabled(false);
newInst.setEnabled(false);
newLhpn.setEnabled(false);
newProperty.setEnabled(false);
convertToLPN.setEnabled(false);
newG.setEnabled(false);
newCsp.setEnabled(false);
newHse.setEnabled(false);
newUnc.setEnabled(false);
newRsg.setEnabled(false);
newSpice.setEnabled(false);
graph.setEnabled(false);
probGraph.setEnabled(false);
save.setEnabled(false);
saveModel.setEnabled(false);
saveAs.setEnabled(false);
saveSBOL.setEnabled(false);
run.setEnabled(false);
check.setEnabled(false);
refresh.setEnabled(false);
cut.setEnabled(false);
select.setEnabled(false);
addCompartment.setEnabled(false);
addSpecies.setEnabled(false);
addReaction.setEnabled(false);
addComponent.setEnabled(false);
addPromoter.setEnabled(false);
addVariable.setEnabled(false);
addBoolean.setEnabled(false);
addPlace.setEnabled(false);
addTransition.setEnabled(false);
addRule.setEnabled(false);
addConstraint.setEnabled(false);
addEvent.setEnabled(false);
addSelfInfl.setEnabled(false);
moveLeft.setEnabled(false);
moveRight.setEnabled(false);
moveUp.setEnabled(false);
moveDown.setEnabled(false);
undo.setEnabled(false);
redo.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewLHPN.setEnabled(false);
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewLearnedModel.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
edit.add(undo);
edit.add(redo);
edit.addSeparator();
edit.add(select);
edit.add(cut);
edit.add(moveLeft);
edit.add(moveRight);
edit.add(moveUp);
edit.add(moveDown);
if (!async) {
edit.add(addCompartment);
edit.add(addSpecies);
edit.add(addPromoter);
edit.add(addReaction);
}
edit.add(addComponent);
edit.add(addVariable);
edit.add(addBoolean);
edit.add(addPlace);
edit.add(addTransition);
edit.add(addRule);
edit.add(addConstraint);
if (!async) {
edit.add(addEvent);
edit.add(addSelfInfl);
}
edit.addSeparator();
edit.add(copy);
edit.add(rename);
edit.add(delete);
file.add(newMenu);
newMenu.add(newProj);
if (!async) {
newMenu.add(newSBMLModel);
newMenu.add(newGridModel);
//newMenu.add(newLhpn);
}
else if (atacs) {
newMenu.add(newVhdl);
newMenu.add(newG);
newMenu.add(newLhpn);
newMenu.add(newCsp);
newMenu.add(newHse);
newMenu.add(newUnc);
newMenu.add(newRsg);
newMenu.add(newProperty);
}
else {
newMenu.add(newVhdl);
newMenu.add(newProperty);
newMenu.add(newS);
newMenu.add(newInst);
newMenu.add(newSBMLModel);
newMenu.add(newLhpn);
// newMenu.add(newSpice);
}
newMenu.add(graph);
newMenu.add(probGraph);
file.add(openProj);
file.add(openRecent);
// openMenu.add(openProj);
file.addSeparator();
file.add(close);
file.add(closeAll);
file.addSeparator();
file.add(save);
file.add(saveAs);
file.add(saveAll);
if (!async) {
//file.add(saveSBOL);
file.add(check);
}
file.add(run);
if (lema) {
file.add(saveAsVerilog);
}
else {
file.addSeparator();
file.add(refresh);
}
if (lema) {
file.add(saveModel);
}
file.addSeparator();
file.add(importMenu);
if (!async) {
//importMenu.add(importDot);
importMenu.add(importSbml);
importMenu.add(importBioModel);
importMenu.add(importLpn);
importMenu.add(importSbol);
importMenu.add(importSedml);
}
else if (atacs) {
importMenu.add(importVhdl);
importMenu.add(importG);
importMenu.add(importLpn);
importMenu.add(importCsp);
importMenu.add(importHse);
importMenu.add(importUnc);
importMenu.add(importRsg);
}
else {
importMenu.add(importVhdl);
importMenu.add(importS);
importMenu.add(importInst);
importMenu.add(importLpn);
// importMenu.add(importSpice);
}
file.add(exportMenu);
exportMenu.add(exportDataMenu);
exportMenu.add(exportImageMenu);
exportMenu.add(exportMovieMenu);
exportMenu.add(exportFlatSBML);
exportMenu.add(exportSBML);
exportMenu.add(exportSBOL);
exportMenu.addSeparator();
exportDataMenu.add(exportTsd);
exportDataMenu.add(exportCsv);
exportDataMenu.add(exportDat);
exportImageMenu.add(exportEps);
exportImageMenu.add(exportJpg);
exportImageMenu.add(exportPdf);
exportImageMenu.add(exportPng);
exportImageMenu.add(exportSvg);
exportMovieMenu.add(exportAvi);
exportMovieMenu.add(exportMp4);
//file.addSeparator();
help.add(manual);
help.add(bugReport);
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
edit.addSeparator();
edit.add(pref);
file.add(exit);
//file.addSeparator();
help.add(about);
}
if (lema) {
// view.add(viewVHDL);
// view.add(viewVerilog);
view.add(viewLHPN);
view.addSeparator();
view.add(viewLearnedModel);
view.add(viewCoverage);
view.add(viewLog);
view.add(viewTrace);
}
else if (atacs) {
view.add(viewModGraph);
view.add(viewCircuit);
view.add(viewRules);
view.add(viewTrace);
view.add(viewLog);
}
else {
view.add(viewModGraph);
// view.add(viewModBrowser);
view.add(viewLearnedModel);
view.add(viewSG);
view.add(viewLog);
// view.addSeparator();
// view.add(refresh);
}
if (LPN2SBML) {
tools.add(createAnal);
}
if (!atacs) {
tools.add(createLearn);
}
if (atacs) {
tools.add(createSynth);
}
if (async) {
tools.add(createVer);
}
// else {
// tools.add(createSbml);
root = null;
// Create recent project menu items
numberRecentProj = 0;
recentProjects = new JMenuItem[10];
recentProjectPaths = new String[10];
for (int i = 0; i < 10; i++) {
recentProjects[i] = new JMenuItem();
recentProjects[i].addActionListener(this);
recentProjects[i].setActionCommand("recent" + i);
recentProjectPaths[i] = "";
}
recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, ShortCutKey));
recentProjects[0].setMnemonic(KeyEvent.VK_0);
recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey));
recentProjects[1].setMnemonic(KeyEvent.VK_1);
recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey));
recentProjects[2].setMnemonic(KeyEvent.VK_2);
recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey));
recentProjects[3].setMnemonic(KeyEvent.VK_3);
recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey));
recentProjects[4].setMnemonic(KeyEvent.VK_4);
recentProjects[5].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey));
recentProjects[5].setMnemonic(KeyEvent.VK_5);
recentProjects[6].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_6, ShortCutKey));
recentProjects[6].setMnemonic(KeyEvent.VK_6);
recentProjects[7].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_7, ShortCutKey));
recentProjects[7].setMnemonic(KeyEvent.VK_7);
recentProjects[8].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_8, ShortCutKey));
recentProjects[8].setMnemonic(KeyEvent.VK_8);
recentProjects[9].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_9, ShortCutKey));
recentProjects[9].setMnemonic(KeyEvent.VK_9);
Preferences biosimrc = Preferences.userRoot();
viewer = biosimrc.get("biosim.general.viewer", "");
for (int i = 0; i < 10; i++) {
if (atacs) {
recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, "");
if (!recentProjects[i].getText().trim().equals("") && !recentProjectPaths[i].trim().equals("")) {
openRecent.add(recentProjects[i]);
numberRecentProj = i + 1;
} else {
break;
}
}
else if (lema) {
recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, "");
if (!recentProjects[i].getText().trim().equals("") && !recentProjectPaths[i].trim().equals("")) {
openRecent.add(recentProjects[i]);
numberRecentProj = i + 1;
} else {
break;
}
}
else {
recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, "");
if (!recentProjects[i].getText().trim().equals("") && !recentProjectPaths[i].trim().equals("")) {
openRecent.add(recentProjects[i]);
numberRecentProj = i + 1;
} else {
break;
}
}
}
openRecent.addSeparator();
openRecent.add(clearRecent);
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
// file.add(pref);
// file.add(exit);
help.add(about);
}
/*if (biosimrc.get("biosim.sbml.level_version", "").equals("L2V4")) {
SBMLLevelVersion = "L2V4";
SBML_LEVEL = 2;
SBML_VERSION = 4;
}
else {*/
SBMLLevelVersion = "L3V1";
SBML_LEVEL = 3;
SBML_VERSION = 1;
// Open .biosimrc here
// Packs the frame and displays it
mainPanel = new JPanel(new BorderLayout());
tree = new FileTree(null, this, lema, atacs);
EditPreferences editPreferences = new EditPreferences(frame,async,tree);
editPreferences.setDefaultPreferences();
log = new Log();
tab = new CloseAndMaxTabbedPane(false, this);
tab.setPreferredSize(new Dimension(1100, 550));
// tab.getPaneUI().addMouseListener(this);
topSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tree, tab);
mainSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplit, log);
//mainPanel.add(tree, "West");
mainPanel.add(mainSplit, "Center");
//mainPanel.add(log, "South");
mainPanel.add(toolbar, "North");
frame.setContentPane(mainPanel);
frame.setJMenuBar(menuBar);
// frame.getGlassPane().setVisible(true);
// frame.getGlassPane().addMouseListener(this);
// frame.getGlassPane().addMouseMotionListener(this);
// frame.getGlassPane().addMouseWheelListener(this);
frame.addMouseListener(this);
menuBar.addMouseListener(this);
frame.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
frame.setSize(frameSize);
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
frame.setSize(frameSize);
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
frame.setLocation(x, y);
frame.setVisible(true);
dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyChar() == '') {
if (tab.getTabCount() > 0) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
if (save(tab.getSelectedIndex(), 0) != 0) {
tab.remove(tab.getSelectedIndex());
}
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
}
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
public String getTitleAt(int i) {
return tab.getTitleAt(i).replace("*","");
}
public boolean getCheckUndeclared() {
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.check.undeclared", "").equals("false")) {
return false;
}
else {
return true;
}
}
public boolean getCheckUnits() {
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.check.units", "").equals("false")) {
return false;
}
else {
return true;
}
}
public void about() {
final JFrame f = new JFrame("About");
// frame.setIconImage(new ImageIcon(ENVVAR +
// File.separator
// + "gui"
// + File.separator + "icons" + File.separator +
// "iBioSim.png").getImage());
JLabel name;
JLabel version;
final String developers;
if (lema) {
name = new JLabel("LEMA", JLabel.CENTER);
version = new JLabel("Version 1.9", JLabel.CENTER);
developers = "Satish Batchu\nAndrew Fisher\nKevin Jones\nDhanashree Kulkarni\nScott Little\nCurtis Madsen\nChris Myers\nNicholas Seegmiller\n"
+ "Robert Thacker\nDavid Walter\nZhen Zhang";
}
else if (atacs) {
name = new JLabel("ATACS", JLabel.CENTER);
version = new JLabel("Version 6.9", JLabel.CENTER);
developers = "Wendy Belluomini\nJeff Cuthbert\nHans Jacobson\nKevin Jones\nSung-Tae Jung\n"
+ "Christopher Krieger\nScott Little\nCurtis Madsen\nEric Mercer\nChris Myers\n"
+ "Curt Nelson\nEric Peskin\nNicholas Seegmiller\nDavid Walter\nHao Zheng";
}
else {
name = new JLabel("iBioSim", JLabel.CENTER);
version = new JLabel("Version 2.4.5", JLabel.CENTER);
developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n"
+ "Curtis Madsen\nChris Myers\nNam Nguyen\nTyler Patterson\nNicholas Roehner\nJason Stevens\nLeandro Watanabe";
}
Font font = name.getFont();
font = font.deriveFont(Font.BOLD, 36.0f);
name.setFont(font);
JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER);
JButton credits = new JButton("Credits");
credits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Close" };
JOptionPane.showOptionDialog(f, developers, "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
});
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(credits);
buttons.add(close);
JPanel aboutPanel = new JPanel(new BorderLayout());
JPanel uOfUPanel = new JPanel(new BorderLayout());
uOfUPanel.add(name, "North");
uOfUPanel.add(version, "Center");
uOfUPanel.add(uOfU, "South");
if (lema) {
aboutPanel.add(new javax.swing.JLabel(
new javax.swing.ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "LEMA.png")), "North");
}
else if (atacs) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator
+ "ATACS.png")), "North");
}
else {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator
+ "iBioSim.png")), "North");
}
// aboutPanel.add(bioSim, "North");
aboutPanel.add(uOfUPanel, "Center");
aboutPanel.add(buttons, "South");
f.setContentPane(aboutPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
public boolean exit() {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return false;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < numberRecentProj; i++) {
if (atacs) {
biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText());
biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]);
}
else if (lema) {
biosimrc.put("lema.recent.project." + i, recentProjects[i].getText());
biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]);
}
else {
biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText());
biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]);
}
}
for (int i = numberRecentProj; i < 10 ; i++) {
if (atacs) {
biosimrc.put("atacs.recent.project." + i,"");
biosimrc.put("atacs.recent.project.path." + i,"");
} else if (lema) {
biosimrc.put("lema.recent.project." + i,"");
biosimrc.put("lema.recent.project.path." + i,"");
} else {
biosimrc.put("biosim.recent.project." + i,"");
biosimrc.put("biosim.recent.project.path," + i,"");
}
}
System.exit(1);
return true;
}
/**
* This method performs different functions depending on what menu items are
* selected.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewCircuit) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnGCM) {
((LearnGCM) component).viewModel();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
else if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).viewLhpn();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Verification) {
((Verification) array[0]).viewCircuit();
}
else if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewCircuit();
}
}
}
else if (e.getSource() == viewLog) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Verification) {
((Verification) comp).viewLog();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewLog();
}
}
else if (comp instanceof JTabbedPane) {
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
Component component = ((JTabbedPane) comp).getComponent(i);
if (component instanceof LearnGCM) {
((LearnGCM) component).viewLog();
return;
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLog();
return;
}
}
}
}
else if (e.getSource() == viewCoverage) {
Component comp = tab.getSelectedComponent();
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
Component component = ((JTabbedPane) comp).getComponent(i);
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewCoverage();
return;
}
}
}
else if (e.getSource() == saveModel) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
if (component instanceof LearnGCM) {
((LearnGCM) component).saveModel();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).saveLhpn();
}
}
}
}
else if (e.getSource() == saveAsVerilog) {
new Lpn2verilog(tree.getFile());
String theFile = "";
if (tree.getFile().lastIndexOf('/') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1);
}
if (tree.getFile().lastIndexOf('\\') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1);
}
addToTree(theFile.replace(".lpn", ".sv"));
}
else if (e.getSource() == close && tab.getSelectedComponent() != null) {
Component comp = tab.getSelectedComponent();
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), tab.getSelectedIndex());
}
else if (e.getSource() == saveAll) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
break;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
markTabClean(i);
}
}
else if (e.getSource() == closeAll) {
while (tab.getSelectedComponent() != null) {
int index = tab.getSelectedIndex();
Component comp = tab.getComponent(index);
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), index);
}
}
else if (e.getSource() == viewRules) {
Component comp = tab.getSelectedComponent();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).viewRules();
}
else if (e.getSource() == viewTrace) {
Component comp = tab.getSelectedComponent();
if (comp.getName().equals("Verification")) {
Component[] array = ((JPanel) comp).getComponents();
((Verification) array[0]).viewTrace();
}
else if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).viewTrace();
}
}
else if (e.getSource() == exportFlatSBML) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).exportFlatSBML();
}
}
else if (e.getSource() == exportSBML) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).exportSBML();
}
}
else if (e.getSource() == exportSBOL) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).exportSBOL();
}
}
else if (e.getSource() == saveSBOL) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).saveSBOL(false);
}
}
else if (e.getSource() == exportCsv) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(5);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5);
}
}
else if (e.getSource() == exportDat) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(6);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export();
}
}
else if (e.getSource() == exportEps) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(3);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3);
}
}
else if (e.getSource() == exportJpg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(0);
}
else if (comp instanceof JTabbedPane) {
if (((JTabbedPane) comp).getSelectedComponent().getName().equals("ModelViewMovie"))
((MovieContainer) ((JTabbedPane) comp).getSelectedComponent()).outputJPG(-1, false);
else
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0);
}
else if (comp instanceof ModelEditor) {
((ModelEditor) comp).saveSchematic();
}
}
else if (e.getSource() == exportPdf) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(2);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2);
}
}
else if (e.getSource() == exportPng) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(1);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1);
}
}
else if (e.getSource() == exportSvg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(4);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4);
}
}
else if (e.getSource() == exportTsd) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(7);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7);
}
}
else if (e.getSource() == exportAvi) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
((MovieContainer) ((JTabbedPane) comp).getSelectedComponent()).outputMovie("avi");
}
}
else if (e.getSource() == exportMp4) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
((MovieContainer) ((JTabbedPane) comp).getSelectedComponent()).outputMovie("mp4");
}
}
else if (e.getSource() == about) {
about();
}
else if (e.getSource() == bugReport) {
submitBugReport("");
}
else if (e.getSource() == manual) {
try {
String directory = "";
String theFile = "";
if (!async) {
theFile = "iBioSim.html";
}
else if (atacs) {
theFile = "ATACS.html";
}
else {
theFile = "LEMA.html";
}
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
directory = ENVVAR + "/docs/";
command = "open ";
}
else {
directory = ENVVAR + "\\docs\\";
command = "cmd /c start ";
}
File work = new File(directory);
log.addText("Executing:\n" + command + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command + theFile, null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the exit menu item is selected
else if (e.getSource() == exit) {
exit();
}
// if the open popup menu is selected on a sim directory
else if (e.getActionCommand().equals("openSim")) {
try {
openSim();
}
catch (Exception e0) {
}
}
else if (e.getActionCommand().equals("openLearn")) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
else if (e.getActionCommand().equals("openSynth")) {
openSynth();
}
else if (e.getActionCommand().equals("openVerification")) {
openVerify();
}
else if (e.getActionCommand().equals("convertToSBML")) {
Translator t1 = new Translator();
t1.convertLPN2SBML(tree.getFile(), "");
t1.outputSBML();
String theFile = "";
if (tree.getFile().lastIndexOf('/') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1);
}
if (tree.getFile().lastIndexOf('\\') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1);
}
//updateOpenSBML(theFile.replace(".lpn", ".xml"));
addToTree(theFile.replace(".lpn", ".xml"));
}
else if (e.getActionCommand().equals("convertToVerilog")) {
new Lpn2verilog(tree.getFile());
String theFile = "";
if (tree.getFile().lastIndexOf('/') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1);
}
if (tree.getFile().lastIndexOf('\\') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1);
}
addToTree(theFile.replace(".lpn", ".sv"));
}
else if (e.getActionCommand().equals("convertToLPN")) {
BuildProperty prop = new BuildProperty();
try {
prop.buildProperty(tree.getFile());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RecognitionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String theFile = "";
if (tree.getFile().lastIndexOf('/') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1);
}
if (tree.getFile().lastIndexOf('\\') >= 0) {
theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1);
}
addToTree(theFile.replace(".prop", ".lpn"));
}
else if (e.getActionCommand().equals("createAnalysis")) {
try {
createAnalysisView(2);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "You must select a valid lpn file for simulation.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the create simulation popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSim")) {
try {
createAnalysisView(1);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "You must select a valid model file for simulation.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the simulate popup menu is selected on an sbml file
else if (e.getActionCommand().equals("simulate")) {
try {
createAnalysisView(0);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the synthesis popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createSynthesis")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE);
if (synthName != null && !synthName.trim().equals("")) {
synthName = synthName.trim();
try {
if (overwrite(root + separator + synthName, synthName)) {
new File(root + separator + synthName).mkdir();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator
+ synthName.trim() + ".syn"));
out.write(("synthesis.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane
.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
try {
FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath));
FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator
+ circuitFileNoPath));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
addToTree(synthName.trim());
String work = root + separator + synthName;
String circuitFile = root + separator + synthName.trim() + separator + circuitFileNoPath;
JPanel synthPane = new JPanel();
Synthesis synth = new Synthesis(work, circuitFile, log, this);
synthPane.add(synth);
addTab(synthName, synthPane, "Synthesis");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the verify popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createVerify")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE);
if (verName != null && !verName.trim().equals("")) {
verName = verName.trim();
// try {
if (overwrite(root + separator + verName, verName)) {
new File(root + separator + verName).mkdir();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim()
+ ".ver"));
out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
addToTree(verName.trim());
Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs);
verify.save();
addTab(verName, verify, "Verification");
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the delete popup menu is selected
else if (e.getActionCommand().contains("delete") || e.getSource() == delete) {
delete();
}
else if (e.getActionCommand().equals("openLPN")) {
openLPN();
}
else if (e.getActionCommand().equals("browseSbol")) {
openSBOL();
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("gcmEditor")) {
openGCM(false);
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("gcmTextEditor")) {
openGCM(true);
}
// if the edit popup menu is selected on an sbml file
else if (e.getActionCommand().equals("sbmlEditor")) {
openSBML(tree.getFile());
}
else if (e.getActionCommand().equals("stateGraph")) {
try {
String directory = root + separator + getTitleAt(tab.getSelectedIndex());
File work = new File(directory);
for (String f : new File(directory).list()) {
if (f.contains("_sg.dot")) {
Runtime exec = Runtime.getRuntime();
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + separator + f + "\n");
exec.exec("dotty " + f, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + separator + f + "\n");
exec.exec("open " + f, null, work);
}
else {
log.addText("Executing:\ndotty " + directory + separator + f + "\n");
exec.exec("dotty " + f, null, work);
}
return;
}
}
JOptionPane.showMessageDialog(frame, "State graph file has not been generated.", "Error", JOptionPane.ERROR_MESSAGE);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing state graph.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("graphTree")) {
String directory = "";
String theFile = "";
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
File work = new File(directory);
String out = theFile;
try {
if (out.contains(".lpn")) {
String file = theFile;
String[] findTheFile = file.split("\\.");
theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
LhpnFile lhpn = new LhpnFile(log);
lhpn.load(directory + separator + theFile);
lhpn.printDot(directory + separator + file);
// String cmd = "atacs -cPllodpl " + file;
Runtime exec = Runtime.getRuntime();
// Process ATACS = exec.exec(cmd, null, work);
// ATACS.waitFor();
// log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
return;
}
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".gcm")) {
try {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("cp " + theFile + " " + theFile + ".dot", null, work);
exec = Runtime.getRuntime();
exec.exec("open " + theFile + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
return;
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
JList empty = new JList();
JRadioButton emptyButton = new JRadioButton();
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1, 1, new String[0], "tsd.printer", "amount", "false",
(directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, 2.0, empty, empty, empty,
null, false, false, false, false, false);
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work);
String error = "";
String output = "";
InputStream reb = graph.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = graph.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
graph.waitFor();
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + ".properties";
}
System.gc();
new File(remove).delete();
}
catch (InterruptedException e1) {
JOptionPane.showMessageDialog(frame, "Error graphing SBML file.", "Error", JOptionPane.ERROR_MESSAGE);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Error graphing SBML file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == viewLearnedModel) {
Component comp = tab.getSelectedComponent();
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
Component component = ((JTabbedPane) comp).getComponent(i);
if (component instanceof LearnGCM) {
((LearnGCM) component).viewModel();
return;
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
return;
}
}
}
// if the graph popup menu is selected on an sbml file
else if (e.getActionCommand().equals("graph")) {
String directory = "";
String theFile = "";
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
File work = new File(directory);
String out = theFile;
try {
if (out.contains(".lpn")) {
String file = theFile;
String[] findTheFile = file.split("\\.");
theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
LhpnFile lhpn = new LhpnFile(log);
lhpn.load(root + separator + file);
lhpn.printDot(root + separator + theFile);
// String cmd = "atacs -cPllodpl " + file;
Runtime exec = Runtime.getRuntime();
// Process ATACS = exec.exec(cmd, null, work);
// ATACS.waitFor();
// log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
return;
}
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".gcm")) {
try {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("cp " + theFile + " " + theFile + ".dot", null, work);
exec = Runtime.getRuntime();
exec.exec("open " + theFile + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
return;
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
JList empty = new JList();
JRadioButton emptyButton = new JRadioButton();
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1, 1, new String[0], "tsd.printer", "amount", "false",
(directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, 2.0, empty, empty, empty,
null, false, false, false, false, false);
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work);
String error = "";
String output = "";
InputStream reb = graph.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = graph.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
graph.waitFor();
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + ".properties";
}
System.gc();
new File(remove).delete();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e1) {
JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the browse popup menu is selected on an sbml file
else if (e.getActionCommand().equals("browse")) {
String directory;
String theFile;
String filename = tree.getFile();
directory = "";
theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
try {
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
JList empty = new JList();
dummy.setSelected(false);
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1, 1, new String[0], "tsd.printer", "amount", "false",
(directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, 2.0, empty, empty, empty,
null, false, false, false, false, false);
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work);
String error = "";
String output = "";
InputStream reb = browse.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = browse.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
browse.waitFor();
String command = "";
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "cmd /c start ";
}
log.addText("Executing:\n" + command + directory + out + ".xhtml\n");
exec.exec(command + out + ".xhtml", null, work);
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + ".properties";
}
System.gc();
new File(remove).delete();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing SBML file in a browser.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the save button is pressed on the Tool Bar
else if (e.getActionCommand().equals("save")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).save();
}
else if (comp instanceof ModelEditor) {
((ModelEditor) comp).save("Save GCM");
}
/*
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(false, "", true, true);
}
*/
else if (comp instanceof Graph) {
((Graph) comp).save();
}
else if (comp instanceof Verification) {
((Verification) comp).save();
}
else if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
int index = ((JTabbedPane) comp).getSelectedIndex();
if (component instanceof Graph) {
((Graph) component).save();
}
else if (component instanceof LearnGCM) {
((LearnGCM) component).save();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
}
else if (component instanceof DataManager) {
((DataManager) component).saveChanges(((JTabbedPane) comp).getTitleAt(index));
}
/*
else if (component instanceof SBML_Editor) {
((SBML_Editor) component).save(false, "", true, true);
}
*/
else if (component instanceof ModelEditor) {
((ModelEditor) component).saveParams(false, "", true);
}
else if (component instanceof AnalysisView) {
((AnalysisView) component).save();
}
else if (component instanceof MovieContainer) {
((MovieContainer) component).savePreferences();
}
}
}
if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
// ((Synthesis) tab.getSelectedComponent()).save();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
}
}
else if (comp instanceof JScrollPane) {
String fileName = getTitleAt(tab.getSelectedIndex());
try {
File output = new File(root + separator + fileName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + fileName);
this.updateAsyncViews(fileName);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the save as button is pressed on the Tool Bar
else if (e.getActionCommand().equals("saveas")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
String newName = JOptionPane.showInputDialog(frame, "Enter LPN name:", "LPN Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".lpn") && !newName.endsWith(".xml")) {
newName = newName + ".lpn";
}
((LHPNEditor) comp).saveAs(newName);
if (newName.endsWith(".lpn")) {
tab.setTitleAt(tab.getSelectedIndex(), newName);
}
}
else if (comp instanceof ModelEditor) {
String newName = JOptionPane.showInputDialog(frame, "Enter model name:", "Model Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (newName.contains(".gcm")) {
newName = newName.replace(".gcm", "");
}
if (newName.contains(".xml")) {
newName = newName.replace(".xml", "");
}
if (newName.endsWith(".lpn")) {
((ModelEditor) comp).saveAsLPN(newName);
} else {
((ModelEditor) comp).saveAs(newName);
}
}
/*
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).saveAs();
}
*/
else if (comp instanceof Graph) {
((Graph) comp).saveAs();
}
else if (comp instanceof Verification) {
((Verification) comp).saveAs();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).saveAs();
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).saveAs();
}
}
else if (comp instanceof JScrollPane) {
String fileName = getTitleAt(tab.getSelectedIndex());
String newName = "";
if (fileName.endsWith(".vhd")) {
newName = JOptionPane.showInputDialog(frame, "Enter VHDL name:", "VHDL Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".vhd")) {
newName = newName + ".vhd";
}
}
if (fileName.endsWith(".prop")) {
newName = JOptionPane.showInputDialog(frame, "Enter Property name:", "Property Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".prop")) {
newName = newName + ".prop";
}
}
else if (fileName.endsWith(".s")) {
newName = JOptionPane.showInputDialog(frame, "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".s")) {
newName = newName + ".s";
}
}
else if (fileName.endsWith(".inst")) {
newName = JOptionPane.showInputDialog(frame, "Enter Instruction File Name:", "Instruction File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".inst")) {
newName = newName + ".inst";
}
}
else if (fileName.endsWith(".g")) {
newName = JOptionPane.showInputDialog(frame, "Enter Petri net name:", "Petri net Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".g")) {
newName = newName + ".g";
}
}
else if (fileName.endsWith(".csp")) {
newName = JOptionPane.showInputDialog(frame, "Enter CSP name:", "CSP Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".csp")) {
newName = newName + ".csp";
}
}
else if (fileName.endsWith(".hse")) {
newName = JOptionPane.showInputDialog(frame, "Enter HSE name:", "HSE Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".hse")) {
newName = newName + ".hse";
}
}
else if (fileName.endsWith(".unc")) {
newName = JOptionPane.showInputDialog(frame, "Enter UNC name:", "UNC Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".unc")) {
newName = newName + ".unc";
}
}
else if (fileName.endsWith(".rsg")) {
newName = JOptionPane.showInputDialog(frame, "Enter RSG name:", "RSG Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".rsg")) {
newName = newName + ".rsg";
}
}
try {
File output = new File(root + separator + newName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + newName);
File oldFile = new File(root + separator + fileName);
oldFile.delete();
tab.setTitleAt(tab.getSelectedIndex(), newName);
addToTree(newName);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the run button is selected on the tool bar
else if (e.getActionCommand().equals("run")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof JTabbedPane) {
// int index = -1;
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
Component component = ((JTabbedPane) comp).getComponent(i);
if (component instanceof AnalysisView) {
((AnalysisView) component).getRunButton().doClick();
break;
}
else if (component instanceof LearnGCM) {
((LearnGCM) component).save();
new Thread((LearnGCM) component).start();
break;
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
((LearnLHPN) component).learn();
break;
}
}
}
else if (comp.getName().equals("Verification")) {
if (comp instanceof Verification) {
((Verification) comp).save();
new Thread((Verification) comp).start();
}
else {
// Not sure if this is necessary anymore
Component[] array = ((JPanel) comp).getComponents();
((Verification) array[0]).save();
new Thread((Verification) array[0]).start();
}
}
else if (comp.getName().equals("Synthesis")) {
if (comp instanceof Synthesis) {
((Synthesis) comp).save();
new Thread((Synthesis) comp).start();
}
else {
// Not sure if this is necessary anymore
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
new Thread((Synthesis) array[0]).start();
}
}
}
else if (e.getActionCommand().equals("refresh")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).refresh();
}
}
else if (comp instanceof Graph) {
((Graph) comp).refresh();
}
}
else if (e.getActionCommand().equals("check")) {
Component comp = tab.getSelectedComponent();
/*if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(true, "", true, true);
((SBML_Editor) comp).check();
}
else*/ if (comp instanceof ModelEditor) {
((ModelEditor) comp).save("Save and Check GCM");
}
}
else if (e.getActionCommand().equals("export")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export();
}
else if (comp instanceof ModelEditor) {
((ModelEditor) comp).exportSBML();
// TODO: should give choice of SBML or SBOL
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).export();
}
}
}
// if the new menu item is selected
else if (e.getSource() == newProj) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
String filename = Utility.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "New", -1);
if (!filename.trim().equals("")) {
filename = filename.trim();
biosimrc.put("biosim.general.project_dir", filename);
File f = new File(filename);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(filename);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return;
}
}
new File(filename).mkdir();
try {
if (lema) {
new FileWriter(new File(filename + separator + "LEMA.prj")).close();
}
else if (atacs) {
new FileWriter(new File(filename + separator + "ATACS.prj")).close();
}
else {
new FileWriter(new File(filename + separator + "BioSim.prj")).close();
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create a new project.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
root = filename;
refresh();
tab.removeAll();
addRecentProject(filename);
//importDot.setEnabled(true);
importSbol.setEnabled(true);
importSedml.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newSBMLModel.setEnabled(true);
newGridModel.setEnabled(true);
newVhdl.setEnabled(true);
newProperty.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
}
// if the open project menu item is selected
else if (e.getSource() == pref) {
EditPreferences editPreferences = new EditPreferences(frame,async,tree);
editPreferences.preferences();
}
else if (e.getSource() == clearRecent) {
removeAllRecentProjects();
}
else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1])
|| (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])
|| (e.getSource() == recentProjects[5]) || (e.getSource() == recentProjects[6]) || (e.getSource() == recentProjects[7])
|| (e.getSource() == recentProjects[8]) || (e.getSource() == recentProjects[9])) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
String projDir = "";
if (e.getSource() == openProj) {
File file;
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
projDir = Utility.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "Open", -1);
if (projDir.endsWith(".prj")) {
biosimrc.put("biosim.general.project_dir", projDir);
String[] tempArray = projDir.split(separator);
projDir = "";
for (int i = 0; i < tempArray.length - 1; i++) {
projDir = projDir + tempArray[i] + separator;
}
}
}
else if (e.getSource() == recentProjects[0]) {
projDir = recentProjectPaths[0];
}
else if (e.getSource() == recentProjects[1]) {
projDir = recentProjectPaths[1];
}
else if (e.getSource() == recentProjects[2]) {
projDir = recentProjectPaths[2];
}
else if (e.getSource() == recentProjects[3]) {
projDir = recentProjectPaths[3];
}
else if (e.getSource() == recentProjects[4]) {
projDir = recentProjectPaths[4];
}
else if (e.getSource() == recentProjects[5]) {
projDir = recentProjectPaths[5];
}
else if (e.getSource() == recentProjects[6]) {
projDir = recentProjectPaths[6];
}
else if (e.getSource() == recentProjects[7]) {
projDir = recentProjectPaths[7];
}
else if (e.getSource() == recentProjects[8]) {
projDir = recentProjectPaths[8];
}
else if (e.getSource() == recentProjects[9]) {
projDir = recentProjectPaths[9];
}
// log.addText(projDir);
if (!projDir.equals("")) {
biosimrc.put("biosim.general.project_dir", projDir);
if (new File(projDir).isDirectory()) {
boolean isProject = false;
for (String temp : new File(projDir).list()) {
if (temp.equals(".prj")) {
isProject = true;
}
if (lema && temp.equals("LEMA.prj")) {
isProject = true;
}
else if (atacs && temp.equals("ATACS.prj")) {
isProject = true;
}
else if (temp.equals("BioSim.prj")) {
isProject = true;
}
}
if (isProject) {
root = projDir;
refresh();
tab.removeAll();
addRecentProject(projDir);
//importDot.setEnabled(true);
importSbol.setEnabled(true);
importSedml.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newSBMLModel.setEnabled(true);
newGridModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newProperty.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE);
removeRecentProject(projDir);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE);
removeRecentProject(projDir);
}
}
}
// if the new circuit model menu item is selected
else if (e.getSource() == newSBMLModel) {
createModel(false);
}
else if (e.getSource() == newGridModel) {
createModel(true);
}
// if the new vhdl menu item is selected
else if (e.getSource() == newVhdl) {
newModel("VHDL", ".vhd");
}
// if the new assembly menu item is selected
else if (e.getSource() == newS) {
newModel("Assembly", ".s");
}
// if the new instruction file menu item is selected
else if (e.getSource() == newInst) {
newModel("Instruction", ".inst");
}
// if the new petri net menu item is selected
else if (e.getSource() == newG) {
newModel("Petri Net", ".g");
}
// if the new lhpn menu item is selected
else if (e.getSource() == newLhpn) {
createLPN();
}
/*else if (e.getSource() == newProperty) { //DK
Property prop = new Property();
prop.property(root, separator);
//property();
} */
/* else if (e.getSource() == newProperty) { //DK
BuildProperty prop = new BuildProperty();
try {
prop.buildProperty(root, separator);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RecognitionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//property();
} */
else if (e.getSource() == newProperty) {
newModel("Property", ".prop");
}
/* else if (e.getSource() == newProperty) { //DK
//importFile("txt", ".txt", ".txt");
BuildProperty prop = new BuildProperty();
try {
prop.buildProperty();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RecognitionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//newModel("PROP" , ".prop");
} */
// if the new csp menu item is selected
else if (e.getSource() == newCsp) {
newModel("CSP", ".csp");
}
// if the new hse menu item is selected
else if (e.getSource() == newHse) {
newModel("Handshaking Expansion", ".hse");
}
// if the new unc menu item is selected
else if (e.getSource() == newUnc) {
newModel("Extended Burst Mode Machine", ".unc");
}
// if the new rsg menu item is selected
else if (e.getSource() == newRsg) {
newModel("Reduced State Graph", ".rsg");
}
// if the new rsg menu item is selected
else if (e.getSource() == newSpice) {
newModel("Spice Circuit", ".cir");
}
else if (e.getSource().equals(importSbol)) {
importFile("SBOL", ".sbol", ".xml");
}
else if (e.getSource().equals(importSedml)) {
importSEDML();
}
// if the import sbml menu item is selected
else if (e.getSource() == importSbml) {
importSBML(null);
}
else if (e.getSource() == importBioModel) {
importBioModel();
}
// if the import dot menu item is selected
/*
else if (e.getSource() == importDot) {
importGCM();
}
*/
// if the import vhdl menu item is selected
else if (e.getSource() == importVhdl) {
importFile("VHDL", ".vhd", ".vhd");
}
else if (e.getSource() == importS) {
importFile("Assembly", ".s", ".s");
}
else if (e.getSource() == importInst) {
importFile("Instruction", ".inst", ".inst");
}
else if (e.getSource() == importLpn) {
importLPN();
}
else if (e.getSource() == importG) {
importFile("Petri Net", ".g", ".g");
}
// if the import csp menu item is selected
else if (e.getSource() == importCsp) {
importFile("CSP", ".csp", ".csp");
}
// if the import hse menu item is selected
else if (e.getSource() == importHse) {
importFile("Handshaking Expansion", ".hse", ".hse");
}
// if the import unc menu item is selected
else if (e.getSource() == importUnc) {
importFile("Extended Burst State Machine", ".unc", ".unc");
}
// if the import rsg menu item is selected
else if (e.getSource() == importRsg) {
importFile("Reduced State Graph", ".rsg", ".rsg");
}
// if the import spice menu item is selected
else if (e.getSource() == importSpice) {
importFile("Spice Circuit", ".cir", ".cir");
}
// if the Graph data menu item is clicked
else if (e.getSource() == graph) {
createGraph();
}
else if (e.getSource() == probGraph) {
createHistogram();
}
else if (e.getActionCommand().equals("createLearn")) {
createLearn();
}
else if (e.getActionCommand().equals("viewModel")) {
viewModel();
}
else if (e.getSource() == select) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).select();
}
}
else if (e.getSource() == cut) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).cut();
}
}
else if (e.getSource() == addCompartment) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addCompartment();
}
}
else if (e.getSource() == addSpecies) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addSpecies();
}
}
else if (e.getSource() == addReaction) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addReaction();
}
}
else if (e.getSource() == addComponent) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addComponent();
}
}
else if (e.getSource() == addPromoter) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addPromoter();
}
}
else if (e.getSource() == addVariable) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addVariable();
}
}
else if (e.getSource() == addBoolean) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addBoolean();
}
}
else if (e.getSource() == addPlace) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addPlace();
}
}
else if (e.getSource() == addTransition) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addTransition();
}
}
else if (e.getSource() == addRule) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addRule();
}
}
else if (e.getSource() == addConstraint) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addConstraint();
}
}
else if (e.getSource() == addEvent) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addEvent();
}
}
else if (e.getSource() == addSelfInfl) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).addSelfInfluence();
}
}
else if (e.getSource() == moveLeft) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).moveLeft();
}
}
else if (e.getSource() == moveRight) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).moveRight();
}
}
else if (e.getSource() == moveUp) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).moveUp();
}
}
else if (e.getSource() == moveDown) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).moveDown();
}
}
else if (e.getSource() == undo) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).undo();
}
}
else if (e.getSource() == redo) {
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
((ModelEditor) comp).redo();
}
}
else if (e.getActionCommand().equals("copy") || e.getSource() == copy) {
copy();
}
else if (e.getActionCommand().equals("rename") || e.getSource() == rename) {
rename();
}
else if (e.getActionCommand().equals("openGraph")) {
openGraph();
}
else if (e.getActionCommand().equals("openHistogram")) {
openHistogram();
}
enableTabMenu(tab.getSelectedIndex());
enableTreeMenu();
}
private void delete() {
if (!tree.getFile().equals(root)) {
if (new File(tree.getFile()).isDirectory()) {
String dirName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(dirName)) {
tab.remove(i);
}
}
File dir = new File(tree.getFile());
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
deleteFromTree(dirName);
}
else {
String[] views = canDelete(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]);
if (views.length == 0) {
String fileName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(fileName)) {
tab.remove(i);
}
}
System.gc();
if (tree.getFile().endsWith(".xml")) {
SBMLDocument document = readSBML(tree.getFile());
Iterator<URI> sbolIterator = AnnotationUtility.parseSBOLAnnotation(document.getModel()).iterator();
while (sbolIterator != null && sbolIterator.hasNext()) {
URI sbolURI = sbolIterator.next();
if (sbolURI.toString().endsWith("iBioSim")) {
sbolIterator = null;
for (String filePath : getFilePaths(".sbol")) {
SBOLDocument sbolDoc = SBOLUtility.loadSBOLFile(filePath);
SBOLUtility.deleteDNAComponent(sbolURI, sbolDoc);
SBOLUtility.writeSBOLDocument(filePath, sbolDoc);
}
}
}
new File(tree.getFile().replace(".xml", ".gcm")).delete();
}
new File(tree.getFile()).delete();
deleteFromTree(fileName);
}
else {
String view = "";
String gcms = "";
for (int i = 0; i < views.length; i++) {
if (views[i].endsWith(".xml")) {
gcms += views[i] + "\n";
}
else {
view += views[i] + "\n";
}
}
String message;
if (gcms.equals("")) {
message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
}
else if (view.equals("")) {
message = "Unable to delete the selected file." + "\nIt is linked to the following models:\n" + gcms
+ "\nDelete these models first.";
}
else {
message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view
+ "\nIt is also linked to the following models:\n" + gcms + "\nDelete these views and models first.";
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void importBioModel() {
final BioModelsWSClient client = new BioModelsWSClient();
if (BioModelIds == null) {
try {
BioModelIds = client.getAllCuratedModelsId();
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
final JPanel BioModelsPanel = new JPanel(new BorderLayout());
final JList ListOfBioModels = new JList();
sort(BioModelIds);
ListOfBioModels.setListData(BioModelIds);
ListOfBioModels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel TextBioModels = new JLabel("List of BioModels");
JScrollPane ScrollBioModels = new JScrollPane();
ScrollBioModels.setMinimumSize(new Dimension(520, 250));
ScrollBioModels.setPreferredSize(new Dimension(552, 250));
ScrollBioModels.setViewportView(ListOfBioModels);
JPanel GetButtons = new JPanel();
JButton GetNames = new JButton("Get Names");
JButton GetDescription = new JButton("Get Description");
JButton GetReference = new JButton("Get Reference");
final JProgressBar progressBar = new JProgressBar(0,100);
progressBar.setStringPainted(true);
progressBar.setValue(0);
runGetNames = true;
final Thread getNamesThread = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < BioModelIds.length && runGetNames; i++) {
try {
progressBar.setValue(100 * i / BioModelIds.length);
if (!BioModelIds[i].contains(" ")) {
BioModelIds[i] += " " + client.getModelNameById(BioModelIds[i]);
ListOfBioModels.setListData(BioModelIds);
ListOfBioModels.revalidate();
ListOfBioModels.repaint();
}
}
catch (BioModelsWSException e1) {
JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE);
}
}
ListOfBioModels.setListData(BioModelIds);
runGetNames = false;
}
});
GetNames.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (runGetNames && !getNamesThread.isAlive()) {
getNamesThread.start();
}
}
});
GetDescription.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ListOfBioModels.isSelectionEmpty()) return;
String SelectedModel = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0];
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open http:
}
else {
command = "cmd /c start http:
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open model description.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
GetReference.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ListOfBioModels.isSelectionEmpty()) return;
String SelectedModel = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0];
try {
String Pub = (client.getSimpleModelById(SelectedModel)).getPublicationId();
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open http:
}
else {
command = "cmd /c start http:
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command);
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open model description.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
GetButtons.add(GetNames);
GetButtons.add(GetDescription);
GetButtons.add(GetReference);
GetButtons.add(progressBar);
BioModelsPanel.add(TextBioModels, "North");
BioModelsPanel.add(ScrollBioModels, "Center");
BioModelsPanel.add(GetButtons, "South");
Object[] options = { "OK", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, BioModelsPanel, "List of BioModels", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
runGetNames = false;
if (value == JOptionPane.YES_OPTION && ListOfBioModels.getSelectedValue() != null) {
String ModelId = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0];
String filename = ModelId + ".xml";
try {
if (overwrite(root + separator + filename, filename)) {
String model = client.getModelSBMLById(ModelId);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(root + separator + filename), "UTF-8"));
out.write(model);
out.close();
String[] file = filename.trim().split(separator);
SBMLDocument document = readSBML(root + separator + filename.trim());
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML file contains the errors listed below. ");
messageArea.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + file[file.length - 1]);
addToTree(file[file.length - 1]);
openSBML(root + separator + file[file.length - 1]);
}
}
catch (MalformedURLException e1) {
JOptionPane.showMessageDialog(frame, e1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, filename + " not found.", "Error", JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void createLPN() {
try {
String lhpnName = JOptionPane.showInputDialog(frame, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 3) {
if (!lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
String modelID = "";
if (lhpnName.length() > 3) {
if (lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
modelID = lhpnName.substring(0, lhpnName.length() - 4);
}
else {
modelID = lhpnName.substring(0, lhpnName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + lhpnName, lhpnName)) {
File f = new File(root + separator + lhpnName);
f.createNewFile();
new LhpnFile(log).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(), null, this, log);
// lhpn.addMouseListener(this);
addTab(f.getName(), lhpn, "LHPN Editor");
addToTree(f.getName());
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void importLPN() {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Utility.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import LPN", -1);
if ((filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals(".g"))
&& (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".lpn"))) {
JOptionPane.showMessageDialog(frame, "You must select a valid LPN file to import.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
if (new File(filename).exists()) {
file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_");
if (checkFiles(root + separator + file[file.length - 1], filename.trim())) {
if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) {
// Identify which LPN format is imported.
BufferedReader input = new BufferedReader(new FileReader(filename));
String str;
boolean lpnUSF = false;
while ((str = input.readLine()) != null) {
if (str.startsWith(".")) {
break;
}
else if (str.startsWith("<")) {
lpnUSF = true;
break;
}
else {
JOptionPane.showMessageDialog(frame, "LPN file format is not valid.", "Error", JOptionPane.ERROR_MESSAGE);
break;
}
}
if (!lpnUSF) {
String outFileName = file[file.length - 1];
if (!lema && !atacs) {
Translator t1 = new Translator();
t1.convertLPN2SBML(filename, "");
t1.setFilename(root + separator + outFileName.replace(".lpn", ".xml"));
t1.outputSBML();
outFileName = outFileName.replace(".lpn", ".xml");
} else {
FileOutputStream out = new FileOutputStream(new File(root + separator + outFileName));
FileInputStream in = new FileInputStream(new File(filename));
// log.addText(filename);
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
addToTree(outFileName);
}
else {
ANTLRFileStream in = new ANTLRFileStream(filename);
PlatuGrammarLexer lexer = new PlatuGrammarLexer(in);
TokenStream tokenStream = new CommonTokenStream(lexer);
PlatuGrammarParser antlrParser = new PlatuGrammarParser(tokenStream);
Set<LhpnFile> lpnSet = antlrParser.lpn();
for (LhpnFile lpn : lpnSet) {
lpn.save(root + separator + lpn.getLabel() + ".lpn");
addToTree(lpn.getLabel() + ".lpn");
}
}
}
}
}
if (filename.substring(filename.length() - 2, filename.length()).equals(".g")) {
// log.addText(filename + file[file.length - 1]);
File work = new File(root);
String oldName = root + separator + file[file.length - 1];
// String newName = oldName.replace(".lpn",
// "_NEW.g");
Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName, null, work);
atacs.waitFor();
String lpnName = oldName.replace(".g", ".lpn");
String newName = oldName.replace(".g", "_NEW.lpn");
atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work);
atacs.waitFor();
lpnName = lpnName.replaceAll("[^a-zA-Z0-9_.]+", "_");
FileOutputStream out = new FileOutputStream(new File(lpnName));
FileInputStream in = new FileInputStream(new File(newName));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
new File(newName).delete();
addToTree(file[file.length - 1].replace(".g", ".lpn"));
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/*
private void importGCM() {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Utility.browse(frame, importFile, null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1);
if (filename != null && !filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
}
if (new File(filename.trim()).isDirectory()) {
for (String s : new File(filename.trim()).list()) {
if (!(filename.trim() + separator + s).equals("")
&& (filename.trim() + separator + s).length() > 3
&& (filename.trim() + separator + s).substring((filename.trim() + separator + s).length() - 4,
(filename.trim() + separator + s).length()).equals(".gcm")) {
try {
// GCMParser parser =
new GCMParser((filename.trim() + separator + s));
s = s.replaceAll("[^a-zA-Z0-9_.]+", "_");
if (overwrite(root + separator + s, s)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + s));
FileInputStream in = new FileInputStream(new File((filename.trim() + separator + s)));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
addToTree(s);
importSBML(filename.trim().replace(".gcm", ".xml"));
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()).equals(".gcm")) {
JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.trim().equals("")) {
String[] file = filename.trim().split(separator);
try {
// GCMParser parser =
new GCMParser(filename.trim());
file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_");
if (checkFiles(root + separator + file[file.length - 1], filename.trim())) {
if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) {
FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename.trim()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
addToTree(file[file.length - 1]);
importSBML(filename.trim().replace(".gcm", ".xml"));
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
*/
/*
private void createSBML() {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".xml";
}
}
else {
simName += ".xml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
String f = new String(root + separator + simName);
SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION);
document.createModel();
Compartment c = document.getModel().createCompartment();
c.setId("default");
c.setSize(1.0);
c.setSpatialDimensions(3);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + simName);
SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null);
addTab(f.split(separator)[f.split(separator).length - 1], sbml, "SBML Editor");
addToTree(f.split(separator)[f.split(separator).length - 1]);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
*/
private void createModel(boolean grid) {
if (root != null) {
try {
String modelId = null;
JTextField modelChooser = new JTextField("");
modelChooser.setColumns(20);
JPanel modelPanel = new JPanel(new GridLayout(2, 1));
modelPanel.add(new JLabel("Enter Model ID: "));
modelPanel.add(modelChooser);
frame.add(modelPanel);
String[] options = { GlobalConstants.OK, GlobalConstants.CANCEL };
int okCancel = JOptionPane.showOptionDialog(frame, modelPanel, "Model ID", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
// if the user clicks "ok" on the panel
if (okCancel == JOptionPane.OK_OPTION) {
modelId = modelChooser.getText();
}
else
return;
// String simName = JOptionPane.showInputDialog(frame,
// "Enter Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (modelId != null && !modelId.trim().equals("")) {
modelId = modelId.trim();
if (modelId.length() > 3) {
if (!modelId.substring(modelId.length() - 4).equals(".xml")) {
modelId += ".xml";
}
}
else {
modelId += ".xml";
}
if (!(IDpat.matcher(modelId.replace(".xml","")).matches())) {
JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + modelId, modelId)) {
BioModel bioModel = new BioModel(root);
bioModel.createSBMLDocument(modelId.replace(".xml", ""),grid,lema);
bioModel.save(root + separator + modelId);
int i = getTab(modelId);
if (i != -1) {
tab.remove(i);
}
ModelEditor modelEditor = new ModelEditor(root + separator, modelId, this, log, false, null, null, null, false, grid,lema);
modelEditor.save("Save GCM");
addTab(modelId, modelEditor, "GCM Editor");
addToTree(modelId);
}
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private String importSBML(String filename) {
String newFile = null;
Preferences biosimrc = Preferences.userRoot();
if (filename == null) {
File importFile;
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
filename = Utility.browse(frame, importFile, null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1);
}
if (!filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
if (new File(filename.trim()).isDirectory()) {
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML files contain the errors listed below. ");
messageArea.append("It is recommended that you fix them before using these models or you may get " + "unexpected results.\n\n");
boolean display = false;
for (String s : new File(filename.trim()).list()) {
if (s.endsWith(".xml") || s.endsWith(".sbml")) {
try {
SBMLDocument document = readSBML(filename.trim() + separator + s);
checkModelCompleteness(document);
if (overwrite(root + separator + s, s)) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
display = true;
messageArea.append("
+ "
messageArea.append(s);
messageArea.append("\n
+ "
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
SBMLWriter writer = new SBMLWriter();
s = s.replaceAll("[^a-zA-Z0-9_.]+", "_");
writer.writeSBML(document, root + separator + s);
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
addToTree(s);
}
if (display) {
final JFrame f = new JFrame("SBML Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
}
else {
String[] file = filename.trim().split(separator);
try {
SBMLDocument document = readSBML(filename.trim());
if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) {
checkModelCompleteness(document);
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML file contains the errors listed below. ");
messageArea.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
newFile = file[file.length - 1];
newFile = newFile.replaceAll("[^a-zA-Z0-9_.]+", "_");
if (document != null) {
document.getModel().setId(newFile.replace(".xml",""));
document.enablePackage(LayoutExtension.getXmlnsL3V1V1(), "layout", true);
document.setPackageRequired("layout", false);
document.enablePackage(CompExtension.getXmlnsL3V1V1(), "comp", true);
document.setPackageRequired("comp", true);
((CompSBMLDocumentPlugin)document.getPlugin("comp")).setRequired(true);
CompSBMLDocumentPlugin documentComp = (CompSBMLDocumentPlugin)document.getPlugin("comp");
CompModelPlugin documentCompModel = (CompModelPlugin)document.getModel().getPlugin("comp");
if (documentComp.getNumModelDefinitions() > 0 ||
documentComp.getNumExternalModelDefinitions() > 0) {
if (!extractModelDefinitions(documentComp,documentCompModel)) return null;
}
updateReplacementsDeletions(document, documentComp, documentCompModel);
SBMLWriter writer = new SBMLWriter();
if (document.getModel().getId()==null||document.getModel().getId().equals("")) {
document.setId(newFile.replace(".xml",""));
} else {
newFile = document.getModel().getId()+".xml";
}
writer.writeSBML(document, root + separator + newFile);
addToTree(newFile);
openSBML(root + separator + newFile);
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
return newFile;
}
private void performAnalysis(String modelId, String simName, SEDMLDocument sedmlDoc) throws Exception {
String sbmlFile = root + separator + modelId + ".xml";
String[] sbml1 = null;
File sedmlFile = new File(root + separator + simName + separator + modelId + "-sedml.xml");
sedmlDoc.writeDocument(sedmlFile);
sbml1 = sbmlFile.split(separator);
String sbmlFileProp;
sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1];
new FileOutputStream(new File(sbmlFileProp)).close();
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim"));
out.write((sbml1[sbml1.length - 1] + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
addToTree(simName);
JTabbedPane simTab = new JTabbedPane();
simTab.addMouseListener(this);
AnalysisView reb2sac = new AnalysisView(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null, sbml1[sbml1.length - 1], null,
null);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Advanced Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
String gcmFile = sbml1[sbml1.length - 1].replace(".xml", ".gcm");
ModelEditor gcm = new ModelEditor(root + separator, gcmFile, this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac, false, false,lema);
reb2sac.setGcm(gcm);
addModelViewTab(reb2sac, simTab, gcm);
simTab.addTab("Parameters", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
ElementsPanel elementsPanel = new ElementsPanel(gcm.getBioModel().getSBMLDocument(),
root + separator + simName.trim() + separator + simName.trim() + ".sim");
simTab.addTab("SBML Elements", elementsPanel);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setElementsPanel(elementsPanel);
gcm.createSBML("",".");
reb2sac.run(".", true);
Graph tsdGraph;
tsdGraph = reb2sac.createGraph(root + separator + simName + separator + simName + ".grf");
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
simTab.addTab("Histogram", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
addTab(simName, simTab, null);
}
private void importSEDML() {
Preferences biosimrc = Preferences.userRoot();
File importFile;
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Utility.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import SED-ML", -1);
if (!filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
String[] file = filename.trim().split(separator);
try {
File sedmlFile = new File(filename.trim());
SEDMLDocument sedmlDoc = Libsedml.readDocument(sedmlFile);
sedmlDoc.validate();
if(sedmlDoc.hasErrors()) {
List<SedMLError> errors = sedmlDoc.getErrors();
final JFrame f = new JFrame("SED-ML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SED-ML file contains the errors listed below. ");
messageArea.append("It is recommended that you fix them before performing this analysis or you may get unexpected results.\n\n");
for (int i = 0; i < errors.size(); i++) {
SedMLError error = errors.get(i);
messageArea.append(i + ":" + error.getMessage() + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
SedML sedml = sedmlDoc.getSedMLModel();
List<Model> models = sedml.getModels();
HashMap<String,String> modelMap = new HashMap<String,String>();
for (int i = 0; i < models.size(); i++) {
Model model = models.get(i);
String sbmlFile = filename.substring(0,filename.lastIndexOf(separator)) + model.getSource();
String newFile = importSBML(sbmlFile);
model.setSource(newFile);
modelMap.put(model.getId(), newFile);
}
List<Task> tasks = sedml.getTasks();
for (int i = 0; i < tasks.size(); i++) {
Task task = tasks.get(i);
if (modelMap.containsKey(task.getModelReference())) {
String modelId = modelMap.get(task.getModelReference()).replace(".xml", "");
String analysisId = modelId;
if (tasks.size()>1) {
analysisId += "_" + task.getId();
}
if (overwrite(root + separator + analysisId, analysisId)) {
new File(root + separator + analysisId).mkdir();
String newFile = file[file.length - 1];
newFile = newFile.replaceAll("[^a-zA-Z0-9_.]+", "_");
List<Output> outputs = sedml.getOutputs();
if (outputs.size() > 0 && outputs.get(0).isPlot2d()) {
Plot2D plot = (Plot2D)outputs.get(0);
Properties graph = new Properties();
graph.setProperty("title", plot.getName());
graph.setProperty("chart.background.paint", "" + new java.awt.Color(238, 238, 238).getRGB());
graph.setProperty("plot.background.paint", "" + java.awt.Color.WHITE.getRGB());
graph.setProperty("plot.domain.grid.line.paint", "" + java.awt.Color.LIGHT_GRAY.getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + java.awt.Color.LIGHT_GRAY.getRGB());
graph.setProperty("x.axis", "");
graph.setProperty("y.axis", "");
graph.setProperty("x.min", "0.0");
graph.setProperty("x.max", "1.0");
graph.setProperty("x.scale", "0.1");
graph.setProperty("y.min", "0.0");
graph.setProperty("y.max", "1.0");
graph.setProperty("y.scale", "0.1");
graph.setProperty("auto.resize", "true");
graph.setProperty("LogX", "false");
graph.setProperty("LogY", "false");
graph.setProperty("visibleLegend", "true");
List<Curve> curves = plot.getListOfCurves();
for (int j = 0; j < curves.size(); j++) {
Curve curve = curves.get(j);
graph.setProperty("species.connected." + j, "true");
graph.setProperty("species.filled." + j, "true");
graph.setProperty("species.xnumber." + j, "0");
graph.setProperty("species.number." + j, "" + j);
graph.setProperty("species.run.number." + j, "run-" + 1);
graph.setProperty("species.name." + j, curve.getName() + " (1)");
graph.setProperty("species.id." + j, curve.getName() + " (1)");
graph.setProperty("species.visible." + j, "true");
graph.setProperty("species.paint." + j, "Black");
graph.setProperty("species.shape." + j, "Circle");
graph.setProperty("species.directory." + j, "");
}
try {
FileOutputStream store = new FileOutputStream(new
File(root + separator + analysisId + separator + analysisId + ".grf"));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + root + separator + analysisId + separator + analysisId + ".grf" + "\n");
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
performAnalysis(modelId,analysisId,sedmlDoc);
}
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void importFile(String fileType, String extension1, String extension2) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Utility.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import " + fileType, -1);
if (filename.length() > 1 && !filename.endsWith(extension1) && !filename.endsWith(extension2)) {
JOptionPane.showMessageDialog(frame, "You must select a valid " + fileType + " file to import.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_");
file[file.length - 1] = file[file.length - 1].replaceAll(extension2, extension1);
if (checkFiles(root + separator + file[file.length - 1], filename.trim())) {
if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) {
FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
addToTree(file[file.length - 1]);
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void createGraph() {
String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of molecules", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), true, false);
addTab(graphName.trim(), g, "TSD Graph");
g.save();
addToTree(graphName.trim());
}
}
}
private void createHistogram() {
String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Histogram:", "Histogram Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of Molecules", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), false, false);
addTab(graphName.trim(), g, "Histogram");
g.save();
addToTree(graphName.trim());
}
}
}
private void createLearn() {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE);
if (lrnName != null && !lrnName.trim().equals("")) {
lrnName = lrnName.trim();
// try {
if (overwrite(root + separator + lrnName, lrnName)) {
new File(root + separator + lrnName).mkdir();
// new FileWriter(new File(root + separator +
// lrnName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String sbmlFileNoPath = getFilename[getFilename.length - 1];
if (sbmlFileNoPath.endsWith(".vhd")) {
try {
File work = new File(root);
Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null, work);
sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".lpn");
log.addText("atacs -lvsl " + sbmlFileNoPath + "\n");
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to generate LPN from VHDL file!", "Error Generating File",
JOptionPane.ERROR_MESSAGE);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn"));
if (lema) {
out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes());
}
else {
out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes());
}
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
addToTree(lrnName);
JTabbedPane lrnTab = new JTabbedPane();
lrnTab.addMouseListener(this);
DataManager data = new DataManager(root + separator + lrnName, this, lema);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
if (lema) {
LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this);
lrnTab.addTab("Learn Options", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn Options");
lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel());
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options");
}
else {
LearnGCM learn = new LearnGCM(root + separator + lrnName, log, this);
lrnTab.addTab("Learn Options", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn Options");
lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel());
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options");
}
Graph tsdGraph;
tsdGraph = new Graph(null, "Number of molecules", lrnName + " data", "tsd.printer", root + separator + lrnName, "Time", this,
null, log, null, true, false);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
addTab(lrnName, lrnTab, null);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void viewModel() {
try {
if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
LhpnFile lhpn = new LhpnFile(log);
lhpn.load(tree.getFile());
lhpn.printDot(root + separator + theFile);
File work = new File(root);
Runtime exec = Runtime.getRuntime();
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "dotty start ";
//command = "dotty ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPlgodpe " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(vhdFile);
BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "VHDL Model", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame, "VHDL model does not exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view VHDL model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(vamsFileName);
BufferedReader input = new BufferedReader(new FileReader(vamsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame, "Verilog-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view Verilog-AMS model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) {
try {
String svFileName = tree.getFile();
if (new File(svFileName).exists()) {
File svFile = new File(svFileName);
BufferedReader input = new BufferedReader(new FileReader(svFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "SystemVerilog Model", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame, "SystemVerilog model does not exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view SystemVerilog model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lcslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lhslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lxodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lsodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
private void copy() {
if (!tree.getFile().equals(root)) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String copy = JOptionPane.showInputDialog(frame, "Enter a New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE);
if (copy == null || copy.equals("")) {
return;
}
copy = copy.trim();
if (tree.getFile().contains(".")) {
String extension = tree.getFile().substring(tree.getFile().lastIndexOf("."), tree.getFile().length());
if (!copy.endsWith(extension)) {
copy += extension;
}
}
if (copy.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
if (checkFiles(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], copy)) {
if (overwrite(root + separator + copy, copy)) {
if (copy.endsWith(".xml")) {
SBMLDocument document = readSBML(tree.getFile());
List<URI> sbolURIs = AnnotationUtility.parseSBOLAnnotation(document.getModel());
Iterator<URI> sbolIterator = sbolURIs.iterator();
while (sbolIterator != null && sbolIterator.hasNext()) {
if (sbolIterator.next().toString().endsWith("iBioSim")) {
sbolIterator.remove();
sbolIterator = null;
if (sbolURIs.size() > 0)
AnnotationUtility.setSBOLAnnotation(document.getModel(),
new SBOLAnnotation(document.getModel().getMetaId(), sbolURIs));
else
AnnotationUtility.removeSBOLAnnotation(document.getModel());
}
}
document.getModel().setId(copy.substring(0, copy.lastIndexOf(".")));
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy);
}
else if (copy.endsWith(".gcm")) {
SBMLDocument document = readSBML(tree.getFile().replace(".gcm", ".xml"));
document.getModel().setId(copy.substring(0, copy.lastIndexOf(".")));
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy.replace(".gcm", ".xml"));
addToTree(copy.replace(".gcm", ".xml"));
BioModel gcm = new BioModel(root);
gcm.load(tree.getFile());
gcm.setSBMLFile(copy.replace(".gcm", ".xml"));
gcm.save(root + separator + copy);
}
else if (copy.contains(".")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + copy));
FileInputStream in = new FileInputStream(new File(tree.getFile()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else {
boolean sim = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
}
if (sim) {
new File(root + separator + copy).mkdir();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3
&& ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(tree.getFile() + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy + separator + ss);
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss));
FileInputStream in = new FileInputStream(new File(tree.getFile() + separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss
.substring(ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree.getFile() + separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
else {
new File(root + separator + copy).mkdir();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".lrn"))) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".lrn")) {
out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn"));
}
else {
out = new FileOutputStream(new File(root + separator + copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree.getFile() + separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
}
addToTree(copy);
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void rename() {
if (!tree.getFile().equals(root)) {
if (!new File(tree.getFile()).isDirectory()) {
String[] views = canDelete(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]);
if (views.length != 0) {
String view = "";
String gcms = "";
for (int i = 0; i < views.length; i++) {
if (views[i].endsWith(".xml")) {
gcms += views[i] + "\n";
}
else {
view += views[i] + "\n";
}
}
String message;
if (gcms.equals("")) {
message = "Unable to rename the selected file." + "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
}
else if (view.equals("")) {
message = "Unable to rename the selected file." + "\nIt is linked to the following models:\n" + gcms
+ "\nDelete these models first.";
}
else {
message = "Unable to rename the selected file." + "\nIt is linked to the following views:\n" + view
+ "\nIt is also linked to the following models:\n" + gcms + "\nDelete these views and models first.";
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scroll, "Unable To Rename File", JOptionPane.ERROR_MESSAGE);
return;
}
}
String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String rename = JOptionPane.showInputDialog(frame, "Enter a New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE);
if (rename == null || rename.equals("")) {
return;
}
rename = rename.trim();
if (tree.getFile().contains(".")) {
String extension = tree.getFile().substring(tree.getFile().lastIndexOf("."), tree.getFile().length());
if (!rename.endsWith(extension)) {
rename += extension;
}
}
if (rename.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
int index = rename.lastIndexOf(".");
String modelID = rename;
if (index != -1) {
modelID = rename.substring(0, rename.lastIndexOf("."));
}
try {
if (checkFiles(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], rename)) {
if (overwrite(root + separator + rename, rename)) {
if (tree.getFile().endsWith(".sbml") || tree.getFile().endsWith(".xml") || tree.getFile().endsWith(".gcm")
|| tree.getFile().endsWith(".lpn") || tree.getFile().endsWith(".vhd") || tree.getFile().endsWith(".csp")
|| tree.getFile().endsWith(".hse") || tree.getFile().endsWith(".unc") || tree.getFile().endsWith(".rsg") || tree.getFile().endsWith(".prop")) {
reassignViews(oldName, rename);
}
if (tree.getFile().endsWith(".gcm")) {
String newSBMLfile = rename.replace(".gcm", ".xml");
new File(tree.getFile()).renameTo(new File(root + separator + rename));
new File(tree.getFile().replace(".gcm", ".xml")).renameTo(new File(root + separator + newSBMLfile));
BioModel gcm = new BioModel(root);
gcm.load(root + separator + rename);
gcm.setSBMLFile(newSBMLfile);
gcm.save(root + separator + rename);
SBMLDocument document = readSBML(root + separator + newSBMLfile);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + newSBMLfile);
deleteFromTree(oldName.replace(".gcm", ".xml"));
addToTree(newSBMLfile);
}
else if (tree.getFile().endsWith(".xml")) {
new File(tree.getFile()).renameTo(new File(root + separator + rename));
SBMLDocument document = readSBML(root + separator + rename);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + rename);
}
else {
new File(tree.getFile()).renameTo(new File(root + separator + rename));
}
if (rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")) {
for (String s : new File(root).list()) {
if (s.endsWith(".gcm")) {
boolean update = false;
BufferedReader in = new BufferedReader(new FileReader(root + separator + s));
String line = null;
String file = "";
while ((line = in.readLine()) != null) {
if (line.contains("gcm=" + oldName)) {
line = line.replaceAll("gcm=" + oldName, "gcm=" + rename);
update = true;
}
file += line;
file += "\n";
}
in.close();
BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + s));
out.write(file);
out.close();
if (update) {
renameOpenGCMComponents(s, oldName, rename);
}
}
}
}
if (tree.getFile().endsWith(".sbml") || tree.getFile().endsWith(".xml") || tree.getFile().endsWith(".gcm")
|| tree.getFile().endsWith(".lpn") || tree.getFile().endsWith(".vhd") || tree.getFile().endsWith(".csp")
|| tree.getFile().endsWith(".hse") || tree.getFile().endsWith(".unc") || tree.getFile().endsWith(".rsg")|| tree.getFile().endsWith(".prop")) {
updateAsyncViews(rename);
}
if (new File(root + separator + rename).isDirectory()) {
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").renameTo(new File(
root + separator + rename + separator + rename + ".sim"));
}
else if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").renameTo(new File(
root + separator + rename + separator + rename + ".sim"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").renameTo(new File(
root + separator + rename + separator + rename + ".lrn"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".ver").exists()) {
new File(root + separator + rename + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".ver").renameTo(new File(root + separator + rename + separator + rename + ".ver"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").renameTo(new File(
root + separator + rename + separator + rename + ".grf"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").renameTo(new File(
root + separator + rename + separator + rename + ".prb"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prop").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prop").renameTo(new File(
root + separator + rename + separator + rename + ".prop"));
}
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
/*
if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID);
((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename);
tab.setTitleAt(i, rename);
}
else */ if (tree.getFile().length() > 3
&& (tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree.getFile()
.substring(tree.getFile().length() - 4).equals(".prb"))) {
((Graph) tab.getComponentAt(i)).setGraphName(rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
((ModelEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename.length() - 4));
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
((ModelEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename.length() - 4));
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbol")) {
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
((LHPNEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename.length() - 4));
tab.setTitleAt(i, rename);
}
else if (tab.getComponentAt(i) instanceof JTabbedPane) {
JTabbedPane t = new JTabbedPane();
t.addMouseListener(this);
int selected = ((JTabbedPane) tab.getComponentAt(i)).getSelectedIndex();
boolean analysis = false;
ArrayList<Component> comps = new ArrayList<Component>();
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) {
Component c = ((JTabbedPane) tab.getComponentAt(i)).getComponent(j);
comps.add(c);
}
//SBML_Editor sbml = null;
AnalysisView reb2sac = null;
for (Component c : comps) {
if (c instanceof AnalysisView) {
((AnalysisView) c).setSim(rename);
analysis = true;
}
/*
else if (c instanceof SBML_Editor) {
String properties = root + separator + rename + separator + rename + ".sim";
new File(properties).renameTo(new File(properties.replace(".sim", ".temp")));
try {
boolean dirty = ((SBML_Editor) c).isDirty();
((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator + rename);
((SBML_Editor) c).save(false, "", true, true);
((SBML_Editor) c).updateSBML(i, 0);
((SBML_Editor) c).setDirty(dirty);
}
catch (Exception e1) {
e1.printStackTrace();
}
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(properties));
}
*/
else if (c instanceof Graph) {
// c.addMouseListener(this);
Graph g = ((Graph) c);
g.setDirectory(root + separator + rename);
if (g.isTSDGraph()) {
g.setGraphName(rename + ".grf");
}
else {
g.setGraphName(rename + ".prb");
}
}
else if (c instanceof LearnGCM) {
LearnGCM l = ((LearnGCM) c);
l.setDirectory(root + separator + rename);
}
else if (c instanceof DataManager) {
DataManager d = ((DataManager) c);
d.setDirectory(root + separator + rename);
}
if (analysis) {
if (c instanceof AnalysisView) {
reb2sac = (AnalysisView) c;
t.addTab("Simulation Options", c);
t.getComponentAt(t.getComponents().length - 1).setName("Simulate");
}
else if (c instanceof MovieContainer) {
t.addTab("Schematic", c);
t.getComponentAt(t.getComponents().length - 1).setName("ModelViewMovie");
}
/*
else if (c instanceof SBML_Editor) {
sbml = (SBML_Editor) c;
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1).setName("SBML Editor");
}
*/
else if (c instanceof ModelEditor) {
ModelEditor gcm = (ModelEditor) c;
/*
if (!gcm.getSBMLFile().equals("--none--")) {
sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator
+ rename, root + separator + rename + separator + rename + ".sim");
}
*/
t.addTab("Parameters", c);
t.getComponentAt(t.getComponents().length - 1).setName("GCM Editor");
}
else if (c instanceof Graph) {
if (((Graph) c).isTSDGraph()) {
t.addTab("TSD Graph", c);
t.getComponentAt(t.getComponents().length - 1).setName("TSD Graph");
}
else {
t.addTab("Histogram", c);
t.getComponentAt(t.getComponents().length - 1).setName("ProbGraph");
}
}
else if (c instanceof JScrollPane) {
/*
if (sbml != null) {
t.addTab("SBML Elements", sbml.getElementsPanel());
t.getComponentAt(t.getComponents().length - 1).setName("");
}
else {*/
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
t.addTab("SBML Elements", scroll);
t.getComponentAt(t.getComponents().length - 1).setName("");
}
else {
t.addTab("Advanced Options", c);
t.getComponentAt(t.getComponents().length - 1).setName("");
}
}
}
if (analysis) {
t.setSelectedIndex(selected);
tab.setComponentAt(i, t);
}
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
else {
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
}
else if (tab.getComponentAt(i) instanceof JTabbedPane) {
ArrayList<Component> comps = new ArrayList<Component>();
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) {
Component c = ((JTabbedPane) tab.getComponentAt(i)).getComponent(j);
comps.add(c);
}
for (Component c : comps) {
if (c instanceof AnalysisView && ((AnalysisView) c).getBackgroundFile().equals(oldName)) {
((AnalysisView) c).updateBackgroundFile(rename);
}
else if (c instanceof LearnGCM && ((LearnGCM) c).getBackgroundFile().equals(oldName)) {
((LearnGCM) c).updateBackgroundFile(rename);
}
}
}
}
// updateAsyncViews(rename);
updateViewNames(tree.getFile(), rename);
deleteFromTree(oldName);
addToTree(rename);
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void openGCM(boolean textBased) {
String file = tree.getFile();
String filename = "";
if (file.lastIndexOf('/') >= 0) {
filename = file.substring(file.lastIndexOf('/') + 1);
}
if (file.lastIndexOf('\\') >= 0) {
filename = file.substring(file.lastIndexOf('\\') + 1);
}
openGCM(filename, textBased);
}
public void openGCM(String filename, boolean textBased) {
try {
File work = new File(root);
int i = getTab(filename);
if (i == -1) {
i = getTab(filename.replace(".gcm", ".xml"));
}
if (i != -1) {
if (((ModelEditor)tab.getComponentAt(i)).isTextBased()) {
if (!textBased) {
((ModelEditor)tab.getComponentAt(i)).setTextBased(textBased);
((ModelEditor)tab.getComponentAt(i)).rebuildGui();
}
} else {
if (textBased) {
((ModelEditor)tab.getComponentAt(i)).setTextBased(textBased);
((ModelEditor)tab.getComponentAt(i)).rebuildGui();
}
}
tab.setSelectedIndex(i);
}
else {
String path = work.getAbsolutePath();
/*
* GCMFile gcmFile = new GCMFile(path); String gcmname =
* theFile.replace(".gcm", ""); gcmFile.load(filename); if
* ((gcmFile.getSBMLFile() == null ||
* !gcmFile.getSBMLFile().equals(gcmname + ".xml")) && new
* File(path + separator + gcmname + ".xml").exists()) {
* Object[] options = { "Overwrite", "Cancel" }; int value;
* value = JOptionPane.showOptionDialog(Gui.frame, gcmname +
* ".xml already exists." + "\nDo you want to overwrite?",
* "Overwrite", JOptionPane.YES_NO_OPTION,
* JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if
* (value == JOptionPane.YES_OPTION) { GCM2SBMLEditor gcm = new
* GCM2SBMLEditor(path, theFile, this, log, false, null, null,
* null, textBased); addTab(theFile, gcm, "GCM Editor"); } }
* else {
*/
try {
ModelEditor gcm = new ModelEditor(path, filename, this, log, false, null, null, null, textBased, false, lema);
addTab(filename, gcm, "GCM Editor");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to open this GCM file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void openSBML(String fullPath) {
try {
boolean done = false;
String theSBMLFile = fullPath.split(separator)[fullPath.split(separator).length - 1];
String theGCMFile = theSBMLFile.replace(".xml", ".gcm");
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(theSBMLFile) || getTitleAt(i).equals(theGCMFile)) {
tab.setSelectedIndex(i);
done = true;
break;
}
}
if (!done) {
//createGCMFromSBML(root, fullPath, theSBMLFile, theGCMFile, false);
//addToTree(theGCMFile);
ModelEditor gcm = new ModelEditor(root + separator, theGCMFile, this, log, false, null, null, null, false, false, lema);
addTab(theSBMLFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "You must select a valid SBML file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
/*
public static boolean createGCMFromSBML(String root, String fullPath, String theSBMLFile, String theGCMFile, boolean force) {
if (force || !new File(fullPath.replace(".xml", ".gcm").replace(".sbml", ".gcm")).exists()) {
SBMLDocument document = readSBML(fullPath);
Model m = document.getModel();
GCMFile gcmFile = new GCMFile(root);
gcmFile.setSBMLDocument(document);
gcmFile.setSBMLFile(theSBMLFile);
document.enablePackage(LayoutExtension.getXmlnsL3V1V1(), "layout", true);
document.setPackageRequired("layout", false);
document.enablePackage(CompExtension.getXmlnsL3V1V1(), "comp", true);
document.setPackageRequired("comp", true);
gcmFile.setSBMLLayout((LayoutModelPlugin)document.getModel().getPlugin("layout"));
gcmFile.setSBMLComp((CompSBMLDocumentPlugin)document.getPlugin("comp"));
gcmFile.setSBMLCompModel((CompModelPlugin)document.getModel().getPlugin("comp"));
int x = 50;
int y = 50;
if (m != null) {
for (int i = 0; i < m.getNumSpecies(); i++) {
gcmFile.createSpecies(document.getModel().getSpecies(i).getId(), x, y);
x += 50;
y += 50;
}
}
gcmFile.save(fullPath.replace(".xml", ".gcm").replace(".sbml", ".gcm"));
return true;
}
else
return false;
}
*/
private void openSBOL() {
String filePath = tree.getFile();
String fileName = "";
fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
int i = getTab(fileName);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
SBOLBrowser browser = new SBOLBrowser(this, filePath);
}
}
public HashSet<String> getFilePaths(String fileExtension) {
HashSet<String> filePaths = new HashSet<String>();
TreeModel tree = getFileTree().tree.getModel();
for (int i = 0; i < tree.getChildCount(tree.getRoot()); i++) {
String fileName = tree.getChild(tree.getRoot(), i).toString();
if (fileName.endsWith(fileExtension))
filePaths.add(getRoot() + File.separator + fileName);
}
return filePaths;
}
public HashSet<String> getSbolFiles() {
HashSet<String> sbolFiles = new HashSet<String>();
TreeModel tree = getFileTree().tree.getModel();
for (int i = 0; i < tree.getChildCount(tree.getRoot()); i++) {
String fileName = tree.getChild(tree.getRoot(), i).toString();
if (fileName.endsWith(".sbol"))
sbolFiles.add(fileName);
}
return sbolFiles;
}
private void openGraph() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Number of molecules", "title",
"tsd.printer", root, "Time", this, tree.getFile(), log,
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph");
}
}
private void openHistogram() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Percent", "title", "tsd.printer",
root, "Time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], false,
false), "Histogram");
}
}
private void openLPN() {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
LhpnFile lhpn = new LhpnFile(log);
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log);
addTab(theFile, editor, "LHPN Editor");
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to view this LPN file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void newModel(String fileType, String extension) {
if (root != null) {
try {
String modelID = JOptionPane.showInputDialog(frame, "Enter " + fileType + " Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (modelID != null && !modelID.trim().equals("")) {
String fileName;
modelID = modelID.trim();
if (modelID.length() >= extension.length()) {
if (!modelID.substring(modelID.length() - extension.length()).equals(extension)) {
fileName = modelID + extension;
}
else {
fileName = modelID;
modelID = modelID.substring(0, modelID.length() - extension.length());
}
}
else {
fileName = modelID + extension;
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + fileName);
f.createNewFile();
addToTree(fileName);
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + fileName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
addTab(fileName, scroll, fileType + " Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void openModel(String fileType) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
addTab(theFile, scroll, fileType + " Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this " + fileType + " file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public int getTab(String name) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(name)) {
return i;
}
}
return -1;
}
public void deleteDir(File dir) {
int count = 0;
do {
File[] list = dir.listFiles();
System.gc();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteDir(list[i]);
}
else {
list[i].delete();
}
}
count++;
}
while (!dir.delete() && count != 100);
if (count == 100) {
JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method adds a new project to recent list
*/
public void addRecentProject(String projDir) {
// boolean newOne = true;
for (int i = 0; i < numberRecentProj; i++) {
if (recentProjectPaths[i].equals(projDir)) {
for (int j = 0; j <= i; j++) {
String save = recentProjectPaths[j];
recentProjects[j].setText(projDir.split(separator)[projDir.split(separator).length - 1]);
openRecent.insert(recentProjects[j], j);
/*
if (openRecent.getItem(openRecent.getItemCount() - 1) == exit) {
openRecent.insert(recentProjects[j], openRecent.getItemCount() - 3 - numberRecentProj);
}
else {
openRecent.add(recentProjects[j]);
}
*/
recentProjectPaths[j] = projDir;
projDir = save;
}
for (int j = i + 1; j < numberRecentProj; j++) {
openRecent.insert(recentProjects[j], j);
/*
if (openRecent.getItem(openRecent.getItemCount() - 1) == exit) {
openRecent.insert(recentProjects[j], openRecent.getItemCount() - 3 - numberRecentProj);
}
else {
openRecent.add(recentProjects[j]);
}
*/
}
return;
}
}
if (numberRecentProj < 10) {
numberRecentProj++;
}
for (int i = 0; i < numberRecentProj; i++) {
String save = recentProjectPaths[i];
recentProjects[i].setText(projDir.split(separator)[projDir.split(separator).length - 1]);
openRecent.insert(recentProjects[i], i);
/*
if (openRecent.getItem(openRecent.getItemCount() - 1) == exit) {
openRecent.insert(recentProjects[i], openRecent.getItemCount() - 3 - numberRecentProj);
}
else {
openRecent.add(recentProjects[i]);
}
*/
recentProjectPaths[i] = projDir;
projDir = save;
}
}
/**
* This method removes a project from the recent list
*/
public void removeRecentProject(String projDir) {
for (int i = 0; i < numberRecentProj; i++) {
if (recentProjectPaths[i].equals(projDir)) {
for (int j = i; j < numberRecentProj-1; j++) {
recentProjects[j].setText(recentProjects[j+1].getText());
recentProjectPaths[j] = recentProjectPaths[j+1];
}
openRecent.remove(recentProjects[numberRecentProj-1]);
recentProjectPaths[numberRecentProj-1]="";
numberRecentProj
return;
}
}
}
/**
* This method removes all projects from the recent list
*/
public void removeAllRecentProjects() {
for (int i = 0; i < numberRecentProj; i++) {
openRecent.remove(recentProjects[i]);
recentProjectPaths[i]="";
}
numberRecentProj=0;
}
/**
* This method refreshes the menu.
*/
public void refresh() {
mainPanel.remove(tree);
tree = new FileTree(new File(root), this, lema, atacs);
topSplit.setLeftComponent(tree);
//mainPanel.add(tree, "West");
mainPanel.validate();
}
/**
* This method refreshes the tree.
*/
public void refreshTree() {
mainPanel.remove(tree);
tree = new FileTree(new File(root), this, lema, atacs);
topSplit.setLeftComponent(tree);
//mainPanel.add(tree, "West");
// updateGCM();
mainPanel.validate();
}
public void addToTree(String item) {
tree.addToTree(item, root);
// updateGCM();
mainPanel.validate();
}
public void addToTreeNoUpdate(String item) {
tree.addToTree(item, root);
mainPanel.validate();
}
public void deleteFromTree(String item) {
tree.deleteFromTree(item);
// updateGCM();
mainPanel.validate();
}
public FileTree getFileTree() {
return tree;
}
public void markTabDirty(boolean dirty) {
int i = tab.getSelectedIndex();
if (dirty) {
if (i>=0 && !tab.getTitleAt(i).endsWith("*")) {
tab.setTitleAt(i, tab.getTitleAt(i)+"*");
}
} else {
if (i>=0 && tab.getTitleAt(i).endsWith("*")) {
tab.setTitleAt(i, tab.getTitleAt(i).replace("*",""));
}
}
}
public void markTabClean(int i) {
if (i>=0 && tab.getTitleAt(i).endsWith("*")) {
tab.setTitleAt(i, tab.getTitleAt(i).replace("*",""));
}
}
/**
* This method adds the given Component to a tab.
*/
public void addTab(String name, Component panel, String tabName) {
tab.addTab(name, panel);
// panel.addMouseListener(this);
if (tabName != null) {
tab.getComponentAt(tab.getTabCount() - 1).setName(tabName);
}
else {
tab.getComponentAt(tab.getTabCount() - 1).setName(name);
}
tab.setSelectedIndex(tab.getTabCount() - 1);
}
/**
* This method removes the given component from the tabs.
*/
public void removeTab(Component component) {
tab.remove(component);
if (tab.getTabCount() > 0) {
tab.setSelectedIndex(tab.getTabCount() - 1);
enableTabMenu(tab.getSelectedIndex());
}
else {
enableTreeMenu();
}
}
public void refreshTabListeners() {
for (ChangeListener l : tab.getChangeListeners()) {
tab.removeChangeListener(l);
}
for (int i = 0; i < tab.getTabCount(); i ++) {
if (tab.getComponent(i) instanceof ModelEditor) {
((ModelEditor)tab.getComponent(i)).getSchematic().addChangeListener();
}
}
}
public JTabbedPane getTab() {
return tab;
}
/**
* Prompts the user to save work that has been done.
*/
public int save(int index, int autosave) {
if (tab.getComponentAt(index).getName().contains(("GCM")) || tab.getComponentAt(index).getName().contains("LHPN")) {
if (tab.getComponentAt(index) instanceof ModelEditor) {
ModelEditor editor = (ModelEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save("gcm");
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save("gcm");
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save("gcm");
return 2;
}
else {
return 3;
}
}
}
else if (tab.getComponentAt(index) instanceof LHPNEditor) {
LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
/*
else if (tab.getComponentAt(index).getName().equals("SBML Editor")) {
if (tab.getComponentAt(index) instanceof SBML_Editor) {
if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true, true);
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true, true);
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true, true);
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
*/
else if (tab.getComponentAt(index).getName().contains("Graph") || tab.getComponentAt(index).getName().equals("Histogram")) {
if (tab.getComponentAt(index) instanceof Graph) {
if (((Graph) tab.getComponentAt(index)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else {
if (tab.getComponentAt(index) instanceof JTabbedPane) {
for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() != null) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName().equals("Simulate")) {
if (((AnalysisView) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save simulation option changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((AnalysisView) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((AnalysisView) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((AnalysisView) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
}
/*
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals("SBML Editor")) {
if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(false, "", true, true);
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(false, "", true, true);
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(false, "", true, true);
}
}
}
*/
/*
* else if (((JTabbedPane)
* tab.getComponentAt(index)).getComponent(i)
* .getName().equals("GCM Editor")) { if
* (((GCM2SBMLEditor) ((JTabbedPane)
* tab.getComponentAt(index))
* .getComponent(i)).isDirty()) { if (autosave == 0) {
* int value = JOptionPane.showOptionDialog(frame,
* "Do you want to save parameter changes for " +
* tab.getTitleAt(index) + "?", "Save Changes",
* JOptionPane.YES_NO_CANCEL_OPTION,
* JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
* OPTIONS[0]); if (value == YES_OPTION) {
* ((GCM2SBMLEditor) ((JTabbedPane)
* tab.getComponentAt(index))
* .getComponent(i)).saveParams(false, ""); } else if
* (value == CANCEL_OPTION) { return 0; } else if (value
* == YES_TO_ALL_OPTION) { ((GCM2SBMLEditor)
* ((JTabbedPane) tab.getComponentAt(index))
* .getComponent(i)).saveParams(false, ""); autosave =
* 1; } else if (value == NO_TO_ALL_OPTION) { autosave =
* 2; } } else if (autosave == 1) { ((GCM2SBMLEditor)
* ((JTabbedPane) tab.getComponentAt(index))
* .getComponent(i)).saveParams(false, ""); } } }
*/
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof MovieContainer) {
if (((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).getGCM2SBMLEditor().isDirty()
|| ((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).getIsDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).savePreferences();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).savePreferences();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).savePreferences();
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals("Learn Options")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnGCM) {
if (((LearnGCM) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnGCM) {
((LearnGCM) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnGCM) {
((LearnGCM) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnGCM) {
((LearnGCM) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
}
}
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals("Data Manager")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) {
((DataManager) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).saveChanges(getTitleAt(index));
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().contains("Graph")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save graph changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i));
g.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i));
g.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i));
g.save();
}
}
}
}
}
}
}
}
else if (tab.getComponentAt(index) instanceof JPanel) {
if ((tab.getComponentAt(index)).getName().equals("Synthesis")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Synthesis) {
if (((Synthesis) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save synthesis option changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
}
}
}
else if (tab.getComponentAt(index).getName().equals("Verification")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Verification) {
if (((Verification) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save verification option changes for " + getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Verification) array[0]).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Verification) array[0]).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Verification) array[0]).save();
}
}
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveGcm(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + filename));
FileInputStream in = new FileInputStream(new File(path));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
BioModel gcm = new BioModel(root);
gcm.load(root + separator + filename);
GCM2SBML gcm2sbml = new GCM2SBML(gcm);
gcm2sbml.load(root + separator + filename);
gcm2sbml.convertGCM2SBML(root + separator + filename);
String sbmlFile = filename.replace(".gcm", ".xml");
gcm.save(root + separator + sbmlFile);
addToTree(sbmlFile);
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveLhpn(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + filename));
BufferedReader in = new BufferedReader(new FileReader(path));
String str;
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
addToTree(filename);
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save LPN.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void copySFiles(String filename, String directory) {
StringBuffer data = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new FileReader(directory + separator + filename));
String str;
while ((str = in.readLine()) != null) {
data.append(str + "\n");
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Error opening file");
}
Pattern sLinePattern = Pattern.compile(SFILELINE);
Matcher sLineMatcher = sLinePattern.matcher(data);
while (sLineMatcher.find()) {
String sFilename = sLineMatcher.group(1);
try {
File newFile = new File(directory + separator + sFilename);
newFile.createNewFile();
FileOutputStream copyin = new FileOutputStream(newFile);
FileInputStream copyout = new FileInputStream(new File(root + separator + sFilename));
int read = copyout.read();
while (read != -1) {
copyin.write(read);
read = copyout.read();
}
copyin.close();
copyout.close();
}
catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame, "Cannot copy file " + sFilename, "Copy Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void updateMenu(boolean logEnabled, boolean othersEnabled) {
viewLearnedModel.setEnabled(othersEnabled);
viewCoverage.setEnabled(othersEnabled);
save.setEnabled(othersEnabled);
viewLog.setEnabled(logEnabled);
// Do saveas & save button too
}
public void mousePressed(MouseEvent e) {
executePopupMenu(e);
}
public void mouseReleased(MouseEvent e) {
executePopupMenu(e);
}
public void executePopupMenu(MouseEvent e) {
if (e.getSource() instanceof JTree && tree.getFile() != null && e.isPopupTrigger()) {
// frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem edit = new JMenuItem("View/Edit (graphical)");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("gcmEditor");
JMenuItem editText = new JMenuItem("View/Edit (tabular)");
editText.addActionListener(this);
editText.addMouseListener(this);
editText.setActionCommand("gcmTextEditor");
// JMenuItem graph = new JMenuItem("View Model");
// graph.addActionListener(this);
// graph.addMouseListener(this);
// graph.setActionCommand("graphTree");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.addSeparator();
// popup.add(graph);
// popup.addSeparator();
popup.add(edit);
popup.add(editText);
popup.add(copy);
popup.add(rename);
popup.add(delete);
/*
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graphTree");
JMenuItem browse = new JMenuItem("View Model in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
*/
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbol")) {
JMenuItem view = new JMenuItem("View");
view.addActionListener(this);
view.addMouseListener(this);
view.setActionCommand("browseSbol");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
popup.add(view);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem edit = new JMenuItem("View/Edit (graphical)");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("gcmEditor");
JMenuItem editText = new JMenuItem("View/Edit (tabular)");
editText.addActionListener(this);
editText.addMouseListener(this);
editText.setActionCommand("gcmTextEditor");
// JMenuItem graph = new JMenuItem("View Model");
// graph.addActionListener(this);
// graph.addMouseListener(this);
// graph.setActionCommand("graphTree");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.addSeparator();
// popup.add(graph);
// popup.addSeparator();
popup.add(edit);
popup.add(editText);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (lema) {
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
else if (tree.getFile().length() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) {
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (lema) {
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem convertToSBML = new JMenuItem("Convert To SBML");
convertToSBML.addActionListener(this);
convertToSBML.addMouseListener(this);
convertToSBML.setActionCommand("convertToSBML");
JMenuItem convertToVerilog = new JMenuItem("Save as Verilog");
convertToVerilog.addActionListener(this);
convertToVerilog.addMouseListener(this);
convertToVerilog.setActionCommand("convertToVerilog");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem view = new JMenuItem("View/Edit");
view.addActionListener(this);
view.addMouseListener(this);
view.setActionCommand("openLPN");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
if (LPN2SBML) {
popup.add(createAnalysis);
}
popup.add(createVerification);
if (lema) {
popup.add(createLearn);
popup.addSeparator();
}
// popup.add(createAnalysis); // TODO
// popup.add(viewStateGraph);
/*
* if (!atacs && !lema && LPN2SBML) { popup.add(convertToSBML);
* // changed the order. SB }
*/
if (atacs || lema) {
popup.add(convertToVerilog);
}
// popup.add(markovAnalysis);
popup.add(viewModel);
popup.addSeparator();
popup.add(view);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".prop")) {
JMenuItem convertToLPN = new JMenuItem("Convert To LPN");
convertToLPN.addActionListener(this);
convertToLPN.addMouseListener(this);
convertToLPN.setActionCommand("convertToLPN");
JMenuItem view = new JMenuItem("View/Edit");
view.addActionListener(this);
view.addMouseListener(this);
view.setActionCommand("openLPN");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (lema) {
popup.add(createLearn);
popup.addSeparator();
popup.add(viewModel);
}
// popup.add(createAnalysis); // TODO
// popup.add(viewStateGraph);
/*
* if (!atacs && !lema && LPN2SBML) { popup.add(convertToSBML);
* // changed the order. SB }
*/
// popup.add(markovAnalysis);
popup.addSeparator();
popup.add(view);
popup.add(copy);
popup.add(rename);
popup.add(delete);
popup.add(convertToLPN);
}
else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createAnalysis);
popup.add(createVerification);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openHistogram");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver || synth || learn) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
public void executeMouseClickEvent(MouseEvent e) {
if (!(e.getSource() instanceof JTree)) {
enableTabMenu(tab.getSelectedIndex());
// frame.getGlassPane().setVisible(true);
}
else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2 && e.getSource() instanceof JTree && tree.getFile() != null) {
if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
openSBML(tree.getFile());
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
openGCM(false);
}
else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbol")) {
openSBOL();
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
openModel("VHDL");
}
else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
openModel("Assembly File");
}
else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) {
openModel("Instruction File");
}
else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".prop")) { //Dhanashree
openModel("Property File");
}
else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
openModel("Verilog-AMS");
}
else if (tree.getFile().length() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) {
openModel("SystemVerilog");
}
else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
openModel("Petri Net");
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
openLPN();
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
openModel("CSP");
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
openModel("Handshaking Expansion");
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
openModel("Extended Burst-Mode Machine");
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
openModel("Reduced State Graph");
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) {
openModel("Spice Circuit");
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
openGraph();
}
else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
openHistogram();
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim) {
try {
openSim();
}
catch (Exception e0) {
e0.printStackTrace();
}
}
else if (synth) {
openSynth();
}
else if (ver) {
openVerify();
}
else if (learn) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
}
else if (new File(tree.getFile()).isDirectory() && tree.getFile().equals(root)) {
tree.expandPath(tree.getRoot());
}
}
else {
enableTreeMenu();
return;
}
enableTabMenu(tab.getSelectedIndex());
}
public void mouseMoved(MouseEvent e) {
}
public void mouseWheelMoved(MouseWheelEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y,
e.getClickCount(), e.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x,
componentPoint.y, e.getClickCount(), e.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation()));
}
}
private void createAnalysisView(int fileType) throws Exception {
String sbmlFile;
String modelId = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1].replace(".xml","").replace(".lpn","");
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (fileType == 0) {
readSBML(tree.getFile());
}
sbmlFile = tree.getFile();
String[] sbml1 = null;
String simName = JOptionPane.showInputDialog(frame, "Enter analysis ID (default=" + modelId + "):",
"Analysis ID", JOptionPane.PLAIN_MESSAGE);
if (simName == null) return;
if (simName.equals("")) simName = modelId;
simName = simName.trim();
if (!overwrite(root + separator + simName, simName)) return;
new File(root + separator + simName).mkdir();
sbml1 = tree.getFile().split(separator);
String sbmlFileProp;
if (fileType == 1) {
sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml");
new File(root + separator + simName + separator + sbmlFile).createNewFile();
sbmlFileProp = root + separator + simName + separator
+ (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml");
sbmlFile = sbmlFileProp;
}
else if (fileType == 2) {
sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml");
Translator t1 = new Translator();
t1.convertLPN2SBML(tree.getFile(), "");
t1.setFilename(root + separator + simName + separator + sbmlFile);
t1.outputSBML();
sbmlFileProp = root + separator + simName + separator
+ (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml");
sbmlFile = sbmlFileProp;
}
else {
sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1];
new FileOutputStream(new File(sbmlFileProp)).close();
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim"));
out.write((sbml1[sbml1.length - 1] + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
addToTree(simName);
JTabbedPane simTab = new JTabbedPane();
simTab.addMouseListener(this);
AnalysisView reb2sac = new AnalysisView(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null, sbml1[sbml1.length - 1], null,
null);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
if (fileType == 2) {
simTab.addTab("Advanced Options", new AbstPane(root, sbml1[sbml1.length - 1], log, this, false, false));
}
else {
simTab.addTab("Advanced Options", reb2sac.getAdvanced());
}
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
if (sbml1[sbml1.length - 1].contains(".gcm")) {
String gcmFile = sbml1[sbml1.length - 1];
ModelEditor gcm = new ModelEditor(root + separator, gcmFile, this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac, false, false, lema);
reb2sac.setGcm(gcm);
addModelViewTab(reb2sac, simTab, gcm);
simTab.addTab("Parameters", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
ElementsPanel elementsPanel = new ElementsPanel(gcm.getBioModel().getSBMLDocument(),
root + separator + simName.trim() + separator + simName.trim() + ".sim");
simTab.addTab("SBML Elements", elementsPanel);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setElementsPanel(elementsPanel);
}
else if (sbml1[sbml1.length - 1].contains(".sbml") || sbml1[sbml1.length - 1].contains(".xml")) {
String gcmFile = sbml1[sbml1.length - 1].replace(".xml", ".gcm");
ModelEditor gcm = new ModelEditor(root + separator, gcmFile, this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac, false, false, lema);
reb2sac.setGcm(gcm);
addModelViewTab(reb2sac, simTab, gcm);
simTab.addTab("Parameters", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
ElementsPanel elementsPanel = new ElementsPanel(gcm.getBioModel().getSBMLDocument(),
root + separator + simName.trim() + separator + simName.trim() + ".sim");
simTab.addTab("SBML Elements", elementsPanel);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setElementsPanel(elementsPanel);
}
Graph tsdGraph;
tsdGraph = reb2sac.createGraph(null);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
simTab.addTab("Histogram", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
addTab(simName, simTab, null);
}
private void openLearn() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
lrnTab.addMouseListener(this);
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
if (learnFile.endsWith(".gcm")) {
learnFile = learnFile.replace(".gcm", ".xml");
load.setProperty("genenet.file", learnFile);
}
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
LearnGCM learn = new LearnGCM(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn Options", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn Options");
lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel());
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options");
Graph tsdGraph = new Graph(null, "Number of molecules", tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log, null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null);
}
}
private void openLearnLHPN() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
lrnTab.addMouseListener(this);
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
DataManager data = new DataManager(tree.getFile(), this, lema);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this);
lrnTab.addTab("Learn Options", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn Options");
lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel());
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options");
Graph tsdGraph = new Graph(null, "Number of molecules", tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log, null, true, true);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null);
}
}
private void openSynth() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JPanel synthPanel = new JPanel();
// String graphFile = "";
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
}
}
}
String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn";
String synthFile2 = tree.getFile() + separator + ".syn";
Properties load = new Properties();
String synthesisFile = "";
try {
if (new File(synthFile2).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile2));
load.load(in);
in.close();
new File(synthFile2).delete();
}
if (new File(synthFile).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile));
load.load(in);
in.close();
if (load.containsKey("synthesis.file")) {
synthesisFile = load.getProperty("synthesis.file");
synthesisFile = synthesisFile.split(separator)[synthesisFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(synthesisFile));
load.store(out, synthesisFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(synthesisFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + synthesisFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this);
// synth.addMouseListener(this);
synthPanel.add(synth);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, "Synthesis");
}
}
private void openVerify() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
// JPanel verPanel = new JPanel();
// JPanel abstPanel = new JPanel();
// JPanel verTab = new JTabbedPane();
// String graphFile = "";
/*
* if (new File(tree.getFile()).isDirectory()) { String[] list = new
* File(tree.getFile()).list(); int run = 0; for (int i = 0; i <
* list.length; i++) { if (!(new File(list[i]).isDirectory()) &&
* list[i].length() > 4) { String end = ""; for (int j = 1; j < 5;
* j++) { end = list[i].charAt(list[i].length() - j) + end; } if
* (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv"))
* { if (list[i].contains("run-")) { int tempNum =
* Integer.parseInt(list[i].substring(4, list[i] .length() -
* end.length())); if (tempNum > run) { run = tempNum; // graphFile
* = tree.getFile() + separator + // list[i]; } } } } } }
*/
String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String verFile = tree.getFile() + separator + verName + ".ver";
Properties load = new Properties();
String verifyFile = "";
try {
if (new File(verFile).exists()) {
FileInputStream in = new FileInputStream(new File(verFile));
load.load(in);
in.close();
if (load.containsKey("verification.file")) {
verifyFile = load.getProperty("verification.file");
verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1];
}
}
// FileOutputStream out = new FileOutputStream(new
// File(verifyFile));
// load.store(out, verifyFile);
// out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(verifyFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(verFile).exists())) {
JOptionPane
.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Verification ver = new Verification(root + separator + verName, verName, "flag", log, this, lema, atacs);
// ver.addMouseListener(this);
// verPanel.add(ver);
// AbstPane abst = new AbstPane(root + separator + verName, ver,
// "flag", log, this, lema,
// atacs);
// abstPanel.add(abst);
// verTab.add("verify", verPanel);
// verTab.add("abstract", abstPanel);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], ver, "Verification");
}
}
private void openSim() throws Exception {
String filename = tree.getFile();
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(filename.split(separator)[filename.split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (filename != null && !filename.equals("")) {
if (new File(filename).isDirectory()) {
if (new File(filename + separator + ".sim").exists()) {
new File(filename + separator + ".sim").delete();
}
String[] list = new File(filename).list();
String getAFile = "";
// String probFile = "";
String openFile = "";
// String graphFile = "";
String open = null;
String openProb = null;
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".xml")) {
getAFile = filename + separator + list[i];
}
else if (end.equals("sbml") && getAFile.equals("")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".txt") && list[i].contains("sim-rep")) {
// probFile = filename + separator + list[i];
}
else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) {
openFile = filename + separator + list[i];
}
else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = filename + separator +
// list[i];
}
}
else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.")
|| list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) {
// graphFile = filename + separator +
// list[i];
}
else if (end.contains("=")) {
// graphFile = filename + separator +
// list[i];
}
}
else if (end.equals(".grf")) {
open = filename + separator + list[i];
}
else if (end.equals(".prb")) {
openProb = filename + separator + list[i];
}
}
else if (new File(filename + separator + list[i]).isDirectory()) {
String[] s = new File(filename + separator + list[i]).list();
for (int j = 0; j < s.length; j++) {
if (s[j].contains("sim-rep")) {
// probFile = filename + separator + list[i]
// + separator +
}
else if (s[j].contains(".tsd")) {
// graphFile = filename + separator +
// list[i] + separator +
}
}
}
}
if (!getAFile.equals("")) {
String[] split = filename.split(separator);
String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim";
String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms";
if (new File(pmsFile).exists()) {
if (new File(simFile).exists()) {
new File(pmsFile).delete();
}
else {
new File(pmsFile).renameTo(new File(simFile));
}
}
String sbmlLoadFile = "";
String gcmFile = "";
// ArrayList<String> interestingSpecies = new
// ArrayList<String>();
if (new File(simFile).exists()) {
try {
Scanner s = new Scanner(new File(simFile));
if (s.hasNextLine()) {
sbmlLoadFile = s.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1];
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.endsWith(".gcm"))
sbmlLoadFile = sbmlLoadFile.replace(".gcm", ".xml");
if (sbmlLoadFile.equals("")) {
JOptionPane.showMessageDialog(frame, "Unable to open view because "
+ "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!(new File(root + separator + sbmlLoadFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (sbmlLoadFile.contains(".gcm")) {
// GCMParser parser = new GCMParser(root
// + separator + sbmlLoadFile);
// GeneticNetwork network =
// parser.buildNetwork();
// interestingSpecies.addAll(network.getInterestingSpecies());
// GeneticNetwork.setRoot(root +
// separator);
sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".gcm", ".xml");
// network.mergeSBML(sbmlLoadFile);
}
else if (sbmlLoadFile.contains(".lpn")) {
// Translator t1 = new Translator();
// t1.BuildTemplate(root + separator +
// sbmlLoadFile, "");
sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".lpn", ".xml");
// t1.setFilename(sbmlLoadFile);
// t1.outputSBML();
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (s.hasNextLine()) {
s.nextLine();
}
s.close();
File f = new File(sbmlLoadFile);
if (!f.exists()) {
sbmlLoadFile = root + separator + f.getName();
}
}
catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1];
if (!new File(sbmlLoadFile).exists()) {
sbmlLoadFile = getAFile;
/*
* JOptionPane.showMessageDialog(frame, "Unable
* to load sbml file.", "Error",
* JOptionPane.ERROR_MESSAGE); return;
*/
}
}
if (!new File(sbmlLoadFile).exists()) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
JTabbedPane simTab = new JTabbedPane();
simTab.addMouseListener(this);
AbstPane lhpnAbstraction = null;
if (gcmFile.contains(".lpn")) {
lhpnAbstraction = new AbstPane(root, gcmFile, log, this, false, false);
}
AnalysisView reb2sac;
if (gcmFile.contains(".lpn")) {
reb2sac = new AnalysisView(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile,
lhpnAbstraction, null);
}
else {
reb2sac = new AnalysisView(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile,
null, null);
}
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
if (gcmFile.contains(".lpn")) {
simTab.addTab("Advanced Options", lhpnAbstraction);
}
else {
simTab.addTab("Advanced Options", reb2sac.getAdvanced());
}
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".xml")||gcmFile.contains(".gcm")) {
/*
SBML_Editor sbml = new SBML_Editor(root + separator + gcmFile.replace(".gcm",".xml"), reb2sac, log, this, root + separator
+ split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".sim");
*/
ModelEditor gcm = new ModelEditor(root + separator, gcmFile, this, log, true, split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim", reb2sac,
false, false, lema);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
addModelViewTab(reb2sac, simTab, gcm);
simTab.addTab("Parameters", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
ElementsPanel elementsPanel = new ElementsPanel(gcm.getBioModel().getSBMLDocument(),
root + separator + split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".sim");
simTab.addTab("SBML Elements", elementsPanel);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setElementsPanel(elementsPanel);
}
/*
else if (gcmFile.contains(".sbml") || gcmFile.contains(".xml")) {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(),
root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
*/
Graph tsdGraph = reb2sac.createGraph(open);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(openProb);
simTab.addTab("Histogram", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
addTab(split[split.length - 1], simTab, null);
}
}
}
}
}
/**
* adds the tab for the modelview and the correct listener.
*
* @return
*/
private void addModelViewTab(AnalysisView reb2sac, JTabbedPane tabPane, ModelEditor gcm2sbml) {
// Add the modelview tab
MovieContainer movieContainer = new MovieContainer(reb2sac, gcm2sbml.getBioModel(), this, gcm2sbml, lema);
tabPane.addTab("Schematic", movieContainer);
tabPane.getComponentAt(tabPane.getComponents().length - 1).setName("ModelViewMovie");
// When the Graphical View panel gets clicked on, tell it to display
// itself.
tabPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JTabbedPane selectedTab = (JTabbedPane) (e.getSource());
if (!(selectedTab.getComponent(selectedTab.getSelectedIndex()) instanceof JScrollPane)) {
JPanel selectedPanel = (JPanel) selectedTab.getComponent(selectedTab.getSelectedIndex());
String className = selectedPanel.getClass().getName();
// The new Schematic
if (className.indexOf("MovieContainer") >= 0) {
((MovieContainer) selectedPanel).display();
}
}
}
});
}
private class NewAction extends AbstractAction {
private static final long serialVersionUID = 1L;
NewAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(newProj);
if (!async) {
popup.add(newSBMLModel);
popup.add(newGridModel);
}
else if (atacs) {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newCsp);
popup.add(newHse);
popup.add(newUnc);
popup.add(newRsg);
}
else {
popup.add(newVhdl);
popup.add(newProperty);
popup.add(newLhpn);
popup.add(newSpice);
}
popup.add(graph);
popup.add(probGraph);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class ImportAction extends AbstractAction {
private static final long serialVersionUID = 1L;
ImportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
//popup.add(importDot);
popup.add(importSbol);
popup.add(importSedml);
popup.add(importSbml);
popup.add(importBioModel);
}
else if (atacs) {
popup.add(importVhdl);
popup.add(importLpn);
popup.add(importCsp);
popup.add(importHse);
popup.add(importUnc);
popup.add(importRsg);
}
else {
popup.add(importVhdl);
popup.add(importS);
popup.add(importInst);
popup.add(importLpn);
popup.add(importSpice);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class ExportAction extends AbstractAction {
private static final long serialVersionUID = 1L;
ExportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
// popup.add(exportCsv);
// popup.add(exportDat);
// popup.add(exportEps);
// popup.add(exportJpg);
// popup.add(exportPdf);
// popup.add(exportPng);
// popup.add(exportSvg);
// popup.add(exportTsd);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class ModelAction extends AbstractAction {
private static final long serialVersionUID = 1L;
ModelAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(viewModGraph);
popup.add(viewModBrowser);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
public void mouseClicked(MouseEvent e) {
executeMouseClickEvent(e);
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e
.getClickCount(), e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x,
componentPoint.y, e.getClickCount(), e.isPopupTrigger()));
}
catch (Exception e1) {
}
}
}
public void windowLostFocus(WindowEvent e) {
}
public JMenuItem getExitButton() {
return exit;
}
/**
* This is the main method. It excecutes the BioSim GUI FrontEnd program.
*/
public static void main(String args[]) {
boolean lemaFlag = false, atacsFlag = false, LPN2SBML = true;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-lema")) {
lemaFlag = true;
}
else if (args[i].equals("-atacs")) {
atacsFlag = true;
}
}
}
if (!lemaFlag && !atacsFlag) {
String varname;
if (System.getProperty("mrj.version") != null)
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
else
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
try {
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the
// classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (UnsatisfiedLinkError e) {
e.printStackTrace();
System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname
+ " environment variable does not include\nthe" + " directory containing the libsbml library file.");
System.exit(1);
}
catch (ClassNotFoundException e) {
System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment"
+ " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file.");
System.exit(1);
}
catch (SecurityException e) {
System.err.println("Could not load the libSBML library files due to a" + " security exception.");
System.exit(1);
}
}
else {
/*
* String varname; if (System.getProperty("mrj.version") != null)
* varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname =
* "LD_LIBRARY_PATH"; // We're not on a Mac.
*/
try {
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the
// classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (UnsatisfiedLinkError e) {
LPN2SBML = false;
}
catch (ClassNotFoundException e) {
LPN2SBML = false;
}
catch (SecurityException e) {
LPN2SBML = false;
}
}
new Gui(lemaFlag, atacsFlag, LPN2SBML);
}
public void copySim(String newSim) {
try {
new File(root + separator + newSim).mkdir();
// new FileWriter(new File(root + separator + newSim + separator +
// ".sim")).close();
String oldSim = getTitleAt(tab.getSelectedIndex());
String[] s = new File(root + separator + oldSim).list();
String sbmlFile = "";
String propertiesFile = "";
String sbmlLoadFile = null;
String gcmFile = null;
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3
&& ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(root + separator + oldSim + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + newSim + separator + ss);
sbmlFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss));
FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
propertiesFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss.substring(ss.length() - 4).equals(".sim"))
&& !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + newSim + separator + ss));
}
FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
if (ss.substring(ss.length() - 4).equals(".pms")) {
if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) {
new File(root + separator + newSim + separator + ss).delete();
}
else {
new File(root + separator + newSim + separator + ss).renameTo(new File(root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim"));
}
ss = ss.substring(0, ss.length() - 4) + ".sim";
}
if (ss.substring(ss.length() - 4).equals(".sim")) {
try {
Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss));
if (scan.hasNextLine()) {
sbmlLoadFile = scan.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1];
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
// GCMParser parser = new GCMParser(root +
// separator + sbmlLoadFile);
// GeneticNetwork network =
// parser.buildNetwork();
// GeneticNetwork.setRoot(root + separator);
sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml");
// network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (scan.hasNextLine()) {
scan.nextLine();
}
scan.close();
}
catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
addToTree(newSim);
JTabbedPane simTab = new JTabbedPane();
simTab.addMouseListener(this);
AnalysisView reb2sac = new AnalysisView(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile, gcmFile, null, null);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Advanced Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options", reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
/*
SBML_Editor sbml = new SBML_Editor(root + separator + gcmFile.replace(".gcm",".xml"), reb2sac, log, this, root + separator + newSim, root
+ separator + newSim + separator + newSim + ".sim");
*/
ModelEditor gcm = new ModelEditor(root + separator, gcmFile, this, log, true, newSim, root + separator + newSim + separator
+ newSim + ".sim", reb2sac, false, false, lema);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
addModelViewTab(reb2sac, simTab, gcm);
simTab.addTab("Parameters", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
ElementsPanel elementsPanel = new ElementsPanel(gcm.getBioModel().getSBMLDocument(),
root + separator + newSim + separator + newSim + ".sim");
simTab.addTab("SBML Elements", elementsPanel);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setElementsPanel(elementsPanel);
}
/*
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator
+ newSim + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
*/
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Histogram", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
tab.setComponentAt(tab.getSelectedIndex(), simTab);
tab.setTitleAt(tab.getSelectedIndex(), newSim);
tab.getComponentAt(tab.getSelectedIndex()).setName(newSim);
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void refreshLearn(String learnName, boolean data) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(learnName)) {
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals("TSD Graph")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) {
((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)).refresh();
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "Number of molecules", learnName + " data",
"tsd.printer", root + separator + learnName, "Time", this, null, log, null, true, true));
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("TSD Graph");
}
}
else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals("Learn Options")) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof LearnGCM) {
}
else {
if (lema) {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root + separator + learnName, log, this));
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnGCM(root + separator + learnName, log, this));
}
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("Learn Options");
}
}
}
}
}
}
/*
private void updateGCM() {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).contains(".gcm")) {
((ModelEditor) tab.getComponentAt(i)).reloadFiles();
tab.setTitleAt(i, ((ModelEditor) tab.getComponentAt(i)).getFilename());
}
}
}
*/
public boolean updateOpenGCM(String gcmName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
if (gcmName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof ModelEditor) {
((ModelEditor) this.tab.getComponentAt(i)).reload(gcmName.replace(".gcm", ""));
((ModelEditor) this.tab.getComponentAt(i)).refresh();
((ModelEditor) this.tab.getComponentAt(i)).getSchematic().getGraph().buildGraph();
return true;
}
}
}
return false;
}
private void renameOpenGCMComponents(String gcmName, String oldname, String newName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
if (gcmName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof ModelEditor) {
((ModelEditor) this.tab.getComponentAt(i)).renameComponents(oldname, newName);
return;
}
}
}
}
public void updateAsyncViews(String updatedFile) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".ver";
String properties1 = root + separator + tab + separator + tab + ".synth";
String properties2 = root + separator + tab + separator + tab + ".lrn";
if (new File(properties).exists()) {
Verification verify = ((Verification) (this.tab.getComponentAt(i)));
verify.reload(updatedFile);
}
if (new File(properties1).exists()) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("Synthesis")) {
((Synthesis) (sim.getComponentAt(j))).reload(updatedFile);
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn Options")) {
((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile);
((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
}
}
public void updateViews(String updatedFile) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
if (this.tab.getComponentAt(i).getName().equals("GCM Editor")) {
//this is so that the grid species list gets updated if there's a diffusibility change
ModelEditor modelEditor = (ModelEditor) this.tab.getComponentAt(i);
modelEditor.getBioModel().updateGridSpecies(updatedFile.replace(".gcm",""));
modelEditor.getSpeciesPanel().refreshSpeciesPanel(modelEditor.getBioModel());
}
if (this.tab.getComponentAt(i).getName().equals("SBOL Browser")) {
int currentIndex = this.tab.getSelectedIndex();
this.tab.setComponentAt(i, new SBOLBrowser(this, tree.getFile()));
this.tab.setSelectedIndex(currentIndex);
}
String properties = root + separator + tab + separator + tab + ".sim";
String properties2 = root + separator + tab + separator + tab + ".lrn";
if (new File(properties).exists()) {
String check = "";
try {
Scanner s = new Scanner(new File(properties));
if (s.hasNextLine()) {
check = s.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
s.close();
}
catch (Exception e) {
e.printStackTrace();
}
if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
// String tabName = sim.getComponentAt(j).getName();
// boolean b =
// sim.getComponentAt(j).getName().equals("ModelViewMovie");
if (sim.getComponentAt(j) instanceof AnalysisView) {
((AnalysisView) sim.getComponentAt(j)).updateProperties();
}
/*
else if (sim.getComponentAt(j).getName().equals("SBML Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim", ".temp")));
try {
boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty();
((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true, true);
if (updatedFile.contains(".gcm")) {
// GCMParser parser = new GCMParser(root +
// separator + updatedFile);
// GeneticNetwork network =
// parser.buildNetwork();
// GeneticNetwork.setRoot(root + separator);
// network.mergeSBML(root + separator + tab
// + separator + updatedFile.replace(".gcm",
// ".xml"));
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j,
root + separator + tab + separator + updatedFile.replace(".gcm", ".xml"));
}
else {
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile);
}
((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty);
}
catch (Exception e) {
e.printStackTrace();
}
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(properties));
sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j))).getElementsPanel());
sim.getComponentAt(j + 1).setName("");
}
*/
else if (sim.getComponentAt(j).getName().equals("GCM Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim", ".temp")));
try {
boolean dirty = ((ModelEditor) (sim.getComponentAt(j))).isDirty();
((ModelEditor) (sim.getComponentAt(j))).saveParams(false, "", true);
((ModelEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm", "").replace(".xml", ""));
((ModelEditor) (sim.getComponentAt(j))).refresh();
((ModelEditor) (sim.getComponentAt(j))).loadParams();
((ModelEditor) (sim.getComponentAt(j))).setDirty(dirty);
}
catch (Exception e) {
e.printStackTrace();
}
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(properties));
/*
SBML_Editor sbml = new SBML_Editor(root + separator + ((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile(),
((Reb2Sac) sim.getComponentAt(0)), log, this, root + separator + tab, root + separator + tab + separator
+ tab + ".sim");
*/
ElementsPanel elementsPanel = new ElementsPanel(((ModelEditor) (sim.getComponentAt(j))).getBioModel().getSBMLDocument(),
root + separator + tab + separator + tab + ".sim");
sim.setComponentAt(j + 1, elementsPanel);
sim.getComponentAt(j + 1).setName("");
((ModelEditor) (sim.getComponentAt(j))).setElementsPanel(elementsPanel);
for (int k = 0; k < sim.getTabCount(); k++) {
if (sim.getComponentAt(k) instanceof MovieContainer) {
// display the schematic and reload the grid
((MovieContainer) (sim.getComponentAt(k))).display();
((MovieContainer) (sim.getComponentAt(k))).reloadGrid();
}
}
}
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn Options")) {
((LearnGCM) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
// ArrayList<String> saved = new ArrayList<String>();
// if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) {
// saved.add(this.getTitleAt(i));
// GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i);
// if (gcm.getSBMLFile().equals(updatedFile)) {
// gcm.save("save");
// String[] files = new File(root).list();
// for (String s : files) {
// if (s.endsWith(".gcm") && !saved.contains(s)) {
// GCMFile gcm = new GCMFile(root);
// gcm.load(root + separator + s);
// if (gcm.getSBMLFile().equals(updatedFile)) {
// updateViews(s);
}
}
private void updateViewNames(String oldname, String newname) {
File work = new File(root);
String[] fileList = work.list();
String[] temp = oldname.split(separator);
oldname = temp[temp.length - 1];
for (int i = 0; i < fileList.length; i++) {
String tabTitle = fileList[i];
String properties = root + separator + tabTitle + separator + tabTitle + ".ver";
String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth";
String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn";
if (new File(properties).exists()) {
String check;
Properties p = new Properties();
try {
FileInputStream load = new FileInputStream(new File(properties));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("verification.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties));
p.store(out, properties);
}
}
catch (Exception e) {
// log.addText("verification");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties1).exists()) {
String check;
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties1));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("synthesis.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties1));
p.store(out, properties1);
}
}
catch (Exception e) {
// log.addText("synthesis");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("learn.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties2));
p.store(out, properties2);
}
}
catch (Exception e) {
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
}
updateAsyncViews(newname);
}
public void enableTabMenu(int selectedTab) {
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
saveAs.setEnabled(false);
saveSBOL.setEnabled(false);
saveModel.setEnabled(false);
run.setEnabled(false);
check.setEnabled(false);
exportMenu.setEnabled(false);
exportSBML.setEnabled(false);
exportFlatSBML.setEnabled(false);
exportSBOL.setEnabled(false);
exportDataMenu.setEnabled(false);
exportImageMenu.setEnabled(false);
exportMovieMenu.setEnabled(false);
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportEps.setEnabled(false);
exportJpg.setEnabled(false);
exportPdf.setEnabled(false);
exportPng.setEnabled(false);
exportSvg.setEnabled(false);
exportTsd.setEnabled(false);
exportAvi.setEnabled(false);
exportMp4.setEnabled(false);
saveAsVerilog.setEnabled(false);
viewCircuit.setEnabled(false);
viewSG.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewLearnedModel.setEnabled(false);
refresh.setEnabled(false);
select.setEnabled(false);
cut.setEnabled(false);
addCompartment.setEnabled(false);
addSpecies.setEnabled(false);
addReaction.setEnabled(false);
addComponent.setEnabled(false);
addPromoter.setEnabled(false);
addVariable.setEnabled(false);
addBoolean.setEnabled(false);
addPlace.setEnabled(false);
addTransition.setEnabled(false);
addRule.setEnabled(false);
addConstraint.setEnabled(false);
addEvent.setEnabled(false);
addSelfInfl.setEnabled(false);
moveLeft.setEnabled(false);
moveRight.setEnabled(false);
moveUp.setEnabled(false);
moveDown.setEnabled(false);
undo.setEnabled(false);
redo.setEnabled(false);
if (selectedTab != -1) {
tab.setSelectedIndex(selectedTab);
}
Component comp = tab.getSelectedComponent();
if (comp instanceof ModelEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
checkButton.setEnabled(true);
exportButton.setEnabled(true);
save.setEnabled(true);
saveAs.setEnabled(true);
saveSBOL.setEnabled(true);
check.setEnabled(true);
select.setEnabled(true);
cut.setEnabled(true);
if (!((ModelEditor) comp).isGridEditor()) {
addCompartment.setEnabled(true);
addSpecies.setEnabled(true);
addReaction.setEnabled(true);
addPromoter.setEnabled(true);
addVariable.setEnabled(true);
addBoolean.setEnabled(true);
addPlace.setEnabled(true);
addTransition.setEnabled(true);
addRule.setEnabled(true);
addConstraint.setEnabled(true);
addEvent.setEnabled(true);
addSelfInfl.setEnabled(true);
moveLeft.setEnabled(true);
moveRight.setEnabled(true);
moveUp.setEnabled(true);
moveDown.setEnabled(true);
}
addComponent.setEnabled(true);
undo.setEnabled(true);
redo.setEnabled(true);
exportMenu.setEnabled(true);
exportSBML.setEnabled(true);
exportFlatSBML.setEnabled(true);
exportSBOL.setEnabled(true);
exportImageMenu.setEnabled(true);
exportJpg.setEnabled(true);
}
else if (comp instanceof SBOLBrowser) {
// save.setEnabled(true);
}
else if (comp instanceof LHPNEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
save.setEnabled(true);
saveAs.setEnabled(true);
viewCircuit.setEnabled(true);
exportMenu.setEnabled(true);
exportSBML.setEnabled(true);
exportFlatSBML.setEnabled(true);
}
/*
else if (comp instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
checkButton.setEnabled(true);
save.setEnabled(true);
saveAs.setEnabled(true);
check.setEnabled(true);
}
*/
else if (comp instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
refreshButton.setEnabled(true);
exportButton.setEnabled(true);
save.setEnabled(true);
saveAs.setEnabled(true);
refresh.setEnabled(true);
exportMenu.setEnabled(true);
exportImageMenu.setEnabled(true);
if (((Graph) comp).isTSDGraph()) {
exportDataMenu.setEnabled(true);
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
// else {
// exportCsv.setEnabled(false);
// exportDat.setEnabled(false);
// exportTsd.setEnabled(false);
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
Component learnComponent = null;
Boolean learn = false;
Boolean learnLHPN = false;
for (String s : new File(root + separator + getTitleAt(tab.getSelectedIndex())).list()) {
if (s.contains("_sg.dot")) {
viewSG.setEnabled(true);
}
}
for (Component c : ((JTabbedPane) comp).getComponents()) {
if (c instanceof LearnGCM) {
learn = true;
learnComponent = c;
}
else if (c instanceof LearnLHPN) {
learnLHPN = true;
learnComponent = c;
}
}
if (component instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(true);
exportButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
if (learn) {
if (new File(root + separator + getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) {
viewLearnedModel.setEnabled(true);
}
run.setEnabled(true);
saveModel.setEnabled(((LearnGCM) learnComponent).getViewModelEnabled());
saveAsVerilog.setEnabled(false);
viewCircuit.setEnabled(((LearnGCM) learnComponent).getViewModelEnabled());
viewLog.setEnabled(((LearnGCM) learnComponent).getViewLogEnabled());
}
else if (learnLHPN) {
run.setEnabled(true);
saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
saveAsVerilog.setEnabled(false);
viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled());
}
saveAs.setEnabled(true);
refresh.setEnabled(true);
exportMenu.setEnabled(true);
exportImageMenu.setEnabled(true);
if (((Graph) component).isTSDGraph()) {
exportDataMenu.setEnabled(true);
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
// else {
// exportCsv.setEnabled(false);
// exportDat.setEnabled(false);
// exportTsd.setEnabled(false);
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
}
else if (component instanceof AnalysisView) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
}
/*
else if (component instanceof SBML_Editor) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
}
*/
else if (component instanceof MovieContainer) {
exportMenu.setEnabled(true);
exportMovieMenu.setEnabled(true);
exportAvi.setEnabled(true);
exportMp4.setEnabled(true);
exportImageMenu.setEnabled(true);
exportJpg.setEnabled(true);
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
}
else if (component instanceof ModelEditor) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
}
else if (component instanceof LearnGCM) {
if (new File(root + separator + getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) {
viewLearnedModel.setEnabled(true);
}
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
viewCircuit.setEnabled(((LearnGCM) component).getViewModelEnabled());
viewLog.setEnabled(((LearnGCM) component).getViewLogEnabled());
saveModel.setEnabled(((LearnGCM) component).getViewModelEnabled());
}
else if (component instanceof LearnLHPN) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
viewLearnedModel.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled());
saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
}
else if (component instanceof DataManager) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
saveAs.setEnabled(true);
if (learn) {
if (new File(root + separator + getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) {
viewLearnedModel.setEnabled(true);
}
run.setEnabled(true);
saveModel.setEnabled(((LearnGCM) learnComponent).getViewModelEnabled());
viewCircuit.setEnabled(((LearnGCM) learnComponent).getViewModelEnabled());
viewLog.setEnabled(((LearnGCM) learnComponent).getViewLogEnabled());
}
else if (learnLHPN) {
run.setEnabled(true);
saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled());
}
}
else if (component instanceof JPanel) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
if (learn) {
if (new File(root + separator + getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) {
viewLearnedModel.setEnabled(true);
}
run.setEnabled(true);
saveModel.setEnabled(((LearnGCM) learnComponent).getViewModelEnabled());
viewCircuit.setEnabled(((LearnGCM) learnComponent).getViewModelEnabled());
viewLog.setEnabled(((LearnGCM) learnComponent).getViewLogEnabled());
}
else if (learnLHPN) {
run.setEnabled(true);
saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled());
viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled());
}
}
else if (component instanceof JScrollPane) {
saveButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled());
viewLog.setEnabled(((Verification) comp).getViewLogEnabled());
}
else if (comp.getName().equals("Synthesis")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
save.setEnabled(true);
run.setEnabled(true);
viewRules.setEnabled(true/*((Synthesis) comp).getViewRulesEnabled()*/);
viewTrace.setEnabled(true/*((Synthesis) comp).getViewTraceEnabled()*/);
viewCircuit.setEnabled(true/*((Synthesis) comp).getViewCircuitEnabled()*/);
viewLog.setEnabled(true/*((Synthesis) comp).getViewLogEnabled()*/);
}
}
else if (comp instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
save.setEnabled(true);
saveAs.setEnabled(true);
}
}
private void enableTreeMenu() {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createVer.setEnabled(false);
createSbml.setEnabled(false);
check.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewModel.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLHPN.setEnabled(false);
saveAsVerilog.setEnabled(false);
if (tree.getFile() != null) {
if (tree.getFile().equals(root)) {
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graph");
viewModBrowser.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("simulate");
createLearn.setEnabled(true);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
viewModGraph.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSbml.setEnabled(true);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".grf")) {
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbol")) {
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
}
else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
}
else if (tree.getFile().length() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) {
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
}
else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewLHPN.setEnabled(true);
}
else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("createAnalysis");
if (lema) {
createLearn.setEnabled(true);
}
createSynth.setEnabled(true);
createVer.setEnabled(true);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewLHPN.setEnabled(true);
saveAsVerilog.setEnabled(true);
}
else if (tree.getFile().length() > 3
&& (tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd") || tree.getFile()
.substring(tree.getFile().length() - 4).equals(".rsg"))) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewLHPN.setEnabled(true);
}
else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s") || tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) {
createAnal.setEnabled(true);
createVer.setEnabled(true);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewLHPN.setEnabled(true);
}
else if (new File(tree.getFile()).isDirectory()) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim || synth || ver || learn) {
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
}
}
}
}
public String getRoot() {
return root;
}
public boolean checkFiles(String input, String output) {
input = input.replaceAll("
output = output.replaceAll("
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
if (input.toLowerCase().equals(output.toLowerCase())) {
Object[] options = { "Ok" };
JOptionPane.showOptionDialog(frame, "Files are the same.", "Files Same", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
return false;
}
}
else {
if (input.equals(output)) {
Object[] options = { "Ok" };
JOptionPane.showOptionDialog(frame, "Files are the same.", "Files Same", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
return false;
}
}
return true;
}
public boolean overwrite(String fullPath, String name) {
if (new File(fullPath).exists()) {
String[] views = canDelete(name);
Object[] options = { "Overwrite", "Cancel" };
int value;
if (views.length == 0) {
value = JOptionPane.showOptionDialog(frame, name + " already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
else {
String view = "";
String gcms = "";
for (int i = 0; i < views.length; i++) {
if (views[i].endsWith(".gcm")) {
gcms += views[i] + "\n";
}
else {
view += views[i] + "\n";
}
}
String message;
if (gcms.equals("")) {
message = "The file, " + name + ", already exists, and\nit is linked to the following views:\n\n" + view
+ "\n\nAre you sure you want to overwrite?";
}
else if (view.equals("")) {
message = "The file, " + name + ", already exists, and\nit is linked to the following gcms:\n\n" + gcms
+ "\n\nAre you sure you want to overwrite?";
}
else {
message = "The file, " + name + ", already exists, and\nit is linked to the following views:\n\n" + views
+ "\n\nand\nit is linked to the following gcms:\n\n" + gcms + "\n\nAre you sure you want to overwrite?";
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
value = JOptionPane.showOptionDialog(frame, scroll, "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
//value = JOptionPane.NO_OPTION;
}
if (value == JOptionPane.YES_OPTION) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (getTitleAt(i).equals(name)) {
tab.remove(i);
}
}
File dir = new File(fullPath);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
return true;
}
else {
return false;
}
}
else {
return true;
}
}
/*
public boolean updateOpenSBML(String sbmlName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
if (sbmlName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof SBML_Editor) {
SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null);
this.tab.setComponentAt(i, newSBML);
this.tab.getComponentAt(i).setName("SBML Editor");
newSBML.save(false, "", false, true);
return true;
}
}
}
return false;
}
*/
public void updateTabName(String oldName, String newName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
if (oldName.equals(tab)) {
this.tab.setTitleAt(i, newName);
}
}
}
public boolean updateOpenLHPN(String lhpnName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.getTitleAt(i);
if (lhpnName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof LHPNEditor) {
LHPNEditor newLHPN = new LHPNEditor(root, lhpnName, null, this, log);
this.tab.setComponentAt(i, newLHPN);
this.tab.getComponentAt(i).setName("LHPN Editor");
return true;
}
}
}
return false;
}
private String[] canDelete(String filename) {
ArrayList<String> views = new ArrayList<String>();
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
scan.close();
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".ver").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".synth").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
check = check.replace(".gcm",".xml");
if (check.equals(filename)) {
views.add(s);
}
}
else if (s.endsWith(".xml") && filename.endsWith(".xml")) {
BioModel gcm = new BioModel(root);
try {
gcm.load(root + separator + s);
if (gcm.getSBMLComp()!=null) {
for (long i = 0; i < gcm.getSBMLComp().getNumExternalModelDefinitions(); i++) {
ExternalModelDefinition extModel = gcm.getSBMLComp().getExternalModelDefinition(i);
if (extModel.getSource().equals("file:"+ filename)) {
views.add(s);
break;
}
}
}
} catch (Exception e) {
}
}
}
String[] usingViews = views.toArray(new String[0]);
sort(usingViews);
return usingViews;
}
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
private void reassignViews(String oldName, String newName) {
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
ArrayList<String> copy = new ArrayList<String>();
Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
if (check.equals(oldName)) {
while (scan.hasNextLine()) {
copy.add(scan.nextLine());
}
scan.close();
FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim"));
out.write((newName + "\n").getBytes());
for (String cop : copy) {
out.write((cop + "\n").getBytes());
}
out.close();
}
else {
scan.close();
}
}
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
if (check.equals(oldName)) {
p.setProperty("genenet.file", newName);
FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn"));
p.store(store, "Learn File Data");
store.close();
}
}
}
catch (Exception e) {
}
}
}
}
}
protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText, String altText) {
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imageName));
return button;
}
private String changeIdToPortRef(SBaseRef sbaseRef,BioModel bioModel) {
String id = "";
if (sbaseRef.isSetSBaseRef()) {
BioModel subModel = new BioModel(root);
Submodel submodel = bioModel.getSBMLCompModel().getSubmodel(sbaseRef.getIdRef());
String extModel = bioModel.getSBMLComp().getExternalModelDefinition(submodel.getModelRef())
.getSource().replace("file://","").replace("file:","").replace(".gcm",".xml");
subModel.load(root + separator + extModel);
id += changeIdToPortRef(sbaseRef.getSBaseRef(),subModel);
subModel.save(root + separator + extModel);
}
if (sbaseRef.isSetIdRef()) {
Port port = bioModel.getPortBySBaseRef(sbaseRef);
SBase sbase = bioModel.getSBMLDocument().getElementBySId(sbaseRef.getIdRef());
if (sbase!=null) {
if (id.equals("")) {
id = sbase.getElementName() + "__" + sbaseRef.getIdRef();
} else {
id = id + "__" + sbaseRef.getIdRef();
}
if (port == null) {
if (sbase!=null) {
port = bioModel.getSBMLCompModel().createPort();
port.setId(id);
port.setIdRef(sbaseRef.getIdRef());
port.setSBaseRef(sbaseRef.getSBaseRef());
}
}
sbaseRef.unsetIdRef();
sbaseRef.unsetSBaseRef();
sbaseRef.setPortRef(port.getId());
return id;
} else {
return "";
}
}
if (sbaseRef.isSetMetaIdRef()) {
Port port = bioModel.getPortBySBaseRef(sbaseRef);
SBase sbase = bioModel.getSBMLDocument().getElementByMetaId(sbaseRef.getMetaIdRef());
if (id.equals("")) {
id = sbase.getElementName() + "__" + sbaseRef.getMetaIdRef();
} else {
id = id + "__" + sbaseRef.getMetaIdRef();
}
if (port == null) {
if (sbase!=null) {
port = bioModel.getSBMLCompModel().createPort();
port.setId(id);
port.setMetaIdRef(sbaseRef.getMetaIdRef());
port.setSBaseRef(sbaseRef.getSBaseRef());
}
}
sbaseRef.unsetMetaIdRef();
sbaseRef.unsetSBaseRef();
sbaseRef.setPortRef(port.getId());
return id;
}
return "";
}
private boolean updatePortMap(CompSBMLDocumentPlugin sbmlComp,CompSBasePlugin sbmlSBase,BioModel subModel,String subModelId) {
boolean updated = false;
for (long k = 0; k < sbmlSBase.getNumReplacedElements(); k++) {
ReplacedElement replacement = sbmlSBase.getReplacedElement(k);
if (replacement.getSubmodelRef().equals(subModelId)) {
changeIdToPortRef(replacement,subModel);
updated = true;
}
}
if (sbmlSBase.isSetReplacedBy()) {
Replacing replacement = sbmlSBase.getReplacedBy();
if (replacement.getSubmodelRef().equals(subModelId)) {
changeIdToPortRef(replacement,subModel);
updated = true;
}
}
return updated;
}
private boolean updateReplacementsDeletions(SBMLDocument document, CompSBMLDocumentPlugin sbmlComp,
CompModelPlugin sbmlCompModel) {
for (long i = 0; i < sbmlCompModel.getNumSubmodels(); i++) {
BioModel subModel = new BioModel(root);
Submodel submodel = sbmlCompModel.getSubmodel(i);
String extModel = sbmlComp.getExternalModelDefinition(submodel.getModelRef())
.getSource().replace("file://","").replace("file:","").replace(".gcm",".xml");
subModel.load(root + separator + extModel);
SBaseList elements = document.getModel().getListOfAllElements();
for (long j = 0; j < elements.getSize(); j++) {
SBase sbase = elements.get(j);
CompSBasePlugin sbmlSBase = (CompSBasePlugin)sbase.getPlugin("comp");
if (sbmlSBase!=null) {
if (updatePortMap(sbmlComp,sbmlSBase,subModel,submodel.getId())) {
elements = document.getModel().getListOfAllElements();
}
}
}
for (long j = 0; j < submodel.getNumDeletions(); j++) {
Deletion deletion = submodel.getDeletion(j);
changeIdToPortRef(deletion,subModel);
}
subModel.save(root + separator + extModel);
}
return true;
}
private boolean extractModelDefinitions(CompSBMLDocumentPlugin sbmlComp,CompModelPlugin sbmlCompModel) {
for (long i=0; i < sbmlComp.getNumModelDefinitions(); i++) {
ModelDefinition md = sbmlComp.getModelDefinition(i);
String extId = md.getId();
if (overwrite(root + separator + extId + ".xml",extId + ".xml")) {
org.sbml.libsbml.Model model = new org.sbml.libsbml.Model(md);
SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION);
document.setModel(model);
document.enablePackage(LayoutExtension.getXmlnsL3V1V1(), "layout", true);
document.setPackageRequired("layout", false);
//LayoutModelPlugin documentLayout = (LayoutModelPlugin)document.getModel().getPlugin("layout");
document.enablePackage(CompExtension.getXmlnsL3V1V1(), "comp", true);
document.setPackageRequired("comp", true);
((CompSBMLDocumentPlugin)document.getPlugin("comp")).setRequired(true);
CompSBMLDocumentPlugin documentComp = (CompSBMLDocumentPlugin)document.getPlugin("comp");
CompModelPlugin documentCompModel = (CompModelPlugin)document.getModel().getPlugin("comp");
ArrayList<String> comps = new ArrayList<String>();
for (long j=0; j < documentCompModel.getNumSubmodels(); j++) {
String subModelType = documentCompModel.getSubmodel(j).getModelRef();
if (!comps.contains(subModelType)) {
ExternalModelDefinition extModel = documentComp.createExternalModelDefinition();
extModel.setId(subModelType);
extModel.setSource("file:" + subModelType + ".xml");
comps.add(subModelType);
}
}
// Make compartment enclosing
if (document.getModel().getNumCompartments()==0) {
Compartment c = document.getModel().createCompartment();
c.setId("default");
c.setSize(1);
c.setSpatialDimensions(3);
c.setConstant(true);
}
updateReplacementsDeletions(document, documentComp, documentCompModel);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + extId + ".xml");
addToTree(extId+".xml");
if (sbmlComp.getExternalModelDefinition(extId) == null) {
for (long j=0; j < sbmlCompModel.getNumSubmodels(); j++) {
Submodel submodel = sbmlCompModel.getSubmodel(j);
if (submodel.getModelRef().equals(extId)) {
ExternalModelDefinition extModel = sbmlComp.createExternalModelDefinition();
extModel.setSource("file:" + extId + ".xml");
extModel.setId(extId);
break;
}
}
}
/*
if (enclosed && extModel.getAnnotationString().contains("compartment") == false)
extModel.appendAnnotation("compartment");
else
extModel.setAnnotation(extModel.getAnnotationString().replace("compartment",""));
*/
} else {
return false;
}
}
while (sbmlComp.getNumModelDefinitions() > 0) {
sbmlComp.removeModelDefinition(0);
}
for (long i = 0; i < sbmlComp.getNumExternalModelDefinitions(); i++) {
ExternalModelDefinition extModel = sbmlComp.getExternalModelDefinition(i);
if (extModel.isSetModelRef()) {
String oldId = extModel.getId();
extModel.setSource("file:" + extModel.getModelRef() + ".xml");
extModel.setId(extModel.getModelRef());
extModel.unsetModelRef();
for (long j=0; j < sbmlCompModel.getNumSubmodels(); j++) {
Submodel submodel = sbmlCompModel.getSubmodel(j);
if (submodel.getModelRef().equals(oldId)) {
submodel.setModelRef(extModel.getId());
}
}
}
}
return true;
}
public static SBMLDocument readSBML(String filename) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(filename);
if (document.getModel().isSetId()) {
document.getModel().setId(document.getModel().getId().replace(".","_"));
}
JTextArea messageArea = new JTextArea();
messageArea.append("Conversion to SBML level " + SBML_LEVEL + " version " + SBML_VERSION + " produced the errors listed below. ");
messageArea.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
long numErrors = 0;
if (SBMLLevelVersion.equals("L2V4")) {
numErrors = document.checkL2v4Compatibility();
}
else {
numErrors = document.checkL3v1Compatibility();
}
if (numErrors > 0) {
display = true;
messageArea.append("
messageArea.append(filename);
messageArea.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
if (display) {
final JFrame f = new JFrame("SBML Conversion Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
Object[] options = { "Dismiss" };
JOptionPane.showOptionDialog(frame, scroll, "SBML Conversion Errors and Warnings", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
}
if (document.getLevel() < SBML_LEVEL || document.getVersion() < SBML_VERSION) {
document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION,false);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, filename);
document = reader.readSBML(filename);
}
return document;
}
public static void checkModelCompleteness(SBMLDocument document) {
JTextArea messageArea = new JTextArea();
messageArea.append("Model is incomplete. Cannot be simulated until the following information is provided.\n");
boolean display = false;
org.sbml.libsbml.Model model = document.getModel();
ListOf list = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) list.get(i);
if (!compartment.isSetSize()) {
messageArea.append("
messageArea.append("Compartment " + compartment.getId() + " needs a size.\n");
display = true;
}
}
list = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) list.get(i);
if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) {
messageArea.append("
messageArea.append("Species " + species.getId() + " needs an initial amount or concentration.\n");
display = true;
}
}
list = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) list.get(i);
if (!(parameter.isSetValue())) {
messageArea.append("
messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n");
display = true;
}
}
list = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) list.get(i);
if (!(reaction.isSetKineticLaw())) {
messageArea.append("
messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n");
display = true;
}
else {
ListOf params = reaction.getKineticLaw().getListOfParameters();
for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) {
Parameter param = (Parameter) params.get(j);
if (!(param.isSetValue())) {
messageArea.append("
messageArea.append("Local parameter " + param.getId() + " for reaction " + reaction.getId() + " needs an initial value.\n");
display = true;
}
}
}
}
if (display) {
final JFrame f = new JFrame("SBML Model Completeness Errors");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
}
static final String SFILELINE = "input (\\S+?)\n";
private static final String overlap = "|->";
}
|
package org.skyve.impl.util;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.UUID;
import java.util.logging.Logger;
import org.hibernate.internal.util.SerializationHelper;
import org.hibernate.proxy.HibernateProxy;
import org.skyve.CORE;
import org.skyve.cache.CSRFTokenCacheConfig;
import org.skyve.cache.CacheConfig;
import org.skyve.cache.ConversationCacheConfig;
import org.skyve.cache.HibernateCacheConfig;
import org.skyve.domain.Bean;
import org.skyve.impl.bind.BindUtil;
import org.skyve.impl.domain.AbstractPersistentBean;
import org.skyve.impl.metadata.model.document.AssociationImpl;
import org.skyve.impl.persistence.AbstractPersistence;
import org.skyve.impl.util.json.Minifier;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.document.Association.AssociationType;
import org.skyve.metadata.model.document.Collection;
import org.skyve.metadata.model.document.Collection.CollectionType;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.model.document.Inverse;
import org.skyve.metadata.model.document.Reference;
import org.skyve.metadata.model.document.Relation;
import org.skyve.metadata.module.Module;
import org.skyve.metadata.user.User;
import org.skyve.persistence.DataStore;
import org.skyve.util.BeanVisitor;
import org.skyve.util.JSON;
import net.gcardone.junidecode.Junidecode;
public class UtilImpl {
/**
* Disallow instantiation
*/
private UtilImpl() {
// no-op
}
/**
* The raw configuration data from reading the JSON.
*/
public static Map<String, Object> CONFIGURATION = null;
/**
* The raw configuration data from reading the override JSON.
* This will be an empty map if there are no overrides defined.
*/
public static Map<String, Object> OVERRIDE_CONFIGURATION;
// For versioning javascript/css etc for web site
public static final String WEB_RESOURCE_FILE_VERSION = "44";
public static final String SKYVE_VERSION = "8.1.0-SNAPSHOT";
public static final String SMART_CLIENT_DIR = "isomorphic120";
public static boolean XML_TRACE = false;
public static boolean HTTP_TRACE = false;
public static boolean QUERY_TRACE = false;
public static boolean COMMAND_TRACE = false;
public static boolean FACES_TRACE = false;
public static boolean SQL_TRACE = false;
public static boolean CONTENT_TRACE = false;
public static boolean SECURITY_TRACE = false;
public static boolean BIZLET_TRACE = false;
public static boolean DIRTY_TRACE = false;
public static boolean PRETTY_SQL_OUTPUT = false;
public static final Logger LOGGER = Logger.getLogger("SKYVE");
// the name of the application archive, e.g. typically projectName.war or projectName.ear
public static String ARCHIVE_NAME;
// This is set in the web.xml but defaults to windows
// as a dev environment for design time and generation gear
public static String CONTENT_DIRECTORY = "/_/Apps/content/";
// The cron expression to use to fire off the content garbage collection
// Defaults to run at 7 past the hour every hour.
public static String CONTENT_GC_CRON = "0 7 0/1 1/1 * ? *";
// The cron expression to use to fire off the evict expired state job
// Defaults to run at 37 past midnight every day.
public static String STATE_EVICT_CRON = "0 37 0 1/1 * ? *";
// Should the attachments be stored on the file system or inline.
public static boolean CONTENT_FILE_STORAGE = true;
// The arguments to send to the TCP server when running the content management in server mode.
public static String CONTENT_SERVER_ARGS = null;
// Allowed file upload file names - default is a blacklist of harmful "executable" files
public static String UPLOADS_FILE_WHITELIST_REGEX = "^.+\\.(?!(ADE|ADP|APP|ASA|ASP|BAS|BAT|CAB|CER|CHM|CMD|COM|CPL|CRT|CSH|DLL|DOCM|DOTM|EXE|FXP|HLP|HTA|HTR|INF|INS|ISP|ITS|JS|JSE|KSH|LNK|MAD|MAF|MAG|MAM|MAQ|MAR|MAS|MAT|MAU|MAV|MAW|MDA|MDB|MDE|MDT|MDW|MDZ|MSC|MSI|MSP|MST|OCX|OPS|PCD|PIF|POTM|PPAM|PPSM|PPTM|PRF|PRG|REG|SCF|SO|SCR|SCT|SHB|SHS|TMP|URL|VB|VBE|VBS|VBX|VSMACROS|VSS|VST|VSW|WS|WSC|WSF|WSH|XLAM|XLSB|XLSM|XSTM|XSL)$)([^.]+$)";
// Max file upload size - default is 10MB the same as wildfly default
public static int UPLOADS_FILE_MAXIMUM_SIZE_IN_MB = 10;
// Allowed content upload file names - default is a blacklist of harmful "executable" files
public static String UPLOADS_CONTENT_WHITELIST_REGEX = UPLOADS_FILE_WHITELIST_REGEX;
// Max content upload size - default is 10MB the same as wildfly default
public static int UPLOADS_CONTENT_MAXIMUM_SIZE_IN_MB = UPLOADS_FILE_MAXIMUM_SIZE_IN_MB;
// Allowed image upload file names - default is a blacklist of harmful "executable" files
public static String UPLOADS_IMAGE_WHITELIST_REGEX = UPLOADS_FILE_WHITELIST_REGEX;
// Max image upload size - default is 10MB the same as wildfly default
public static int UPLOADS_IMAGE_MAXIMUM_SIZE_IN_MB = UPLOADS_FILE_MAXIMUM_SIZE_IN_MB;
// Allowed bizport upload file names - default is a XLS and XLSX files
public static String UPLOADS_BIZPORT_WHITELIST_REGEX = "^.+\\.(XLS|XLSX)$";
// Max bizport upload size - default is 10MB the same as wildfly default
public static int UPLOADS_BIZPORT_MAXIMUM_SIZE_IN_MB = UPLOADS_FILE_MAXIMUM_SIZE_IN_MB;
// Where to look for add-ins - defaults to <content.directory>/addins/
public static String ADDINS_DIRECTORY = null;
// The number of threads that are allowed to serve thumb nails at once.
// Too many threads can cause out of memory errors.
// You can calculate this as concurrentThreads * memory usage determined by targetSize below
// For the default of 10 concurrentThreads at 4MB the approximately max memory usage is 40MB.
public static int THUMBNAIL_CONCURRENT_THREADS = 10;
// The sub-sampling doesn't kick in until the image's largest dimension is at least double the target size
// Then it sub-samples pixels by 2, 3 etc.
// You can calculate the approximate max memory used per image with
// targetSize * 2 (double width) * targetSize * 2 (double height) * 4 (ARGB bytes per pixel) / 1024 (KB) / 1024 (MB)
// assuming the images are relatively square.
// target of 256 = max 1MB; target of 512 = max 4MB, target of 1024 = max 16MB per image.
public static int THUMBNAIL_SUBSAMPLING_MINIMUM_TARGET_SIZE = 512;
// Thumbnails can be stored on the file system or generated on the fly each time
public static boolean THUMBNAIL_FILE_STORAGE = true;
// Where to put thumbnails if fileStorage is true - defaults to <content.directory>/SKYVE_THUMBNAILS/
// Skyve will recreate this folder if it is deleted whilst running but if defined it must exist at startup.
public static String THUMBNAIL_DIRECTORY = null;
// This is set in web.xml and should only be used when the APP server in use
// doesn't allow us to get the absolute path of a resource - jboss 4.0.5.GA, WebLogic or any zipped deployment
public static String APPS_JAR_DIRECTORY;
public static boolean DEV_MODE = false;
// If it is null, then the login infrastructure will prompt for the customer name.
// If it is set, the customer will be set to that value always.
// This property is also used for single sign on purposes.
public static String CUSTOMER = null;
public static String SERVER_URL = null;
// eg /bizhub/web
public static String SKYVE_CONTEXT = null;
// eg /init.biz
public static String HOME_URI = null;
// This is the path on the server file system of the web context root
public static String SKYVE_CONTEXT_REAL_PATH = null;
// This is the path on the server file system of the properties file
public static String PROPERTIES_FILE_PATH = null;
// Implementations of Key SKYVE classes
public static String SKYVE_REPOSITORY_CLASS = null;
public static String SKYVE_PERSISTENCE_CLASS = null;
public static String SKYVE_DYNAMIC_PERSISTENCE_CLASS = null;
public static String SKYVE_CONTENT_MANAGER_CLASS = null;
public static String SKYVE_NUMBER_GENERATOR_CLASS = null;
// The directory used for temp files for file uploads etc
public static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");
public static boolean USING_JPA = false;
// For caches
public static ConversationCacheConfig CONVERSATION_CACHE = null;
public static CSRFTokenCacheConfig CSRF_TOKEN_CACHE = null;
public static List<HibernateCacheConfig> HIBERNATE_CACHES = new ArrayList<>();
public static boolean HIBERNATE_FAIL_ON_MISSING_CACHE = false;
public static List<CacheConfig<? extends Serializable, ? extends Serializable>> APP_CACHES = new ArrayList<>();
// For database
public static Map<String, DataStore> DATA_STORES = new TreeMap<>();
public static DataStore DATA_STORE = null;
public static boolean DDL_SYNC = true;
public static String CATALOG = null;
public static String SCHEMA = null;
// For E-Mail
public static String SMTP = null;
public static int SMTP_PORT = 0;
public static String SMTP_UID = null;
public static String SMTP_PWD = null;
// Extra java mail properties
public static Map<String, String> SMTP_PROPERTIES = null;
// Extra java mail headers
public static Map<String, String> SMTP_HEADERS = null;
public static String SMTP_SENDER = null;
// used to intercept all email and send to this test email account
public static String SMTP_TEST_RECIPIENT = null;
// used to switch whether to send an email or not - false to actually send the email
public static boolean SMTP_TEST_BOGUS_SEND = false;
// Map Keys
public static enum MapType {
gmap, leaflet;
}
public static MapType MAP_TYPE = MapType.leaflet;
// the layers to display on the map backdrop
public static String MAP_LAYERS = null;
// opening a new empty map will centre here
public static String MAP_CENTRE = null;
// opening a new empty map will apply this zoom level
public static int MAP_ZOOM = 1;
// API Keys etc
public static String GOOGLE_MAPS_V3_API_KEY = null;
public static String GOOGLE_RECAPTCHA_SITE_KEY = null;
public static String CKEDITOR_CONFIG_FILE_URL = "";
// null = prod, could be dev, test, uat or another arbitrary environment
public static String ENVIRONMENT_IDENTIFIER = null;
// email address for error.jsp
public static String SUPPORT_EMAIL_ADDRESS = null;
// Should scheduled jobs be manipulated by the database.
public static boolean JOB_SCHEDULER = true;
// Password hashing algorithm - usually bcrypt, pbkdf2, scrypt. MD5 and SHA1 are unsalted and obsolete.
public static String PASSWORD_HASHING_ALGORITHM = "bcrypt";
// Number of days until a password change is required - Use null to indicate no password aging
public static int PASSWORD_EXPIRY_IN_DAYS = 0;
// Number of previous passwords to check for duplicates - Use null to indicate no password history
public static int PASSWORD_HISTORY_RETENTION = 0;
// Number of sign in attempts until the user account is locked - Use null to indicate no account lockout
public static int ACCOUNT_LOCKOUT_THRESHOLD = 3;
// Number of seconds per failed sign in attempt to lock the account for - Only relevant if account lockout is in use.
public static int ACCOUNT_LOCKOUT_DURATION_MULTIPLE_IN_SECONDS = 10;
// Enables new users to register for an account when true, requires email
public static boolean ACCOUNT_ALLOW_SELF_REGISTRATION = false;
// google auth client id
public static String AUTHENTICATION_GOOGLE_CLIENT_ID = null;
// google auth secret
public static String AUTHENTICATION_GOOGLE_SECRET = null;
// facebook auth client id
public static String AUTHENTICATION_FACEBOOK_CLIENT_ID = null;
// facebook auth secret
public static String AUTHENTICATION_FACEBOOK_SECRET = null;
// github auth client id
public static String AUTHENTICATION_GITHUB_CLIENT_ID = null;
// github auth secret
public static String AUTHENTICATION_GITHUB_SECRET = null;
// The Login URI to forward to
public static String AUTHENTICATION_LOGIN_URI = "/login";
// The Logged Out URI to forward to
public static String AUTHENTICATION_LOGGED_OUT_URI = "/loggedOut";
// Show setup screen on sign-in for DevOps users
public static boolean SHOW_SETUP = false;
// These 3 are used to create a user with all roles for the customer assigned, if the user does not already exist
public static String BOOTSTRAP_CUSTOMER = null;
public static String BOOTSTRAP_USER = null;
public static String BOOTSTRAP_EMAIL = null;
public static String BOOTSTRAP_PASSWORD = null;
public static boolean PRIMEFLEX = false;
// for skyve script
/**
* Absolute path on the filesystem to the source directory where modules live.
* E.g. c:/workspace/project/src/main/java
*/
public static String MODULE_DIRECTORY = null;
private static String absoluteBasePath;
public static String getAbsoluteBasePath() {
if (absoluteBasePath == null) {
if (APPS_JAR_DIRECTORY != null) {
absoluteBasePath = APPS_JAR_DIRECTORY;
} else {
URL url = Thread.currentThread().getContextClassLoader().getResource("schemas/common.xsd");
if (url == null) {
UtilImpl.LOGGER.severe("Cannot determine absolute base path. Where is schemas/common.xsd?");
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl instanceof URLClassLoader) {
UtilImpl.LOGGER.severe("The context classloader paths are:-");
for (URL entry : ((URLClassLoader) cl).getURLs()) {
UtilImpl.LOGGER.severe(entry.getFile());
}
} else {
UtilImpl.LOGGER.severe("Cannot determine the context classloader paths...");
}
} else {
absoluteBasePath = url.getPath();
absoluteBasePath = absoluteBasePath.substring(0, absoluteBasePath.length() - 18); // remove schemas/common.xsd
absoluteBasePath = absoluteBasePath.replace('\\', '/');
}
}
}
return absoluteBasePath;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> readJSONConfig(InputStream inputStream) throws Exception {
String json = null;
try (Scanner scanner = new Scanner(inputStream)) {
json = scanner.useDelimiter("\\Z").next();
}
// minify the file to remove any comments
json = Minifier.minify(json);
return (Map<String, Object>) JSON.unmarshall(null, json);
}
@SuppressWarnings("unchecked")
public static final <T extends Serializable> T cloneBySerialization(T object) {
return (T) SerializationHelper.clone(object);
// try {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// new ObjectOutputStream(baos).writeObject(object);
// ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
// return (T) ois.readObject();
// catch (Exception e) {
}
public static final <T extends Serializable> T cloneToTransientBySerialization(T object)
throws Exception {
if (object instanceof List<?>) {
for (Object element : (List<?>) object) {
if (element instanceof AbstractPersistentBean) {
populateFully((AbstractPersistentBean) object);
}
}
} else if (object instanceof AbstractPersistentBean) {
populateFully((AbstractPersistentBean) object);
}
T result = cloneBySerialization(object);
setTransient(result);
return result;
}
/**
* Recurse the bean ensuring that everything is touched and loaded from the database.
*
* @param bean The bean to load.
*/
public static void populateFully(final Bean bean) {
User user = CORE.getUser();
Customer customer = user.getCustomer();
Module module = customer.getModule(bean.getBizModule());
Document document = module.getDocument(customer, bean.getBizDocument());
// Ensure that everything is loaded
new BeanVisitor(false, true, false) {
@Override
protected boolean accept(String binding,
Document documentAccepted,
Document owningDocument,
Relation owningRelation,
Bean beanAccepted) {
// do nothing - just visiting loads the instance from the database
return true;
}
}.visit(document, bean, customer);
}
/**
* Recurse a bean to determine if anything has changed
*/
private static class ChangedBeanVisitor extends BeanVisitor {
private boolean changed = false;
private ChangedBeanVisitor() {
// Check inverses for the cascade attribute
super(false, true, false);
}
@Override
protected boolean accept(String binding,
Document documentAccepted,
Document owningDocument,
Relation owningRelation,
Bean beanAccepted) {
// Process an inverse if the inverse is specified as cascading.
if ((owningRelation instanceof Inverse) &&
(! Boolean.TRUE.equals(((Inverse) owningRelation).getCascade()))) {
return false;
}
if (beanAccepted.isChanged()) {
changed = true;
if (UtilImpl.DIRTY_TRACE)
UtilImpl.LOGGER.info(
"UtilImpl.hasChanged(): Bean " + beanAccepted.toString() + " with binding " + binding + " is DIRTY");
return false;
}
return true;
}
boolean isChanged() {
return changed;
}
}
/**
* Recurse the bean to determine if anything has changed.
* This is deprecated and has been moved to AbstractBean with the "changed" bean property.
* This enables the method's result to be cached in Bean proxies.
*
* @param bean The bean to test.
* @return if the bean, its collections or its aggregated beans have mutated or not
*/
@Deprecated
public static boolean hasChanged(Bean bean) {
User user = CORE.getUser();
Customer customer = user.getCustomer();
Module module = customer.getModule(bean.getBizModule());
Document document = module.getDocument(customer, bean.getBizDocument());
ChangedBeanVisitor cbv = new ChangedBeanVisitor();
cbv.visit(document, bean, customer);
return cbv.isChanged();
}
/**
* Utility method that tries to properly initialise the persistence layer proxies used by lazy loading.
*
* @param <T>
* @param possibleProxy The possible proxy
* @return the resolved proxy or possibleProxy
*/
@SuppressWarnings("unchecked")
public static <T> T deproxy(T possibleProxy) throws ClassCastException {
if (possibleProxy instanceof HibernateProxy) {
return (T) ((HibernateProxy) possibleProxy).getHibernateLazyInitializer().getImplementation();
}
return possibleProxy;
}
public static void setTransient(Object object) throws Exception {
if (object instanceof List<?>) {
List<?> list = (List<?>) object;
for (Object element : list) {
setTransient(element);
}
} else if (object instanceof AbstractPersistentBean) {
AbstractPersistentBean bean = (AbstractPersistentBean) object;
bean.setBizId(UUID.randomUUID().toString());
bean.setBizLock(null);
bean.setBizVersion(null);
// set references transient if applicable
Customer customer = AbstractPersistence.get().getUser().getCustomer();
Module module = customer.getModule(bean.getBizModule());
Document document = module.getDocument(customer, bean.getBizDocument());
for (String referenceName : document.getReferenceNames()) {
Reference reference = document.getReferenceByName(referenceName);
if (reference.isPersistent()) {
if (reference instanceof AssociationImpl) {
AssociationImpl association = (AssociationImpl) reference;
if (association.getType() != AssociationType.aggregation) {
setTransient(BindUtil.get(bean, referenceName));
}
} else if (reference instanceof Collection) {
Collection collection = (Collection) reference;
if (collection.getType() != CollectionType.aggregation) {
// set each element of the collection transient
setTransient(BindUtil.get(bean, referenceName));
}
}
}
}
}
}
// set the data group of a bean and all its children
public static void setDataGroup(Object object, String bizDataGroupId) throws Exception {
if (object instanceof List<?>) {
List<?> list = (List<?>) object;
for (Object element : list) {
setDataGroup(element, bizDataGroupId);
}
} else if (object instanceof AbstractPersistentBean) {
AbstractPersistentBean bean = (AbstractPersistentBean) object;
bean.setBizDataGroupId(bizDataGroupId);
// set the bizDatagroup of references if applicable
Customer customer = AbstractPersistence.get().getUser().getCustomer();
Module module = customer.getModule(bean.getBizModule());
Document document = module.getDocument(customer, bean.getBizDocument());
for (String referenceName : document.getReferenceNames()) {
Reference reference = document.getReferenceByName(referenceName);
if (reference.isPersistent()) {
if (reference instanceof AssociationImpl) {
AssociationImpl association = (AssociationImpl) reference;
if (association.getType() != AssociationType.aggregation) {
setDataGroup(BindUtil.get(bean, referenceName), bizDataGroupId);
}
} else if (reference instanceof Collection) {
Collection collection = (Collection) reference;
if (collection.getType() != CollectionType.aggregation) {
// set each element of the collection transient
setDataGroup(BindUtil.get(bean, referenceName), bizDataGroupId);
}
}
}
}
}
}
/**
* Process and transform empty Strings.
*
* @param value The String.
* @return null, if the trimmed value is empty, otherwise value.
*/
public static String processStringValue(String value) {
String result = value;
if (result != null) {
result = result.trim();
if (result.isEmpty()) {
result = null;
}
}
return result;
}
/**
* Change unicode text to ascii.
*/
public static String unidecode(String value) {
return Junidecode.unidecode(value);
}
/**
* Checks that the module directory:
* <ul>
* <li>ends with a trailing slash
* <li>ends with modules
* </ul>
*
* @param path The supplied content path
* @return The updated path if any slashes or <code>/modules</code> need to be added
*/
public static String cleanupModuleDirectory(final String path) {
if (path != null && path.length() > 0) {
String updatedPath = path;
// strip the trailing slash if any
if (path.endsWith("/") || path.endsWith("\\")) {
updatedPath = path.substring(0, path.length() - 1);
}
if (!updatedPath.endsWith("modules")) {
updatedPath = updatedPath + "/modules/";
}
if (!updatedPath.endsWith("/") && !updatedPath.endsWith("\\")) {
updatedPath = updatedPath + "/";
}
return updatedPath;
}
return path;
}
}
|
package com.plugin.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.text.TextUtils;
import android.util.Base64;
import com.plugin.content.PluginDescriptor;
import com.plugin.content.PluginIntentFilter;
import com.plugin.util.LogUtil;
import com.plugin.util.ManifestParser;
import com.plugin.util.FileUtil;
import com.plugin.util.RefInvoker;
import dalvik.system.DexClassLoader;
public class PluginLoader {
public static final String ACTION_PLUGIN_CHANGED = "com.plugin.core.action_plugin_changed";
public static final String EXTRA_TYPE = "com.plugin.core.EXTRA_TYPE";
private static Application sApplication;
private static boolean isInited = false;
private static final Hashtable<String, PluginDescriptor> sInstalledPlugins = new Hashtable<String, PluginDescriptor>();
private PluginLoader() {
}
/**
* loader,
*
* @param app
*/
public static synchronized void initLoader(Application app) {
if (!isInited) {
sApplication = app;
readInstalledPlugins();
isInited = true;
}
}
public static Application getApplicatoin() {
return sApplication;
}
public boolean isInstalled(String pluginId, String pluginVersion) {
PluginDescriptor pluginDescriptor = getPluginDescriptorByPluginId(pluginId);
if (pluginDescriptor != null) {
return pluginDescriptor.getVersion().equals(pluginVersion);
}
return false;
}
/**
*
*
* @param srcPluginFile
* @return
*/
public static synchronized boolean installPlugin(String srcPluginFile) {
LogUtil.d("Install plugin ", srcPluginFile);
boolean isInstallSuccess = false;
PluginDescriptor pluginDescriptor = ManifestParser.parseManifest(srcPluginFile);
if (pluginDescriptor == null || TextUtils.isEmpty(pluginDescriptor.getPackageName())) {
return isInstallSuccess;
}
PluginDescriptor oldPluginDescriptor = getPluginDescriptorByPluginId(pluginDescriptor.getPackageName());
if (oldPluginDescriptor != null) {
remove(pluginDescriptor.getPackageName());
}
if (pluginDescriptor != null) {
String destPluginFile = genInstallPath(pluginDescriptor.getPackageName(), pluginDescriptor.getVersion());
boolean isCopySuccess = FileUtil.copyFile(srcPluginFile, destPluginFile);
if (isCopySuccess) {
pluginDescriptor.setInstalledPath(destPluginFile);
PluginDescriptor previous = sInstalledPlugins.put(pluginDescriptor.getPackageName(), pluginDescriptor);
isInstallSuccess = saveInstalledPlugins(sInstalledPlugins);
if (isInstallSuccess) {
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
if (previous == null) {
intent.putExtra(EXTRA_TYPE, "add");
} else {
intent.putExtra(EXTRA_TYPE, "replace");
}
intent.putExtra("id", pluginDescriptor.getPackageName());
intent.putExtra("version", pluginDescriptor.getVersion());
sApplication.sendBroadcast(intent);
}
}
}
return isInstallSuccess;
}
/**
* classIdclass
*
* @param clazzId
* @return
*/
@SuppressWarnings("rawtypes")
public static Class loadPluginClassById(String clazzId) {
LogUtil.d("loadPluginClass for clazzId ", clazzId);
PluginDescriptor pluginDescriptor = getPluginDescriptorByFragmenetId(clazzId);
if (pluginDescriptor != null) {
DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();
if (pluginClassLoader == null) {
initPlugin(pluginDescriptor);
pluginClassLoader = pluginDescriptor.getPluginClassLoader();
}
if (pluginClassLoader != null) {
String clazzName = pluginDescriptor.getPluginClassNameById(clazzId);
LogUtil.d("loadPluginClass clazzName=", clazzName);
if (clazzName != null) {
try {
Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName);
LogUtil.d("loadPluginClass for classId ", clazzId, " Success");
return pluginClazz;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
LogUtil.d("loadPluginClass for classId ", clazzId, " Fail");
return null;
}
@SuppressWarnings("rawtypes")
public static Class loadPluginClassByName(String clazzName) {
LogUtil.d("loadPluginClass for clazzName ", clazzName);
PluginDescriptor pluginDescriptor = getPluginDescriptorByClassName(clazzName);
if (pluginDescriptor != null) {
DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();
if (pluginClassLoader == null) {
initPlugin(pluginDescriptor);
pluginClassLoader = pluginDescriptor.getPluginClassLoader();
}
if (pluginClassLoader != null) {
try {
Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName);
LogUtil.d("loadPluginClass Success for clazzName ", clazzName);
return pluginClazz;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
LogUtil.d("loadPluginClass Fail for clazzName ", clazzName);
return null;
}
/**
* classContext 1DefaultContext,classContext
*
* @param clazz
* @return
*/
public static Context getDefaultPluginContext(@SuppressWarnings("rawtypes") Class clazz) {
// clazz.getClassLoader(); classloader
// classloaderloader
Context pluginContext = null;
PluginDescriptor pluginDescriptor = getPluginDescriptorByClassName(clazz.getName());
if (pluginDescriptor != null) {
pluginContext = pluginDescriptor.getPluginContext();
} else {
LogUtil.d("PluginDescriptor Not Found for ", clazz.getName());
}
if (pluginContext == null) {
LogUtil.d("Context Not Found for ", clazz.getName());
}
return pluginContext;
}
/**
* classContext classcontext
*
* @param clazz
* @return
*/
public static Context getNewPluginContext(@SuppressWarnings("rawtypes") Class clazz) {
Context pluginContext = getDefaultPluginContext(clazz);
if (pluginContext != null) {
pluginContext = PluginCreator.createPluginApplicationContext(sApplication, pluginContext.getResources(),
(DexClassLoader) pluginContext.getClassLoader());
pluginContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme);
}
return pluginContext;
}
/**
*
*
* @param pluginClassBean
*/
private static void initPlugin(PluginDescriptor pluginDescriptor) {
LogUtil.d("initPlugin, Resources, DexClassLoader, Context, Application ", pluginDescriptor.getApplicationName());
LogUtil.d("", pluginDescriptor.isStandalone());
Resources pluginRes = PluginCreator.createPluginResource(sApplication, pluginDescriptor.getInstalledPath(),
pluginDescriptor.isStandalone());
DexClassLoader pluginClassLoader = PluginCreator.createPluginClassLoader(pluginDescriptor.getInstalledPath(),
pluginDescriptor.isStandalone());
Context pluginContext = PluginCreator
.createPluginApplicationContext(sApplication, pluginRes, pluginClassLoader);
pluginContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme);
pluginDescriptor.setPluginContext(pluginContext);
pluginDescriptor.setPluginClassLoader(pluginClassLoader);
checkPluginPublicXml(pluginDescriptor, pluginRes);
callPluginApplicationOncreate(pluginDescriptor);
}
private static void callPluginApplicationOncreate(PluginDescriptor pluginDescriptor) {
if (pluginDescriptor.getApplicationName() != null && pluginDescriptor.getPluginApplication() == null
&& pluginDescriptor.getPluginClassLoader() != null) {
try {
Class pluginApplicationClass = ((ClassLoader) pluginDescriptor.getPluginClassLoader())
.loadClass(pluginDescriptor.getApplicationName());
Application application = (Application) pluginApplicationClass.newInstance();
RefInvoker.invokeMethod(application, "android.app.Application", "attach",
new Class[] { Context.class }, new Object[] { sApplication });
LogUtil.d("apkapplication", pluginDescriptor.getApplicationName());
pluginDescriptor.setPluginApplication(application);
application.onCreate();
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
intent.putExtra(EXTRA_TYPE, "inited");
sApplication.sendBroadcast(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private static boolean checkPluginPublicXml(PluginDescriptor pluginDescriptor, Resources res) {
// "plugin_layout_1"idpublic.xml
// public.xml,
int publicStub = res.getIdentifier("plugin_layout_1", "layout", pluginDescriptor.getPackageName());
if (publicStub == 0) {
publicStub = res.getIdentifier("plugin_layout_1", "layout", sApplication.getPackageName());
}
if (publicStub == 0) {
try {
Class layoutClass = ((ClassLoader) pluginDescriptor.getPluginClassLoader()).loadClass(pluginDescriptor
.getPackageName() + ".R$layout");
Integer layouId = (Integer) RefInvoker.getFieldObject(null, layoutClass, "plugin_layout_1");
if (layouId != null) {
publicStub = layouId;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
if (publicStub == 0) {
throw new IllegalStateException("\npublic.xmlid\n" + "public.xmlid\n"
+ "public.xmlid\n" + "");
}
return true;
}
private static synchronized boolean saveInstalledPlugins(Hashtable<String, PluginDescriptor> installedPlugins) {
ObjectOutputStream objectOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(installedPlugins);
objectOutputStream.flush();
byte[] data = byteArrayOutputStream.toByteArray();
String list = Base64.encodeToString(data, Base64.DEFAULT);
getSharedPreference().edit().putString("plugins.list", list).commit();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* class,class
*/
public static synchronized void removeAll() {
sInstalledPlugins.entrySet().iterator();
sInstalledPlugins.clear();
boolean isSuccess = saveInstalledPlugins(sInstalledPlugins);
if (isSuccess) {
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
intent.putExtra(EXTRA_TYPE, "remove");
sApplication.sendBroadcast(intent);
}
}
public static synchronized void remove(String pluginId) {
PluginDescriptor old = sInstalledPlugins.remove(pluginId);
if (old != null) {
boolean isSuccess = saveInstalledPlugins(sInstalledPlugins);
new File(old.getInstalledPath()).delete();
if (isSuccess) {
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
intent.putExtra(EXTRA_TYPE, "remove");
sApplication.sendBroadcast(intent);
}
}
}
@SuppressWarnings("unchecked")
public static Hashtable<String, PluginDescriptor> listAll() {
return (Hashtable<String, PluginDescriptor>) sInstalledPlugins.clone();
}
/**
* for Fragment
*
* @param clazzId
* @return
*/
public static PluginDescriptor getPluginDescriptorByFragmenetId(String clazzId) {
Iterator<PluginDescriptor> itr = sInstalledPlugins.values().iterator();
while (itr.hasNext()) {
PluginDescriptor descriptor = itr.next();
if (descriptor.containsFragment(clazzId)) {
return descriptor;
}
}
return null;
}
public static PluginDescriptor getPluginDescriptorByPluginId(String pluginId) {
PluginDescriptor pluginDescriptor = sInstalledPlugins.get(pluginId);
if (pluginDescriptor != null && pluginDescriptor.isEnabled()) {
return pluginDescriptor;
}
return null;
}
public static PluginDescriptor getPluginDescriptorByClassName(String clazzName) {
Iterator<PluginDescriptor> itr = sInstalledPlugins.values().iterator();
while (itr.hasNext()) {
PluginDescriptor descriptor = itr.next();
if (descriptor.containsName(clazzName)) {
return descriptor;
}
}
return null;
}
public static synchronized void enablePlugin(String pluginId, boolean enable) {
PluginDescriptor pluginDescriptor = sInstalledPlugins.get(pluginId);
if (pluginDescriptor != null && !pluginDescriptor.isEnabled()) {
pluginDescriptor.setEnabled(enable);
saveInstalledPlugins(sInstalledPlugins);
}
}
/**
* //If getComponent returns an explicit class, that is returned without any
* further consideration. //If getAction is non-NULL, the activity must
* handle this action. //If resolveType returns non-NULL, the activity must
* handle this type. //If addCategory has added any categories, the activity
* must handle ALL of the categories specified. //If getPackage is non-NULL,
* only activity components in that application package will be considered.
*
* @param intent
* @return
*/
public static String isMatchPlugin(Intent intent) {
Hashtable<String, PluginDescriptor> plugins = listAll();
Iterator<PluginDescriptor> itr = plugins.values().iterator();
while (itr.hasNext()) {
PluginDescriptor plugin = itr.next();
if (intent.getComponent() != null) {
if (plugin.containsName(intent.getComponent().getClassName())) {
LogUtil.d("PluginLoader", "Component", intent.getComponent().getClassName());
return intent.getComponent().getClassName();
}
} else {
// IntentFilter
HashMap<String, ArrayList<PluginIntentFilter>> intentFilter = plugin.getComponents();
if (intentFilter != null) {
Iterator<Entry<String, ArrayList<PluginIntentFilter>>> entry = intentFilter.entrySet().iterator();
while (entry.hasNext()) {
Entry<String, ArrayList<PluginIntentFilter>> item = entry.next();
Iterator<PluginIntentFilter> values = item.getValue().iterator();
while (values.hasNext()) {
PluginIntentFilter filter = values.next();
int result = filter.match(intent.getAction(), intent.getType(), intent.getScheme(),
intent.getData(), intent.getCategories());
LogUtil.d("PluginLoader", "result ", result, filter.getAction(0), intent.getAction(),
intent.getType(), intent.getScheme(), intent.getData());
if (result != PluginIntentFilter.NO_MATCH_ACTION
&& result != PluginIntentFilter.NO_MATCH_CATEGORY
&& result != PluginIntentFilter.NO_MATCH_DATA
&& result != PluginIntentFilter.NO_MATCH_TYPE) {
LogUtil.d("PluginLoader", "IntentFilter");
return item.getKey();
}
}
}
}
}
}
return null;
}
@SuppressWarnings("unchecked")
private static synchronized Hashtable<String, PluginDescriptor> readInstalledPlugins() {
if (sInstalledPlugins.size() == 0) {
String list = getSharedPreference().getString("plugins.list", "");
Serializable object = null;
if (!TextUtils.isEmpty(list)) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
Base64.decode(list, Base64.DEFAULT));
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(byteArrayInputStream);
object = (Serializable) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (object != null) {
Hashtable<String, PluginDescriptor> installedPlugin = (Hashtable<String, PluginDescriptor>) object;
sInstalledPlugins.putAll(installedPlugin);
}
}
return sInstalledPlugins;
}
/**
* , apk
*/
private static String genInstallPath(String pluginId, String pluginVersoin) {
return sApplication.getDir("plugin_dir", Context.MODE_PRIVATE).getAbsolutePath() + "/" + pluginId + "/"
+ pluginVersoin + ".apk";
}
private static SharedPreferences getSharedPreference() {
SharedPreferences sp = sApplication.getSharedPreferences("plugins.installed",
Build.VERSION.SDK_INT < 11 ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | 0x0004);
return sp;
}
}
|
package com.naughtyzombie.demo.game;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.Input.Keys;
public class WorldController extends InputAdapter {
private static final String TAG = WorldController.class.getName();
public Sprite[] testSprites;
public int selectedSprite;
public WorldController() {
init();
}
@Override
public boolean keyUp(int keycode) {
//Reset the game world
if (keycode == Keys.R) {
init();
Gdx.app.debug(TAG, "Reset Game World");
} else if (keycode == Keys.SPACE) {
//Select next sprite
selectedSprite = (selectedSprite + 1) % testSprites.length;
Gdx.app.debug(TAG, "Sprite #" + selectedSprite + " selected");
}
return false;
}
private void init() {
Gdx.input.setInputProcessor(this);
initTestObjects();
}
private void initTestObjects() {
testSprites = new Sprite[5];
int width = 32;
int height = 32;
Pixmap pixmap = createProceduralPixmap(width, height);
Texture texture = new Texture(pixmap);
for (int i = 0; i < testSprites.length; i++) {
Sprite spr = new Sprite(texture);
spr.setSize(1, 1);
spr.setOrigin(spr.getWidth() / 2.0f, spr.getHeight() / 2.0f);
float randomX = MathUtils.random(-2.0f, 2.0f);
float randomY = MathUtils.random(-2.0f, 2.0f);
spr.setPosition(randomX, randomY);
testSprites[i] = spr;
}
selectedSprite = 0;
}
private Pixmap createProceduralPixmap(int width, int height) {
Pixmap pixmap = new Pixmap(width,height, Pixmap.Format.RGBA8888);
pixmap.setColor(1,0,0,0.5f);
pixmap.fill();
pixmap.setColor(1,1,0,1);
pixmap.drawLine(0,0,width,height);
pixmap.drawLine(width,0,0,height);
pixmap.setColor(0,1,1,1);
pixmap.drawRectangle(0,0,width,height);
return pixmap;
}
public void update(float deltaTime) {
handleDebugInput(deltaTime);
updateTestObjects(deltaTime);
}
private void handleDebugInput(float deltaTime) {
if (Gdx.app.getType() != Application.ApplicationType.Desktop) return;
float sprMoveSpeed = 5 * deltaTime;
if (Gdx.input.isKeyPressed(Keys.A)) moveSelectedSprite(-sprMoveSpeed, 0);
if (Gdx.input.isKeyPressed(Keys.D)) moveSelectedSprite(sprMoveSpeed, 0);
if (Gdx.input.isKeyPressed(Keys.W)) moveSelectedSprite(0, sprMoveSpeed);
if (Gdx.input.isKeyPressed(Keys.S)) moveSelectedSprite(0, -sprMoveSpeed);
}
private void moveSelectedSprite(float x, float y) {
testSprites[selectedSprite].translate(x, y);
}
private void updateTestObjects(float deltaTime) {
float rotation = testSprites[selectedSprite].getRotation();
rotation += 90 * deltaTime;
rotation %= 360;
testSprites[selectedSprite].setRotation(rotation);
}
}
|
package co.aikar.commands;
import co.aikar.commands.annotation.Single;
import co.aikar.commands.annotation.Split;
import co.aikar.commands.annotation.Values;
import co.aikar.commands.contexts.ContextResolver;
import co.aikar.commands.contexts.IssuerAwareContextResolver;
import co.aikar.commands.contexts.IssuerOnlyContextResolver;
import co.aikar.commands.contexts.OptionalContextResolver;
import org.jetbrains.annotations.NotNull;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("WeakerAccess")
public class CommandContexts<R extends CommandExecutionContext<?, ? extends CommandIssuer>> {
protected final Map<Class<?>, ContextResolver<?, R>> contextMap = new HashMap<>();
protected final CommandManager manager;
CommandContexts(CommandManager manager) {
this.manager = manager;
registerIssuerOnlyContext(CommandIssuer.class, c -> c.getIssuer());
registerContext(Short.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, Short.MIN_VALUE, Short.MAX_VALUE).shortValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(short.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, Short.MIN_VALUE, Short.MAX_VALUE).shortValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(Integer.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, Integer.MIN_VALUE, Integer.MAX_VALUE).intValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(int.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, Integer.MIN_VALUE, Integer.MAX_VALUE).intValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(Long.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, Long.MIN_VALUE, Long.MAX_VALUE).longValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(long.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, Long.MIN_VALUE, Long.MAX_VALUE).longValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(Float.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, -Float.MAX_VALUE, Float.MAX_VALUE).floatValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(float.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, -Float.MAX_VALUE, Float.MAX_VALUE).floatValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(Double.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, -Double.MAX_VALUE, Double.MAX_VALUE).doubleValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(double.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, -Double.MAX_VALUE, Double.MAX_VALUE).doubleValue();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(Number.class, (c) -> {
String number = c.popFirstArg();
try {
return parseAndValidateNumber(number, c, -Double.MAX_VALUE, Double.MAX_VALUE);
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", number);
}
});
registerContext(BigDecimal.class, (c) -> {
String numberStr = c.popFirstArg();
try {
BigDecimal number = ACFUtil.parseBigNumber(numberStr, c.hasFlag("suffixes"));
validateMinMax(c, number);
return number;
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", numberStr);
}
});
registerContext(BigInteger.class, (c) -> {
String numberStr = c.popFirstArg();
try {
BigDecimal number = ACFUtil.parseBigNumber(numberStr, c.hasFlag("suffixes"));
validateMinMax(c, number);
return number.toBigIntegerExact();
} catch (NumberFormatException e) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_A_NUMBER, "{num}", numberStr);
}
});
registerContext(Boolean.class, (c) -> ACFUtil.isTruthy(c.popFirstArg()));
registerContext(boolean.class, (c) -> ACFUtil.isTruthy(c.popFirstArg()));
registerContext(char.class, c -> {
String s = c.popFirstArg();
if (s.length() > 1) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_MAX_LENGTH, "{max}", String.valueOf(1));
}
return s.charAt(0);
});
registerContext(String.class, (c) -> {
// This will fail fast, its either in the values or its not
if (c.hasAnnotation(Values.class)) {
return c.popFirstArg();
}
String ret = (c.isLastArg() && !c.hasAnnotation(Single.class)) ?
ACFUtil.join(c.getArgs())
:
c.popFirstArg();
Integer minLen = c.getFlagValue("minlen", (Integer) null);
Integer maxLen = c.getFlagValue("maxlen", (Integer) null);
if (minLen != null) {
if (ret.length() < minLen) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_MIN_LENGTH, "{min}", String.valueOf(minLen));
}
}
if (maxLen != null) {
if (ret.length() > maxLen) {
throw new InvalidCommandArgument(MessageKeys.MUST_BE_MAX_LENGTH, "{max}", String.valueOf(maxLen));
}
}
return ret;
});
registerContext(String[].class, (c) -> {
String val;
List<String> args = c.getArgs();
if (c.isLastArg() && !c.hasAnnotation(Single.class)) {
val = ACFUtil.join(args);
} else {
val = c.popFirstArg();
}
String split = c.getAnnotationValue(Split.class, Annotations.NOTHING | Annotations.NO_EMPTY);
if (split != null) {
if (val.isEmpty()) {
throw new InvalidCommandArgument();
}
return ACFPatterns.getPattern(split).split(val);
} else if (!c.isLastArg()) {
ACFUtil.sneaky(new IllegalStateException("Weird Command signature... String[] should be last or @Split"));
}
String[] result = args.toArray(new String[0]);
args.clear();
return result;
});
registerContext(Enum.class, (c) -> {
final String first = c.popFirstArg();
//noinspection unchecked
Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>) c.getParam().getType();
Enum<?> match = ACFUtil.simpleMatch(enumCls, first);
if (match == null) {
List<String> names = ACFUtil.enumNames(enumCls);
throw new InvalidCommandArgument(MessageKeys.PLEASE_SPECIFY_ONE_OF, "{valid}", ACFUtil.join(names, ", "));
}
return match;
});
registerOptionalContext(CommandHelp.class, (c) -> {
String first = c.getFirstArg();
String last = c.getLastArg();
int page = 1;
List<String> search = null;
if (last != null && ACFUtil.isInteger(last)) {
c.popLastArg();
page = ACFUtil.parseInt(last);
if (!c.getArgs().isEmpty()) {
search = c.getArgs();
}
} else if (first != null && ACFUtil.isInteger(first)) {
c.popFirstArg();
page = ACFUtil.parseInt(first);
if (!c.getArgs().isEmpty()) {
search = c.getArgs();
}
} else if (!c.getArgs().isEmpty()) {
search = c.getArgs();
}
CommandHelp commandHelp = manager.generateCommandHelp();
commandHelp.setPage(page);
Integer perPage = c.getFlagValue("perpage", (Integer) null);
if (perPage != null) {
commandHelp.setPerPage(perPage);
}
// check if we have an exact match and should display the help page for that sub command instead
if (search != null) {
String cmd = String.join(" ", search);
if (commandHelp.testExactMatch(cmd)) {
return commandHelp;
}
}
commandHelp.setSearch(search);
return commandHelp;
});
}
@NotNull
private Number parseAndValidateNumber(String number, R c, Number minValue, Number maxValue) throws InvalidCommandArgument {
final Number val = ACFUtil.parseNumber(number, c.hasFlag("suffixes"));
validateMinMax(c, val, minValue, maxValue);
return val;
}
private void validateMinMax(R c, Number val) throws InvalidCommandArgument {
validateMinMax(c, val, null, null);
}
private void validateMinMax(R c, Number val, Number minValue, Number maxValue) throws InvalidCommandArgument {
minValue = c.getFlagValue("min", minValue);
maxValue = c.getFlagValue("max", maxValue);
if (maxValue != null && val.doubleValue() > maxValue.doubleValue()) {
throw new InvalidCommandArgument(MessageKeys.PLEASE_SPECIFY_AT_MOST, "{max}", String.valueOf(maxValue));
}
if (minValue != null && val.doubleValue() < minValue.doubleValue()) {
throw new InvalidCommandArgument(MessageKeys.PLEASE_SPECIFY_AT_LEAST, "{min}", String.valueOf(minValue));
}
}
/**
* @see #registerIssuerAwareContext(Class, IssuerAwareContextResolver)
* @deprecated Please switch to {@link #registerIssuerAwareContext(Class, IssuerAwareContextResolver)}
* as the core wants to use the platform agnostic term of "Issuer" instead of Sender
*/
@Deprecated
public <T> void registerSenderAwareContext(Class<T> context, IssuerAwareContextResolver<T, R> supplier) {
contextMap.put(context, supplier);
}
/**
* Registers a context resolver that may conditionally consume input, falling back to using the context of the
* issuer to potentially fulfill this context.
* You may call {@link CommandExecutionContext#getFirstArg()} and then conditionally call {@link CommandExecutionContext#popFirstArg()}
* if you want to consume that input.
*/
public <T> void registerIssuerAwareContext(Class<T> context, IssuerAwareContextResolver<T, R> supplier) {
contextMap.put(context, supplier);
}
/**
* Registers a context resolver that will never consume input. It will always satisfy its context based on the
* issuer of the command, so it will not appear in syntax strings.
*/
public <T> void registerIssuerOnlyContext(Class<T> context, IssuerOnlyContextResolver<T, R> supplier) {
contextMap.put(context, supplier);
}
/**
* Registers a context that can safely accept a null input from the command issuer to resolve. This resolver should always
* call {@link CommandExecutionContext#popFirstArg()}
*/
public <T> void registerOptionalContext(Class<T> context, OptionalContextResolver<T, R> supplier) {
contextMap.put(context, supplier);
}
/**
* Registers a context that requires input from the command issuer to resolve. This resolver should always
* call {@link CommandExecutionContext#popFirstArg()}
*/
public <T> void registerContext(Class<T> context, ContextResolver<T, R> supplier) {
contextMap.put(context, supplier);
}
public ContextResolver<?, R> getResolver(Class<?> type) {
Class<?> rootType = type;
do {
if (type == Object.class) {
break;
}
final ContextResolver<?, R> resolver = contextMap.get(type);
if (resolver != null) {
return resolver;
}
} while ((type = type.getSuperclass()) != null);
this.manager.log(LogLevel.ERROR, "Could not find context resolver", new IllegalStateException("No context resolver defined for " + rootType.getName()));
return null;
}
}
|
package Gui2D;
import Gui2D.Maps.Cellar;
import Gui2D.Maps.House2;
import Gui2D.Maps.Forest;
import Gui2D.Maps.GruulsLair;
import Gui2D.Maps.Map;
import Gui2D.Maps.Menu;
import Gui2D.SpriteController.SpriteController;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author jonas
*/
public class WizardOfTreldan extends Application {
//set all our maps
private static Map cellar;
private static Map gruulslair;
private static Map menu;
private static Map house2;
private static Map forest;
//our global world generator
private SpriteController world;
//set a global stage from the primaryStage
private static Stage primaryStage;
@Override
public void start(Stage primaryStage) {
//set our stage
this.primaryStage = primaryStage;
//remove the top bar of the frame
this.primaryStage.initStyle(StageStyle.UNDECORATED);
//set our width and height
this.primaryStage.setWidth(1024);
this.primaryStage.setHeight(512);
//set the title
this.primaryStage.setTitle("The Wizard of Treldan");
//Init our world sprite controller
world = new SpriteController();
//Init all world maps
cellar = new Cellar(world);
menu = new Menu(world);
house2 = new House2(world);
//set our first scene
primaryStage.setScene(house2.getScene());
forest = new Forest(world);
//set our first scene
primaryStage.setScene(forest.getScene());
gruulslair = new GruulsLair(world);
//set our first scene
primaryStage.setScene(gruulslair.getScene());
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
/**
* Force the game to load menu scene
*/
public static void setMenuScene(){
primaryStage.setScene(menu.getScene());
}
/**
* Force the game to load CellarScene
*/
public static void setCellarScene(){
primaryStage.setScene(cellar.getScene());
}
public static void setForestScene() {
primaryStage.setScene(forest.getScene());
}
public static void setHouse2Scene(){
primaryStage.setScene(house2.getScene());
}
public static void setGruulsLairScene(){
primaryStage.setScene(gruulslair.getScene());
}
}
|
package jenkins.model;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Descriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import javax.annotation.Nonnull;
/**
* Convenient base class for extensions that contributes to the system configuration page but nothing
* else, or to manage the global configuration of a plugin implementing several extension points.
*
* <p>
* All {@link Descriptor}s are capable of contributing fragment to the system config page. If you are
* implementing other extension points that need to expose some global configuration, you can do so
* with {@code global.groovy} or {@code global.jelly} from your {@link Descriptor} instance. However
* each {@code global.*} file will appear as its own section in the global configuration page.
*
* <p>
* An option to present a single section for your plugin in the Jenkins global configuration page is
* to use this class to manage the configuration for your plugin and its extension points. To access
* properties defined in your GlobalConfiguration subclass, here are two possibilities:
* <ul><li>@{@link javax.inject.Inject} into your other {@link hudson.Extension}s (so this does <i>not</i> work
* for classes not annotated with {@link hudson.Extension})</li>
* <li>access it via a call to {@code ExtensionList.lookupSingleton(<your GlobalConfiguration subclass>.class)}</li></ul>
*
* <p>
* While an implementation might store its actual configuration data in various ways,
* meaning {@link #configure(StaplerRequest, JSONObject)} must be overridden,
* in the normal case you would simply define persistable fields with getters and setters.
* The {@code config} view would use data-bound controls like {@code f:entry}.
* Then make sure your constructor calls {@link #load} and your setters call {@link #save}.
*
* <h2>Views</h2>
* <p>
* Subtypes of this class should define a {@code config.groovy} file or {@code config.jelly} file
* that gets pulled into the system configuration page.
* Typically its contents should be wrapped in an {@code f:section}.
*
* @author Kohsuke Kawaguchi
* @since 1.425
*/
public abstract class GlobalConfiguration extends Descriptor<GlobalConfiguration> implements ExtensionPoint, Describable<GlobalConfiguration> {
protected GlobalConfiguration() {
super(self());
}
public final Descriptor<GlobalConfiguration> getDescriptor() {
return this;
}
@Override
public String getGlobalConfigPage() {
return getConfigPage();
}
/**
* By default, calls {@link StaplerRequest#bindJSON(Object, JSONObject)},
* appropriate when your implementation has getters and setters for all fields.
* <p>{@inheritDoc}
*/
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
req.bindJSON(this, json);
return true;
}
/**
* Returns all the registered {@link GlobalConfiguration} descriptors.
*/
public static @Nonnull ExtensionList<GlobalConfiguration> all() {
return Jenkins.get().getDescriptorList(GlobalConfiguration.class);
}
}
|
package jlibs.core.util;
import jlibs.core.lang.NotImplementedException;
import java.util.Comparator;
/**
* This is default implementation of {@link Comparator}, which can compare
* objects implementing {@link Comparable}.
* <p>
* <b>Null-Friendly:</b>
* <p>
* {@code null} is treated less than {@code non-null}.
* <pre class="prettyprint">
* Comparator<String> comp = new DefaultComparator<String>();
* System.out.println(comp.compareTo(null, "helloworld")); // prints -1
* System.out.println(comp.compare("helloworld", null)); // prints 1
* System.out.println(comp.compare(null, null)); // prints 0
* </pre>
*
* If the objects compared doesn't implement {@link Comparable}, it throws
* {@link NotImplementedException}.<br>
* You can extend {@link DefaultComparator} for any objects that doesn't implement {@link Comparable}.<br>
* For Example:
* <pre class="prettyprint">
* class Employee{
* int marks;
* int age;
*
* public Employee(int marks, int age){
* this.marks = marks;
* this.age = age;
* }
* }
*
* class EmployeeAgeComparator extends DefaultComparator<Employee>{
* @Override
* protected int _compare(Employee emp1, Employee emp2){
* return emp1.age - emp2.age;
* }
* }
* </pre>
*
* the {@link #compare(Object, Object) compare(...)} method in {@link DefaultComparator} is final.
* This method takes care of comparing values involving {@code nulls}. If both arguments are {@code non-null},
* then it delegates the comparison to {@link #_compare(Object, Object) _compare(...)}
* <p>
* So it is guaranteed that, both arguments of {@link #_compare(Object, Object) _compare(...)} are {@code non-null}.
*
* @author Santhosh Kumar T
*/
public class DefaultComparator<T> implements Comparator<T>{
/**
* this method can handle nulls ( null<non-null )
*/
@Override
public final int compare(T o1, T o2){
if(o1==o2)
return 0;
else if(o1==null)
return -1;
else if(o2==null)
return 1;
else
return _compare(o1, o2);
}
/**
* Arguments {@code o1} and {@code o2} will be non-null
*/
@SuppressWarnings({"unchecked"})
protected int _compare(T o1, T o2){
if(o1 instanceof Comparable && o2 instanceof Comparable)
return ((Comparable<T>)o1).compareTo(o2);
throw new NotImplementedException("can't compare objects of type: "+o1.getClass());
}
}
|
package org.bitcoinj.core;
import org.bitcoinj.store.FlatDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import static com.google.common.base.Preconditions.checkState;
public abstract class AbstractManager extends Message {
private static final Logger log = LoggerFactory.getLogger(AbstractManager.class);
/**
* The Context.
*/
protected Context context;
/**
* The Default file name.
* The default value is the name of the derived class + ".dat"
*/
protected String defaultFileName;
/**
* The Default magic message.
* The default value is the name of the derived class.
*/
protected String defaultMagicMessage;
/**
* The Magic message.
* The default value is the name of the derived class.
*/
protected String magicMessage;
/**
* The Format version. The default value is 1.
*/
protected int formatVersion;
/**
* The constant defaultExtension.
*/
public static String defaultExtension = ".dat";
/**
* The Filename.
*/
public String filename;
/**
* Instantiates a new AbstractManager.
*
* @param context the context
*/
public AbstractManager(Context context) {
super(context.getParams());
this.context = context;
this.formatVersion = 1;
String fullClassName = this.getClass().getCanonicalName();
this.defaultMagicMessage = fullClassName.substring(fullClassName.lastIndexOf('.')+1);
this.magicMessage = defaultMagicMessage;
this.defaultFileName = this.magicMessage.toLowerCase() + defaultExtension;
}
/**
* Instantiates a new Abstract manager.
*
* @param params the params
* @param payload the payload
* @param cursor the cursor
*/
public AbstractManager(NetworkParameters params, byte [] payload, int cursor) {
super(params, payload, cursor);
this.context = Context.get();
this.formatVersion = 1;
String fullClassName = this.getClass().getCanonicalName();
this.defaultMagicMessage = fullClassName.substring(fullClassName.lastIndexOf('.')+1);
this.magicMessage = defaultMagicMessage;
this.defaultFileName = fullClassName + defaultExtension;
}
/**
* Calculates size in bytes of this object.
*
* @return the size
*/
public abstract int calculateMessageSizeInBytes();
/**
* Check and remove. Called to check the validity of all objects
* and remove the expired objects.
*/
public abstract void checkAndRemove();
/**
* Clear. Removes all objects and settings.
*/
public abstract void clear();
/**
* Loads a payload into the object
*
* @param payload the payload
* @param offset the offset
*/
public void load(byte [] payload, int offset)
{
load(payload, offset, getFormatVersion());
}
public void load(byte [] payload, int offset, int version) {
this.protocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
this.payload = payload;
this.cursor = this.offset = offset;
this.length = payload.length;
this.formatVersion = version;
if (this.length == UNKNOWN_LENGTH)
checkState(false, "Length field has not been set in constructor for %s after %s parse. " +
"Refer to Message.parseLite() for detail of required Length field contract.",
getClass().getSimpleName(), /*parseLazy ? "lite" :*/ "full");
parse();
}
/**
* Create empty abstract manager.
*
* @return the abstract manager
*/
public abstract AbstractManager createEmpty();
/**
* Gets default file name.
*
* @return the default file name
*/
public String getDefaultFileName() {
return defaultFileName;
}
/**
* Gets magic message with the version number.
*
* @return the magic message
*/
public String getMagicMessage() {
return magicMessage + "-" + formatVersion;
}
/**
* Gets default magic message.
*
* @return the default magic message
*/
public String getDefaultMagicMessage() { return defaultMagicMessage; }
/**
* Gets format version.
*
* @return the format version
*/
public int getFormatVersion() {
return formatVersion;
}
public int getCurrentFormatVersion() {
return formatVersion;
}
public void setFormatVersion(int formatVersion) {
this.formatVersion = formatVersion;
}
/**
* Save.
*
* @throws NullPointerException the null pointer exception
*/
public void save() throws FileNotFoundException {
if(filename != null) {
//save in a separate thread
new Thread(new Runnable() {
@Override
public void run() {
try {
long start = Utils.currentTimeMillis();
FlatDB<AbstractManager> flatDB = new FlatDB<AbstractManager>(context, filename, true, magicMessage, getFormatVersion());
flatDB.dump(AbstractManager.this);
long end = Utils.currentTimeMillis();
log.info(AbstractManager.class.getCanonicalName() + " Save time: " + (end - start) + "ms");
} catch (Exception x) {
log.warn("Saving failed for " + getDefaultFileName());
}
}
}).start();
} else throw new FileNotFoundException("filename is not set");
}
/**
* Sets filename to which the object data will be saved.
*
* @param filename the filename
*/
public void setFilename(String filename) {
this.filename = filename;
}
public abstract void close();
public void onFirstSaveComplete() {
}
}
|
package bndtools;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.bndtools.api.ILogger;
import org.bndtools.api.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import aQute.bnd.service.Refreshable;
import aQute.bnd.service.RepositoryPlugin;
import bndtools.central.Central;
import bndtools.central.RepositoryUtils;
public class RefreshReposHandler extends AbstractHandler {
private static final ILogger logger = Logger.getLogger(RefreshReposHandler.class);
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
try {
final IFile buildFile = Central.getWorkspaceBuildFile();
if (buildFile == null) {
MessageDialog.openError(window.getShell(), "Error", "Unable to refresh repositories: workspace build file is missing.");
return null;
}
window.run(true, false, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
buildFile.getWorkspace().run(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
List<RepositoryPlugin> repos = RepositoryUtils.listRepositories(true);
for (RepositoryPlugin i : repos) {
if (i instanceof Refreshable) {
boolean success = false;
try {
success = ((Refreshable) i).refresh();
} catch (Exception e) {
logger.logError("Exception while refreshing repository: " + i.getName(), e);
}
if (!success) {
logger.logError("Failed to refresh repository: " + i.getName(), null);
}
}
}
buildFile.touch(monitor);
}
}, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (Exception e) {
logger.logError("Error refreshing repositories.", e);
}
return null;
}
}
|
package Feeds;
import java.util.ArrayList;
public class MainFeeds {
/**
* Creating Static objects of ThreatFeedsFetcher.java
* and getting the categorized feeds in respective ArrayLists
*/
public static ArrayList<String> Malwares, DB, Probing, SIP, SSH, Web, Urls;
static ThreatFeedsFetcher malwares = new ThreatFeedsFetcher();
static ThreatFeedsFetcher db = new ThreatFeedsFetcher();
static ThreatFeedsFetcher probing = new ThreatFeedsFetcher();
static ThreatFeedsFetcher sip = new ThreatFeedsFetcher();
static ThreatFeedsFetcher ssh = new ThreatFeedsFetcher();
static ThreatFeedsFetcher web = new ThreatFeedsFetcher();
static ThreatFeedsFetcher urls = new ThreatFeedsFetcher();
static {
Malwares = malwares.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=ip&type=malware", "MALWARE FEEDS");
DB = db.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=ip&type=db", "DB FEEDS");
Probing = probing.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=ip&type=probing", "PROBING FEEDS");
SIP = sip.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=ip&type=sip", "SIP FEEDS");
SSH = ssh.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=ip&type=ssh", "SSH FEEDS");
Web = web.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=ip&type=web", "WEB FEEDS");
Urls = urls.FeedsFetchers("http://115.186.132.18:8080/TI/feeds?indicator=url", "URLS FEEDS");
}
}
|
package com.knr.recyclr;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
public class AddItemActivity extends ActionBarActivity {
private boolean isTrash;
private String upcCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
getActionBar().hide();
Intent intent = getIntent();
upcCode = intent.getStringExtra(MainActivity.UPC_IDENTIFIER);
new RetrieveUpcTask(getApplicationContext(), (Activity)this, R.id.itemImagePlaceholder).execute(upcCode);
DatabaseWrapper db_wrap = new DatabaseWrapper(getApplicationContext(), (Activity)this, MainActivity.getConn());
db_wrap.getAction(upcCode);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_item, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_recycle:
if (checked)
isTrash = false;
break;
case R.id.radio_trash:
if (checked)
isTrash = true;
break;
}
}
public void onSubmitButtonClicked(View view)
{
DatabaseWrapper db_wrap = new DatabaseWrapper(getApplicationContext(), (Activity)this, MainActivity.getConn());
db_wrap.setUpc(upcCode, isTrash);
finish();
}
}
|
package edu.umd.cs.findbugs;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.ClassFormatException;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.ClassObserver;
import edu.umd.cs.findbugs.ba.InnerClassAccessMap;
import edu.umd.cs.findbugs.visitclass.Constants2;
/**
* An instance of this class is used to apply the selected set of
* analyses on some collection of Java classes. It also implements the
* comand line interface.
*
* @author Bill Pugh
* @author David Hovemeyer
*/
public class FindBugs implements Constants2, ExitCodes {
/**
* Delegating InputStream wrapper that never closes the
* underlying input stream.
*/
private static class NoCloseInputStream extends DataInputStream {
/**
* Constructor.
* @param in the real InputStream
*/
public NoCloseInputStream(InputStream in) {
super(in);
}
public void close() {
}
}
/**
* Work list item specifying a file/directory/URL containing
* class files to analyze.
*/
private static class ArchiveWorkListItem {
private String fileName;
private boolean explicit;
/**
* Constructor.
*
* @param fileName file/directory/URL
* @param explicit true if this source of classes appeared explicitly
* in the project file, false if was found indirectly
* (e.g., a nested jar file in a .war file)
*/
public ArchiveWorkListItem(String fileName, boolean explicit) {
this.fileName = fileName;
this.explicit = explicit;
}
/**
* Get the file/directory/URL.
*/
public String getFileName() {
return fileName;
}
/**
* Return whether this class source appeared explicitly in
* the project file.
*/
public boolean isExplicit() {
return explicit;
}
}
/**
* Interface for an object representing a source of class files to analyze.
*/
private interface ClassProducer {
/**
* Get the next class to analyze.
*
* @return the class, or null of there are no more classes for this ClassProducer
* @throws IOException if an IOException occurs
* @throws InterruptedException if the thread is interrupted
*/
public JavaClass getNextClass() throws IOException, InterruptedException;
/**
* Did this class producer scan any Java source files?
*/
public boolean containsSourceFiles();
/**
* Close any internal files or streams.
*/
public void close();
}
/**
* ClassProducer for single class files.
*/
private class SingleClassProducer implements ClassProducer {
private URL url;
/**
* Constructor.
*
* @param url the single class file to be analyzed
*/
public SingleClassProducer(URL url) {
this.url = url;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
if (url == null)
return null;
if (Thread.interrupted())
throw new InterruptedException();
URL urlToParse = url;
url = null; // don't return it next time
// ClassScreener may veto this class.
if (!classScreener.matches(urlToParse.toString()))
return null;
try {
return parseClass(urlToParse);
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
url.toString() + ": " + e.getMessage());
}
}
public boolean containsSourceFiles() {
return false;
}
public void close() {
// Nothing to do here
}
}
/**
* ClassProducer for zip/jar archives.
*/
private class ZipClassProducer implements ClassProducer {
private URL url;
private LinkedList<ArchiveWorkListItem> archiveWorkList;
private List<String> additionalAuxClasspathEntryList;
private ZipInputStream zipInputStream;
private boolean containsSourceFiles;
public ZipClassProducer(URL url, LinkedList<ArchiveWorkListItem> archiveWorkList,
List<String> additionalAuxClasspathEntryList)
throws IOException {
this.url = url;
this.archiveWorkList = archiveWorkList;
this.additionalAuxClasspathEntryList = additionalAuxClasspathEntryList;
if (DEBUG) System.out.println("Opening jar/zip input stream for " + url.toString());
this.zipInputStream = new ZipInputStream(url.openStream());
this.containsSourceFiles = false;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
for (;;) {
if (Thread.interrupted())
throw new InterruptedException();
ZipEntry zipEntry = zipInputStream.getNextEntry();
if (zipEntry == null)
return null;
try {
String entryName = zipEntry.getName();
// ClassScreener may veto this class.
if (!classScreener.matches(entryName)) {
// Add archive URL to aux classpath
if (!additionalAuxClasspathEntryList.contains(url.toString())) {
//System.out.println("Adding additional aux classpath entry: " + url.toString());
additionalAuxClasspathEntryList.add(url.toString());
}
continue;
}
String fileExtension = getFileExtension(entryName);
if (fileExtension != null) {
if (fileExtension.equals(".class")) {
return parseClass(url.toString(), new NoCloseInputStream(zipInputStream), entryName);
} else if (archiveExtensionSet.contains(fileExtension)) {
// Add nested archive to archive work list
ArchiveWorkListItem nestedItem =
new ArchiveWorkListItem("jar:" + url.toString() + "!/" + entryName, false);
archiveWorkList.addFirst(nestedItem);
} else if (fileExtension.equals(".java")) {
containsSourceFiles = true;
}
}
} finally {
zipInputStream.closeEntry();
}
}
}
public boolean containsSourceFiles() {
return containsSourceFiles;
}
public void close() {
if (zipInputStream != null) {
try {
zipInputStream.close();
} catch (IOException ignore) {
// Ignore
}
}
}
}
/**
* ClassProducer for directories.
* The directory is scanned recursively for class files.
*/
private class DirectoryClassProducer implements ClassProducer {
private String dirName;
private List<String> additionalAuxClasspathEntryList;
private Iterator<String> rfsIter;
private boolean containsSourceFiles;
public DirectoryClassProducer(String dirName,
List<String> additionalAuxClasspathEntryList) throws InterruptedException {
this.dirName = dirName;
this.additionalAuxClasspathEntryList = additionalAuxClasspathEntryList;
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
String fileName = file.getName();
if (file.isDirectory() || fileName.endsWith(".class"))
return true;
if (fileName.endsWith(".java"))
containsSourceFiles = true;
return false;
}
};
// This will throw InterruptedException if the thread is
// interrupted.
RecursiveFileSearch rfs = new RecursiveFileSearch(dirName, filter).search();
this.rfsIter = rfs.fileNameIterator();
this.containsSourceFiles = false;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
String fileName;
for (;;) {
if (!rfsIter.hasNext())
return null;
fileName = rfsIter.next();
if (classScreener.matches(fileName)) {
break;
} else {
// Add directory URL to aux classpath
String dirURL= "file:" + dirName;
if (!additionalAuxClasspathEntryList.contains(dirURL)) {
//System.out.println("Adding additional aux classpath entry: " + dirURL);
additionalAuxClasspathEntryList.add(dirURL);
}
}
}
try {
return parseClass(new URL("file:" + fileName));
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ": " + e.getMessage());
}
}
public boolean containsSourceFiles() {
return containsSourceFiles;
}
public void close() {
// Nothing to do here
}
}
/**
* A delegating bug reporter which counts reported bug instances,
* missing classes, and serious analysis errors.
*/
private static class ErrorCountingBugReporter extends DelegatingBugReporter {
private int bugCount;
private int missingClassCount;
private int errorCount;
private Set<String> missingClassSet = new HashSet<String>();
public ErrorCountingBugReporter(BugReporter realBugReporter) {
super(realBugReporter);
this.bugCount = 0;
this.missingClassCount = 0;
this.errorCount = 0;
// Add an observer to record when bugs make it through
// all priority and filter criteria, so our bug count is
// accurate.
realBugReporter.addObserver(new BugReporterObserver() {
public void reportBug(BugInstance bugInstance) {
++bugCount;
}
});
}
public int getBugCount() {
return bugCount;
}
public int getMissingClassCount() {
return missingClassCount;
}
public int getErrorCount() {
return errorCount;
}
public void logError(String message) {
++errorCount;
super.logError(message);
}
public void reportMissingClass(ClassNotFoundException ex) {
String missing = AbstractBugReporter.getMissingClassName(ex);
if (missingClassSet.add(missing))
++missingClassCount;
super.reportMissingClass(ex);
}
}
private static class CategoryFilteringBugReporter extends DelegatingBugReporter {
private Set<String> categorySet;
public CategoryFilteringBugReporter(BugReporter realBugReporter, Set<String> categorySet) {
super(realBugReporter);
this.categorySet = categorySet;
}
public void reportBug(BugInstance bugInstance) {
BugPattern bugPattern = bugInstance.getBugPattern();
String category = bugPattern.getCategory();
if (categorySet.contains(category))
getRealBugReporter().reportBug(bugInstance);
}
}
/**
* Handling callback for choose() method,
* used to implement the -chooseVisitors and -choosePlugins options.
*/
private interface Chooser {
/**
* Choose a detector, plugin, etc.
*
* @param enable whether or not the item should be enabled
* @param what the item
*/
public void choose(boolean enable, String what);
}
private static final int PRINTING_REPORTER = 0;
private static final int SORTING_REPORTER = 1;
private static final int XML_REPORTER = 2;
private static final int EMACS_REPORTER = 3;
private static final int HTML_REPORTER = 4;
private static final int XDOCS_REPORTER = 5;
/**
* Helper class to parse the command line and create
* the FindBugs engine object.
*/
private static class FindBugsCommandLine extends CommandLine {
private int bugReporterType = PRINTING_REPORTER;
private boolean xmlWithMessages = false;
private String stylesheet = null;
private Project project = new Project();
private boolean quiet = false;
private ClassScreener classScreener = new ClassScreener();
private String filterFile = null;
private boolean include = false;
private boolean setExitCode = false;
private int priorityThreshold = Detector.NORMAL_PRIORITY;
private PrintStream outputStream = null;
private Set<String> bugCategorySet = null;
public FindBugsCommandLine() {
addOption("-home", "home directory", "specify FindBugs home directory");
addOption("-pluginList", "jar1[" + File.pathSeparator + "jar2...]",
"specify list of plugin Jar files to load");
addSwitch("-showPlugins", "show list of available plugins");
addSwitch("-quiet", "suppress error messages");
addSwitch("-experimental", "report all warnings including experimental bug patterns");
addSwitch("-low", "report all warnings");
addSwitch("-medium", "report only medium and high priority warnings [default]");
addSwitch("-high", "report only high priority warnings");
addSwitch("-sortByClass", "sort warnings by class");
addSwitchWithOptionalExtraPart("-xml", "withMessages",
"XML output (optionally with messages)");
addSwitch("-xdocs", "xdoc XML output to use with Apache Maven");
addSwitchWithOptionalExtraPart("-html", "stylesheet",
"Generate HTML output (default stylesheet is default.xsl)");
addSwitch("-emacs", "Use emacs reporting format");
addOption("-outputFile", "filename", "Save output in named file");
addOption("-visitors", "v1[,v2...]", "run only named visitors");
addOption("-omitVisitors", "v1[,v2...]", "omit named visitors");
addOption("-chooseVisitors", "+v1,-v2,...", "selectively enable/disable detectors");
addOption("-choosePlugins", "+p1,-p2,...", "selectively enable/disable plugins");
addSwitch("-adjustExperimental", "lower the priority of Bug Patterns that are experimental");
addOption("-adjustPriority", "v1=(raise|lower)[,...]",
"raise/lower priority of warnings for given visitor(s)");
addOption("-bugCategories", "cat1[,cat2...]", "only report bugs in given categories");
addOption("-onlyAnalyze", "classes/packages", "only analyze given classes and packages");
addOption("-exclude", "filter file", "exclude bugs matching given filter");
addOption("-include", "filter file", "include only bugs matching given filter");
addOption("-auxclasspath", "classpath", "set aux classpath for analysis");
addOption("-sourcepath", "source path", "set source path for analyzed classes");
addOption("-project", "project", "analyze given project");
addSwitch("-exitcode", "set exit code of process");
}
public Project getProject() {
return project;
}
public boolean setExitCode() {
return setExitCode;
}
public boolean quiet() {
return quiet;
}
protected void handleOption(String option, String optionExtraPart) {
if (option.equals("-showPlugins")) {
System.out.println("Available plugins:");
int count = 0;
for (Iterator<Plugin> i = DetectorFactoryCollection.instance().pluginIterator(); i.hasNext(); ) {
Plugin plugin = i.next();
System.out.println(" " + plugin.getPluginId() + " (default: " +
(plugin.isEnabled() ? "enabled" : "disabled") + ")");
++count;
}
if (count == 0) {
System.out.println(" No plugins are available (FindBugs installed incorrectly?)");
}
System.exit(0);
} else if (option.equals("-experimental"))
priorityThreshold = Detector.EXP_PRIORITY;
else if (option.equals("-low"))
priorityThreshold = Detector.LOW_PRIORITY;
else if (option.equals("-medium"))
priorityThreshold = Detector.NORMAL_PRIORITY;
else if (option.equals("-high"))
priorityThreshold = Detector.HIGH_PRIORITY;
else if (option.equals("-adjustExperimental"))
BugInstance.setAdjustExperimental(true);
else if (option.equals("-sortByClass"))
bugReporterType = SORTING_REPORTER;
else if (option.equals("-xml")) {
bugReporterType = XML_REPORTER;
if (!optionExtraPart.equals("")) {
if (optionExtraPart.equals("withMessages"))
xmlWithMessages = true;
else
throw new IllegalArgumentException("Unknown option: -xml:" + optionExtraPart);
}
} else if (option.equals("-emacs"))
bugReporterType = EMACS_REPORTER;
else if (option.equals("-html")) {
bugReporterType = HTML_REPORTER;
if (!optionExtraPart.equals("")) {
stylesheet = optionExtraPart;
} else {
stylesheet = "default.xsl";
}
} else if (option.equals("-xdocs"))
bugReporterType = XDOCS_REPORTER;
else if (option.equals("-quiet"))
quiet = true;
else if (option.equals("-exitcode"))
setExitCode = true;
else
throw new IllegalStateException();
}
protected void handleOptionWithArgument(String option, String argument) throws IOException {
if (option.equals("-home")) {
FindBugs.setHome(argument);
} else if (option.equals("-pluginList")) {
String pluginListStr = argument;
ArrayList<File> pluginList = new ArrayList<File>();
StringTokenizer tok = new StringTokenizer(pluginListStr, File.pathSeparator);
while (tok.hasMoreTokens()) {
pluginList.add(new File(tok.nextToken()));
}
DetectorFactoryCollection.setPluginList((File[]) pluginList.toArray(new File[pluginList.size()]));
} else if (option.equals("-outputFile")) {
String outputFile = argument;
try {
outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
} catch (IOException e) {
System.err.println("Couldn't open " + outputFile + " for output: " + e.toString());
System.exit(1);
}
} else if (option.equals("-visitors") || option.equals("-omitVisitors")) {
boolean omit = option.equals("-omitVisitors");
if (!omit) {
// Selecting detectors explicitly, so start out by
// disabling all of them. The selected ones will
// be re-enabled.
DetectorFactoryCollection.instance().disableAll();
}
// Explicitly enable or disable the selected detectors.
StringTokenizer tok = new StringTokenizer(argument, ",");
while (tok.hasMoreTokens()) {
String visitorName = tok.nextToken();
DetectorFactory factory = DetectorFactoryCollection.instance().getFactory(visitorName);
if (factory == null)
throw new IllegalArgumentException("Unknown detector: " + visitorName);
factory.setEnabled(!omit);
}
} else if (option.equals("-chooseVisitors")) {
// This is like -visitors and -omitVisitors, but
// you can selectively enable and disable detectors,
// starting from the default set (or whatever set
// happens to be in effect).
choose(argument, "Detector choices", new Chooser() {
public void choose(boolean enabled, String what) {
DetectorFactory factory = DetectorFactoryCollection.instance()
.getFactory(what);
if (factory == null)
throw new IllegalArgumentException("Unknown detector: " + what);
factory.setEnabled(enabled);
}
});
} else if (option.equals("-choosePlugins")) {
// Selectively enable/disable plugins
choose(argument, "Plugin choices", new Chooser() {
public void choose(boolean enabled, String what) {
Plugin plugin = DetectorFactoryCollection.instance().getPluginById(what);
if (plugin == null)
throw new IllegalArgumentException("Unknown plugin: " + what);
plugin.setEnabled(enabled);
}
});
} else if (option.equals("-adjustPriority")) {
// Selectively raise or lower the priority of warnings
// produced by specified detectors.
StringTokenizer tok = new StringTokenizer(argument, ",");
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
int eq = token.indexOf('=');
if (eq < 0)
throw new IllegalArgumentException("Illegal priority adjustment: " + token);
String visitorName = token.substring(0, eq);
DetectorFactory factory = DetectorFactoryCollection.instance()
.getFactory(visitorName);
if (factory == null)
throw new IllegalArgumentException("Unknown detector: " + visitorName);
String adjustment = token.substring(eq + 1);
if (!(adjustment.equals("raise") || adjustment.equals("lower")))
throw new IllegalArgumentException("Illegal priority adjustment value: " +
adjustment);
// Recall that lower values are higher priorities
factory.setPriorityAdjustment(adjustment.equals("raise") ? -1 : +1);
}
} else if (option.equals("-bugCategories")) {
this.bugCategorySet = handleBugCategories(argument);
} else if (option.equals("-onlyAnalyze")) {
// The argument is a comma-separated list of classes and packages
// to select to analyze. (If a list item ends with ".*",
// it specifies a package, otherwise it's a class.)
StringTokenizer tok = new StringTokenizer(argument, ",");
while (tok.hasMoreTokens()) {
String item = tok.nextToken();
if (item.endsWith(".*"))
classScreener.addAllowedPackage(item.substring(0, item.length() - ".*".length()));
else
classScreener.addAllowedClass(item);
}
} else if (option.equals("-exclude") || option.equals("-include")) {
filterFile = argument;
include = option.equals("-include");
} else if (option.equals("-auxclasspath")) {
StringTokenizer tok = new StringTokenizer(argument, File.pathSeparator);
while (tok.hasMoreTokens())
project.addAuxClasspathEntry(tok.nextToken());
} else if (option.equals("-sourcepath")) {
StringTokenizer tok = new StringTokenizer(argument, File.pathSeparator);
while (tok.hasMoreTokens())
project.addSourceDir(new File(tok.nextToken()).getAbsolutePath());
} else if (option.equals("-project")) {
String projectFile = argument;
// Convert project file to be an absolute path
projectFile = new File(projectFile).getAbsolutePath();
try {
project = new Project();
project.read(projectFile);
} catch (IOException e) {
System.err.println("Error opening " + projectFile);
e.printStackTrace(System.err);
throw e;
}
}
}
/**
* Common handling code for -chooseVisitors and -choosePlugins options.
*
* @param argument the list of visitors or plugins to be chosen
* @param desc String describing what is being chosen
* @param chooser callback object to selectively choose list members
*/
private void choose(String argument, String desc, Chooser chooser) {
StringTokenizer tok = new StringTokenizer(argument, ",");
while (tok.hasMoreTokens()) {
String what = tok.nextToken();
if (!what.startsWith("+") && !what.startsWith("-"))
throw new IllegalArgumentException(desc + " must start with " +
"\"+\" or \"-\" (saw " + what + ")");
boolean enabled = what.startsWith("+");
chooser.choose(enabled, what.substring(1));
}
}
public FindBugs createEngine() throws IOException, FilterException {
TextUIBugReporter textuiBugReporter = null;
switch (bugReporterType) {
case PRINTING_REPORTER:
textuiBugReporter = new PrintingBugReporter();
break;
case SORTING_REPORTER:
textuiBugReporter = new SortingBugReporter();
break;
case XML_REPORTER:
{
XMLBugReporter xmlBugReporter = new XMLBugReporter(project);
xmlBugReporter.setAddMessages(xmlWithMessages);
textuiBugReporter = xmlBugReporter;
}
break;
case EMACS_REPORTER:
textuiBugReporter = new EmacsBugReporter();
break;
case HTML_REPORTER:
textuiBugReporter = new HTMLBugReporter(project, stylesheet);
break;
case XDOCS_REPORTER:
textuiBugReporter = new XDocsBugReporter(project);
break;
default:
throw new IllegalStateException();
}
if (quiet)
textuiBugReporter.setErrorVerbosity(BugReporter.SILENT);
textuiBugReporter.setPriorityThreshold(priorityThreshold);
if (outputStream != null)
textuiBugReporter.setOutputStream(outputStream);
BugReporter bugReporter = textuiBugReporter;
if (bugCategorySet != null) {
bugReporter = new CategoryFilteringBugReporter(bugReporter, bugCategorySet);
}
FindBugs findBugs = new FindBugs(bugReporter, project);
if (filterFile != null)
findBugs.setFilter(filterFile, include);
findBugs.setClassScreener(classScreener);
return findBugs;
}
}
static final boolean DEBUG = Boolean.getBoolean("findbugs.debug");
/**
* FindBugs home directory.
*/
private static String home;
/**
* File extensions that indicate an archive (zip, jar, or similar).
*/
private static final Set<String> archiveExtensionSet = new HashSet<String>();
static {
archiveExtensionSet.add(".jar");
archiveExtensionSet.add(".zip");
archiveExtensionSet.add(".war");
archiveExtensionSet.add(".ear");
archiveExtensionSet.add(".sar");
}
/**
* Known URL protocols.
* Filename URLs that do not have an explicit protocol are
* assumed to be files.
*/
private static final Set<String> knownURLProtocolSet = new HashSet<String>();
static {
knownURLProtocolSet.add("file");
knownURLProtocolSet.add("http");
knownURLProtocolSet.add("https");
knownURLProtocolSet.add("jar");
}
private ErrorCountingBugReporter bugReporter;
private Project project;
private List<ClassObserver> classObserverList;
private Detector detectors [];
private FindBugsProgress progressCallback;
private ClassScreener classScreener;
private AnalysisContext analysisContext;
private String currentClass;
/**
* Constructor.
*
* @param bugReporter the BugReporter object that will be used to report
* BugInstance objects, analysis errors, class to source mapping, etc.
* @param project the Project indicating which files to analyze and
* the auxiliary classpath to use; note that the FindBugs
* object will create a private copy of the Project object
*/
public FindBugs(BugReporter bugReporter, Project project) {
if (bugReporter == null)
throw new IllegalArgumentException("null bugReporter");
if (project == null)
throw new IllegalArgumentException("null project");
this.bugReporter = new ErrorCountingBugReporter(bugReporter);
this.project = project.duplicate();
this.classObserverList = new LinkedList<ClassObserver>();
// Create a no-op progress callback.
this.progressCallback = new FindBugsProgress() {
public void reportNumberOfArchives(int numArchives) {
}
public void finishArchive() {
}
public void startAnalysis(int numClasses) {
}
public void finishClass() {
}
public void finishPerClassAnalysis() {
}
};
// Class screener
this.classScreener = new ClassScreener();
addClassObserver(bugReporter);
}
/**
* Set the progress callback that will be used to keep track
* of the progress of the analysis.
*
* @param progressCallback the progress callback
*/
public void setProgressCallback(FindBugsProgress progressCallback) {
this.progressCallback = progressCallback;
}
/**
* Set filter of bug instances to include or exclude.
*
* @param filterFileName the name of the filter file
* @param include true if the filter specifies bug instances to include,
* false if it specifies bug instances to exclude
*/
public void setFilter(String filterFileName, boolean include) throws IOException, FilterException {
Filter filter = new Filter(filterFileName);
BugReporter origBugReporter = bugReporter.getRealBugReporter();
BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, filter, include);
bugReporter.setRealBugReporter(filterBugReporter);
}
/**
* Add a ClassObserver.
*
* @param classObserver the ClassObserver
*/
public void addClassObserver(ClassObserver classObserver) {
classObserverList.add(classObserver);
}
/**
* Set the ClassScreener.
* This object chooses which individual classes to analyze.
* By default, all classes are analyzed.
*
* @param classScreener the ClassScreener to use
*/
public void setClassScreener(ClassScreener classScreener) {
this.classScreener = classScreener;
}
/**
* Execute FindBugs on the Project.
* All bugs found are reported to the BugReporter object which was set
* when this object was constructed.
*
* @throws java.io.IOException if an I/O exception occurs analyzing one of the files
* @throws InterruptedException if the thread is interrupted while conducting the analysis
*/
public void execute() throws java.io.IOException, InterruptedException {
// Configure the analysis context
analysisContext = new AnalysisContext(bugReporter);
analysisContext.setSourcePath(project.getSourceDirList());
// Give the BugReporter a reference to this object,
// in case it wants to access information such
// as the AnalysisContext
bugReporter.setEngine(this);
// Create detectors
createDetectors();
// Clear the repository of classes
clearRepository();
// Get list of files to analyze.
// Note that despite the name getJarFileArray(),
// they can also be zip files, directories,
// and single class files.
LinkedList<ArchiveWorkListItem> archiveWorkList = new LinkedList<ArchiveWorkListItem>();
for (Iterator<String> i = project.getFileList().iterator(); i.hasNext(); ) {
String fileName = i.next();
archiveWorkList.add(new ArchiveWorkListItem(fileName, true));
}
// Report how many archives/directories/files will be analyzed,
// for progress dialog in GUI
progressCallback.reportNumberOfArchives(archiveWorkList.size());
// Keep track of the names of all classes to be analyzed
List<String> repositoryClassList = new LinkedList<String>();
// Record additional entries that should be added to
// the aux classpath. These occur when one or more classes
// in a directory or archive are skipped, to ensure that
// the skipped classes can still be referenced.
List<String> additionalAuxClasspathEntryList = new LinkedList<String>();
// Add all classes in analyzed archives/directories/files
while (!archiveWorkList.isEmpty()) {
ArchiveWorkListItem item = archiveWorkList.removeFirst();
scanArchiveOrDirectory(item, archiveWorkList, repositoryClassList,
additionalAuxClasspathEntryList);
}
// Now that we have scanned all specified archives and directories,
// we can set the repository classpath.
setRepositoryClassPath(additionalAuxClasspathEntryList);
// Callback for progress dialog: analysis is starting
progressCallback.startAnalysis(repositoryClassList.size());
// Examine all classes for bugs.
// Don't examine the same class more than once.
// (The user might specify two jar files that contain
// the same class.)
Set<String> examinedClassSet = new HashSet<String>();
for (Iterator<String> i = repositoryClassList.iterator(); i.hasNext();) {
String className = i.next();
if (examinedClassSet.add(className))
examineClass(className);
}
// Callback for progress dialog: analysis finished
progressCallback.finishPerClassAnalysis();
// Force any detectors which defer work until all classes have
// been seen to do that work.
this.reportFinal();
// Flush any queued bug reports
bugReporter.finish();
// Flush any queued error reports
bugReporter.reportQueuedErrors();
}
/**
* Get the analysis context.
* It is only valid to call this method after the execute()
* method has been called.
*/
public AnalysisContext getAnalysisContext() {
return analysisContext;
}
/**
* Get the name of the most recent class to be analyzed.
* This is useful for diagnosing an unexpected exception.
* Returns null if no class has been analyzed.
*/
public String getCurrentClass() {
return currentClass;
}
/**
* Get the number of bug instances that were reported during analysis.
*/
public int getBugCount() {
return bugReporter.getBugCount();
}
/**
* Get the number of errors that occurred during analysis.
*/
public int getErrorCount() {
return bugReporter.getErrorCount();
}
/**
* Get the number of time missing classes were reported during analysis.
*/
public int getMissingClassCount() {
return bugReporter.getMissingClassCount();
}
/**
* Set the FindBugs home directory.
*/
public static void setHome(String home) {
FindBugs.home = home;
}
/**
* Get the FindBugs home directory.
*/
public static String getHome() {
if (home == null) {
home = System.getProperty("findbugs.home");
if (home == null) {
System.err.println("Error: The findbugs.home property is not set!");
}
}
return home;
}
/**
* Create Detectors for each DetectorFactory which is enabled.
* This will populate the detectors array.
*/
private void createDetectors() {
ArrayList<Detector> result = new ArrayList<Detector>();
Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator();
while (i.hasNext()) {
DetectorFactory factory = i.next();
if (factory.getPlugin().isEnabled() && factory.isEnabled()) {
Detector detector = factory.create(bugReporter);
detector.setAnalysisContext(analysisContext);
result.add(detector);
}
}
detectors = result.toArray(new Detector[result.size()]);
}
/**
* Clear the Repository and update it to reflect the classpath
* specified by the current project.
*/
private void clearRepository() {
// Purge repository of previous contents
Repository.clearCache();
// Clear InnerClassAccessMap cache.
InnerClassAccessMap.instance().clearCache();
// Create a URLClassPathRepository based on the current project,
// and make it current.
URLClassPathRepository repository = new URLClassPathRepository();
Repository.setRepository(repository);
}
/**
* Based on Project settings, set the classpath to be used
* by the Repository when looking up classes.
* @throws IOException
*/
private void setRepositoryClassPath(List<String> additionalAuxClasspathEntryList)
throws IOException {
URLClassPathRepository repository =
(URLClassPathRepository) Repository.getRepository();
// Set aux classpath entries
addCollectionToClasspath(project.getAuxClasspathEntryList(), repository);
// Set implicit classpath entries
addCollectionToClasspath(project.getImplicitClasspathEntryList(), repository);
// Add "extra" aux classpath entries needed to ensure that
// skipped classes can be referenced.
addCollectionToClasspath(additionalAuxClasspathEntryList, repository);
// Add system classpath entries
repository.addSystemClasspathComponents();
}
/**
* Add all classpath entries in given Collection to the given
* URLClassPathRepository. Missing entries are not fatal:
* we'll log them as analysis errors, but the analysis can
* continue.
*
* @param collection classpath entries to add
* @param repository URLClassPathRepository to add the entries to
*/
private void addCollectionToClasspath(Collection<String> collection,
URLClassPathRepository repository) {
for (Iterator<String> i = collection.iterator(); i.hasNext(); ) {
String entry = i.next();
try {
repository.addURL(entry);
} catch (IOException e) {
bugReporter.logError("Warning: could not add URL " +
entry + " to classpath: " + e.toString());
}
}
}
/**
* Add all classes contained in given file or directory to the BCEL Repository.
*
* @param item work list item representing the file, which may be a jar/zip
* archive, a single class file, or a directory to be recursively
* searched for class files
* @param archiveWorkList work list of archives to analyze: this method
* may add to the work list if it finds nested archives
* @param repositoryClassList a List to which all classes found in
* the archive or directory are added, so we later know
* which files to analyze
*/
private void scanArchiveOrDirectory(ArchiveWorkListItem item,
LinkedList<ArchiveWorkListItem> archiveWorkList, List<String> repositoryClassList,
List<String> additionalAuxClasspathEntryList)
throws IOException, InterruptedException {
String fileName = item.getFileName();
ClassProducer classProducer = null;
try {
// Create a URL for the filename.
// The protocol defaults to "file" if not explicitly
// specified in the filename.
String protocol = getURLProtocol(fileName);
if (protocol == null) {
protocol = "file";
fileName = "file:" + fileName;
}
URL url = new URL(fileName);
// Figure out the file extension
String fileExtension = null;
int lastDot = fileName.lastIndexOf('.');
if (lastDot >= 0) {
fileExtension = fileName.substring(lastDot);
}
// Create the ClassProducer
if (fileExtension != null && isArchiveExtension(fileExtension))
classProducer = new ZipClassProducer(url, archiveWorkList, additionalAuxClasspathEntryList);
else if (fileExtension != null && fileExtension.equals(".class"))
classProducer = new SingleClassProducer(url);
else if (protocol.equals("file")) {
// Assume it's a directory
fileName = fileName.substring("file:".length());
File dir = new File(fileName);
if (!dir.isDirectory())
throw new IOException("Path " + fileName + " is not an archive, class file, or directory");
classProducer = new DirectoryClassProducer(fileName, additionalAuxClasspathEntryList);
} else
throw new IOException("URL " + fileName + " is not an archive, class file, or directory");
// Load all referenced classes into the Repository
for (; ;) {
if (Thread.interrupted())
throw new InterruptedException();
try {
JavaClass jclass = classProducer.getNextClass();
if (jclass == null)
break;
if (DEBUG) System.out.println("Scanned " + jclass.getClassName());
Repository.addClass(jclass);
repositoryClassList.add(jclass.getClassName());
} catch (ClassFormatException e) {
e.printStackTrace();
bugReporter.logError(e.getMessage());
}
}
if (item.isExplicit())
progressCallback.finishArchive();
// If the archive or directory scanned contained source files,
// add it to the end of the source path.
if (classProducer.containsSourceFiles())
project.addSourceDir(fileName);
} catch (IOException e) {
// You'd think that the message for a FileNotFoundException would include
// the filename, but you'd be wrong. So, we'll add it explicitly.
throw new IOException("Could not analyze " + fileName + ": " + e.getMessage());
} finally {
if (classProducer != null) {
classProducer.close();
}
}
}
/**
* Examine a single class by invoking all of the Detectors on it.
*
* @param className the fully qualified name of the class to examine
*/
private void examineClass(String className) throws InterruptedException {
if (DEBUG) System.out.println("Examining class " + className);
this.currentClass = className;
try {
JavaClass javaClass = Repository.lookupClass(className);
// Notify ClassObservers
for (Iterator<ClassObserver> i = classObserverList.iterator(); i.hasNext();) {
i.next().observeClass(javaClass);
}
// Create a ClassContext for the class
ClassContext classContext = analysisContext.getClassContext(javaClass);
// Run the Detectors
for (int i = 0; i < detectors.length; ++i) {
if (Thread.interrupted())
throw new InterruptedException();
try {
Detector detector = detectors[i];
if (DEBUG) System.out.println(" running " + detector.getClass().getName());
detector.visitClassContext(classContext);
} catch (AnalysisException e) {
reportRecoverableException(className, e);
} catch (ArrayIndexOutOfBoundsException e) {
reportRecoverableException(className, e);
} catch (ClassCastException e) {
reportRecoverableException(className, e);
}
}
} catch (ClassNotFoundException e) {
// This should never happen unless there are bugs in BCEL.
bugReporter.reportMissingClass(e);
reportRecoverableException(className, e);
} catch (ClassFormatException e) {
reportRecoverableException(className, e);
}
progressCallback.finishClass();
}
private void reportRecoverableException(String className, Exception e) {
if (DEBUG) {
e.printStackTrace();
}
bugReporter.logError("Exception analyzing " + className + ": " + e.toString());
}
/**
* Call report() on all detectors, to give them a chance to
* report any accumulated bug reports.
*/
private void reportFinal() throws InterruptedException {
for (int i = 0; i < detectors.length; ++i) {
if (Thread.interrupted())
throw new InterruptedException();
detectors[i].report();
}
}
/**
* Get the file extension of given fileName.
* @return the file extension, or null if there is no file extension
*/
static String getFileExtension(String fileName) {
int lastDot = fileName.lastIndexOf('.');
return (lastDot >= 0)
? fileName.substring(lastDot)
: null;
}
/**
* Get the URL protocol of given URL string.
* @param urlString the URL string
* @return the protocol name ("http", "file", etc.), or null if there is no protocol
*/
static String getURLProtocol(String urlString) {
String protocol = null;
int firstColon = urlString.indexOf(':');
if (firstColon >= 0) {
String specifiedProtocol = urlString.substring(0, firstColon);
if (knownURLProtocolSet.contains(specifiedProtocol))
protocol = specifiedProtocol;
}
return protocol;
}
/**
* Determine if given file extension indicates an archive file.
*
* @param fileExtension the file extension (e.g., ".jar")
* @return true if the file extension indicates an archive,
* false otherwise
*/
static boolean isArchiveExtension(String fileExtension) {
return archiveExtensionSet.contains(fileExtension);
}
/**
* Parse the data for a class to create a JavaClass object.
*/
private static JavaClass parseClass(String archiveName, InputStream in, String fileName)
throws IOException {
if (DEBUG) System.out.println("About to parse " + fileName + " in " + archiveName);
return parseFromStream(in, fileName);
}
/**
* Parse the data for a class to create a JavaClass object.
*/
private static JavaClass parseClass(URL url) throws IOException {
if (DEBUG) System.out.println("About to parse " + url.toString());
InputStream in = url.openStream();
return parseFromStream(in, url.toString());
}
/**
* Parse an input stream to produce a JavaClass object.
* Makes sure that the input stream is closed no
* matter what.
*/
private static JavaClass parseFromStream(InputStream in, String fileName) throws IOException {
boolean parsed = false;
try {
JavaClass jclass = new ClassParser(in, fileName).parse();
parsed = true;
return jclass;
} finally {
if (!parsed) {
// BCEL does not close the input stream unless
// parsing was successful.
try {
in.close();
} catch (IOException ignore) {
// Ignore
}
}
}
}
/**
* Process -bugCategories option.
* @param categories comma-separated list of bug categories
* @return Set of categories to be used
*/
private static Set<String> handleBugCategories(String categories) {
// Parse list of bug categories
HashSet<String> categorySet = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(categories, ",");
while (tok.hasMoreTokens()) {
categorySet.add(tok.nextToken());
}
// Enable only those detectors that can emit those categories
// (and the ones that produce unknown bug patterns, just to be safe).
// Skip disabled detectors, though.
for (Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator(); i.hasNext();) {
DetectorFactory factory = i.next();
if (!factory.isEnabled())
continue;
Collection<BugPattern> reported = factory.getReportedBugPatterns();
boolean enable = false;
if (reported.isEmpty()) {
// Don't know what bug patterns are produced by this detector
if (DEBUG) System.out.println("Unknown bug patterns for " + factory.getShortName());
enable = true;
} else {
for (Iterator<BugPattern> j = reported.iterator(); j.hasNext();) {
BugPattern bugPattern = j.next();
if (categorySet.contains(bugPattern.getCategory())) {
if (DEBUG)
System.out.println("MATCH ==> " + categorySet +
" -- " + bugPattern.getCategory());
enable = true;
break;
}
}
}
if (DEBUG && enable) {
System.out.println("Enabling " + factory.getShortName());
}
factory.setEnabled(enable);
}
return categorySet;
}
public static void main(String[] argv) {
try {
FindBugsCommandLine commandLine = new FindBugsCommandLine();
FindBugs findBugs = createEngine(commandLine, argv);
try {
runMain(findBugs, commandLine);
} catch (RuntimeException e) {
System.err.println("Fatal exception: " + e.toString());
String currentClass = findBugs.getCurrentClass();
if (currentClass != null) {
System.err.println("\tWhile analyzing " + currentClass);
}
e.printStackTrace();
System.err.println("Please report the failure to " + Version.SUPPORT_EMAIL);
System.exit(1);
}
} catch (java.io.IOException e) {
// Probably a missing file
if (DEBUG) {
e.printStackTrace();
}
System.err.println("IO Error: " + e.getMessage());
System.exit(1);
} catch (FilterException e) {
System.err.println("Filter exception: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.err.println("Illegal argument: " + e.getMessage());
System.exit(1);
}
}
private static FindBugs createEngine(FindBugsCommandLine commandLine, String[] argv)
throws java.io.IOException, FilterException {
// Expand option files in command line.
// An argument beginning with "@" is treated as specifying
// the name of an option file.
// Each line of option files are treated as a single argument.
// Blank lines and comment lines (beginning with "
// are ignored.
argv = CommandLine.expandOptionFiles(argv, true, true);
int argCount = commandLine.parse(argv);
Project project = commandLine.getProject();
for (int i = argCount; i < argv.length; ++i)
project.addFile(argv[i]);
if (project.getFileCount() == 0) {
System.out.println("FindBugs version " + Version.RELEASE + ", " + Version.WEBSITE);
System.out.println("Usage: findbugs -textui [options...] [jar/zip/class files, directories...]");
System.out.println("Options:");
commandLine.printUsage(System.out);
System.exit(0);
}
return commandLine.createEngine();
}
private static void runMain(FindBugs findBugs, FindBugsCommandLine commandLine)
throws java.io.IOException, RuntimeException, FilterException {
try {
findBugs.execute();
} catch (InterruptedException e) {
// Not possible when running from the command line
}
int bugCount = findBugs.getBugCount();
int missingClassCount = findBugs.getMissingClassCount();
int errorCount = findBugs.getErrorCount();
if (!commandLine.quiet() || commandLine.setExitCode()) {
if (bugCount > 0)
System.err.println("Warnings generated: " + bugCount);
if (missingClassCount > 0)
System.err.println("Missing classes: " + missingClassCount);
if (errorCount > 0)
System.err.println("Analysis errors: " + errorCount);
}
if (commandLine.setExitCode()) {
int exitCode = 0;
if (errorCount > 0)
exitCode |= ERROR_FLAG;
if (missingClassCount > 0)
exitCode |= MISSING_CLASS_FLAG;
if (bugCount > 0)
exitCode |= BUGS_FOUND_FLAG;
System.exit(exitCode);
}
}
}
// vim:ts=4
|
package com.iluwatar.composite;
/**
* The Composite pattern is a partitioning design pattern. The Composite pattern
* describes that a group of objects is to be treated in the same way as a single
* instance of an object. The intent of a composite is to "compose" objects into
* tree structures to represent part-whole hierarchies. Implementing the Composite
* pattern lets clients treat individual objects and compositions uniformly.
* <p>
* In this example we have sentences composed of words composed of letters. All of
* the objects can be treated through the same interface ({@link LetterComposite}).
*
*/
public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main(String[] args) {
System.out.println("Message from the orcs: ");
LetterComposite orcMessage = new Messenger().messageFromOrcs();
orcMessage.print();
System.out.println("\n");
System.out.println("Message from the elves: ");
LetterComposite elfMessage = new Messenger().messageFromElves();
elfMessage.print();
}
}
|
package Cache;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import Cache.CacheReplacement.Policy;
import Database.DatabaseManager;
public class CacheItem {
/**
* Database: Setting up the SQL statement strings used in this class. These
* are static PreparedStatements that can be shared across all cache items.
*/
static Connection conn = DatabaseManager.getConnection();
static final String findNumberOfAuthors = "select count(distinct(scmlog.author_id)) " +
"from scmlog, actions, files " +
"where scmlog.id=actions.commit_id and actions.file_id=files.id " +
"and date between ? and ? and file_name = ? and scmlog.repository_id=?";
static final String findNumberOfChanges = "select count(actions.file_id) " +
"from scmlog, actions, files where scmlog.id=actions.commit_id " +
"and actions.file_id=files.id and date between ? and ? and file_name = ? " +
"and scmlog.repository_id=?";
static final String findNumberOfBugs = "select count(actions.file_id) " +
"from scmlog, actions, files where scmlog.id = actions.commit_id " +
"and actions.file_id=files.id and file_name=? and date between ? and ? " +
"and scmlog.repository_id=? and is_bug_fix=1";
// static final String findNumberOfAuthors =
// "select count(id) from people " +
// "where id in( " +
// "select author_id from scmlog, actions, files" +
// " where scmlog.id = actions.commit_id " +
// "and date between ? and ? and actions.file_id=files.id and file_name = ?)";
// static final String findNumberOfChanges =
// "select count(actions.id) " +
// "from actions, scmlog, files" +
// " where actions.commit_id = scmlog.id " +
// "and date between ? and ? and actions.file_id=files.id and file_name=?";
// static final String findNumberOfBugs =
// "select count(commit_id) from actions, files " +
// "where actions.file_id=files.id and file_name=? and commit_id in " +
// "(select id from scmlog " +
// "where is_bug_fix=1 and date between ? and ?)";
static final String findLoc = "select loc from content_loc, files where content_loc.file_id=files.id and"
+ " file_name=? and commit_id =?";
private static PreparedStatement findNumberOfAuthorsQuery;
private static PreparedStatement findNumberOfChangesQuery;
private static PreparedStatement findNumberOfBugsQuery;
private static PreparedStatement findLocQuery;
/**
* Member fields
*/
// this enum tracks reason for cache entry and is used by other classes
public enum CacheReason {
Preload, CoChange, NewEntity, ModifiedEntity, BugEntity
}
private final String fileName; // id of file
private int loadDate; // changed on cache hit
private int LOC; // changed on cache hit
private int number; // represents either the number of bugs, changes, or
// authors
private int loadCount = 0; // count how many time a file is put into cache
private int loadDuration = 0; // represents how long in repo time a file
// stays in cache
private String timeAdded; // represents repo time when a file is added to
// cache
private final Cache parent;
private boolean inCache = false; // stores whether the cacheitem is in the
// cache
private int hitCount = 0;
private int missCount = 0;
// @SuppressWarnings("unused") // may be useful output
private CacheReason reason;
/**
* Methods
*/
public CacheItem(String fName, int cid, String cdate, CacheReason r, Cache p) {
fileName = fName;
reason = r;
parent = p;
update(cid, cdate, p.getStartDate(), r);
assert (r != CacheReason.BugEntity || missCount != 0);
assert (parent.neverInCache(fileName));
}
/**
* called every time entityId moved into the cache, or cache hit occurs
* updates the time of cache load, loc, and number
*
* @param cid
* -- commit id
* @param cdate
* -- commit date
* @param sdate
* -- starting date
*/
public void update(int cid, String cdate, String sdate, CacheReason r) {
// update the load count each time an entry is added to the cache
if (!inCache) {
inCache = true;
loadCount++;
timeAdded = cdate;
if (r == CacheReason.BugEntity)
missCount++;
} else { // is in cache
if (r == CacheReason.BugEntity)
hitCount++;
}
loadDate = parent.getTime();
LOC = findLoc(fileName, cid);
number = findNumber(fileName, parent.repID, cdate, sdate,
parent.getPolicy());
}
public boolean isInCache() {
return inCache;
}
public int removeFromCache(String cdate) {
loadDuration += Util.Dates.getMinuteDuration(timeAdded, cdate);
assert (inCache);
inCache = false;
return loadDuration;
}
// XXX: Do we need pid? or is eid unique enough for the called methods?
/**
*
* @param eid
* -- entity id
* @param pid
* -- repository id
* @param cdate
* -- the commit date
* @param start
* -- the starting date for repository access
* @return the number of bug fixes for file eid in repository pid between
* cdate and start
*/
private static int findNumber(String fileName, int pid, String cdate,
String sdate, Policy pol) {
int ret = 0;
switch (pol) {
case BUGS:
ret = findNumberOfBugs(fileName, pid, cdate, sdate);
break;
case CHANGES:
ret = findNumberOfChanges(fileName, pid, cdate, sdate);
break;
case AUTHORS:
ret = findNumberOfAuthors(fileName, pid, cdate, sdate);
break;
case LRU: // do nothing
}
return ret;
}
// XXX: Do we need pid? or is eid unique enough for this query?
/**
*
* @param eid
* -- entity id
* @param pid
* -- repository id
* @param cdate
* -- the commit date
* @param start
* -- the starting date for repository access
* @return the number of distinct authors for file eid in repository pid
* between cdate and start
*/
private static int findNumberOfAuthors(String fileName, int pid,
String cdate, String start) {
int ret = 0;
try {
if (findNumberOfAuthorsQuery == null)
findNumberOfAuthorsQuery = conn
.prepareStatement(findNumberOfAuthors);
findNumberOfAuthorsQuery.setString(1, start);
findNumberOfAuthorsQuery.setString(2, cdate);
findNumberOfAuthorsQuery.setString(3, fileName); // XXX fix query to use file_name
findNumberOfAuthorsQuery.setInt(4, pid);
ret = Util.Database.getIntResult(findNumberOfAuthorsQuery);
} catch (SQLException e1) {
e1.printStackTrace();
}
return ret;
}
// XXX: Do we need pid? or is eid unique enough for this query?
/**
*
* @param eid
* -- entity id
* @param pid
* -- repository id
* @param cdate
* -- the commit date
* @param start
* -- the starting date for repository access
* @return the number of commits for file eid in repository pid between
* cdate and start
*/
private static int findNumberOfChanges(String fileName, int pid,
String cdate, String start) {
int ret = 0;
try {
if (findNumberOfChangesQuery == null)
findNumberOfChangesQuery = conn
.prepareStatement(findNumberOfChanges);
findNumberOfChangesQuery.setString(1, start);
findNumberOfChangesQuery.setString(2, cdate);
findNumberOfChangesQuery.setString(3, fileName); // XXX fix query to use file_name
findNumberOfChangesQuery.setInt(4, pid);
ret = Util.Database.getIntResult(findNumberOfChangesQuery);
} catch (SQLException e1) {
e1.printStackTrace();
}
return ret;
}
/**
*
* @param eid
* -- entity id
* @param pid
* -- repository id
* @param cdate
* -- the commit date
* @param start
* -- the starting date for repository access
* @return the number of bug fixes for file eid in repository pid between
* cdate and start
*/
private static int findNumberOfBugs(String fileName, int pid, String cdate,
String start) {
int ret = 0;
try {
if (findNumberOfBugsQuery == null)
findNumberOfBugsQuery = conn.prepareStatement(findNumberOfBugs);
findNumberOfBugsQuery.setString(1, fileName); // XXX fix query to use file_name
findNumberOfBugsQuery.setString(2, start);
findNumberOfBugsQuery.setString(3, cdate);
findNumberOfBugsQuery.setInt(4, pid);
ret = Util.Database.getIntResult(findNumberOfBugsQuery);
} catch (SQLException e1) {
e1.printStackTrace();
}
return ret;
}
/**
*
* @param eid
* -- entity id
* @param cid
* -- commit id
* @return the lines of code for eid at cid
*/
private static int findLoc(String fileName, int cid) {
int ret = 0;
try {
if (findLocQuery == null)
findLocQuery = conn.prepareStatement(findLoc);
findLocQuery.setString(1, fileName); // XXX fix query to use
// file_name
findLocQuery.setInt(2, cid);
ret = Util.Database.getIntResult(findLocQuery);
} catch (SQLException e1) {
e1.printStackTrace();
}
return ret;
}
/**
* @return Returns the entityId.
*/
public String getFileName() {
return fileName;
}
/**
* @return Returns the cachedDate.
*/
public int getLoadedDate() {
return loadDate;
}
/**
* @return Returns the LOC.
*/
public int getLOC() {
return LOC;
}
/**
* @return Returns the numberOfChanges.
*/
public int getNumberOfChanges() {
assert (parent.getPolicy() == CacheReplacement.Policy.CHANGES);
return number;
}
/**
* @return Returns the numberOfBugs.
*/
public int getNumberOfBugs() {
assert (parent.getPolicy() == CacheReplacement.Policy.BUGS);
return number;
}
/**
* @return Returns the numberOfAuthors
*/
public int getNumberOfAuthors() {
assert (parent.getPolicy() == CacheReplacement.Policy.AUTHORS);
return number;
}
/**
* @return Returns the loadCount
*/
public int getLoadCount() {
return loadCount;
}
/**
* @return Returns the hitcount
*/
public int getHitCount() {
return hitCount;
}
/**
* for debugging; used only for the DBUnit tests
*
* @return number
*/
protected int getNumber() {
return number;
}
public CacheReason getReason() {
return reason;
}
/**
*
* @return the amount of time this cache item was in cache
*/
public int getDuration() {
if (inCache)
loadDuration += Util.Dates.getMinuteDuration(timeAdded,
parent.endDate);
return loadDuration;
}
public int getMissCount() {
return missCount;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.